diff --git a/deps_src/libnest2d/include/libnest2d/nester.hpp b/deps_src/libnest2d/include/libnest2d/nester.hpp index 13281c389b..f1852478d2 100644 --- a/deps_src/libnest2d/include/libnest2d/nester.hpp +++ b/deps_src/libnest2d/include/libnest2d/nester.hpp @@ -78,6 +78,12 @@ public: std::vector extrude_ids; int filament_temp_type = -1; // -1 means unset. otherwise should be {0,1,2} double height{ 0 }; + double z_min{ 0 }; + double z_max{ 0 }; + bool has_z_range{ false }; + bool is_bed_exclusion{ false }; + std::vector bed_exclusion_extruder_ids; + int bed_exclusion_extruder_id{ -1 }; double print_temp{ 0 }; double bed_temp{ 0 }; double vitrify_temp{ 0 }; // vitrify temperature diff --git a/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp b/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp index ba015b0faa..f41e9ade61 100644 --- a/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp +++ b/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp @@ -123,6 +123,10 @@ struct NfpPConfig { std::function on_preload; + // Return false when a packed item does not constrain this candidate. + // By default every pair participates in the 2D collision calculation. + std::function&, const _Item&)> should_check_collision; + //BBS: sort function for selector std::function& i1, _Item& i2)> sortfunc; //BBS: excluded region for V4 bed @@ -579,7 +583,14 @@ private: { using namespace nfp; - Shapes nfps(items_.size()); + std::vector collision_items; + collision_items.reserve(items_.size()); + for (Item &item : items_) { + if (!config_.should_check_collision || config_.should_check_collision(trsh, item)) + collision_items.emplace_back(&item); + } + + Shapes nfps(collision_items.size()); // ///////////////////////////////////////////////////////////////////// // TODO: this is a workaround and should be solved in Item with mutexes @@ -590,21 +601,21 @@ private: trsh.rightmostTopVertex(); trsh.leftmostBottomVertex(); - for(Item& itm : items_) { - itm.transformedShape(); - itm.referenceVertex(); - itm.rightmostTopVertex(); - itm.leftmostBottomVertex(); + for (Item *item : collision_items) { + item->transformedShape(); + item->referenceVertex(); + item->rightmostTopVertex(); + item->leftmostBottomVertex(); } // ///////////////////////////////////////////////////////////////////// - __parallel::enumerate(items_.begin(), items_.end(), - [&nfps, &trsh](const Item& sh, size_t n) + __parallel::enumerate(collision_items.begin(), collision_items.end(), + [&nfps, &trsh](Item *const &sh, size_t n) { - auto& fixedp = sh.transformedShape(); + auto& fixedp = sh->transformedShape(); auto& orbp = trsh.transformedShape(); auto subnfp_r = noFitPolygon(fixedp, orbp); - correctNfpPosition(subnfp_r, sh, trsh); + correctNfpPosition(subnfp_r, *sh, trsh); nfps[n] = subnfp_r.first; }); diff --git a/docs/HLSD/exclusion-volumes.md b/docs/HLSD/exclusion-volumes.md new file mode 100644 index 0000000000..1b68c256d5 --- /dev/null +++ b/docs/HLSD/exclusion-volumes.md @@ -0,0 +1,69 @@ +# Bed exclusions and toolhead collision volumes + +## Purpose and configuration + +Bed exclusions have two distinct meanings. A material keep-out prevents model +placement without prohibiting deliberate machine travel, such as entering a +filament cutter. A toolhead collision volume represents an obstacle that travel +and extrusion must avoid. Keeping separate settings preserves existing printer +profiles, project files and command-line usage without enabling new motion +constraints implicitly. + +- `bed_exclude_area` remains a points-array polygon and a shared, bed-fixed + material/placement keep-out. +- `bed_exclude_volumes` contains collision-volume polygons, with optional + `ZMIN..ZMAX;` prefixes and `|` separators. A polygon without a Z prefix applies + over the printable height. +- `bed_exclude_volume_mode` selects shared volumes, toolhead-relative volumes + derived from nozzle XY offsets, or individually configured extruder volumes. +- `extruder_bed_exclude_volumes` stores the individual definitions. These are + selected by physical extruder, not simply by filament slot. + +Material keep-outs and collision volumes are additive. Nozzle offsets apply only +to collision volumes in toolhead-relative mode. The existing bed area never moves +or disappears when collision volumes are configured. + +On belt printers, the region resolver projects material keep-outs onto the +tilted bed surface before placement and tower validation. Collision volumes +remain in model coordinates; the bed-surface projection is not applied to them. + +The printer settings expose the bed area as a normal editable field with Orca's +standard reset controls. Collision volumes appear directly below it in Printable +space, as a separate field. A bed-area polygon can be manually copied into this +field to define a full-height collision volume. Pasted volume syntax in the +area field requires confirmation before it is added to the volume settings; +declining or invalid input leaves the stored area intact. + +## Geometry and slicing + +The region resolver retains the distinction between material keep-outs and +collision volumes, and supplies nozzle-specific regions to placement, arrangement, +generated geometry and motion consumers. An object is checked conservatively +against the collision volumes for every nozzle it uses, over its complete geometry +rather than only a painted portion. Shared support geometry likewise uses a +conservative union of the relevant nozzle and instance exclusions. + +Collision-volume footprints are selected by their overlap with the applicable Z +slab. Brim and supported support-generation paths subtract these footprints before +extrusion generation. The travel router attempts to avoid active collision +volumes; the final G-code checker validates emitted motion independently. + +The checker cannot infer movements inside opaque firmware macros. Homing leaves +the affected coordinates unknown until explicit coordinates establish them. +Skirts and draft shields are not rebuilt around obstacles, extrusion is not +rerouted, and the circular XY sweep of spiral Z-hop is not available to the travel +router when it plans the primary travel. The final checker can warn about these +violations; that warning is not an automatic repair or a guarantee of safe output. + +## Preview + +Ground footprints remain visible. Nozzle-specific collision volumes have thin +nozzle-coloured borders; shared volumes and single-nozzle configurations do not +imply ownership by a particular filament. Automatic 3D previews are limited to +nearby object height to avoid obscuring the workspace. + +**View → Show all collision volumes** displays each volume over its complete +resolved Z range, including on an empty bed. Its default shortcut is Ctrl+Shift+K +(Command+Shift+K on macOS), configurable through Orca's shortcut settings. The +application remembers this display preference independently of printer presets; +it changes neither collision checking nor slicing results. diff --git a/docs/HLSD/keyboard-shortcuts.md b/docs/HLSD/keyboard-shortcuts.md index cf48a13c8d..18b8cf8578 100644 --- a/docs/HLSD/keyboard-shortcuts.md +++ b/docs/HLSD/keyboard-shortcuts.md @@ -56,9 +56,34 @@ combo boxes), so it opens the dial from the canvases and the tab strip only. `MainFrame::handle_global_shortcut` skips a chord that `KeyChord::edits_text()` reports while a text field has the focus (a wx text entry, spin control, web view or ImGui InputText), and skips every chord while an ImGui modal is open, as a wx modal dialog -would. `ImGuiWrapper::owns_key()` reads the active InputText and the popup stack -directly, since `WantCaptureKeyboard` lags a frame, and is called only when the focus is on -a visible canvas from `OpenGLManager::create_wxglcanvas()`. +would. `ImGuiWrapper::owns_key()` reads the text input request and the popup stack of the +last drawn frame, since `WantCaptureKeyboard` and `WantTextInput` only catch up when the +next frame starts, and is called only when the focus is on a visible canvas from +`OpenGLManager::create_wxglcanvas()`. + +The `Plater`, `Preview` and `Painting` shortcuts act on the 3D view, so they run only while +the 3D view has the keyboard. `GLCanvas3D` feeds every key event to ImGui and asks +`ImGuiWrapper::claim_key_event()` whether to act on it as well. While an ImGui popup (a +dropdown, a menu or a modal) is open or an ImGui InputText is active, ImGui claims every key, +as a focused sidebar text field or an open native dropdown keeps every key from the canvas. +Esc then closes the topmost dropdown or menu, since this ImGui closes popups on Esc only +through keyboard navigation, which is off; a modal handles Esc itself. A second Esc reaches +the canvas once nothing claims it. A slider or button held with the mouse also claims every +key until it is released, since a shortcut that switches the view or closes the tool would +leave the drag behind. One side handles a key from its key-down to its release. Its +repeats, its char event and its release follow the key-down's decision even when a field or +modal opens or closes in between, so a key never both runs a shortcut and types, and a +keyboard move of the selection always sees the release of the key that started it. + +Key-ups go to whatever window has the focus, so a shortcut that opens a dialog, such as +Ctrl+P, takes the release of its modifier with it. When the canvas loses the focus it sends +itself a key-up for each Shift, Ctrl or Alt still held, which ends a gizmo's Shift mode and +clears ImGui's own copy of the modifier, and then drops its record of held keys. +`ImGuiWrapper::update_mouse_data()` also takes ImGui's modifiers from each mouse event, which +carries the real state, since a stale Ctrl would turn every slider click into a Ctrl+click +and open the slider's text box. The macOS +Edit menu, whose key equivalents run before the canvas sees the key, follows the same rule +as the canvas. ## Which event a chord matches diff --git a/docs/HLSD/preset-plugin-api.md b/docs/HLSD/preset-plugin-api.md new file mode 100644 index 0000000000..4cc481eb12 --- /dev/null +++ b/docs/HLSD/preset-plugin-api.md @@ -0,0 +1,252 @@ +# Preset Plugin API — High Level Design + +## Purpose and scope + +The preset plugin API lets Python plugins update the presets OrcaSlicer is using, +so users do not have to perform every routine setting change by hand. It covers +process, printer, and filament presets. All three use one staged update lifecycle; +the way a target is selected is specific to the preset type. + +The API edits Orca's managed edited preset, not a detached copy or a saved preset +behind the UI's back. It does not save to disk. Saving, discarding, and transferring +unsaved edits remain under Orca's existing preset workflow. + +The API does not create or delete presets or provide off-tab editing. For filament, +choosing a different `preset_name` as the update target also selects that preset for +the requested slot, following the normal UI flow. A standalone slot-assignment or +preset-fork operation is outside this API's contract. + +## Preset and slot model + +Each preset collection maintains a managed edited copy for its selected preset. +Settings tabs apply changes to that copy and own the normal dirty-state, validation, +save/discard/transfer, and downstream refresh behavior. Plugin updates must use the +same path so that the settings tab, dirty indicators, and effective print +configuration observe a consistent state. + +Filament selection adds a slot-to-preset mapping. `PresetBundle::filaments` is the +catalog, while `PresetBundle::filament_presets` maps each slot to a preset name. +Several slots may refer to the same preset. A filament update edits that shared +preset, so all slots referring to it are affected. Slot numbers exposed by the API +are 1-based, matching the UI. + +## API shape + +Each preset API exposes `begin_update()`, which selects and binds one target, and +returns a transaction. The transaction stages setting changes using `set()` and +applies them only on explicit `commit()`. + +```python +# Filament is targeted by its 1-based slot. Omitting preset_name keeps the +# preset currently assigned to the slot; providing it selects that preset for +# the slot before staging updates. +tx = orca.host.preset.filament.begin_update( + slot_number=2, + preset_name="Generic PLA" +) +tx.set("filament_flow_ratio", "0.98") +tx.set("filament_retract_length", "0.8") +result = tx.commit() + +# Process and printer default to their active presets. A caller can request a +# different preset that is selectable in the corresponding UI dropdown. +tx = orca.host.preset.process.begin_update( + preset_name="0.20mm Standard" +) +tx.set("layer_height", "0.2") +tx.commit() +``` + +The example is the API contract, and the Python bridge provides it. `begin_update()` +is synchronous: it blocks the background Script worker until the target selection and +any unsaved-edit dialog settle, then returns the bound transaction. Orca's UI thread +stays responsive because the Script capability runs on its own worker. `set()` and +`commit()` run synchronously on that same worker. The Script worker and its optional +coroutine loop are described in +[python-plugin-async-bridge.md](python-plugin-async-bridge.md). + +### Target resolution + +- **Filament:** `slot_number` identifies the slot. If `preset_name` is omitted, + the transaction targets the preset currently assigned to that slot. If supplied, + it requests that preset for the slot and selects it through the normal UI flow; + the name must be among the presets offered by that slot's dropdown, with one + exception: the preset currently assigned to the slot stays targetable even when the + slot's dropdown hides it (for example an incompatible-but-selected preset). Selecting + a different preset changes the slot-to-preset mapping. In both cases the transaction + edits the shared preset, not an isolated slot override. +- **Process and printer:** omitting `preset_name` targets the currently active + preset. Supplying `preset_name` requests the preset by the name shown in its + dropdown. It must be one of the choices the dropdown currently offers, rather + than merely any preset present in the collection. This is particularly important + for process presets, whose selectable choices can depend on the current context. +- A transaction targets exactly one preset. Multi-preset transactions are not + supported: applying them would require switching among targets while the + application has only one managed edited copy per collection. + +Targets are resolved through Orca's normal preset-selection model. The API should +not accept raw preset pointers or filesystem paths as target identities. A missing, +unavailable, or ambiguous target fails explicitly instead of silently selecting a +different preset. + +## Selection and user interaction + +`begin_update()` resolves its target through shared binding helpers +(`bind_preset_target` for process/printer, `bind_filament_target` for filament) and +performs the selection only when the requested target differs from the active target; +otherwise it returns a transaction without switching. The helpers use Orca's normal +preset selection flow, `Tab::select_preset()`, including updating a filament slot +assignment when requested. If the normal selection flow requires user input, it opens +the relevant existing dialog(s), including unsaved-edit choices such as save, discard, +or transfer. The call remains blocked on the Script worker until those interactions +finish; it returns the bound transaction, or raises on a cancellation, without +applying staged settings. A canceled selection does not change the requested target or +filament slot assignment, but it does not roll back decisions the user already accepted +in an earlier dialog. The helpers then confirm that the requested preset actually +became the edited preset; a successful selection request alone is not sufficient. There +is no separate `switch_preset` plugin API. + +If the requested target is already active, `begin_update()` returns without a +selection prompt, apart from the UI-thread dispatch needed to bind the transaction. +If a different preset is requested, Orca selects it through the normal UI flow. For +filament, this also updates the requested slot's assignment when `preset_name` +differs from its current assignment. When the current preset has unsaved changes, +the Script worker stays blocked until the user chooses among Orca's existing options, +such as transfer, discard, or cancel. + +The API never suppresses that warning, chooses an option for the user, or switches +away from dirty edits silently. Cancel aborts the operation before any staged target +changes are applied. Process and printer updates follow this rule too when the +plugin requests a different `preset_name`; they normally return immediately when +the active preset is the target. + +## Staging and commit semantics + +`set(key, value)` stages a serialized config value and does not mutate the preset. +The transaction is the boundary for a related group of changes, avoiding +intermediate partially-updated states. `commit()` runs synchronously on the background +Script worker. At commit, the API validates keys and values against the target preset +type and applies the batch through `Tab::apply_preset_config_values`, the existing tab +and settings-group update path. Existing setting-specific validation, correction, and +callbacks remain authoritative; plugin updates do not create a parallel setter with +different behavior. + +A successful commit updates dirty state and downstream configuration/Plater state +once for the batch. The edited preset remains unsaved; persistence continues through +Orca's normal save action. A validation or commit failure restores the edited preset's +config to its pre-batch state and recomputes the state derived from it (compatibility +marks, the preset selector, dependent tabs, the Plater and the printer agent), so no +staged setting is left partially applied. That guarantee is limited to the edited +preset and its config-derived state: an `on_change` callback is a GUI method, not a pure +function of the config, so the transaction does not reverse a preset or slot selection +made while resolving the target, a dialog decision the user already accepted, an undo +snapshot, a dependent preset's rewritten config, or anything already sent to a device. +Exact all-or-nothing across those external effects is not achievable while the +authoritative GUI callbacks run; the boundary is documented on +`Tab::apply_preset_config_values`. A filament slot assignment made as part of target +selection is likewise not a staged setting: after the user accepts the selection flow it +may remain changed even if a later commit fails, and the API does not switch back or +reverse the user's selection or any accepted transfer/discard decision for the previous +preset. + +## Outcomes and consistency + +The API distinguishes target resolution failures, invalid setting/value, user +cancellation, stale filament-slot mapping, and commit failure. A result identifies +the target preset, whether preset selection changed, and (for filament) whether the +slot assignment changed and which slots share the edited preset. A canceled +selection applies neither the requested slot assignment nor staged target changes; +a failed commit applies none of the staged target settings. + +Filament slot assignments can change between `begin_update()` and `commit()`. The API +detects that and rejects a stale operation instead of silently editing the new +slot assignment. It must not hold raw preset pointers across reloads. Conflicting +duplicate writes to one setting in a transaction are rejected rather than resolved +by incidental call order. + +The existing one-setting filament call, +`orca.host.preset.filament.update(slot_number, key, value)`, remains available as a +compatibility shorthand. It shares the staged API's target resolution, selection, +validation, and commit path, and it is synchronous like `begin_update()`: both block +the background Script worker while any selection dialog settles. + +## Design principles + +- **Reduce routine interaction, preserve agency.** Clean switches should be + seamless; unsaved user work must still receive the normal warning and decision. +- **One source of truth.** UI and plugins share the managed edited copy and setting + update path, including validation and callbacks. +- **The UI workflow is authoritative.** The API must enter through the same + selection and setting-change workflows as the UI, not reproduce their logic or + write config values directly. This keeps existing and future side effects active: + `on_change` handling for mutually exclusive, invalid, or out-of-range settings; + compatibility and dependent-preset updates; and printer-agent changes when the + selected printer changes. +- **Explicit target and explicit commit.** Plugins know which preset they edit and + when staged changes become visible. +- **No hidden persistence.** Plugin edits remain unsaved until the user saves them + through Orca. +- **Shared means shared.** Editing a filament preset through one slot affects every + slot assigned to it. Choosing another preset for a slot is explicit in + `preset_name`; slot-specific divergence would require a separate fork operation. +- **Consistent lifecycle, type-specific targeting.** Process, printer, and + filament share transaction and error semantics while respecting their existing + selection models. + +## Implementation in the current codebase + +The transaction API is implemented. The current plugin surface exposes `begin_update()`, +`PresetTransaction` with `set()`/`commit()`, and the per-setting `update()` compatibility +shorthand. For filament, `update_filament_slot()` resolves the preset already assigned +to a slot, selects it through `Tab::select_preset()`, and applies one setting through +`Tab::apply_preset_config_values()`; it does not change the slot assignment. + +`begin_update()` and `update()` are synchronous blocking calls +(`begin_preset_update` / `begin_filament_update`). They marshal the target binding to +the UI thread and block the background Script worker until the selection settles, so +the wait never blocks the UI thread. They are valid only on that worker, never from the +UI thread or a slicing pipeline hook. + +`Tab::select_preset()` is the basis for switching to process, printer, or filament +presets and for invoking the normal unsaved-edit flow. The flow is type-specific: a +process selection can trigger compatibility handling for filaments, and a printer +selection can involve technology changes and dependent preset compatibility. It may +therefore show more than one dialog. Cancellation of a later step does not necessarily +undo decisions the user already accepted in an earlier dialog. Target resolution +preserves those side effects and then verifies the resulting edited target. + +Filament `preset_name` is an additional integration on top of `Tab::select_preset()`: +selecting a different name for a slot also updates the slot-to-preset mapping and its +dependent UI/configuration state, mirroring the filament branch of the Plater's normal +selection path (`PresetBundle::set_filament_preset()` plus the project/selection refresh, +the dynamic filament list, the conditional support-filament flushing recalc, the slot +combo refresh and its AMS sync badge). A mixed-color virtual slot is not targetable. + +Process and printer dropdown choices are constrained by visibility and compatibility, +and compatibility may depend on the active context. Target resolution checks the tab +dropdown's actual items before the selection flow, so a target the user cannot pick +fails without raising that flow's unsaved-edit prompt; a name two entries carry is +rejected as ambiguous. A filament `preset_name` resolves against the requested slot's +own sidebar selector rather than the tab's, so that slot's compatibility filter is the +one that applies. A name the slot's dropdown does not show is rejected unless it names +that slot's current assignment (a hidden or incompatible-but-selected preset), which +stays targetable. + +`commit()` applies its batch through `Tab::apply_preset_config_values`, which parses and +validates the whole batch before touching the edited preset and restores the edited +preset and its config-derived state on failure (see "Staging and commit semantics" for +the limit of that rollback). Since `begin_update()` performs target selection before the +caller stages values, invalid staged values can still follow a user-visible selection +prompt; that is a consequence of this API shape and remains explicit in its behavior. + +## Integration boundary + +The plugin API coordinates target resolution, preset selection, staged values, and +the settings commit path. It does not own or duplicate preset dirty-state logic, +selection prompts, setting validation, or persistence. Target changes flow through +the same UI selection path so dependent behavior—such as selecting the printer +agent—still runs. Setting changes flow through the same UI change path so `on_change` +and related validation/correction behavior still runs. The integration bridges UI +prompts to the Python operation through the blocking `begin_update()` and reuses +the normal Plater slot-selection behavior for explicit filament targets, and commits a +batch without losing existing per-setting behavior. diff --git a/docs/HLSD/python-plugin-async-bridge.md b/docs/HLSD/python-plugin-async-bridge.md new file mode 100644 index 0000000000..63a22a498a --- /dev/null +++ b/docs/HLSD/python-plugin-async-bridge.md @@ -0,0 +1,351 @@ +# Python plugin async bridge — High Level Design + +## Purpose and scope + +The embedded Python plugin runtime runs most capability calls synchronously: a C++ call site acquires +the GIL and the capability's Python method runs to completion on the calling thread. The staged preset +update (`begin_update()` in [preset-plugin-api.md](preset-plugin-api.md)) is also synchronous, but +its target selection can open unsaved-edit dialogs. It therefore blocks the Script worker, not the UI +thread, and returns only when the selection settles. + +This document describes the Script capability's background execution path, including the optional +per-invocation asyncio loop for an `async def execute`, and the blocking UI marshalling that host calls +use from that worker. The bridge is deliberately narrow: only the Script capability gains a +background/async execution path. Every other capability — including the SlicingPipeline hooks — stays +synchronous on its caller's thread. + +## Execution baseline + +### How a capability call runs + +A capability instance is a Python object owned through `Slic3r::PluginInstanceHandle` +(`src/slic3r/plugin/PythonPluginBridge.cpp`) and handed to the rest of the program as a +`std::shared_ptr`. Its identity (`name()`, `type()`, +`audit_plugin_key()`) is resolved once at materialization and cached in C++ +(`PluginCapabilityInterface` in `src/slic3r/plugin/PythonPluginInterface.hpp`). + +Every C++→Python call crosses a trampoline method. `PyPluginCommonTrampoline` and +`PyPluginInterfaceTrampoline` (`src/slic3r/plugin/PyPluginTrampoline.hpp`), and the per-type subclass +`PyScriptPluginCapabilityTrampoline` +(`src/slic3r/plugin/pluginTypes/script/ScriptPluginCapabilityTrampoline.hpp`), wrap the call in the +`ORCA_PY_OVERRIDE_AUDITED` macro. For one synchronous call that macro, in order: + +1. constructs a `PluginCapabilityInterface::RefCounter`, which `increment()`s the capability's + reference count for the call's duration; +2. constructs a `PythonGILState`, which first acquires a `PythonRuntimeLease` and then + `PyGILState_Ensure()`; +3. opens a `ScopedPluginAuditContext(audit_plugin_key(), name())`; +4. dispatches into Python via `PYBIND11_OVERRIDE`/`PYBIND11_OVERRIDE_PURE`; + +and unwinds those guards when the call returns. + +`PythonGILState` and `PythonRuntimeLease` live in `src/slic3r/plugin/PythonInterpreter.hpp`. A lease is +a `shared_lock` on `PythonInterpreter::m_runtime_mutex`; `PythonInterpreter::shutdown()` takes the +exclusive side, so a thread that holds a lease can safely touch Python objects, and interpreter +finalization cannot run underneath it. `ScopedPluginAuditContext` +(`src/slic3r/plugin/PluginAuditManager.hpp`) stores the previous thread-local plugin/capability pair +and scoped filesystem roots, sets this call's, and restores them on destruction; the audit hook then +attributes every filesystem/socket/process event to the plugin currently executing on that thread. + +### The Script capability + +`Slic3r::ScriptPluginCapability` (`src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.hpp`) +declares one pure virtual method, `ExecutionResult execute()`. The async runtime invokes it through +`invoke_script_execute` (`src/slic3r/plugin/PyPluginTrampoline.hpp`), which replicates the audited +trampoline call (ref counter, audit scope, traceback-preserving rethrow) but returns a +`ScriptExecuteInvocation` instead of forcing a cast: + +- a plain `def execute` runs to completion in `invoke_script_execute` and yields + `ScriptExecuteInvocation::result`; +- an `async def execute` (or any override that returns a coroutine, detected with + `inspect.iscoroutine`) yields the coroutine object in `ScriptExecuteInvocation::awaitable` without + running it, so the runtime can drive it. + +`ScriptExecuteInvocation` is defined in `PyPluginTrampoline.hpp`; `py_is_coroutine` is the detection +helper. + +### UI marshalling + +`PluginHostUi::run_on_ui_thread` (`src/slic3r/plugin/host/PluginHostUi.cpp`) forwards to the +file-local `run_on_ui_blocking`: + +- if the caller is already on the wx main thread, it runs the callable inline after a + `py::gil_scoped_release`; +- otherwise it sets up a `std::promise`/`std::future`, releases the GIL, posts the callable with + `GUI::wxGetApp().CallAfter`, and blocks on `future.get()`. + +That is a blocking handoff: the caller's stack is parked on a thread while the UI thread runs the +callable. It is the correct primitive for the synchronous `update()`/`commit()` path and for +`reload_local_bundle`/`list_bundle_ids`, but it cannot be used by an operation that must suspend. + +### Slicing hooks + +`Print::set_slicing_pipeline_hook_fn` is installed by `src/slic3r/plugin/PluginHooks.cpp`. The hook +runs on the slicing worker thread and dispatches to `SlicingPipelinePluginCapability::execute(ctx)` +per capability, acquiring a `PythonGILState` per capability. `SlicingPipelineContext` +(`SlicingPipelinePluginCapability.hpp`) holds raw pointers into the live slicing graph +(`ctx.print`, `ctx.object`) that are valid only for the duration of `execute(ctx)`. The UI thread can +be blocked waiting on the slicing worker (`BackgroundSlicingProcess::stop()` parks it), so a +marshalled UI call from a hook can deadlock; `PluginHostSlicing.cpp`, `SlicingPipelinePluginCapability.hpp` +and `PluginHostUi.hpp` all document this. + +## Script-only async execution + +### Per-invocation worker and loop + +`ScriptAsyncRuntime` (declared in `src/slic3r/plugin/PluginManager.hpp`, implemented in +`PluginManager.cpp`) drives every Script invocation off the caller's thread. Its `start()` creates a +`Run` and launches a detached worker thread that runs `Impl::run_invocation`. There is one worker +thread per invocation, so no invocation ever blocks the UI thread and no invocation is queued behind +another plugin's. + +`run_invocation` runs detection and execution on the worker: + +- it re-checks `cancel_requested` before anything (a cancellation that arrived before the run + started is honored without running the plugin); +- it calls `invoke_script_execute`; a plain `def execute` result is used directly, and an `async def` + coroutine is driven on a loop created for that invocation: + `asyncio.new_event_loop()` → `asyncio.set_event_loop(loop)` → `loop.create_task(coroutine)` → + `loop.run_until_complete(task)` → `loop.close()`, then `asyncio.set_event_loop(None)`. + +The loop is per invocation, not global, and no loop outlives its invocation. The loop for the +calling thread is published in the thread-local `tl_script_loop` and exposed through +`ScriptAsyncRuntime::current_loop()` (GIL held). A host call such as `begin_update()` does not suspend +the loop: it blocks the worker thread while the UI settles, then returns a value the coroutine uses +directly. + +`PluginManager::launch_script_capability` is the entry point: it resolves the capability, hands it to +`ScriptAsyncRuntime::start`, and sets `ScriptLaunchResult::launched_async`. The completion callback +runs on the GUI thread (or inline when there is no wx app), and `launch_script_capability` records a +run error through `set_plugin_error` before invoking the caller's `ScriptCompletionFn`. +`PluginManager::run_script_capability` is kept as a compatibility wrapper: it waits for the +completion callback, pumping `wxYield()` when it is itself on the GUI thread, and returns the +`ExecutionResult`. + +### Capability, runtime, GIL and audit lifetime across a suspension + +For the whole invocation — including an `async def` suspended at an `await` — `run_invocation` holds: + +- a `PluginCapabilityInterface::RefCounter` per invocation and a `shared_ptr` to the capability in the + `Run`, so the capability and its module stay alive across awaits and unload cannot drop them; +- a `PythonRuntimeLease` (acquired before the GIL). `PythonInterpreter::shutdown()` cannot finalize + the interpreter while any invocation worker holds a lease; +- the GIL, acquired with `pybind11::gil_scoped_acquire` on the worker; +- a `ScopedPluginAuditContext(audit_plugin_key(), name())`, so filesystem/socket/process events + raised by the coroutine are attributed to the plugin. + +The capability reference is released inside the GIL scope (`run->capability.reset()`), because +dropping the pybind holder from a non-Python thread would `DECREF` without the GIL. The loop is +closed and `tl_script_loop` cleared before the worker exits. + +A consequence of running Script on a non-main thread: the audit permission prompt is fail-closed off +the main thread. `request_permission` in `src/slic3r/plugin/PluginAuditManager.cpp` posts the dialog +with `CallAfter` and denies the current event, persisting the grant when the user accepts, so a +Script sees a denial on the first attempt and can succeed on a later one. This matches the existing +behavior for the plugin-load worker and the slicing worker. + +### Blocking UI continuation + +`PluginHostUi::run_on_ui_thread` (in `src/slic3r/plugin/host/PluginHostUi.cpp`) is the primitive host +calls use from the Script worker. It forwards to `run_on_ui_blocking`: + +- if the caller is already on the wx main thread, it runs the callable inline after a + `py::gil_scoped_release`; +- otherwise it sets up a `std::promise`/`std::future`, releases the GIL, posts the callable with + `GUI::wxGetApp().CallAfter`, and blocks on `future.get()`. + +Because the Script capability owns a worker thread, blocking there does not freeze the UI. The same +primitive is used by `begin_update()`, `set()`/`commit()`, `reload_local_bundle()` and +`list_bundle_ids()`. + +### Synchronous `begin_update()` + +`begin_preset_update` and `begin_filament_update` (`src/slic3r/plugin/host/PluginHostPresets.cpp`) run +on the Script worker with the GIL held and block it: + +1. the binding enters through `PluginHostUi::run_on_ui_thread`, which fails with a `RuntimeError` + before posting when there is no wx application; +2. the UI thread runs the target binding with the GIL released — `bind_preset_target` for + process/printer, `bind_filament_target` for filament — including `Tab::select_preset()` and any + unsaved-edit prompt; +3. the worker resumes with the name-based `PresetTransaction`, and nothing is staged until the + caller's later `set()`/`commit()`. + +An unavailable target is rejected before selection and changes no preset. A selection the user +declines raises `RuntimeError` and creates no transaction; decisions already accepted in an earlier +dialog are not rolled back. No GUI or preset pointer outlives the call: the transaction holds only +copied category/name/slot values. + +`set()` stages a serialized value without mutating the preset, and `commit()` applies the batch +through `Tab::apply_preset_config_values` on the UI thread. Both are synchronous and, per their +bindings, valid only on the background Script worker. + +### Cancellation + +`ScriptAsyncRuntime::cancel_plugin(plugin_key)` sets `cancel_requested` on every active run for the +plugin and, when a loop is live (`has_loop`), cancels the task with +`loop.call_soon_threadsafe(task.cancel)` while holding the GIL. A synchronous `def execute` +invocation has no loop, so only the flag is set (checked before the run starts). + +A task cancellation cannot interrupt a blocking `begin_update()` native call: the worker is inside +that call, so the loop does not run the scheduled `task.cancel()` until the selection settles and the +call returns. The transaction is therefore delivered, and any accepted UI selection stands; the +cancellation is observed at the coroutine's next suspension point. A user-declined selection is an +ordinary `RuntimeError`, not `asyncio.CancelledError`. + +A plugin's own `asyncio.CancelledError` is treated as a cancellation only when `cancel_requested` was +set; otherwise it stays a genuine error (see `run_invocation`), so a plugin that cancels its own task +does not masquerade as an unload cancellation. + +### Unload and shutdown drain + +Unloading or shutting down must guarantee that no plugin Python code runs after its module is +unloaded, and that a blocking UI selection cannot mutate presets after teardown. + +- `PluginManager::cancel_and_wait_for_capabilities` calls `on_cancelled()` first (so the plugin can + observe state while the run is intact), then `ScriptAsyncRuntime::cancel_plugin`, then drains. + The drain is **unbounded while a Script invocation worker is outstanding** — its loop-exit + condition is `all_released && !invocation_active`. `has_active_run()` distinguishes a run that was + cancelled before it started from one whose worker is still live, and a worker blocked in + `begin_update()` keeps the run active until its UI callback returns. On the GUI thread the drain + pumps `wxYield()` so a modal selection can settle instead of being starved by the blocking wait. + Only the non-Script path keeps the historical bounded 2-second grace: when no invocation is active, + the drain stops waiting for capability references at the grace deadline and logs any remaining + ones. +- `PluginManager::shutdown` detaches the libslic3r hooks (`plugin_hooks::uninstall`), stops new + loads, waits for in-flight loads, unloads every plugin (draining the async runs above), then calls + `ScriptAsyncRuntime::instance().shutdown()`, which refuses new runs and waits without a deadline + for every invocation worker to finish — nothing is torn down by force. `ScriptAsyncRuntime::reset()` + re-arms the runtime so a later `initialize()` in the same process can start runs again. + +Cancellation triggered by unload or shutdown is a separate, expected completion, not a plugin +failure. `run_invocation` marks a run whose `cancel_requested` was set as `completion.cancelled` and +clears any error, whatever the coroutine body did. `launch_script_capability` records a plugin error +only when `!completion.cancelled && !completion.error.empty()`; `run_script_capability` reports an +empty error for a cancelled completion; and the two GUI launchers treat `cancelled` as neither error +nor success (the speed dial stays silent, the Plugins dialog updates no status). A plugin's own +`CancelledError` is not counted as this expected termination unless `cancel_requested` is set, so a +self-cancelled plugin still records its failure. + +## Supported and unsupported capabilities + +| Capability | Async support | Reason | +| --- | --- | --- | +| Script | `def execute` and `async def execute` both run on the per-invocation worker | The runtime owns the worker and, for a coroutine, a per-invocation loop; nothing about a Script invocation borrows C++ state. | +| SlicingPipeline | Synchronous only | `execute(ctx)` borrows `Print`/`PrintObject` for the callback's duration, and the UI thread can be blocked on the slicing worker. `PluginHooks.cpp` rejects an async override: `cap->execute()` casts its Python result to `ExecutionResult`, and a coroutine object cannot be cast, so it surfaces as a `SlicingError` rather than being scheduled. | +| PrinterConnection, Pages, Analysis, Importer, Exporter, Visualization, ResourceTexture | Unchanged | Not part of this bridge; they keep their existing synchronous contract. | + +## Deadlock constraints + +- **Never block the UI thread on plugin work.** Every Script launch path goes through + `launch_script_capability`; the speed-dial `ActionRegistry` action and the Plugins dialog launcher + return immediately and report the outcome later (see Examples). +- **Never call `orca.host.ui.*` from a slicing hook.** The slicing worker runs while the UI thread + can be parked on it. +- **Marshal host UI work from the Script worker only.** `PluginHostUi::run_on_ui_thread` blocks the + calling worker while the UI thread runs the callback; calling it from the UI thread itself would + deadlock the marshalling path. +- **No pointer crosses a call boundary.** `begin_update()` returns copied category/name/slot values; + the `SlicingPipelineContext` graph is valid only within one synchronous `execute(ctx)`. + +## File and symbol map + +Script execution runtime: + +- `src/slic3r/plugin/PluginManager.hpp` / `.cpp` — `ScriptAsyncRuntime` (`instance`, `start`, + `cancel_plugin`, `has_active_run`, `shutdown`, `reset`, `current_loop`), `ScriptCompletion`, + `ScriptCompletionFn`, `ScriptLaunchResult`, `launch_script_capability`, `run_script_capability`. +- `src/slic3r/plugin/PyPluginTrampoline.hpp` — `invoke_script_execute`, `ScriptExecuteInvocation`, + `py_is_coroutine`. +- `src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.hpp` / `ScriptPluginCapabilityTrampoline.hpp` + — `ScriptPluginCapability::execute`, `PyScriptPluginCapabilityTrampoline`. + +Lifetime and GIL primitives: + +- `src/slic3r/plugin/PythonInterpreter.hpp` — `PythonInterpreter`, `PythonRuntimeLease`, + `PythonGILState`. +- `src/slic3r/plugin/PythonPluginInterface.hpp` — `PluginCapabilityInterface`, `RefCounter`, + `increment`/`decrement`/`ref_count`. +- `src/slic3r/plugin/PluginAuditManager.hpp` / `.cpp` — `ScopedPluginAuditContext`, + `request_filesystem_read_permissions`, `request_permission` (fail-closed off the main thread). + +UI marshalling: + +- `src/slic3r/plugin/host/PluginHostUi.hpp` / `.cpp` — `PluginHostUi::run_on_ui_thread`, the + file-local `run_on_ui_blocking`, and `close_windows_for_plugin`. +- `GUI::wxGetApp().CallAfter` — the post-to-UI-thread primitive. + +Preset targets: + +- `src/slic3r/plugin/host/PluginHostPresets.cpp` — `PresetEditor`, `PresetTransaction`, + `bind_preset_target`, `bind_filament_target`, `begin_preset_update`, `begin_filament_update`, + `SelectionCancelled`, `resolve_combo_preset`/`resolve_preset_in_combo`. +- `src/slic3r/GUI/Tab.hpp` / `.cpp` — `Tab::select_preset`, `Tab::apply_preset_config_values`, + `Tab::commit_preset_config_value`. + +Launch paths: + +- `src/slic3r/GUI/ActionRegistry.cpp` — `PluginScriptAction::run`, `notify_script_outcome`. +- `src/slic3r/GUI/PluginsDialog.cpp` — `PluginsDialog::run_script_plugin_capability`. + +Slicing (synchronous only): + +- `src/slic3r/plugin/PluginHooks.cpp` — `install_slicing_pipeline_hook`. +- `src/slic3r/plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp` — + `SlicingPipelineContext`, `execute`. + +Unload/shutdown: + +- `src/slic3r/plugin/PluginManager.cpp` — `unload_plugin`, `unload_all_plugins`, + `cancel_and_wait_for_capabilities`, `shutdown`. + +## Examples + +An `async def execute` that updates a preset. `execute` runs on the background Script worker with its +own asyncio loop; `begin_update()` blocks that worker until any selection / unsaved-edit dialog is +answered, without blocking the UI thread; `set()`/`commit()` then run synchronously on the same +worker. This is the shape used by `sandboxes/orca_preset_transaction_demo.py`: + +```python +import asyncio + +import orca + + +class AutoTune(orca.script.ScriptPluginCapabilityBase): + def get_name(self): + return "Auto tune" + + async def execute(self): + # begin_update() blocks this worker until the user answers any + # selection / unsaved-edit dialog. The UI thread stays responsive. + tx = orca.host.preset.process.begin_update(preset_name="0.20mm Standard") + tx.set("layer_height", "0.2") + tx.commit() + return orca.ExecutionResult.success("process preset updated") +``` + +The window-driven demo shows the same pattern where the plugin's own UI must hand work to the worker: +`on_message` fires on the UI thread and only enqueues onto the worker loop with +`loop.call_soon_threadsafe`; `execute` consumes that queue and calls `begin_update()` per command. + +Sequence for one `begin_update(...)`: + +```text +Script worker (owned, per invocation) UI thread + loop.run_until_complete(task) + begin_update() ───────────────────────► CallAfter(run_on_ui_blocking) + (blocked; not suspended) bind_*_target → + Tab::select_preset() … dialog + settles + promise set; worker resumes with PresetTransaction + set(); commit() (UI thread for the batch) + coroutine resumes at its next await + execute() returns ExecutionResult +``` + +A plain `def execute` needs no loop and runs to completion on the same worker; both kinds are +launched with `launch_script_capability`, so the caller (UI thread) never blocks. A launch failure is +reported inline; a started run reports its outcome through the completion callback — the speed dial +shows "started" and pushes a completion notification, and the Plugins dialog updates its status when +`finish` runs. diff --git a/localization/i18n/OrcaSlicer.pot b/localization/i18n/OrcaSlicer.pot index aa12e329b2..a98d6c4a6c 100644 --- a/localization/i18n/OrcaSlicer.pot +++ b/localization/i18n/OrcaSlicer.pot @@ -5320,6 +5320,9 @@ msgstr "" msgid "This parameter expects a valid template." msgstr "" +msgid "Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |." +msgstr "" + msgid "Invalid pattern. Use N, N#K, or a comma-separated list with optional #K per entry. Examples: 5, 5#2, 1,7,9, 5,9#2,18." msgstr "" @@ -6518,6 +6521,12 @@ msgstr "" msgid "Show object labels in 3D scene." msgstr "" +msgid "Show all collision volumes" +msgstr "" + +msgid "Show the full height of every configured collision volume, including on an empty bed." +msgstr "" + msgid "Show &Overhang" msgstr "" @@ -11049,6 +11058,12 @@ msgstr "" msgid "Click to reset all settings to the last saved preset." msgstr "" +msgid "This definition contains collision-volume syntax. Add it to the toolhead collision volumes for G-code checking and travel avoidance? The existing excluded bed area will be preserved." +msgstr "" + +msgid "Add collision volumes" +msgstr "" + msgid "Prime tower is required for nozzle changing. There may be flaws on the model without prime tower. Are you sure you want to disable prime tower?" msgstr "" @@ -12708,6 +12723,17 @@ msgid "" "Is the disk full?" msgstr "" +#, possible-boost-format +msgid "A G-code move intersects a collision volume for extruder %1%. This may cause a printer collision." +msgstr "" + +msgid "A G-code move intersects a collision volume. This may cause a printer collision." +msgstr "" + +#, possible-boost-format +msgid "The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height." +msgstr "" + #. TRN %1% is the temporary file path, %2% the output file path, %3% the system error message. #, possible-boost-format msgid "" @@ -12974,6 +13000,14 @@ msgstr "" msgid "%1% is too close to exclusion area. There may be collisions when printing." msgstr "" +#, possible-boost-format +msgid "%1% intersects collision volumes for every available extruder." +msgstr "" + +#, possible-boost-format +msgid "%1% intersects a collision volume for extruder %2%." +msgstr "" + #, possible-boost-format msgid "%1% is too close to others, and collisions may be caused." msgstr "" @@ -13303,7 +13337,34 @@ msgstr "" msgid "Excluded bed area" msgstr "" -msgid "Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. The area is expressed as polygon by points in following format: \"XxY, XxY, ...\"" +msgid "Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. The area is expressed as a polygon in the format \"XxY, XxY, ...\". It constrains material and model placement, but allows machine travel. Configure toolhead collision volumes separately for G-code checking and travel avoidance." +msgstr "" + +msgid "Toolhead collision volumes" +msgstr "" + +msgid "Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. Separate multiple volumes with \"|\". These volumes are additional to the excluded bed area. Automatic arrangement conservatively uses the bounding box of a non-convex volume." +msgstr "" + +msgid "Collision volume behavior" +msgstr "" + +msgid "Choose whether all nozzles use the same collision volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, select each extruder on the Extruder page to configure its volumes." +msgstr "" + +msgid "Shared" +msgstr "" + +msgid "Toolhead-relative (nozzle offsets)" +msgstr "" + +msgid "Individual per extruder" +msgstr "" + +msgid "Extruder collision volumes" +msgstr "" + +msgid "Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared collision volumes. Leave empty for no collision volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume." msgstr "" msgid "Bed custom texture" @@ -18216,6 +18277,15 @@ msgstr "" msgid "invalid value " msgstr "" +msgid "Invalid collision volume definition." +msgstr "" + +msgid "A nozzle offset is required for every extruder when toolhead-relative collision volumes are enabled." +msgstr "" + +msgid "Invalid per-extruder collision volume definition." +msgstr "" + msgid "Invalid value when spiral vase mode is enabled: " msgstr "" diff --git a/sandboxes/orca_preset_transaction_demo.py b/sandboxes/orca_preset_transaction_demo.py new file mode 100644 index 0000000000..5cdfd80197 --- /dev/null +++ b/sandboxes/orca_preset_transaction_demo.py @@ -0,0 +1,99 @@ +# /// script +# requires-python = ">=3.12" +# +# [tool.orcaslicer.plugin] +# id = "preset-transaction-demo" +# name = "Preset Transaction Demo" +# description = "Stages several settings on one preset with begin_update()/set()/commit() (demo)." +# author = "OrcaSlicer contributors" +# version = "0.2.0" +# type = "script" +# /// +"""Preset transaction demo: change several settings with one commit. + +Enable the plugin, then run "Preset Transaction Demo" from the Plugins dialog. +Edit CATEGORY, PRESET_NAME, FILAMENT_SLOT and UPDATES below to try other presets +and settings. + +``begin_update()`` resolves the target through Orca's normal preset-selection +flow, so it may open Orca's usual "unsaved changes" dialog. The call is +synchronous: the background Script worker waits until the user answers, while +the UI thread stays responsive. ``set()`` only stages values; ``commit()`` +validates and applies the whole batch. The edited preset stays unsaved (dirty) +until the user saves it through the normal preset workflow; nothing here writes +to disk. + +Values are Orca's serialized config strings: numbers plain, percentages with +"%", booleans "1"/"0", choices by their internal key, lists ";"-separated. +""" + +import orca + +# --------------------------------------------------------------------------- +# Edit these. CATEGORY and UPDATES belong together: each presets category only +# accepts its own setting keys. +# --------------------------------------------------------------------------- + +# Preset category: "process", "printer", or "filament". +CATEGORY = "process" + +# Target preset name for process/printer. "" keeps the currently active preset. +# For filament this optionally selects and assigns the preset for FILAMENT_SLOT; +# "" keeps the preset the slot already has. +PRESET_NAME = "" + +# 1-based filament slot. Only used when CATEGORY is "filament". +FILAMENT_SLOT = 1 + +# Settings staged in order, then committed together. +UPDATES = ( + ("layer_height", "0.25"), + ("wall_loops", "3"), +) + + +def _begin_update(): + """Bind CATEGORY's target and return a transaction to stage changes on.""" + if CATEGORY not in ("process", "printer", "filament"): + raise ValueError('CATEGORY must be "process", "printer", or "filament"') + if CATEGORY == "filament": + # Filament updates are addressed by their 1-based slot number. + return orca.host.preset.filament.begin_update(FILAMENT_SLOT, PRESET_NAME) + return getattr(orca.host.preset, CATEGORY).begin_update(PRESET_NAME) + + +class PresetTransactionDemo(orca.script.ScriptPluginCapabilityBase): + def get_name(self): + return "Preset transaction demo" + + def execute(self): + # A plain def runs on the background Script worker, so begin_update() may + # block here through Orca's selection / unsaved-edit prompts. + try: + transaction = _begin_update() + for key, value in UPDATES: + transaction.set(key, value) + result = transaction.commit() + except Exception as error: + return orca.ExecutionResult.failure( + orca.PluginResult.RecoverableError, + "Preset transaction demo failed: %s" % error, + ) + + return orca.ExecutionResult.success( + 'Committed %d setting(s) to the %s preset "%s"; %s.' + % ( + len(result.keys), + result.category, + result.target_name, + "it stays unsaved until you save it" + if result.dirty + else "it already matches its saved state", + ) + ) + + +@orca.plugin +class PresetTransactionDemoPackage(orca.base): + def register_capabilities(self): + orca.register_capability(PresetTransactionDemo) diff --git a/sandboxes/orca_preset_update_demo.py b/sandboxes/orca_preset_update_demo.py new file mode 100644 index 0000000000..44c9923ec7 --- /dev/null +++ b/sandboxes/orca_preset_update_demo.py @@ -0,0 +1,188 @@ +# /// script +# requires-python = ">=3.12" +# +# [tool.orcaslicer.plugin] +# id = "preset-update-demo" +# name = "Preset Update Demo" +# description = "Browse and edit settings in process, printer, and filament presets." +# author = "OrcaSlicer contributors" +# version = "0.4.0" +# type = "script" +# /// +"""Interactive preset editor. Snapshots are read on the UI thread; edits run on execute's worker.""" + +import queue +import orca + + +PAGE = r''' +
◈

Preset editor

+
+
Selected setting

Choose a setting

Current value
—
Choose a category, preset and filament slot. Edit any listed key, then apply. Orca may ask to switch presets or resolve unsaved changes. Values stay unsaved until saved in Orca.
Loading presets…
+''' + + +class PresetUpdateDemo(orca.script.ScriptPluginCapabilityBase): + window = None + _commands = None + _cancelled = False + + def get_name(self): + return "Preset editor demo" + + def execute(self): + if self.window is not None and self.window.is_open(): + return orca.ExecutionResult.success("Preset editor is already open.") + # The queue exists before the window so on_cancelled() can always unblock this worker, even + # when a forced unload destroys the window without firing on_close. + commands = queue.Queue() + self._commands = commands + try: + if self._cancelled: + return orca.ExecutionResult.success("Preset editor closed.") + self.window = orca.host.ui.create_window( + title="Preset editor", html=PAGE, width=900, height=620, + on_message=self._on_message, + on_close=self._on_close, + ) + while True: + message = commands.get() + if self._cancelled or message.get("command") == "close": + return orca.ExecutionResult.success("Preset editor closed.") + try: + notice = {"command": "refresh", "message": self._apply(message)} + except Exception as error: + notice = {"command": "refresh", "error": str(error)} + if self.window is not None and self.window.is_open(): + self.window.post(notice) + except Exception as error: + return orca.ExecutionResult.failure(orca.PluginResult.RecoverableError, + "Preset editor failed: %s" % error) + finally: + if self._commands is commands: + self._commands = None + self.window = None + + # Both UI callbacks run on the wx main thread with the GIL held. + def _on_message(self, message): + message = dict(message) if isinstance(message, dict) else {} + if message.get("command") == "apply": + self._enqueue(message) + return + try: + state = self._snapshot(message) + except Exception as error: + state = {"command": "state", "kind": message.get("kind", "process"), + "slot": message.get("slot", 1), "rows": [], "presets": [], "slots": [], + "preset_name": "", "dirty": False, "error": str(error)} + window = self.window + if window is not None and window.is_open(): + window.post(state) + + def _on_close(self): + self._enqueue({"command": "close"}) + + def on_cancelled(self): + # Called before the unload drain. Enqueueing a close lets a worker parked in get() exit; a + # callback that arrives after the worker already left sees no queue and is harmless. + self._cancelled = True + self._enqueue({"command": "close"}) + + def _enqueue(self, message): + commands = self._commands + if commands is not None: + commands.put(message) + + def _apply(self, message): + kind = message.get("kind", "process") + if kind not in ("process", "printer", "filament"): + raise ValueError("Unknown preset category") + name = message.get("preset") or "" + if not isinstance(name, str): + raise ValueError("Preset name must be a string") + key, value = message.get("key"), message.get("value") + if not isinstance(key, str) or not key or not isinstance(value, str): + raise ValueError("Setting key and serialized value required") + editor = getattr(orca.host.preset, kind) + if kind == "filament": + slot = int(message.get("slot", 1)) + if slot < 1: + raise ValueError("Filament slot numbers are 1-based") + transaction = editor.begin_update(slot, name) + else: + transaction = editor.begin_update(name) + transaction.set(key, value) + result = transaction.commit() + status = "Set %s on %s. Changes remain unsaved." % (key, result.target_name) + if result.selection_changed: + status += " Orca switched the active preset." + if kind == "filament" and len(result.shared_slots) > 1: + status += " Shared by filament slots: %s." % ", ".join(str(s) for s in result.shared_slots) + return status + + # Read-only snapshot. Runs on the UI thread so no live Preset or PresetBundle object is read + # from the Script worker, and never calls begin_update() or another blocking preset operation. + def _snapshot(self, message): + kind = message.get("kind", "process") + if kind not in ("process", "printer", "filament"): + raise ValueError("Unknown preset category") + try: + slot = int(message.get("slot", 1)) + except (TypeError, ValueError): + slot = 1 + requested = message.get("preset") or "" + if not isinstance(requested, str): + requested = "" + bundle = orca.host.preset_bundle() + slots = [] + if kind == "filament": + assigned_names = list(bundle.current_filament_preset_names()) + presets = list(bundle.current_filament_presets()) + slots = [{"slot": index + 1, + "name": presets[index].name if presets[index] is not None + else (assigned_names[index] or None)} + for index in range(len(presets))] + if not 1 <= slot <= len(presets): + slot = 1 + preset = bundle.filaments.find_preset(requested) if requested else None + if preset is None and presets: + preset = presets[slot - 1] + available = list(bundle.filaments.preset_names()) + else: + collection = bundle.prints if kind == "process" else bundle.printers + available = list(collection.preset_names()) + preset = collection.find_preset(requested) if requested else None + if preset is None: + preset = (bundle.current_process_preset() if kind == "process" + else bundle.current_printer_preset()) + rows = [] + if preset is not None: + for key in sorted(preset.config_keys()): + value = preset.config_value(key) + rows.append({"k": key, "v": "" if value is None else str(value)}) + return {"command": "state", "kind": kind, "slot": slot, "slots": slots, + "presets": available, "preset_name": preset.name if preset is not None else "", + "dirty": bool(preset.is_dirty) if preset is not None else False, "rows": rows} + + +@orca.plugin +class PresetUpdateDemoPackage(orca.base): + def register_capabilities(self): + orca.register_capability(PresetUpdateDemo) diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index d125699932..67ee7c8ec4 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -104,6 +104,7 @@ #include "libslic3r/ModelArrange.hpp" #include "libslic3r/Platform.hpp" #include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" #include "libslic3r/SLAPrint.hpp" #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/Format/AMF.hpp" @@ -183,6 +184,12 @@ using namespace Slic3r; #define MAX_CLONEABLE_SIZE 512 +static Pointfs legacy_bed_exclude_area_points(const DynamicPrintConfig &config) +{ + const ConfigOptionPoints *option = config.option("bed_exclude_area"); + return option != nullptr ? option->values : Pointfs{}; +} + std::map cli_errors = { {CLI_SUCCESS, "Success."}, {CLI_ENVIRONMENT_ERROR, "Failed setting up server environment."}, @@ -1842,7 +1849,7 @@ int CLI::run(int argc, char **argv) //use Pointfs insteadof Points old_printable_area = config.option("printable_area", true)->values; - old_exclude_area = config.option("bed_exclude_area", true)->values; + old_exclude_area = legacy_bed_exclude_area_points(config); if (old_printable_area.size() >= 4) { BoundingBoxf old_printable_bbox(old_printable_area); old_printable_width = static_cast(old_printable_bbox.size().x()); @@ -4262,7 +4269,7 @@ int CLI::run(int argc, char **argv) Slic3r::GUI::PartPlateList partplate_list(NULL, m_models.data(), printer_technology); //use Pointfs insteadof Points Pointfs current_printable_area = m_print_config.opt("printable_area")->values; - Pointfs current_exclude_area = m_print_config.opt("bed_exclude_area")->values; + Pointfs current_exclude_area = legacy_bed_exclude_area_points(m_print_config); std::vector current_extruder_areas; //update part plate's size double print_height = m_print_config.opt_float("printable_height"); @@ -4672,7 +4679,7 @@ int CLI::run(int argc, char **argv) printer_plate.printer_name = config_name; temp_printable_area = config.option("printable_area", true)->values; - temp_exclude_area = config.option("bed_exclude_area", true)->values; + temp_exclude_area = legacy_bed_exclude_area_points(config); temp_wrapping_area = config.option("wrapping_exclude_area", true)->values; temp_extruder_areas = config.option("extruder_printable_area", true)->values; temp_extruder_print_heights = config.option("extruder_printable_height", true)->values; @@ -5395,7 +5402,7 @@ int CLI::run(int argc, char **argv) } // add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect, i + 1); + partplate_list.preprocess_exclude_areas(unselected, m_print_config, enable_wrapping_detect, i + 1); if (avoid_extrusion_cali_region) partplate_list.preprocess_nonprefered_areas(unselected, i + 1); @@ -5427,7 +5434,8 @@ int CLI::run(int argc, char **argv) beds = get_shrink_bedpts(&m_print_config, arrange_cfg); - partplate_list.preprocess_exclude_areas(arrange_cfg.excluded_regions, enable_wrapping_detect, 1, scale_(1)); + partplate_list.preprocess_exclude_areas( + arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); @@ -5637,7 +5645,7 @@ int CLI::run(int argc, char **argv) } //add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect); + partplate_list.preprocess_exclude_areas(unselected, m_print_config, enable_wrapping_detect); // Filament ids given on the command line size the tower for STL input. A project // records its filament use per plate, so count there and keep its tower positions. @@ -5868,7 +5876,8 @@ int CLI::run(int argc, char **argv) } // add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect, plate_to_slice); + partplate_list.preprocess_exclude_areas( + unselected, m_print_config, enable_wrapping_detect, plate_to_slice); } @@ -5900,7 +5909,8 @@ int CLI::run(int argc, char **argv) beds=get_shrink_bedpts(&m_print_config, arrange_cfg); - partplate_list.preprocess_exclude_areas(arrange_cfg.excluded_regions, enable_wrapping_detect, 1, scale_(1)); + partplate_list.preprocess_exclude_areas( + arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 98efc032b8..0d62d6c553 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -410,6 +410,8 @@ void AppConfig::set_defaults() if (get("show_labels").empty()) set_bool("show_labels", false); + if (get("show_collision_volumes").empty()) + set_bool("show_collision_volumes", false); if (get("show_overhang").empty()) set_bool("show_overhang", false); diff --git a/src/libslic3r/Arrange.cpp b/src/libslic3r/Arrange.cpp index 50b20bacd1..997ae00a56 100644 --- a/src/libslic3r/Arrange.cpp +++ b/src/libslic3r/Arrange.cpp @@ -105,6 +105,46 @@ using ItemGroup = std::vector>; const double BIG_ITEM_TRESHOLD = 0.02; #define VITRIFY_TEMP_DIFF_THRSH 15 // bed temp can be higher than vitrify temp, but not higher than this thresh +static bool z_ranges_overlap(double first_min, double first_max, double second_min, double second_max) +{ + if (first_min > first_max) + std::swap(first_min, first_max); + if (second_min > second_max) + std::swap(second_min, second_max); + + // Touching a volume is treated as a collision. Arrangement may leave some + // usable space empty, but it must not create a marginally unsafe placement. + return first_max >= second_min - EPSILON && second_max >= first_min - EPSILON; +} + +template +static bool bed_exclusion_applies_impl(const T &item, const T &fixed_item) +{ + if (!fixed_item.is_bed_exclusion) + return false; + if (item.has_z_range && fixed_item.has_z_range && + !z_ranges_overlap(item.z_min, item.z_max, fixed_item.z_min, fixed_item.z_max)) + return false; + + // Shared volumes and unresolved object mappings apply conservatively to + // every nozzle. Otherwise only the owning physical nozzle participates. + return fixed_item.bed_exclusion_extruder_id < 0 || item.bed_exclusion_extruder_ids.empty() || + std::find(item.bed_exclusion_extruder_ids.begin(), item.bed_exclusion_extruder_ids.end(), + fixed_item.bed_exclusion_extruder_id) != item.bed_exclusion_extruder_ids.end(); +} + +bool has_bed_exclusion_regions(const ArrangePolygons &polygons) +{ + return std::any_of(polygons.begin(), polygons.end(), [](const ArrangePolygon &polygon) { + return polygon.is_bed_exclusion; + }); +} + +bool bed_exclusion_applies(const ArrangePolygon &item, const ArrangePolygon &fixed_item) +{ + return bed_exclusion_applies_impl(item, fixed_item); +} + void update_arrange_params(ArrangeParams& params, const DynamicPrintConfig* print_cfg, const ArrangePolygons& selected) { double skirt_distance = get_real_skirt_dist(*print_cfg); @@ -122,8 +162,8 @@ void update_arrange_params(ArrangeParams& params, const DynamicPrintConfig* prin void update_selected_items_inflation(ArrangePolygons& selected, const DynamicPrintConfig* print_cfg, ArrangeParams& params) { // do not inflate brim_width. Objects are allowed to have overlapped brim. - Points bedpts = get_shrink_bedpts(print_cfg, params); - BoundingBox bedbb = Polygon(bedpts).bounding_box(); + // A brim reaching the printable area's edge is fine, so measure against the full bed. + BoundingBox bedbb = Polygon(get_bed_shape(*print_cfg)).bounding_box(); // set obj distance for auto seq_print if (params.is_seq_print) { bool all_objects_are_short = std::all_of(selected.begin(), selected.end(), [&](ArrangePolygon& ap) { return ap.height < params.nozzle_height; }); @@ -144,14 +184,30 @@ void update_selected_items_inflation(ArrangePolygons& selected, const DynamicPri // 3. otherwise, use each object's own brim width ap.inflation = params.min_obj_distance != 0 ? params.min_obj_distance / 2 : plate_has_tree_support ? scaled(brim_max / 2) : scaled(ap.brim_width); - BoundingBox apbb = ap.poly.contour.bounding_box(); - auto diffx = bedbb.size().x() - apbb.size().x() - 5; - auto diffy = bedbb.size().y() - apbb.size().y() - 5; - if (diffx > 0 && diffy > 0) { - auto min_diff = std::min(diffx, diffy); - ap.inflation = std::min(min_diff / 2, ap.inflation); - } + if (params.min_obj_distance != 0) + return; // an explicit object distance is the user's call, not ours to shrink + // An item cannot be larger than the printable area, inflation included. Inflating + // an almost bed filling item would leave it too big to ever be placed. + BoundingBox apbb = ap.poly.contour.bounding_box(); + auto diffx = bedbb.size().x() - apbb.size().x(); + auto diffy = bedbb.size().y() - apbb.size().y(); + ap.inflation = std::max(0, std::min({ ap.inflation, diffx / 2, diffy / 2 })); }); + + // Give the bed margin, which the arrange bed keeps from the printable area, back + // where the largest item needs it. The skirt keeps its room: pushing a skirt off + // the bed is worse than saying the item does not fit. + if (!selected.empty()) { + coord_t max_width = 0, max_height = 0; + for (const ArrangePolygon &ap : selected) { + BoundingBox apbb = ap.poly.contour.bounding_box(); + max_width = std::max(max_width, apbb.size().x() + 2 * ap.inflation); + max_height = std::max(max_height, apbb.size().y() + 2 * ap.inflation); + } + auto margin = [](coord_t bed, coord_t item) { return std::max(0., unscale(bed - item) / 2.); }; + params.bed_shrink_x = std::min(params.bed_shrink_x, std::max(params.brim_skirt_distance, margin(bedbb.size().x(), max_width))); + params.bed_shrink_y = std::min(params.bed_shrink_y, std::max(params.brim_skirt_distance, margin(bedbb.size().y(), max_height))); + } } void update_unselected_items_inflation(ArrangePolygons& unselected, const DynamicPrintConfig* print_cfg, const ArrangeParams& params) @@ -334,6 +390,14 @@ void fill_config(PConf& pcfg, const ArrangeParams ¶ms) { // Allow parallel execution. pcfg.parallel = params.parallel; + pcfg.should_check_collision = [](const Item &candidate, const Item &packed) { + if (packed.is_bed_exclusion) + return bed_exclusion_applies_impl(candidate, packed); + if (candidate.is_bed_exclusion) + return bed_exclusion_applies_impl(packed, candidate); + return true; + }; + // BBS: excluded regions in BBS bed for (auto& poly : params.excluded_regions) process_arrangeable(poly, pcfg.m_excluded_regions); @@ -1175,6 +1239,12 @@ static void process_arrangeable(const ArrangePolygon &arrpoly, item.itemId(arrpoly.itemid); item.extrude_ids = arrpoly.extrude_ids; item.height = arrpoly.height; + item.z_min = arrpoly.z_min; + item.z_max = arrpoly.z_max; + item.has_z_range = arrpoly.has_z_range; + item.is_bed_exclusion = arrpoly.is_bed_exclusion; + item.bed_exclusion_extruder_ids = arrpoly.bed_exclusion_extruder_ids; + item.bed_exclusion_extruder_id = arrpoly.bed_exclusion_extruder_id; item.name = arrpoly.name; //BBS: add virtual object logic item.is_virt_object = arrpoly.is_virt_object; diff --git a/src/libslic3r/Arrange.hpp b/src/libslic3r/Arrange.hpp index b63b8c938b..20f5e7db9a 100644 --- a/src/libslic3r/Arrange.hpp +++ b/src/libslic3r/Arrange.hpp @@ -81,6 +81,17 @@ struct ArrangePolygon { int itemid{ 0 }; // item id in the vector, used for accessing all possible params like extrude_id int is_applied{ 0 }; // transform has been applied double height{ 0 }; // item height + double z_min{ 0 }; // lowest occupied Z coordinate + double z_max{ 0 }; // highest occupied Z coordinate + bool has_z_range{ false }; // whether z_min / z_max are authoritative + bool is_bed_exclusion{ false }; // conditional bed-exclusion obstacle + // Physical nozzle ids used only for per-nozzle exclusion checks. These are + // deliberately separate from extrude_ids, which contains logical filament + // ids used by Orca's normal material-aware arrangement. Empty is treated + // conservatively as unresolved and therefore applicable to every nozzle. + std::vector bed_exclusion_extruder_ids{}; + // Zero-based nozzle owning an exclusion obstacle; -1 means shared. + int bed_exclusion_extruder_id{ -1 }; double brim_width{ 0 }; // brim width std::string name; @@ -201,6 +212,9 @@ void update_unselected_items_inflation(ArrangePolygons& unselected, const Dynami void update_selected_items_axis_align(ArrangePolygons& selected, const DynamicPrintConfig* print_cfg, const ArrangeParams& params); +bool has_bed_exclusion_regions(const ArrangePolygons& polygons); +bool bed_exclusion_applies(const ArrangePolygon& item, const ArrangePolygon& fixed_item); + Points get_shrink_bedpts(const DynamicPrintConfig* print_cfg, const ArrangeParams& params); /** diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 23b515647b..1ab8cecbce 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -2,6 +2,7 @@ #include "BrimEarsPoint.hpp" #include "ClipperUtils.hpp" #include "EdgeGrid.hpp" +#include "ExclusionVolumeGeometry.hpp" #include "ExPolygon.hpp" #include "Flow.hpp" #include "Geometry.hpp" @@ -20,11 +21,14 @@ #include "PrintConfig.hpp" #include "MaterialType.hpp" #include "Model.hpp" +#include "Support/SupportCommon.hpp" #include #include #include #include #include +#include +#include #include #include #include @@ -48,6 +52,20 @@ namespace Slic3r { +static coord_t brim_exclusion_clearance(const Flow &flow) +{ + const coord_t width_spacing_delta = std::max(0, flow.scaled_width() - flow.scaled_spacing()); + return (width_spacing_delta + 1) / 2 + coord_t(SCALED_EPSILON); +} + +static bool combine_object_brims(const Print &print) +{ + const bool has_per_object_skirt_or_shield = print.config().skirt_type == stPerObject && + (print.has_skirt() || print.has_infinite_skirt()); + return print.config().combine_brims.value && !has_per_object_skirt_or_shield && + print.config().print_sequence != PrintSequence::ByObject; +} + static void append_and_translate(ExPolygons &dst, const ExPolygons &src, const PrintInstance &instance) { size_t dst_idx = dst.size(); expolygons_append(dst, src); @@ -444,6 +462,17 @@ static ExPolygons outer_inner_brim_area(const Print& print, { unsigned int support_material_extruder = printExtruders.front() + 1; Flow flow = print.brim_flow(); + std::vector> exclusion_regions_by_extruder; + if (has_bed_exclude_volumes(print.config())) { + exclusion_regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); + // The established bed polygon below still clips the bed edge and + // legacy areas. Only explicit volumes use the new Z-aware trimming. + for (std::vector ®ions : exclusion_regions_by_extruder) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } + const double first_layer_top_z = std::max(0.0, print.skirt_first_layer_height()); + const coord_t exclusion_clearance = brim_exclusion_clearance(flow); ExPolygons brim_area; ExPolygons no_brim_area; @@ -638,14 +667,13 @@ static ExPolygons outer_inner_brim_area(const Print& print, } } - int extruder_nums = print.config().nozzle_diameter.values.size(); std::vector extruder_unprintable_area = print.get_extruder_printable_polygons(); + const size_t extruder_count = print.config().nozzle_diameter.size(); // Orca: if per-extruder print area is not specified, use the whole bed as printable area for all extruders - if (extruder_unprintable_area.empty()) { - extruder_unprintable_area.resize(extruder_nums, Polygons{Model::getBedPolygon()}); - } - std::vector filament_map = print.get_filament_maps(); - + if (extruder_unprintable_area.empty()) + extruder_unprintable_area.resize(extruder_count, Polygons{Model::getBedPolygon()}); + const size_t physical_extruder_count = std::max( + extruder_count, extruder_unprintable_area.size()); if (print.has_wipe_tower() && !print.get_fake_wipe_tower().outer_wall.empty()) { ExPolygons expolyFromLines{}; for (auto polyline : print.get_fake_wipe_tower().outer_wall.begin()->second) { @@ -661,22 +689,36 @@ static ExPolygons outer_inner_brim_area(const Print& print, auto iter = std::find_if(objPrintVec.begin(), objPrintVec.end(), [object](const std::pair& item) { return item.first == object->id(); }); + std::vector object_physical_extruders; - if (iter != objPrintVec.end()) { - int extruder_id = filament_map[iter->second - 1] - 1; - auto bedPoly = extruder_unprintable_area[extruder_id]; - auto bedExPoly = diff_ex((offset(bedPoly, scale_(30.), jtRound, SCALED_RESOLUTION)), {bedPoly}); - if (!bedExPoly.empty()) { - extruder_no_brim_area.push_back(bedExPoly.front()); + if (iter != objPrintVec.end() && iter->second > 0) { + object_physical_extruders = bed_exclusion_physical_extruders( + print, { iter->second - 1 }, physical_extruder_count, 0); + for (const size_t extruder_id : object_physical_extruders) { + if (extruder_id >= extruder_unprintable_area.size()) + continue; + const Polygons &bed_poly = extruder_unprintable_area[extruder_id]; + ExPolygons bed_exterior = diff_ex( + offset(bed_poly, scale_(30.), jtRound, SCALED_RESOLUTION), bed_poly); + expolygons_append(extruder_no_brim_area, std::move(bed_exterior)); } //extruder_no_brim_area = offset2_ex(extruder_no_brim_area, scaled_flow_width, -scaled_flow_width); // connect scattered small areas to prevent generating very small brims - } - for (auto& [key, areas] : brimAreaMap) - if (key.object_id == object->id()) - areas = diff_ex(areas, extruder_no_brim_area); - + if (object_physical_extruders.empty()) { + object_physical_extruders.resize(physical_extruder_count); + std::iota(object_physical_extruders.begin(), object_physical_extruders.end(), size_t(0)); + } + const ExPolygons exclusions = active_bed_exclusion_footprints( + exclusion_regions_by_extruder, object_physical_extruders, + 0.0, first_layer_top_z, Point(0, 0), exclusion_clearance); + for (auto& [key, areas] : brimAreaMap) { + if (key.object_id != object->id()) + continue; + areas = diff_ex(areas, extruder_no_brim_area); + if (!exclusions.empty()) + areas = diff_ex(areas, exclusions); + } } brim_area.clear(); diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 4acea143cc..f9866cf09f 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -127,6 +127,8 @@ set(lisbslic3r_sources Emboss.hpp EmbossShape.hpp enum_bitmask.hpp + ExclusionVolumeGeometry.cpp + ExclusionVolumeGeometry.hpp Execution/Execution.hpp Execution/ExecutionSeq.hpp Execution/ExecutionTBB.hpp @@ -257,6 +259,10 @@ set(lisbslic3r_sources GCode/ConflictChecker.hpp GCode/CoolingBuffer.cpp GCode/CoolingBuffer.hpp + GCode/ExclusionVolumePathCheck.cpp + GCode/ExclusionVolumePathCheck.hpp + GCode/ExclusionVolumeTravelAvoidance.cpp + GCode/ExclusionVolumeTravelAvoidance.hpp GCode/TimelapsePosPicker.cpp GCode/TimelapsePosPicker.hpp GCode.cpp diff --git a/src/libslic3r/ClipperUtils.cpp b/src/libslic3r/ClipperUtils.cpp index a3a38ad2cf..bdfd97b01d 100644 --- a/src/libslic3r/ClipperUtils.cpp +++ b/src/libslic3r/ClipperUtils.cpp @@ -748,6 +748,24 @@ Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygon { return _clipper(ctDifference, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } Slic3r::Polygons diff(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) { return _clipper(ctDifference, ClipperUtils::SurfacesProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons diff_expanded(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, float delta) +{ + if (subject.empty()) + return {}; + // Each path simplified on its own, and kept as it is where simplifying would turn a contour into a hole or back. + Polygons coarse; + for (const Polygon &path : clip) { + Polygons simplified = polygons_simplify({ path }, delta / 8.); + if (!simplified.empty() && (area(simplified) > 0.) != path.is_counter_clockwise()) + coarse.emplace_back(path); + else + append(coarse, std::move(simplified)); + } + // The miter limit argument of a round join is its arc tolerance. + if (diff(subject, expand(coarse, 0.7f * delta, jtRound, 0.01 * delta)).empty()) + return {}; + return diff(subject, expand(clip, delta)); +} Slic3r::Polygons intersection(const Slic3r::Polygon &subject, const Slic3r::Polygon &clip, ApplySafetyOffset do_safety_offset) { return _clipper(ctIntersection, ClipperUtils::SinglePathProvider(subject.points), ClipperUtils::SinglePathProvider(clip.points), do_safety_offset); } Slic3r::Polygons intersection_clipped(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) diff --git a/src/libslic3r/ClipperUtils.hpp b/src/libslic3r/ClipperUtils.hpp index 4e09eaaf58..438f753fe4 100644 --- a/src/libslic3r/ClipperUtils.hpp +++ b/src/libslic3r/ClipperUtils.hpp @@ -463,6 +463,12 @@ Slic3r::ExPolygons diff_clipped(const Slic3r::ExPolygons &src, const Slic3r::ExP Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::Polygons diff(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +// The part of subject farther than delta from clip, as diff(subject, expand(clip, delta)). Expanding finely detailed polygons by +// a large delta is slow, so a cheaper, smaller round expansion of the simplified clip, which lies within the full one, is tried +// first: where it covers the subject, so does the full expansion. That holds as long as both expansions grow the regions their +// paths enclose; the offsets' own input decimation can fold a sliver thinner than about 0.01 * delta and break it, so the +// result may then differ from diff with expand. Callers use it where such a difference cannot matter. +Slic3r::Polygons diff_expanded(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, float delta); Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp index 9f70498499..495fac2263 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -37,6 +37,7 @@ #include #include +#include #include // The serialize() members below archive ConfigOption hierarchies through // cereal::base_class, whose registration machinery lives in polymorphic.hpp. @@ -1615,6 +1616,11 @@ public: bool deserialize(const std::string &str, bool append = false) override { + // Extended exclusion-volume syntax belongs to the dedicated string option. + // Rejecting it here also makes --bed-exclude-area fail instead of silently + // turning a volume definition into malformed legacy points. + if (str.find('|') != std::string::npos || str.find(';') != std::string::npos || str.find("..") != std::string::npos) + return false; if (! append) this->values.clear(); std::istringstream is(str); @@ -1635,18 +1641,18 @@ public: } private: - friend class cereal::access; - template void save(Archive& archive) const { - size_t cnt = this->values.size(); - archive(cnt); - archive.saveBinary((const char*)this->values.data(), sizeof(Vec2d) * cnt); - } - template void load(Archive& archive) { - size_t cnt; - archive(cnt); - this->values.assign(cnt, Vec2d()); - archive.loadBinary((char*)this->values.data(), sizeof(Vec2d) * cnt); - } + friend class cereal::access; + template void save(Archive& archive) const { + size_t cnt = this->values.size(); + archive(cnt); + archive.saveBinary((const char*)this->values.data(), sizeof(Vec2d) * cnt); + } + template void load(Archive& archive) { + size_t cnt; + archive(cnt); + this->values.assign(cnt, Vec2d()); + archive.loadBinary((char*)this->values.data(), sizeof(Vec2d) * cnt); + } }; class ConfigOptionPoint3 : public ConfigOptionSingle diff --git a/src/libslic3r/ConnectedBodies.cpp b/src/libslic3r/ConnectedBodies.cpp index 8cfe5a3e43..e9fe96511d 100644 --- a/src/libslic3r/ConnectedBodies.cpp +++ b/src/libslic3r/ConnectedBodies.cpp @@ -89,11 +89,14 @@ std::vector> connected_bodies(const std::vector order(m_boxes.size()); for (size_t i = 0; i < order.size(); ++i) diff --git a/src/libslic3r/ConnectedBodies.hpp b/src/libslic3r/ConnectedBodies.hpp index a420401d28..d6f43a8bb5 100644 --- a/src/libslic3r/ConnectedBodies.hpp +++ b/src/libslic3r/ConnectedBodies.hpp @@ -26,7 +26,9 @@ class IslandLocator { public: // The islands must outlive the locator. Their boxes are widened by the margin, for points reaching past an outline. - IslandLocator(const ExPolygons &islands, coord_t margin); + // A caller that needs only to know that some island holds a point, not which one, need not tell them apart: then the + // box of every island vouches for it unless the call is strict. + IslandLocator(const ExPolygons &islands, coord_t margin, bool tell_apart = true); // Whether the island holds the point, or its box does where no other box reaches unless strict. bool holds(size_t island, const Point &point, bool strict = false) const; // The island holding the point as above, else the nearest one whose box holds it, with the squared distance to it; -1 diff --git a/src/libslic3r/ExclusionVolumeGeometry.cpp b/src/libslic3r/ExclusionVolumeGeometry.cpp new file mode 100644 index 0000000000..cee9f9506f --- /dev/null +++ b/src/libslic3r/ExclusionVolumeGeometry.cpp @@ -0,0 +1,182 @@ +#include "ExclusionVolumeGeometry.hpp" +#include "ExPolygon.hpp" +#include "Point.hpp" +#include "Polygon.hpp" +#include "PrintConfig.hpp" +#include "libslic3r.h" +#include +#include +#include + +#include "BoundingBox.hpp" +#include "ClipperUtils.hpp" +#include "Geometry/ConvexHull.hpp" +#include "Print.hpp" + +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; + +void append_active_footprints( + Polygons &out, + const std::vector ®ions, + const double z_min, + const double z_max, + const Point &translation) +{ + for (const BedExcludeRegion ®ion : regions) { + if (region.polygon.points.size() < 3 || region.z_max < region.z_min || + !bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + continue; + + Polygon footprint = region.polygon; + footprint.translate(translation); + out.emplace_back(std::move(footprint)); + } +} + +ExPolygons union_active_footprints(Polygons footprints, const coord_t clearance) +{ + if (footprints.empty()) + return {}; + + ExPolygons result = union_ex(footprints); + if (clearance > 0) + result = offset_ex(result, float(clearance)); + return result; +} + +} // namespace + +bool bed_exclusion_z_ranges_overlap( + double first_min, + double first_max, + double second_min, + double second_max) +{ + if (first_min > first_max) + std::swap(first_min, first_max); + if (second_min > second_max) + std::swap(second_min, second_max); + return first_max >= second_min - Z_EPSILON_MM && first_min <= second_max + Z_EPSILON_MM; +} + +Polygon bed_exclusion_arrange_polygon(const Polygon &polygon) +{ + if (polygon.points.size() < 3) + return polygon; + + const Polygon convex_hull = Geometry::convex_hull(polygon.points); + const double polygon_area = std::abs(polygon.area()); + const double hull_area = std::abs(convex_hull.area()); + const double tolerance = std::max(1.0, hull_area) * 1e-12; + if (std::abs(hull_area - polygon_area) <= tolerance) + return polygon; + + return get_extents(polygon).polygon(); +} + +ExPolygons active_bed_exclusion_footprints( + const std::vector ®ions, + const double z_min, + const double z_max, + const Point &translation, + const coord_t clearance) +{ + Polygons footprints; + footprints.reserve(regions.size()); + append_active_footprints(footprints, regions, z_min, z_max, translation); + return union_active_footprints(std::move(footprints), clearance); +} + +ExPolygons active_bed_exclusion_footprints( + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + const double z_min, + const double z_max, + const Point &translation, + const coord_t clearance) +{ + Polygons footprints; + std::vector visited(regions_by_extruder.size(), false); + for (const size_t extruder_id : physical_extruders) { + if (extruder_id >= regions_by_extruder.size() || visited[extruder_id]) + continue; + visited[extruder_id] = true; + const std::vector ®ions = regions_by_extruder[extruder_id]; + footprints.reserve(footprints.size() + regions.size()); + append_active_footprints(footprints, regions, z_min, z_max, translation); + } + return union_active_footprints(std::move(footprints), clearance); +} + +std::vector bed_exclusion_physical_extruders( + const Print &print, + const std::vector &filament_ids, + const size_t physical_extruder_count, + const int layer_id) +{ + if (physical_extruder_count == 0) + return {}; + + std::vector result; + const auto grouping = print.get_layered_nozzle_group_result(); + const bool automatic_mapping_resolved = + !is_auto_filament_map_mode(print.get_filament_map_mode()) || !print.is_BBL_printer() || + print.get_nozzle_group_result() != nullptr; + bool unresolved = filament_ids.empty(); + + for (const unsigned int filament_id : filament_ids) { + if (grouping) { + if (const auto nozzle = grouping->get_nozzle_for_filament(int(filament_id), layer_id); + nozzle.has_value() && nozzle->extruder_id >= 0 && + size_t(nozzle->extruder_id) < physical_extruder_count) { + result.emplace_back(size_t(nozzle->extruder_id)); + continue; + } + } + + const int resolved = bed_exclusion_extruder_for_filament( + filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), + automatic_mapping_resolved, physical_extruder_count); + if (resolved >= 0) + result.emplace_back(size_t(resolved)); + else + unresolved = true; + } + + std::sort(result.begin(), result.end()); + result.erase(std::unique(result.begin(), result.end()), result.end()); + if (!unresolved && !result.empty()) + return result; + + result.resize(physical_extruder_count); + std::iota(result.begin(), result.end(), size_t(0)); + return result; +} + +ExPolygons active_bed_exclusion_footprints_for_object( + const PrintObject &object, + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + const double z_min, + const double z_max, + const coord_t clearance) +{ + ExPolygons result; + for (const PrintInstance &instance : object.instances()) { + const Point instance_shift = instance.shift_without_plate_offset(); + const Point shift(-instance_shift.x(), -instance_shift.y()); + expolygons_append(result, active_bed_exclusion_footprints( + regions_by_extruder, physical_extruders, z_min, z_max, shift, clearance)); + } + return result.empty() ? ExPolygons{} : union_ex(result); +} + +} // namespace Slic3r diff --git a/src/libslic3r/ExclusionVolumeGeometry.hpp b/src/libslic3r/ExclusionVolumeGeometry.hpp new file mode 100644 index 0000000000..fc745bb5dd --- /dev/null +++ b/src/libslic3r/ExclusionVolumeGeometry.hpp @@ -0,0 +1,63 @@ +#pragma once + +#include "ExPolygon.hpp" +#include "Polygon.hpp" +#include "libslic3r.h" +#include "Point.hpp" +#include "PrintConfig.hpp" + +#include +#include + +namespace Slic3r { + +class Print; +class PrintObject; + +bool bed_exclusion_z_ranges_overlap(double first_min, double first_max, double second_min, double second_max); + +// libnest2d currently accepts only convex fixed obstacles. Keep convex +// exclusions exact and conservatively use the bounding box for concave ones. +Polygon bed_exclusion_arrange_polygon(const Polygon &polygon); + +// Return the union of exclusion footprints intersecting the requested extrusion +// slab. Regions are already resolved into physical-nozzle/model coordinates by +// PrintConfig; callers only provide the physical nozzles that may emit the +// generated geometry and the translation into the caller's coordinate space. +ExPolygons active_bed_exclusion_footprints( + const std::vector ®ions, + double z_min, + double z_max, + const Point &translation = Point(0, 0), + coord_t clearance = 0); + +ExPolygons active_bed_exclusion_footprints( + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + double z_min, + double z_max, + const Point &translation = Point(0, 0), + coord_t clearance = 0); + +// Resolve logical filaments to every physical extruder which may print them. +// An unresolved automatic mapping deliberately returns every physical +// extruder, keeping generated geometry conservative until tool assignment is +// known. +std::vector bed_exclusion_physical_extruders( + const Print &print, + const std::vector &filament_ids, + size_t physical_extruder_count, + int layer_id = -1); + +// Exclusion areas are stored in bed coordinates while generated support is +// shared in PrintObject coordinates. Return the conservative union transformed +// for every instance of the object. +ExPolygons active_bed_exclusion_footprints_for_object( + const PrintObject &object, + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + double z_min, + double z_max, + coord_t clearance = 0); + +} // namespace Slic3r diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index d1436184e1..610d6c7147 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -1,4 +1,5 @@ #include "ArcFitter.hpp" +#include #include "BoundingBox.hpp" #include "Circle.hpp" #include "Config.hpp" @@ -152,6 +153,53 @@ namespace fs = boost::filesystem; namespace Slic3r { +namespace { + +// Follow XY commands in a generated G-code block. This deliberately handles +// only standard motion/modal commands: an opaque macro that moves the head is +// already outside the position guarantees made by GCodeWriter. +std::optional emitted_xy_after_gcode(const std::string &gcode, const Vec2d &initial_xy) +{ + Vec2d position = initial_xy; + bool absolute = true; + bool coordinate_frame_known = true; + + GCodeReader reader; + reader.parse_buffer(gcode, [&position, &absolute, &coordinate_frame_known](GCodeReader &, const GCodeReader::GCodeLine &line) { + if (line.cmd_is("G90")) { + absolute = true; + return; + } + if (line.cmd_is("G91")) { + absolute = false; + return; + } + + const bool is_motion = line.cmd_is("G0") || line.cmd_is("G1") || line.cmd_is("G2") || line.cmd_is("G3"); + if (is_motion) { + if (line.has_x()) + position.x() = absolute ? line.x() : position.x() + line.x(); + if (line.has_y()) + position.y() = absolute ? line.y() : position.y() + line.y(); + return; + } + + // G92 changes the coordinate system without moving the machine, and + // G28 moves to a firmware-defined position. Do not invent a position + // if either command affects XY. + if (line.cmd_is("G92")) { + coordinate_frame_known = coordinate_frame_known && !line.has_x() && !line.has_y(); + } else if (line.cmd_is("G28")) { + const bool homes_all = !line.has_x() && !line.has_y() && !line.has_z(); + coordinate_frame_known = coordinate_frame_known && !homes_all && !line.has_x() && !line.has_y(); + } + }); + + return coordinate_frame_known ? std::optional(position) : std::nullopt; +} + +} // namespace + //! macro used to mark string used at localization, //! return same string #define L(s) (s) @@ -1056,6 +1104,9 @@ static std::vector get_path_of_change_filament(const Print& print) if (new_filament_id != -1 && new_filament_id != tcr.new_tool) throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect."); + const std::optional position_before_toolchange = + gcodegen.capture_toolchange_position(); + int new_extruder_id = get_extruder_index(*m_print_config, new_filament_id); // Logical nozzle grouping for this print (null on paths that don't populate it). @@ -1437,6 +1488,13 @@ static std::vector get_path_of_change_filament(const Print& print) // We have informed the m_writer about the current extruder_id, we can ignore the generated G-code. } + // The change G-code may move the carriage even when the incoming + // filament uses the same physical nozzle (the common AMS case). + // Synchronize before planning the tower-entry travel so exclusion + // avoidance starts from the emitted position, not the stale one. + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, toolchange_gcode_str); + if (need_travel_after_change_filament_gcode) { // move to start_pos for wiping after toolchange if (!is_used_travel_avoid_perimeter) { @@ -1585,6 +1643,8 @@ static std::vector get_path_of_change_filament(const Print& print) // Let the planner know we are traveling between objects. gcodegen.m_avoid_crossing_perimeters.use_external_mp_once(); + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -1596,6 +1656,9 @@ static std::vector get_path_of_change_filament(const Print& print) if (new_extruder_id != -1 && new_extruder_id != tcr.new_tool) throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect."); + const std::optional position_before_toolchange = + gcodegen.capture_toolchange_position(); + std::string gcode; // Toolchangeresult.gcode assumes the wipe tower corner is at the origin (except for priming lines) @@ -1880,6 +1943,8 @@ static std::vector get_path_of_change_filament(const Print& print) // Let the planner know we are traveling between objects. gcodegen.m_avoid_crossing_perimeters.use_external_mp_once(); + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -2649,9 +2714,11 @@ static void set_mass_locator(GCodeProcessor &processor, const Print &print) model_instances.begin()); } bodies_total += int(count * object->instances().size()); + // Without bodies only the instance matters, which any island box of an instance no other reaches proves. The + // islands of crowded instances are tested strictly anyway. for (const Layer *layer : layers) { o.print_zs.emplace_back(layer->print_z); - o.islands.emplace_back(layer->lslices, scaled(1.)); + o.islands.emplace_back(layer->lslices, scaled(1.), o.bodies_count > 0); } } if (objects.empty()) @@ -2711,12 +2778,13 @@ static void set_mass_locator(GCodeProcessor &processor, const Print &print) return GCodeProcessor::MassLocation{ o.first_instance + int(hit.instance), o.bodies_count == 0 ? -1 : o.first_body + int(hit.instance * o.bodies_count + o.bodies[hit.layer][hit.island]) }; }; - // A point lies on the first layer at or above it, as spiral vase rises through each layer. + // A point lies on the first layer whose print_z is at least its height less the tolerance, as spiral vase rises + // through each layer. Both paths below pick it alike, as lower_bound does. + const double z = point.z() - z_tolerance; // Extrusions mostly follow each other on one island. if (last) { const Object &o = objects[last->object]; - if (point.z() <= o.print_zs[last->layer] + z_tolerance && - (last->layer == 0 || point.z() > o.print_zs[last->layer - 1] + z_tolerance) && + if (!(o.print_zs[last->layer] < z) && (last->layer == 0 || o.print_zs[last->layer - 1] < z) && o.islands[last->layer].holds(last->island, local(last->object, last->instance), o.crowded[last->instance])) return location(*last); } @@ -2725,10 +2793,10 @@ static void set_mass_locator(GCodeProcessor &processor, const Print &print) double distance = std::numeric_limits::max(); for (size_t object = 0; object < objects.size(); ++object) { const Object &o = objects[object]; - const auto z = std::lower_bound(o.print_zs.begin(), o.print_zs.end(), point.z() - z_tolerance); - if (z == o.print_zs.end()) + const auto above = std::lower_bound(o.print_zs.begin(), o.print_zs.end(), z); + if (above == o.print_zs.end()) continue; - const size_t layer = size_t(z - o.print_zs.begin()); + const size_t layer = size_t(above - o.print_zs.begin()); for (size_t instance = 0; instance < o.object->instances().size(); ++instance) { const auto [island, d] = o.islands[layer].find(local(object, instance), o.crowded[instance]); if (island < 0) @@ -2754,6 +2822,8 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu // BBS m_curr_print = print; m_skirt_group_done.clear(); + m_pending_start_gcode_position.reset(); + m_exclusion_volume_travel_avoidance.init(print->config(), print->get_plate_origin()); GCodeWriter::full_gcode_comment = print->config().gcode_comments; CNumericLocalesSetter locales_setter; @@ -2935,6 +3005,23 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu m_processor.result().nozzle_group_result = m_print->get_layered_nozzle_group_result(); m_processor.finalize(true); + if (m_processor.get_result().exclusion_volume_path_conflict) { + const int extruder_id = m_processor.get_result().exclusion_volume_conflict_extruder_id; + std::string warning = extruder_id >= 0 ? + Slic3r::format( + _(L("A G-code move intersects a collision volume for extruder %1%. This may cause a printer collision.")), + std::to_string(extruder_id + 1)) : + _(L("A G-code move intersects a collision volume. This may cause a printer collision.")); + if (m_processor.get_result().exclusion_volume_conflict_used_unknown_z) { + warning += "\n" + Slic3r::format( + _(L("The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height.")), + std::to_string(m_processor.get_result().exclusion_volume_conflict_gcode_id)); + } + print->active_step_add_warning( + PrintStateBase::WarningLevel::CRITICAL, + warning, + PrintStateBase::SlicingExclusionVolumeToolpath); + } // DoExport::update_print_estimated_times_stats(m_processor, print->m_print_statistics); DoExport::update_print_estimated_stats(m_processor, m_writer.extruders(), print->m_print_statistics, print->config()); // Printed-mass safety check. Flushed filament leaves the bed, so subtract it @@ -3017,6 +3104,7 @@ namespace DoExport { processor.initialize_from_context(nozzle_group_result); processor.initialize_result_moves(); processor.apply_config(config); + processor.configure_exclusion_volume_path_check(config); processor.enable_stealth_time_estimator(silent_time_estimator_enabled); } @@ -4446,6 +4534,17 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato } } + // Direct output writes are parsed synchronously. Preserve the startup + // endpoint before the generator establishes its first model-space point, + // so that first travel can be planned from the position the G-code actually + // left the machine at rather than the default last_pos value. + GCodeProcessor::PositionState startup_position = m_processor.get_current_position(); + const Vec2f plate_offset = m_writer.get_xy_offset(); + startup_position.position.x() += plate_offset.x(); + startup_position.position.y() += plate_offset.y(); + m_pending_start_gcode_position = !m_last_pos_defined && startup_position.has_known_xy() ? + std::optional(startup_position) : std::nullopt; + this->m_objsWithBrim.clear(); m_brim_done = false; @@ -5402,7 +5501,9 @@ int GCode::get_highest_bed_temperature(const bool is_first_layer, const Print& p { auto bed_type = m_config.curr_bed_type; int bed_temp = 0; - for (auto fidx : print.get_slice_used_filaments(is_first_layer)) { + // Only the filaments printed on the first layer touch the bed, so a filament that starts higher up, such as a + // support interface, must not raise the bed temperature for the rest of the print. + for (auto fidx : print.get_slice_used_filaments(true)) { bed_temp = std::max(bed_temp, get_bed_temperature(fidx, is_first_layer, bed_type)); } return bed_temp; @@ -5883,8 +5984,13 @@ std::string GCode::generate_object_skirt_group(const Print &print, object_skirt_tools, layer, extruder_id, m_skirt_group_done[group_idx]); } -std::string GCode::generate_object_brim(const Print &print, const PrintObject &object, size_t instance_id, bool first_layer, - const Layer *object_layer) +std::string GCode::generate_object_brim( + const Print &print, + const PrintObject &object, + const size_t instance_id, + const bool first_layer, + const unsigned int extruder_id, + const Layer *object_layer) { // Belt printers lay the brim onto the tilted belt over many layers, so there is // nothing special about the first one. The bands that coincide with an object @@ -5923,8 +6029,17 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o if (!first_layer) return {}; - auto emit_brim = [this](const ExtrusionEntityCollection& brim, const std::vector& instances) { + const bool wait_for_owner_filament = has_bed_exclude_volumes(m_config) && + active_bed_exclude_volume_mode(m_config) != BedExcludeVolumeMode::Shared; + auto emit_brim = [this, extruder_id, wait_for_owner_filament](const ExtrusionEntityCollection& brim, + const std::vector& instances, + const unsigned int brim_filament_id) { std::string gcode; + // Combined brims have an explicit owner filament. Waiting for that + // filament is only required when each nozzle has different obstacles. + // Otherwise retain Orca's established first-visit emission order. + if (wait_for_owner_filament && brim_filament_id != extruder_id) + return gcode; const bool already_emitted = std::none_of(instances.begin(), instances.end(), [this](const ObjectInstanceID& instance) { return m_objsWithBrim.find(instance) != m_objsWithBrim.end(); }); @@ -5949,7 +6064,7 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o std::string gcode; for (const Print::SkirtBrimGroup::Brim& brim : print.skirt_brim_groups()[group_idx].brims) if (std::find(brim.instances.begin(), brim.instances.end(), object_instance_id) != brim.instances.end()) - gcode += emit_brim(brim.brim, brim.instances); + gcode += emit_brim(brim.brim, brim.instances, brim.filament_id); return gcode; } @@ -7467,10 +7582,10 @@ LayerResult GCode::process_layer( // sweep below never re-emits it. if (extruder_id == (unsigned int)(vobj.belt_brim_filament() - 1) && belt_brim_emitted.insert({ instance_to_print.layer_id, instance_to_print.instance_id }).second) - gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, + gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, extruder_id, layer_to_print.object_layer); } else { - gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, + gcode += generate_object_brim(print, vobj, instance_to_print.instance_id, first_layer, extruder_id, layer_to_print.object_layer); } } @@ -8009,7 +8124,7 @@ LayerResult GCode::process_layer( continue; if (m_writer.filament() == nullptr || m_writer.filament()->id() != brim0) gcode += this->set_extruder(brim0, print_z); - gcode += generate_object_brim(print, *obj, instance_id, first_layer, ltp.object_layer); + gcode += generate_object_brim(print, *obj, instance_id, first_layer, brim0, ltp.object_layer); } } this->set_origin(saved_origin); @@ -8248,6 +8363,41 @@ void GCode::set_extruders(const std::vector &extruder_ids) } } +std::optional GCode::capture_toolchange_position() +{ + if (m_exclusion_volume_travel_avoidance.empty() || !m_last_pos_defined || m_writer.filament() == nullptr) + return std::nullopt; + + const Vec2d plate_offset = m_writer.get_xy_offset().cast(); + return ToolchangePositionState{ + this->point_to_gcode(m_last_pos.to_point()) - plate_offset + }; +} + +void GCode::synchronize_toolchange_position(const ToolchangePositionState &before, const std::string &emitted_gcode) +{ + if (m_writer.filament() == nullptr) + return; + + const std::optional emitted_xy = emitted_xy_after_gcode(emitted_gcode, before.emitted_xy); + if (!emitted_xy) + return; + + // GCodeWriter stores coordinates before applying the per-plate output + // offset. Convert the parsed file coordinates back into that space, then + // into model space using the newly active nozzle offset. + const Vec2d writer_xy = *emitted_xy + m_writer.get_xy_offset().cast(); + Vec3d writer_position = m_writer.get_position(); + writer_position.head<2>() = writer_xy; + m_writer.set_position(writer_position); + // Updating the known XY origin must not cancel Orca's deliberate + // post-toolchange Z restore. set_last_pos() normally marks the entire + // position as defined, so preserve the caller's state across the XY sync. + const bool last_pos_defined = m_last_pos_defined; + this->set_last_pos(this->gcode_to_point(writer_xy)); + m_last_pos_defined = last_pos_defined; +} + void GCode::set_origin(const Vec2d &pointf) { // if origin increases (goes towards right), last_pos decreases because it goes towards left @@ -9752,7 +9902,7 @@ std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_d } // BBS: use G1 if not enable arc fitting or has no arc fitting result or in spiral_mode mode or we are doing sloped extrusion // Attention: G2 and G3 is not supported in spiral_mode mode - if (!m_config.enable_arc_fitting || path.polyline.fitting_result.empty() || m_config.spiral_mode || sloped != nullptr || path.z_contoured || this->should_disable_arc_fitting()) { + if (m_config.enable_arc_fitting.value == ArcFittingMode::Disabled || path.polyline.fitting_result.empty() || m_config.spiral_mode || sloped != nullptr || path.z_contoured || this->should_disable_arc_fitting()) { double path_length = 0.; double total_length = sloped == nullptr ? 0. : path.polyline.length() * SCALING_FACTOR; double saved_z = m_writer.get_position().z(); @@ -10127,10 +10277,17 @@ std::string GCode::_encode_label_ids_to_base64(std::vector ids) // This method accepts &point in print coordinates. std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string comment, double z/* = DBL_MAX*/) { + const std::optional start_gcode_position = + !m_exclusion_volume_travel_avoidance.empty() && !m_last_pos_defined && + !m_writer.is_current_position_clear() && m_pending_start_gcode_position.has_value() ? + m_pending_start_gcode_position : std::nullopt; + /* Define the travel move as a line between current position and the taget point. This is expressed in print coordinates, so it will need to be translated by this->origin in order to get G-code coordinates. */ - Polyline travel { this->last_pos(), point }; + const Point travel_start = start_gcode_position ? + this->gcode_to_point(to_2d(start_gcode_position->position)) : this->last_pos(); + Polyline travel { travel_start, point }; // check whether a straight travel move would need retraction LiftType lift_type = LiftType::SpiralLift; @@ -10140,6 +10297,66 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string // Save state of use_external_mp_once for the case that will be needed to call twice m_avoid_crossing_perimeters.travel_to. const bool used_external_mp_once = m_avoid_crossing_perimeters.used_external_mp_once(); std::string gcode; + bool exclusion_volume_travel_rerouted = false; + + const auto active_extruder_id = [this]() { + if (m_writer.filament() == nullptr) + return -1; + const size_t id = m_writer.filament()->extruder_id(); + return id < m_config.nozzle_diameter.size() ? int(id) : -1; + }; + const auto to_gcode_point = [this](const Point &local_point) { + const Vec2d point = this->point_to_gcode(local_point); + return Point(scale_(point.x()), scale_(point.y())); + }; + const auto to_local_point = [this](const Point &gcode_point) { + return this->gcode_to_point(unscaled(gcode_point)); + }; + const auto to_gcode_polyline = [&to_gcode_point](const Polyline &local_path) { + Polyline result; + result.points.reserve(local_path.points.size()); + for (const Point &local_point : local_path.points) + result.append(to_gcode_point(local_point)); + return result; + }; + const auto to_local_polyline = [&to_local_point](const Polyline &gcode_path) { + Polyline result; + result.points.reserve(gcode_path.points.size()); + for (const Point &gcode_point : gcode_path.points) + result.append(to_local_point(gcode_point)); + return result; + }; + const auto nominal_writer_z = [this]() { + return m_writer.get_position().z() - m_writer.get_zhop(); + }; + const auto route_around_exclusion_volumes = [&]( + Polyline &path, + const std::optional &start_z_override, + const bool include_planned_lift = false) { + if (m_exclusion_volume_travel_avoidance.empty() || path.size() < 2) + return false; + + const double target_z = z == DBL_MAX ? m_nominal_z : z; + double route_start_z = start_z_override.value_or(nominal_writer_z()); + double route_end_z = target_z; + if (include_planned_lift) { + const Vec2d destination_xy = this->point_to_gcode(path.back()); + std::tie(route_start_z, route_end_z) = m_writer.planned_travel_z( + Vec3d(destination_xy.x(), destination_xy.y(), target_z), + m_need_change_layer_lift_z); + } + const ExclusionVolumeTravelAvoidance::Result result = + m_exclusion_volume_travel_avoidance.route( + to_gcode_polyline(path), + route_start_z, + route_end_z, + active_extruder_id()); + if (!result.rerouted()) + return false; + + path = to_local_polyline(result.path); + return true; + }; // Orca: we don't need to optimize the Klipper as only set once double jerk_to_set = 0.0; @@ -10205,6 +10422,14 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string //if (needs_retraction && m_layer_index > 1) exit(0); } + const std::optional start_gcode_z = + start_gcode_position && start_gcode_position->has_known_z() ? + std::optional(start_gcode_position->position.z()) : std::nullopt; + if (route_around_exclusion_volumes(travel, start_gcode_z)) { + exclusion_volume_travel_rerouted = true; + needs_retraction = this->needs_retraction(travel, role, lift_type); + } + // Re-allow reduce_crossing_wall for the next travel moves m_avoid_crossing_perimeters.reset_once_modifiers(); @@ -10220,16 +10445,22 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string // When "Wipe while retracting" is enabled, then extruder moves to another position, and travel from this position can cross perimeters. // Because of it, it is necessary to call avoid crossing perimeters again with new starting point after calling retraction() // FIXME Lukas H.: Try to predict if this second calling of avoid crossing perimeters will be needed or not. It could save computations. - if (last_post_before_retract != this->last_pos() && m_config.reduce_crossing_wall - && m_layer != nullptr) { // A brim apron layer has no Layer to avoid crossing - // If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call. - if (used_external_mp_once) - m_avoid_crossing_perimeters.use_external_mp_once(); - travel = m_avoid_crossing_perimeters.travel_to(*this, point); - // If state of use_external_mp_once was changed reset it to right value. - if (used_external_mp_once) - m_avoid_crossing_perimeters.reset_once_modifiers(); + if (last_post_before_retract != this->last_pos()) { + travel = Polyline { this->last_pos(), point }; + if (m_config.reduce_crossing_wall && m_layer != nullptr) { // Belt brim apron layers have no Layer. + // If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call. + if (used_external_mp_once) + m_avoid_crossing_perimeters.use_external_mp_once(); + travel = m_avoid_crossing_perimeters.travel_to(*this, point); + // If state of use_external_mp_once was changed reset it to right value. + if (used_external_mp_once) + m_avoid_crossing_perimeters.reset_once_modifiers(); + } } + + exclusion_volume_travel_rerouted = + route_around_exclusion_volumes(travel, std::nullopt, true) || + (last_post_before_retract == this->last_pos() && exclusion_volume_travel_rerouted); } else { // Reset the wipe path when traveling, so one would not wipe along an old path. m_wipe.reset_path(); @@ -10261,6 +10492,24 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string Vec3d dest3d(dest2d(0), dest2d(1), z == DBL_MAX ? m_nominal_z : z); gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z); m_need_change_layer_lift_z = false; + } else if (exclusion_volume_travel_rerouted && z != DBL_MAX) { + // Preserve the original sloped-Z move over the longer detour. + // The router activates every volume touched by the complete Z + // range, so this interpolation remains conservative. + const double start_z = m_writer.get_position().z(); + const double total_length = std::max(travel.length(), 1.0); + double traveled = 0.0; + for (size_t i = 1; i < travel.size(); ++i) { + traveled += (travel.points[i] - travel.points[i - 1]).cast().norm(); + const Vec2d dest2d = this->point_to_gcode(travel.points[i]); + const Vec3d dest3d( + dest2d.x(), + dest2d.y(), + start_z + (z - start_z) * std::min(1.0, traveled / total_length)); + gcode += m_writer.travel_to_xyz(dest3d, comment, i == 1 && m_need_change_layer_lift_z); + if (i == 1) + m_need_change_layer_lift_z = false; + } } else { // Extra movements emitted by avoid_crossing_perimeters, lift the z to normal height at the beginning, then apply the z // ratio at the last point @@ -10587,6 +10836,9 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo if (!m_writer.need_toolchange(new_filament_id)) return ""; + const std::optional position_before_toolchange = + this->capture_toolchange_position(); + // if we are running a single-extruder setup, just set the extruder and return nothing if (!m_writer.multiple_extruders) { this->placeholder_parser().set("current_extruder", new_filament_id); @@ -10641,6 +10893,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo gcode += toolchange_command; if (Extruder *fil = m_writer.filament()) fil->set_config_index((int)get_filament_config_index((int)fil->id())); + if (position_before_toolchange) + this->synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -11057,6 +11311,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo imex_pem_tool_for((int) new_filament_id, m_imex_parallel_mode, m_config.physical_extruder_map)); //Orca: tool changer or IDEX's firmware may change Z position, so we set it to unknown/undefined m_last_pos_defined = false; + if (position_before_toolchange) + this->synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 38740abd7e..e9a346889a 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -14,6 +14,7 @@ #include "PrintConfig.hpp" #include "GCode/AvoidCrossingPerimeters.hpp" #include "GCode/CoolingBuffer.hpp" +#include "GCode/ExclusionVolumeTravelAvoidance.hpp" #include "GCode/FanMover.hpp" #include "GCode/RetractWhenCrossingPerimeters.hpp" #include "GCode/SpiralVase.hpp" @@ -470,6 +471,7 @@ protected: const PrintObject &object, size_t instance_id, bool first_layer, + unsigned int extruder_id, const Layer *object_layer); // Belt printers: emit one brim-only apron layer. These print below the @@ -540,8 +542,16 @@ protected: size_t get_extruder_id(unsigned int filament_id) const; void update_placeholder_parser_with_variant_params(); - void set_last_pos(const Point &pos) { m_last_pos = Point3(pos, 0); m_last_pos_defined = true; } - void set_last_pos(const Point3 &pos) { m_last_pos = pos; m_last_pos_defined = true; } + void set_last_pos(const Point &pos) { + m_last_pos = Point3(pos, 0); + m_last_pos_defined = true; + m_pending_start_gcode_position.reset(); + } + void set_last_pos(const Point3 &pos) { + m_last_pos = pos; + m_last_pos_defined = true; + m_pending_start_gcode_position.reset(); + } bool last_pos_defined() const { return m_last_pos_defined; } void set_extruders(const std::vector &extruder_ids); std::string preamble(); @@ -766,6 +776,7 @@ protected: OozePrevention m_ooze_prevention; Wipe m_wipe; AvoidCrossingPerimeters m_avoid_crossing_perimeters; + ExclusionVolumeTravelAvoidance m_exclusion_volume_travel_avoidance; RetractWhenCrossingPerimeters m_retract_when_crossing_perimeters; TimelapsePosPicker m_timelapse_pos_picker; bool m_timelapse_uses_pos{ false }; @@ -855,6 +866,18 @@ protected: Point3 m_last_pos; bool m_last_pos_defined; + struct ToolchangePositionState + { + Vec2d emitted_xy{Vec2d::Zero()}; + }; + + // Capture and restore the actual command-space position around a physical + // nozzle change. Model-space m_last_pos is tied to the active nozzle offset, + // while the machine position itself does not change when Tx is emitted. + std::optional capture_toolchange_position(); + void synchronize_toolchange_position(const ToolchangePositionState &before, + const std::string &emitted_gcode); + std::unique_ptr m_cooling_buffer; std::unique_ptr m_spiral_vase; std::unique_ptr m_pressure_equalizer; @@ -896,6 +919,10 @@ protected: // Processor GCodeProcessor m_processor; + // Command-space endpoint after startup G-code. The processor sees direct + // file writes synchronously, while the generator has not established its + // first model-space point yet. + std::optional m_pending_start_gcode_position; //some post-processing on the file, with their data class std::unique_ptr m_fan_mover; diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp new file mode 100644 index 0000000000..fbe3e6b465 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp @@ -0,0 +1,234 @@ +#include "ExclusionVolumePathCheck.hpp" +#include "libslic3r/AABBTreeLines.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/PrintConfig.hpp" +#include +#include + +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" + +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; + +Point scaled_point(const Vec3d &point) +{ + return { scale_(point.x()), scale_(point.y()) }; +} + +BoundingBox line_bbox(const Point &a, const Point &b) +{ + BoundingBox bbox; + bbox.merge(a); + bbox.merge(b); + bbox.offset(SCALED_EPSILON); + return bbox; +} + +bool intervals_overlap(coord_t a_min, coord_t a_max, coord_t b_min, coord_t b_max) +{ + if (a_min > a_max) + std::swap(a_min, a_max); + if (b_min > b_max) + std::swap(b_min, b_max); + return std::max(a_min, b_min) <= std::min(a_max, b_max); +} + +bool collinear_segments_overlap(const Line &a, const Line &b) +{ + const Vec2crd a_dir = a.b - a.a; + if (a_dir == Vec2crd::Zero()) + return a.a == b.a || a.a == b.b; + + if (cross2(a_dir, b.a - a.a) != 0 || cross2(a_dir, b.b - a.a) != 0) + return false; + + return std::abs(a_dir.x()) >= std::abs(a_dir.y()) ? + intervals_overlap(a.a.x(), a.b.x(), b.a.x(), b.b.x()) : + intervals_overlap(a.a.y(), a.b.y(), b.a.y(), b.b.y()); +} + +bool overlaps_collinear_boundary(const Line &line, const Lines &edges) +{ + const BoundingBox line_bounds = line_bbox(line.a, line.b); + for (const Line &edge : edges) { + if (line_bounds.overlap(line_bbox(edge.a, edge.b)) && collinear_segments_overlap(line, edge)) + return true; + } + return false; +} + +bool clip_segment_to_z_range( + const Vec3d &from, + const Vec3d &to, + double z_min, + double z_max, + Vec3d &out_from, + Vec3d &out_to) +{ + const double segment_min_z = std::min(from.z(), to.z()); + const double segment_max_z = std::max(from.z(), to.z()); + if (segment_max_z < z_min - Z_EPSILON_MM || segment_min_z > z_max + Z_EPSILON_MM) + return false; + + double t0 = 0.0; + double t1 = 1.0; + const double dz = to.z() - from.z(); + if (std::abs(dz) < Z_EPSILON_MM) { + if (from.z() < z_min - Z_EPSILON_MM || from.z() > z_max + Z_EPSILON_MM) + return false; + } else { + const double z0 = (z_min - from.z()) / dz; + const double z1 = (z_max - from.z()) / dz; + t0 = std::max(t0, std::min(z0, z1)); + t1 = std::min(t1, std::max(z0, z1)); + if (t0 > t1 + Z_EPSILON_MM) + return false; + } + + t0 = std::clamp(t0, 0.0, 1.0); + t1 = std::clamp(t1, 0.0, 1.0); + const Vec3d delta = to - from; + out_from = from + t0 * delta; + out_to = from + t1 * delta; + return true; +} + +} // namespace + +void ExclusionVolumePathChecker::configure(const PrintConfig &config) +{ + clear(); + m_configured = true; + m_extruder_offsets = config.extruder_offset.values; + + const std::vector> regions = + get_bed_excluded_regions_by_extruder(config); + m_regions_by_extruder.resize(regions.size()); + if (m_extruder_offsets.size() < regions.size()) + m_extruder_offsets.resize(regions.size(), Vec2d::Zero()); + + for (size_t extruder_id = 0; extruder_id < regions.size(); ++extruder_id) { + std::vector &prepared = m_regions_by_extruder[extruder_id]; + prepared.reserve(regions[extruder_id].size()); + for (const BedExcludeRegion ®ion : regions[extruder_id]) { + // Legacy excluded areas are material keep-outs. Some stock profiles + // deliberately move the nozzle into them (for example, a cutter), so + // only explicitly configured collision volumes constrain motion. + if (!region.is_collision_volume() || region.polygon.points.size() < 3 || region.z_max < region.z_min) + continue; + + PreparedRegion item; + item.region = region; + item.bbox = BoundingBox(region.polygon.points); + item.bbox.offset(SCALED_EPSILON); + item.edge_tree = AABBTreeLines::LinesDistancer(to_lines(region.polygon)); + prepared.emplace_back(std::move(item)); + } + } +} + +void ExclusionVolumePathChecker::clear() +{ + m_configured = false; + m_extruder_offsets.clear(); + m_regions_by_extruder.clear(); + m_result = {}; +} + +bool ExclusionVolumePathChecker::segment_intersects_region( + const Vec3d &from, + const Vec3d &to, + const bool z_known, + const PreparedRegion ®ion) const +{ + Vec3d clipped_from = from; + Vec3d clipped_to = to; + if (z_known && !clip_segment_to_z_range( + from, to, region.region.z_min, region.region.z_max, clipped_from, clipped_to)) + return false; + + const Point a = scaled_point(clipped_from); + const Point b = scaled_point(clipped_to); + if (!line_bbox(a, b).overlap(region.bbox)) + return false; + + if (region.region.polygon.contains(a) || region.region.polygon.contains(b)) + return true; + if (a == b) + return false; + + const Line line(a, b); + if (!region.edge_tree.intersections_with_line(line).empty()) + return true; + + // The line tree intentionally omits collinear intersections. + return overlaps_collinear_boundary(line, region.edge_tree.get_lines()); +} + +void ExclusionVolumePathChecker::check_motion( + const Vec3d &from, + const Vec3d &to, + const bool start_xy_known, + const bool end_xy_known, + const bool start_z_known, + const bool end_z_known, + const int active_extruder_id, + const ExclusionVolumeMotionType motion_type, + const unsigned char source_move_type, + const unsigned int gcode_id, + const size_t move_id) +{ + if (!m_configured || m_result.has_any_conflict || !start_xy_known || !end_xy_known || + m_regions_by_extruder.empty()) + return; + + const bool z_known = start_z_known && end_z_known; + const bool active_extruder_valid = + active_extruder_id >= 0 && size_t(active_extruder_id) < m_regions_by_extruder.size(); + const size_t first_extruder = active_extruder_valid ? size_t(active_extruder_id) : 0; + const size_t last_extruder = active_extruder_valid ? first_extruder + 1 : m_regions_by_extruder.size(); + + for (size_t extruder_id = first_extruder; extruder_id < last_extruder; ++extruder_id) { + const Vec2d offset = extruder_id < m_extruder_offsets.size() ? + m_extruder_offsets[extruder_id] : Vec2d::Zero(); + Vec3d model_from = from; + Vec3d model_to = to; + model_from.head<2>() += offset; + model_to.head<2>() += offset; + + const std::vector ®ions = m_regions_by_extruder[extruder_id]; + for (size_t region_id = 0; region_id < regions.size(); ++region_id) { + if (!segment_intersects_region(model_from, model_to, z_known, regions[region_id])) + continue; + + m_result.has_any_conflict = true; + m_result.has_travel_conflict = motion_type == ExclusionVolumeMotionType::Travel; + m_result.has_extrusion_conflict = motion_type == ExclusionVolumeMotionType::Extrude; + m_result.has_other_motion_conflict = motion_type == ExclusionVolumeMotionType::Other; + m_result.first_hit = ExclusionVolumePathHit{ + move_id, + gcode_id, + motion_type, + source_move_type, + int(extruder_id), + region_id, + model_from, + model_to, + !z_known + }; + return; + } + } +} + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp new file mode 100644 index 0000000000..af94ef0076 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include "libslic3r/AABBTreeLines.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include +#include +#include + +namespace Slic3r { + +enum class ExclusionVolumeMotionType : unsigned char +{ + Travel, + Extrude, + Other +}; + +struct ExclusionVolumePathHit +{ + size_t move_id { 0 }; + unsigned int gcode_id { 0 }; + ExclusionVolumeMotionType motion_type { ExclusionVolumeMotionType::Other }; + unsigned char source_move_type { 0 }; + int extruder_id { -1 }; + size_t region_id { 0 }; + Vec3d from { Vec3d::Zero() }; + Vec3d to { Vec3d::Zero() }; + bool used_unknown_z { false }; +}; + +struct ExclusionVolumePathCheckResult +{ + bool has_any_conflict { false }; + bool has_travel_conflict { false }; + bool has_extrusion_conflict { false }; + bool has_other_motion_conflict { false }; + std::optional first_hit; +}; + +// Checks G-code coordinates as they are parsed. Exclusion regions are expressed +// in nozzle/model space, so each candidate physical extruder offset is applied +// before testing a motion. This keeps the checker independent of preview +// vertices, whose extruder_id field represents a filament rather than a nozzle. +class ExclusionVolumePathChecker +{ +public: + void configure(const PrintConfig &config); + void clear(); + + bool configured() const { return m_configured; } + const ExclusionVolumePathCheckResult &result() const { return m_result; } + + void check_motion( + const Vec3d &from, + const Vec3d &to, + bool start_xy_known, + bool end_xy_known, + bool start_z_known, + bool end_z_known, + int active_extruder_id, + ExclusionVolumeMotionType motion_type, + unsigned char source_move_type, + unsigned int gcode_id, + size_t move_id); + +private: + struct PreparedRegion + { + BedExcludeRegion region; + BoundingBox bbox; + AABBTreeLines::LinesDistancer edge_tree; + }; + + bool segment_intersects_region( + const Vec3d &from, + const Vec3d &to, + bool z_known, + const PreparedRegion ®ion) const; + + bool m_configured { false }; + std::vector m_extruder_offsets; + std::vector> m_regions_by_extruder; + ExclusionVolumePathCheckResult m_result; +}; + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp new file mode 100644 index 0000000000..5f702ccdec --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -0,0 +1,672 @@ +#include "ExclusionVolumeTravelAvoidance.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/libslic3r.h" +#include +#include +#include + +#include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/Polygon.hpp" + +#include +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double T_EPSILON = 1e-9; +constexpr size_t MAX_REROUTE_ITERATIONS = 16; + +struct SegmentIntersection +{ + double t { 0.0 }; + Point point; + size_t edge_idx { 0 }; +}; + +double boundary_epsilon() +{ + return std::max(SCALED_EPSILON, scale_(0.005)); +} + +bool line_intersection_t( + const Point &a, + const Point &b, + const Point &c, + const Point &d, + double &t, + Point &intersection) +{ + const Vec2d p = a.cast(); + const Vec2d r = (b - a).cast(); + const Vec2d q = c.cast(); + const Vec2d s = (d - c).cast(); + const double denominator = cross2(r, s); + if (std::abs(denominator) < T_EPSILON) + return false; + + const Vec2d qp = q - p; + const double candidate_t = cross2(qp, s) / denominator; + const double u = cross2(qp, r) / denominator; + if (candidate_t < -T_EPSILON || candidate_t > 1.0 + T_EPSILON || + u < -T_EPSILON || u > 1.0 + T_EPSILON) + return false; + + t = std::clamp(candidate_t, 0.0, 1.0); + intersection = (p + t * r).cast(); + return true; +} + +template +void for_each_expolygon_contour(const ExPolygon &expolygon, Fn &&fn) +{ + fn(expolygon.contour); + for (const Polygon &hole : expolygon.holes) + fn(hole); +} + +void add_unique_param(std::vector ¶ms, double t) +{ + const double clamped = std::clamp(t, 0.0, 1.0); + if (std::none_of(params.begin(), params.end(), [clamped](double value) { + return std::abs(value - clamped) < T_EPSILON; + })) + params.emplace_back(clamped); +} + +std::vector contour_intersections( + const Point &a, + const Point &b, + const Polygon &polygon) +{ + std::vector intersections; + if (polygon.points.size() < 2) + return intersections; + + intersections.reserve(4); + for (size_t edge_idx = 0; edge_idx < polygon.points.size(); ++edge_idx) { + const Point &c = polygon.points[edge_idx]; + const Point &d = polygon.points[(edge_idx + 1) % polygon.points.size()]; + double t = 0.0; + Point point; + if (line_intersection_t(a, b, c, d, t, point) && + std::none_of(intersections.begin(), intersections.end(), [t](const SegmentIntersection &other) { + return std::abs(other.t - t) < T_EPSILON; + })) + intersections.push_back({ t, point, edge_idx }); + } + + std::sort(intersections.begin(), intersections.end(), [](const SegmentIntersection &lhs, const SegmentIntersection &rhs) { + return lhs.t < rhs.t; + }); + return intersections; +} + +bool point_in_expolygons(const ExPolygons &expolygons, const Point &point, bool border_result) +{ + return std::any_of(expolygons.begin(), expolygons.end(), [&point, border_result](const ExPolygon &expolygon) { + return expolygon.contains(point, border_result); + }); +} + +bool point_on_expolygon_boundary(const ExPolygon &expolygon, const Point &point) +{ + const double epsilon = boundary_epsilon(); + if (expolygon.contour.on_boundary(point, epsilon)) + return true; + return std::any_of(expolygon.holes.begin(), expolygon.holes.end(), [&point, epsilon](const Polygon &hole) { + return hole.on_boundary(point, epsilon); + }); +} + +bool point_on_expolygons_boundary(const ExPolygons &expolygons, const Point &point) +{ + return std::any_of(expolygons.begin(), expolygons.end(), [&point](const ExPolygon &expolygon) { + return point_on_expolygon_boundary(expolygon, point); + }); +} + +bool point_in_expolygons_interior(const ExPolygons &expolygons, const Point &point) +{ + return point_in_expolygons(expolygons, point, false) && + !point_on_expolygons_boundary(expolygons, point); +} + +std::vector boundary_params_for_segment( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + std::vector params { 0.0, 1.0 }; + for (const ExPolygon &expolygon : expolygons) { + for_each_expolygon_contour(expolygon, [&](const Polygon &contour) { + for (const SegmentIntersection &intersection : contour_intersections(a, b, contour)) + add_unique_param(params, intersection.t); + }); + } + std::sort(params.begin(), params.end()); + return params; +} + +Point interpolate(const Point &a, const Point &b, double t) +{ + return (a.cast() + t * (b - a).cast()).cast(); +} + +bool segment_enters_expolygons_interior( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + if (expolygons.empty()) + return false; + if (point_in_expolygons_interior(expolygons, a) || point_in_expolygons_interior(expolygons, b)) + return true; + + const std::vector params = boundary_params_for_segment(a, b, expolygons); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (point_in_expolygons_interior(expolygons, interpolate(a, b, 0.5 * (low + high)))) + return true; + } + return false; +} + +std::optional first_interior_param_for_segment( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + if (expolygons.empty()) + return std::nullopt; + if (point_in_expolygons_interior(expolygons, a)) + return 0.0; + + const std::vector params = boundary_params_for_segment(a, b, expolygons); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (point_in_expolygons_interior(expolygons, interpolate(a, b, 0.5 * (low + high)))) + return low; + } + + return point_in_expolygons_interior(expolygons, b) ? std::optional(1.0) : std::nullopt; +} + +bool segment_inside_bed(const Point &a, const Point &b, const ExPolygons &valid_bed) +{ + if (valid_bed.empty()) + return true; + if (!point_in_expolygons(valid_bed, a, true) || !point_in_expolygons(valid_bed, b, true)) + return false; + + const std::vector params = boundary_params_for_segment(a, b, valid_bed); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (!point_in_expolygons(valid_bed, interpolate(a, b, 0.5 * (low + high)), false)) + return false; + } + return true; +} + +double polyline_length(const Polyline &polyline) +{ + double length = 0.0; + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + length += (polyline.points[idx] - polyline.points[idx - 1]).cast().norm(); + return length; +} + +bool points_near(const Point &lhs, const Point &rhs) +{ + const double epsilon = boundary_epsilon(); + return (lhs - rhs).cast().squaredNorm() <= epsilon * epsilon; +} + +bool replacement_matches_original_segment(const Polyline &replacement, const Point &a, const Point &b) +{ + return replacement.points.size() == 2 && + points_near(replacement.points.front(), a) && points_near(replacement.points.back(), b); +} + +void append_point(Points &points, const Point &point) +{ + if (points.empty() || points.back() != point) + points.emplace_back(point); +} + +Polyline make_forward_detour( + const Point &a, + const Point &b, + const Polygon &contour, + const SegmentIntersection &entry, + const SegmentIntersection &exit) +{ + Points points; + append_point(points, a); + append_point(points, entry.point); + + const size_t count = contour.points.size(); + for (size_t idx = (entry.edge_idx + 1) % count; idx != (exit.edge_idx + 1) % count; idx = (idx + 1) % count) + append_point(points, contour.points[idx]); + + append_point(points, exit.point); + append_point(points, b); + return Polyline(std::move(points)); +} + +Polyline make_backward_detour( + const Point &a, + const Point &b, + const Polygon &contour, + const SegmentIntersection &entry, + const SegmentIntersection &exit) +{ + Points points; + append_point(points, a); + append_point(points, entry.point); + + const size_t count = contour.points.size(); + const size_t last_vertex = (exit.edge_idx + 1) % count; + for (size_t idx = entry.edge_idx;; idx = idx == 0 ? count - 1 : idx - 1) { + append_point(points, contour.points[idx]); + if (idx == last_vertex) + break; + } + + append_point(points, exit.point); + append_point(points, b); + return Polyline(std::move(points)); +} + +bool routed_polyline_inside_bed( + const Polyline &polyline, + const ExPolygons &valid_bed, + const bool allow_start_outside, + const bool allow_end_outside) +{ + if (valid_bed.empty()) + return true; + + const size_t last_idx = polyline.points.size() - 1; + for (size_t idx = 0; idx < polyline.points.size(); ++idx) { + if ((idx == 0 && allow_start_outside) || (idx == last_idx && allow_end_outside)) + continue; + if (!point_in_expolygons(valid_bed, polyline.points[idx], true)) + return false; + } + + for (size_t idx = 1; idx < polyline.points.size(); ++idx) { + // A start or end produced by machine G-code may legitimately lie on + // or beyond the printable boundary. Constrain only the route vertices + // Orca adds; the firmware-defined transition to the bed remains intact. + if ((idx == 1 && allow_start_outside) || (idx == last_idx && allow_end_outside)) + continue; + if (!segment_inside_bed(polyline.points[idx - 1], polyline.points[idx], valid_bed)) + return false; + } + return true; +} + +bool polyline_intersects_obstacles(const Polyline &polyline, const ExPolygons &obstacles) +{ + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + if (segment_enters_expolygons_interior(polyline.points[idx - 1], polyline.points[idx], obstacles)) + return true; + return false; +} + +std::optional first_intersected_obstacle( + const Point &a, + const Point &b, + const ExPolygons &obstacles) +{ + std::optional best_idx; + double best_t = std::numeric_limits::infinity(); + for (size_t idx = 0; idx < obstacles.size(); ++idx) { + const ExPolygons single { obstacles[idx] }; + if (const std::optional t = first_interior_param_for_segment(a, b, single); t && *t < best_t) { + best_t = *t; + best_idx = idx; + } + } + return best_idx; +} + +std::optional detour_around_obstacle( + const Point &a, + const Point &b, + const ExPolygon &obstacle, + const ExPolygons &obstacles, + const ExPolygons &valid_bed, + const bool allow_start_outside, + const bool allow_end_outside) +{ + const std::vector intersections = contour_intersections(a, b, obstacle.contour); + if (intersections.size() < 2) + return std::nullopt; + + const SegmentIntersection &entry = intersections.front(); + const SegmentIntersection &exit = intersections.back(); + const Polyline forward = make_forward_detour(a, b, obstacle.contour, entry, exit); + const Polyline backward = make_backward_detour(a, b, obstacle.contour, entry, exit); + + const bool forward_bed_valid = routed_polyline_inside_bed( + forward, valid_bed, allow_start_outside, allow_end_outside); + const bool backward_bed_valid = routed_polyline_inside_bed( + backward, valid_bed, allow_start_outside, allow_end_outside); + const bool forward_clear = forward_bed_valid && !polyline_intersects_obstacles(forward, obstacles); + const bool backward_clear = backward_bed_valid && !polyline_intersects_obstacles(backward, obstacles); + + if (forward_clear || backward_clear) { + if (forward_clear && !backward_clear) + return forward; + if (!forward_clear && backward_clear) + return backward; + return polyline_length(forward) <= polyline_length(backward) ? forward : backward; + } + + // If another obstacle blocks both immediate choices, retain the valid local + // detour and let the outer repair loop address the next crossing. + if (!forward_bed_valid && !backward_bed_valid) + return std::nullopt; + if (forward_bed_valid && !backward_bed_valid) + return forward; + if (!forward_bed_valid && backward_bed_valid) + return backward; + return polyline_length(forward) <= polyline_length(backward) ? forward : backward; +} + +void replace_segment(Polyline &path, size_t segment_idx, const Polyline &replacement) +{ + Points points; + points.reserve(path.points.size() + replacement.points.size()); + for (size_t idx = 0; idx < segment_idx; ++idx) + append_point(points, path.points[idx]); + for (const Point &point : replacement.points) + append_point(points, point); + for (size_t idx = segment_idx + 2; idx < path.points.size(); ++idx) + append_point(points, path.points[idx]); + path.points = std::move(points); +} + +Polyline simplify_path(const Polyline &path, const ExPolygons &obstacles, const ExPolygons &valid_bed) +{ + if (path.points.size() <= 2) + return path; + + Points simplified; + simplified.reserve(path.points.size()); + size_t current = 0; + append_point(simplified, path.points.front()); + while (current + 1 < path.points.size()) { + size_t next = path.points.size() - 1; + for (; next > current + 1; --next) { + if (segment_inside_bed(path.points[current], path.points[next], valid_bed) && + !segment_enters_expolygons_interior(path.points[current], path.points[next], obstacles)) + break; + } + append_point(simplified, path.points[next]); + current = next; + } + return Polyline(std::move(simplified)); +} + +} // namespace + +void ExclusionVolumeTravelAvoidance::init(const PrintConfig &config, const Vec3d &plate_origin) +{ + clear(); + + double max_nozzle_diameter = 0.0; + for (double diameter : config.nozzle_diameter.values) + max_nozzle_diameter = std::max(max_nozzle_diameter, diameter); + + // This is a numerical/perimeter-walk clearance, not a hidden toolhead + // footprint. The exact configured volume remains Stage 2's source of truth. + const coord_t minimum_clearance = static_cast(SCALED_EPSILON); + const coord_t configured_clearance = + static_cast(scale_(std::max(0.05, 0.1 * max_nozzle_diameter))); + m_clearance = std::max(minimum_clearance, configured_clearance); + + std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(config); + m_spaces.resize(regions_by_extruder.size()); + + const Polygon base_bed_shape(get_bed_shape(config)); + const Vec2d plate_xy = plate_origin.head<2>(); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + RoutingSpace &space = m_spaces[extruder_id]; + space.regions = std::move(regions_by_extruder[extruder_id]); + space.regions.erase(std::remove_if(space.regions.begin(), space.regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), space.regions.end()); + + const Vec2d extruder_offset = extruder_id < config.extruder_offset.values.size() ? + config.extruder_offset.values[extruder_id] : Vec2d::Zero(); + // Resolved regions are in nozzle/model space. The generator routes in + // emitted G-code space (model - active nozzle offset), before the writer + // subtracts the plate origin, so transform both obstacles and bed alike. + const Vec2d translation_mm = plate_xy - extruder_offset; + const Point translation = scaled(translation_mm); + for (BedExcludeRegion ®ion : space.regions) { + region.polygon.translate(translation); + BoundingBox bbox(region.polygon.points); + bbox.offset(m_clearance); + space.region_bboxes.emplace_back(std::move(bbox)); + } + + Polygon bed_shape = base_bed_shape; + bed_shape.translate(translation); + bed_shape.make_counter_clockwise(); + if (bed_shape.points.size() >= 3) { + space.valid_bed = offset_ex(bed_shape, -float(m_clearance)); + if (space.valid_bed.empty()) + space.valid_bed = union_ex(Polygons { std::move(bed_shape) }); + } + } +} + +void ExclusionVolumeTravelAvoidance::clear() +{ + m_spaces.clear(); + m_clearance = static_cast(SCALED_EPSILON); +} + +bool ExclusionVolumeTravelAvoidance::empty() const +{ + return std::all_of(m_spaces.begin(), m_spaces.end(), [](const RoutingSpace &space) { + return space.regions.empty(); + }); +} + +const ExPolygons * +ExclusionVolumeTravelAvoidance::active_obstacles( + RoutingSpace &space, + double z_min, + double z_max) +{ + std::vector active_region_ids; + active_region_ids.reserve(space.regions.size()); + for (size_t region_id = 0; region_id < space.regions.size(); ++region_id) { + const BedExcludeRegion ®ion = space.regions[region_id]; + if (bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + active_region_ids.emplace_back(region_id); + } + if (active_region_ids.empty()) + return nullptr; + + const auto cached = space.obstacle_cache.find(active_region_ids); + if (cached != space.obstacle_cache.end()) + return cached->second.empty() ? nullptr : &cached->second; + + std::vector active_regions; + active_regions.reserve(active_region_ids.size()); + for (const size_t region_id : active_region_ids) + active_regions.emplace_back(space.regions[region_id]); + + ExPolygons obstacles = active_bed_exclusion_footprints( + active_regions, z_min, z_max, Point(0, 0), m_clearance); + const auto cache_result = space.obstacle_cache.emplace( + std::move(active_region_ids), std::move(obstacles)); + return cache_result.first->second.empty() ? nullptr : &cache_result.first->second; +} + +ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( + const Polyline &travel, + double start_z, + double end_z, + int extruder_id) +{ + Result result; + result.path = travel; + if (travel.points.size() < 2) + return result; + if (extruder_id < 0 || size_t(extruder_id) >= m_spaces.size()) { + result.status = Status::Failed; + result.detail = Detail::UnknownExtruder; + return result; + } + + RoutingSpace &space = m_spaces[size_t(extruder_id)]; + if (space.regions.empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + + const double z_min = std::min(start_z, end_z); + const double z_max = std::max(start_z, end_z); + + // Most travels are nowhere near an exclusion. Reject them using the cheap + // precomputed boxes before unioning and inflating obstacle polygons. + const BoundingBox travel_bbox(travel.points); + bool has_active_z = false; + bool may_intersect = false; + for (size_t region_id = 0; region_id < space.regions.size(); ++region_id) { + const BedExcludeRegion ®ion = space.regions[region_id]; + if (!bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + continue; + has_active_z = true; + if (region_id < space.region_bboxes.size() && space.region_bboxes[region_id].overlap(travel_bbox)) { + may_intersect = true; + break; + } + } + if (!has_active_z) { + result.detail = Detail::NoActiveObstacles; + return result; + } + if (!may_intersect) { + result.detail = Detail::NoIntersection; + return result; + } + + const ExPolygons *active = active_obstacles(space, z_min, z_max); + if (active == nullptr || active->empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + result.active_obstacles = active->size(); + + const Point &start = travel.points.front(); + const Point &end = travel.points.back(); + const bool start_outside_bed = !space.valid_bed.empty() && + !point_in_expolygons(space.valid_bed, start, true); + const bool end_outside_bed = !space.valid_bed.empty() && + !point_in_expolygons(space.valid_bed, end, true); + const ExPolygons *start_obstacles = active_obstacles(space, start_z, start_z); + const ExPolygons *end_obstacles = active_obstacles(space, end_z, end_z); + if ((start_obstacles != nullptr && point_in_expolygons_interior(*start_obstacles, start)) || + (end_obstacles != nullptr && point_in_expolygons_interior(*end_obstacles, end))) { + result.status = Status::EndpointInside; + result.detail = Detail::EndpointInside; + return result; + } + + bool needs_reroute = false; + for (size_t idx = 1; idx < travel.points.size(); ++idx) { + if (segment_enters_expolygons_interior(travel.points[idx - 1], travel.points[idx], *active)) { + needs_reroute = true; + break; + } + } + if (!needs_reroute) { + result.detail = Detail::NoIntersection; + return result; + } + + Polyline path = travel; + bool rerouted = false; + for (size_t iteration = 0; iteration < MAX_REROUTE_ITERATIONS; ++iteration) { + result.iterations = iteration + 1; + bool changed = false; + for (size_t segment_idx = 0; segment_idx + 1 < path.points.size(); ++segment_idx) { + const Point &a = path.points[segment_idx]; + const Point &b = path.points[segment_idx + 1]; + const bool allow_a_outside = start_outside_bed && segment_idx == 0; + const bool allow_b_outside = end_outside_bed && segment_idx + 2 == path.points.size(); + const Polyline segment({a, b}); + if (!routed_polyline_inside_bed( + segment, space.valid_bed, allow_a_outside, allow_b_outside)) { + result.status = Status::Failed; + result.detail = Detail::SegmentOutsideBed; + return result; + } + + const std::optional obstacle_idx = first_intersected_obstacle(a, b, *active); + if (!obstacle_idx) + continue; + + const std::optional detour = detour_around_obstacle( + a, b, (*active)[*obstacle_idx], *active, space.valid_bed, + allow_a_outside, allow_b_outside); + if (!detour) { + result.status = Status::Failed; + result.detail = Detail::DetourFailed; + return result; + } + if (replacement_matches_original_segment(*detour, a, b)) + continue; + + replace_segment(path, segment_idx, *detour); + changed = true; + rerouted = true; + break; + } + + if (!changed) { + path = simplify_path(path, *active, space.valid_bed); + if (!routed_polyline_inside_bed( + path, space.valid_bed, start_outside_bed, end_outside_bed) || + polyline_intersects_obstacles(path, *active)) { + result.status = Status::Failed; + result.detail = Detail::FinalPathInvalid; + return result; + } + result.path = std::move(path); + result.status = rerouted ? Status::Rerouted : Status::Unchanged; + result.detail = rerouted ? Detail::None : Detail::NoIntersection; + return result; + } + } + + result.status = Status::Failed; + result.detail = Detail::IterationLimit; + return result; +} + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp new file mode 100644 index 0000000000..64dca94865 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp @@ -0,0 +1,78 @@ +#pragma once + +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/libslic3r.h" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Polyline.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include +#include +#include + +namespace Slic3r { + +class ExclusionVolumeTravelAvoidance +{ +public: + enum class Status : unsigned char + { + Unchanged, + Rerouted, + EndpointInside, + Failed + }; + + enum class Detail : unsigned char + { + None, + UnknownExtruder, + NoActiveObstacles, + NoIntersection, + EndpointInside, + SegmentOutsideBed, + DetourFailed, + FinalPathInvalid, + IterationLimit + }; + + struct Result + { + Status status { Status::Unchanged }; + Detail detail { Detail::None }; + Polyline path; + size_t active_obstacles { 0 }; + size_t iterations { 0 }; + + bool rerouted() const { return status == Status::Rerouted; } + }; + + void init(const PrintConfig &config, const Vec3d &plate_origin); + void clear(); + + bool empty() const; + + // Input and output are scaled XY points in the active nozzle's generated + // G-code coordinates before GCodeWriter subtracts the plate offset. + Result route(const Polyline &travel, double start_z, double end_z, int extruder_id); + +private: + struct RoutingSpace + { + std::vector regions; + std::vector region_bboxes; + ExPolygons valid_bed; + std::map, ExPolygons> obstacle_cache; + }; + + const ExPolygons *active_obstacles( + RoutingSpace &space, + double z_min, + double z_max); + + std::vector m_spaces; + coord_t m_clearance { 0 }; +}; + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 3512df6ab8..ba22abf4a0 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -1,4 +1,5 @@ #include "libslic3r/ArcFitter.hpp" +#include "ExclusionVolumePathCheck.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/Exception.hpp" @@ -2682,6 +2683,17 @@ void GCodeProcessorResult::reset() { wrapping_exclude_area = Pointfs(); //BBS: add toolpath_outside toolpath_outside = false; + exclusion_volume_path_checked = false; + exclusion_volume_path_conflict = false; + exclusion_volume_travel_conflict = false; + exclusion_volume_extrusion_conflict = false; + exclusion_volume_other_motion_conflict = false; + exclusion_volume_conflict_gcode_id = 0; + exclusion_volume_conflict_move_id = 0; + exclusion_volume_conflict_move_type = EMoveType::Noop; + exclusion_volume_conflict_extruder_id = -1; + exclusion_volume_conflict_region_id = 0; + exclusion_volume_conflict_used_unknown_z = false; //BBS: add label_object_enabled label_object_enabled = false; long_retraction_when_cut = false; @@ -3704,6 +3716,10 @@ void GCodeProcessor::reset() m_start_position = { 0.0f, 0.0f, 0.0f, 0.0f }; m_end_position = { 0.0f, 0.0f, 0.0f, 0.0f }; m_origin = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_axis_position_known = { false, false, false }; + m_axis_origin_known = { true, true, true }; + m_processing_homing_move = false; + m_exclusion_volume_path_checker.clear(); m_cached_position.reset(); m_wiping = false; m_flushing = false; @@ -3916,6 +3932,40 @@ void GCodeProcessor::process_buffer(const std::string &buffer) }); } +void GCodeProcessor::configure_exclusion_volume_path_check(const PrintConfig &config) +{ + m_exclusion_volume_path_checker.configure(config); +} + +GCodeProcessor::PositionState GCodeProcessor::get_current_position() const +{ + PositionState state; + state.position = Vec3d(m_end_position[X], m_end_position[Y], m_end_position[Z]); + state.axis_known = m_axis_position_known; + return state; +} + +void GCodeProcessor::update_exclusion_volume_path_check_result() +{ + m_result.exclusion_volume_path_checked = m_exclusion_volume_path_checker.configured(); + const ExclusionVolumePathCheckResult &check = m_exclusion_volume_path_checker.result(); + m_result.exclusion_volume_path_conflict = check.has_any_conflict; + m_result.exclusion_volume_travel_conflict = check.has_travel_conflict; + m_result.exclusion_volume_extrusion_conflict = check.has_extrusion_conflict; + m_result.exclusion_volume_other_motion_conflict = check.has_other_motion_conflict; + + if (!check.first_hit) + return; + + const ExclusionVolumePathHit &hit = *check.first_hit; + m_result.exclusion_volume_conflict_gcode_id = hit.gcode_id; + m_result.exclusion_volume_conflict_move_id = hit.move_id; + m_result.exclusion_volume_conflict_move_type = static_cast(hit.source_move_type); + m_result.exclusion_volume_conflict_extruder_id = hit.extruder_id; + m_result.exclusion_volume_conflict_region_id = hit.region_id; + m_result.exclusion_volume_conflict_used_unknown_z = hit.used_unknown_z; +} + void GCodeProcessor::finalize(bool post_process) { m_result.z_offset = m_z_offset; @@ -3956,6 +4006,7 @@ void GCodeProcessor::finalize(bool post_process) if (m_enable_pre_heating) run_second_pass_injection(); } + update_exclusion_volume_path_check_result(); //BBS: update slice warning update_slice_warnings(); } @@ -5110,6 +5161,30 @@ void GCodeProcessor::process_G0(const GCodeReader::GCodeLine& line) process_G1(line); } +void GCodeProcessor::update_position_known_from_move( + const std::array, 4> &axes, + const G1DiscretizationOrigin origin) +{ + if (origin != G1DiscretizationOrigin::G1 || m_global_positioning_type != EPositioningType::Absolute) + return; + + for (unsigned char axis = X; axis <= Z; ++axis) { + if (axes[axis].has_value()) + m_axis_position_known[axis] = m_axis_origin_known[axis]; + } +} + +void GCodeProcessor::update_position_known_from_move(const GCodeReader::GCodeLine &line) +{ + if (m_global_positioning_type != EPositioningType::Absolute) + return; + + for (unsigned char axis = X; axis <= Z; ++axis) { + if (line.has(static_cast(axis))) + m_axis_position_known[axis] = m_axis_origin_known[axis]; + } +} + void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line, const std::optional& remaining_internal_g1_lines) { std::array, 4> g1_axes = { std::nullopt, std::nullopt, std::nullopt, std::nullopt }; @@ -5133,6 +5208,7 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line, const std::o void GCodeProcessor::process_G1(const std::array, 4>& axes, const std::optional& feedrate, G1DiscretizationOrigin origin, const std::optional& remaining_internal_g1_lines) { + const std::array start_axis_known = m_axis_position_known; int filament_id = get_filament_id(); int last_filament_id = get_last_filament_id(); float filament_diameter = (static_cast(filament_id) < m_result.filament_diameters.size()) ? m_result.filament_diameters[filament_id] : m_result.filament_diameters.back(); @@ -5182,6 +5258,7 @@ void GCodeProcessor::process_G1(const std::array, 4>& axes for (unsigned char a = X; a <= E; ++a) { m_end_position[a] = extract_absolute_position_on_axis((Axis)a, axes[a], double(area_filament_cross_section)); } + update_position_known_from_move(axes, origin); // updates feedrate from line, if present if (feedrate.has_value()) @@ -5203,6 +5280,40 @@ void GCodeProcessor::process_G1(const std::array, 4>& axes const float delta_xyz = std::sqrt(sqr(delta_pos[X]) + sqr(delta_pos[Y]) + sqr(delta_pos[Z])); m_travel_dist = delta_xyz; + if (!m_processing_homing_move) { + std::optional exclusion_motion_type; + switch (type) { + case EMoveType::Travel: + exclusion_motion_type = ExclusionVolumeMotionType::Travel; + break; + case EMoveType::Extrude: + case EMoveType::Wipe: + exclusion_motion_type = ExclusionVolumeMotionType::Extrude; + break; + case EMoveType::Retract: + case EMoveType::Unretract: + exclusion_motion_type = ExclusionVolumeMotionType::Other; + break; + default: + break; + } + + if (exclusion_motion_type) { + m_exclusion_volume_path_checker.check_motion( + Vec3d(m_start_position[X], m_start_position[Y], m_start_position[Z]), + Vec3d(m_end_position[X], m_end_position[Y], m_end_position[Z]), + start_axis_known[X] && start_axis_known[Y], + m_axis_position_known[X] && m_axis_position_known[Y], + start_axis_known[Z], + m_axis_position_known[Z], + get_extruder_id(false), + *exclusion_motion_type, + static_cast(type), + m_line_id, + m_result.moves.size()); + } + } + if (type == EMoveType::Extrude) { float volume_extruded_filament = area_filament_cross_section * delta_pos[E]; float area_toolpath_cross_section = volume_extruded_filament / delta_xyz; @@ -5234,7 +5345,15 @@ void GCodeProcessor::process_G1(const std::array, 4>& axes if (origin == G1DiscretizationOrigin::G1) m_extruded_last_z = m_end_position[Z]; - m_options_z_corrector.update(m_height); + // The queued blocks of the moves after the erased one follow them down the list. + if (const std::optional erased = m_options_z_corrector.update(m_height)) { + for (TimeMachine& machine : m_time_processor.machines) { + for (TimeBlock& block : machine.blocks) { + if (block.move_id > *erased) + --block.move_id; + } + } + } if (m_forced_width > 0.0f) m_width = m_forced_width; @@ -6230,6 +6349,10 @@ void GCodeProcessor::process_G2_G3(const GCodeReader::GCodeLine& line, bool cloc m_start_position = m_end_position; // this is required because we are skipping the call to process_gcode_line() internal_only_g1_line(adjust_target(end_position, prev_target), arc.delta_z() != 0.0, (segments == 1) ? feedrate : std::nullopt, extrusion); } + + // Internal linearized arc segments inherit the arc's starting certainty. + // Only the original absolute command may establish a newly known endpoint. + update_position_known_from_move(line); } //BBS @@ -6303,22 +6426,56 @@ void GCodeProcessor::process_G23(const GCodeReader::GCodeLine& line) store_move_vertex(EMoveType::Unretract); } +static std::array g28_homed_axes(const GCodeReader::GCodeLine &line) +{ + std::array homed { false, false, false }; + std::string_view raw = line.raw(); + const size_t command_end = raw.find_first_of(" \t;"); + size_t pos = command_end == std::string_view::npos ? raw.size() : command_end; + + while (pos < raw.size()) { + pos = raw.find_first_not_of(" \t", pos); + if (pos == std::string_view::npos || raw[pos] == ';') + break; + const size_t end = raw.find_first_of(" \t;", pos); + const std::string_view word = raw.substr(pos, end == std::string_view::npos ? raw.size() - pos : end - pos); + + const bool compact_axes = !word.empty() && std::all_of(word.begin(), word.end(), [](const char c) { + const char upper = static_cast(std::toupper(static_cast(c))); + return upper == 'X' || upper == 'Y' || upper == 'Z'; + }); + if (compact_axes) { + for (const char c : word) + homed[static_cast(std::toupper(static_cast(c)) - 'X')] = true; + } else if (!word.empty()) { + const char axis = static_cast(std::toupper(static_cast(word.front()))); + const bool numeric_axis_word = word.size() > 1 && + (std::isdigit(static_cast(word[1])) || word[1] == '+' || word[1] == '-' || word[1] == '.'); + if (axis >= 'X' && axis <= 'Z' && numeric_axis_word) + homed[static_cast(axis - 'X')] = true; + } + + if (end == std::string_view::npos || raw[end] == ';') + break; + pos = end; + } + return homed; +} + void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line) { std::string_view cmd = line.cmd(); std::string new_line_raw = { cmd.data(), cmd.size() }; - bool found = false; - if (line.has('X')) { + const std::array homed = g28_homed_axes(line); + const bool found = std::any_of(homed.begin(), homed.end(), [](const bool value) { return value; }); + if (homed[X]) { new_line_raw += " X0"; - found = true; } - if (line.has('Y')) { + if (homed[Y]) { new_line_raw += " Y0"; - found = true; } - if (line.has('Z')) { + if (homed[Z]) { new_line_raw += " Z0"; - found = true; } if (!found) new_line_raw += " X0 Y0 Z0"; @@ -6326,7 +6483,19 @@ void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line) GCodeReader::GCodeLine new_gline; GCodeReader reader; reader.parse_line(new_line_raw, [&](GCodeReader& reader, const GCodeReader::GCodeLine& gline) { new_gline = gline; }); + m_processing_homing_move = true; process_G1(new_gline); + m_processing_homing_move = false; + + // G28's physical endpoint is printer-specific even though the preview uses + // zero. Wait for a subsequent explicit absolute coordinate before checking + // a path from any homed axis. + for (unsigned char axis = X; axis <= Z; ++axis) { + if (!found || homed[axis]) { + m_axis_position_known[axis] = false; + m_axis_origin_known[axis] = true; + } + } } void GCodeProcessor::process_G90(const GCodeReader::GCodeLine& line) @@ -6345,16 +6514,19 @@ void GCodeProcessor::process_G92(const GCodeReader::GCodeLine& line) bool any_found = false; if (line.has_x()) { + m_axis_origin_known[X] = m_axis_position_known[X]; m_origin[X] = m_end_position[X] - line.x() * lengths_scale_factor; any_found = true; } if (line.has_y()) { + m_axis_origin_known[Y] = m_axis_position_known[Y]; m_origin[Y] = m_end_position[Y] - line.y() * lengths_scale_factor; any_found = true; } if (line.has_z()) { + m_axis_origin_known[Z] = m_axis_position_known[Z]; m_origin[Z] = m_end_position[Z] - line.z() * lengths_scale_factor; any_found = true; // Belt only: the start G-code's purge-blob advance + G92 Z0 resets leave a constant @@ -6379,6 +6551,8 @@ void GCodeProcessor::process_G92(const GCodeReader::GCodeLine& line) // The G92 may be called for axes that PrusaSlicer does not recognize, for example see GH issue #3510, // where G92 A0 B0 is called although the extruder axis is till E. for (unsigned char a = X; a <= E; ++a) { + if (a <= Z) + m_axis_origin_known[a] = m_axis_position_known[a]; m_origin[a] = m_end_position[a]; } } @@ -7958,6 +8132,7 @@ void GCodeProcessor::calculate_time(GCodeProcessorResult& result, size_t keep_la it->second : block.move_id + (unsigned int)inserted_actual_speed_moves_count; } } + m_options_z_corrector.on_moves_inserted(m_actual_speed_id_map); } void GCodeProcessor::simulate_st_synchronize(float additional_time, EMoveType target_move_type) diff --git a/src/libslic3r/GCode/GCodeProcessor.hpp b/src/libslic3r/GCode/GCodeProcessor.hpp index b1fc911104..151faa10cb 100644 --- a/src/libslic3r/GCode/GCodeProcessor.hpp +++ b/src/libslic3r/GCode/GCodeProcessor.hpp @@ -13,11 +13,13 @@ #include "libslic3r/PrintConfig.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/MultiNozzleUtils.hpp" +#include "libslic3r/GCode/ExclusionVolumePathCheck.hpp" #include "libslic3r/GCode/MachineFrameTransform.hpp" #include #include #include +#include #include #include #include @@ -325,6 +327,17 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; std::vector extruder_heights; //BBS: add toolpath_outside bool toolpath_outside; + bool exclusion_volume_path_checked { false }; + bool exclusion_volume_path_conflict { false }; + bool exclusion_volume_travel_conflict { false }; + bool exclusion_volume_extrusion_conflict { false }; + bool exclusion_volume_other_motion_conflict { false }; + unsigned int exclusion_volume_conflict_gcode_id { 0 }; + size_t exclusion_volume_conflict_move_id { 0 }; + EMoveType exclusion_volume_conflict_move_type { EMoveType::Noop }; + int exclusion_volume_conflict_extruder_id { -1 }; + size_t exclusion_volume_conflict_region_id { 0 }; + bool exclusion_volume_conflict_used_unknown_z { false }; //BBS: add object_label_enabled bool label_object_enabled; //BBS : extra retraction when change filament,experiment func @@ -411,6 +424,17 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; bed_exclude_area = std::forward(other).bed_exclude_area; wrapping_exclude_area = std::forward(other).wrapping_exclude_area; toolpath_outside = std::forward(other).toolpath_outside; + exclusion_volume_path_checked = other.exclusion_volume_path_checked; + exclusion_volume_path_conflict = other.exclusion_volume_path_conflict; + exclusion_volume_travel_conflict = other.exclusion_volume_travel_conflict; + exclusion_volume_extrusion_conflict = other.exclusion_volume_extrusion_conflict; + exclusion_volume_other_motion_conflict = other.exclusion_volume_other_motion_conflict; + exclusion_volume_conflict_gcode_id = other.exclusion_volume_conflict_gcode_id; + exclusion_volume_conflict_move_id = other.exclusion_volume_conflict_move_id; + exclusion_volume_conflict_move_type = other.exclusion_volume_conflict_move_type; + exclusion_volume_conflict_extruder_id = other.exclusion_volume_conflict_extruder_id; + exclusion_volume_conflict_region_id = other.exclusion_volume_conflict_region_id; + exclusion_volume_conflict_used_unknown_z = other.exclusion_volume_conflict_used_unknown_z; label_object_enabled = std::forward(other).label_object_enabled; long_retraction_when_cut = std::forward(other).long_retraction_when_cut; timelapse_warning_code = std::forward(other).timelapse_warning_code; @@ -1076,18 +1100,34 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; m_custom_gcode_per_print_z_id = m_result.custom_gcode_per_print_z.size() - 1; } - void update(float height) { - if (!m_move_id.has_value() || !m_custom_gcode_per_print_z_id.has_value()) + // The time pass inserts actual speed moves in front of the moves of its blocks, and the stored + // vertex has no block of its own, so it shifts with every insertion made before it. + void on_moves_inserted(const std::vector>& id_map) { + if (!m_move_id.has_value()) return; + auto it = std::lower_bound(id_map.begin(), id_map.end(), *m_move_id, + [](const std::pair& entry, size_t id) { return entry.first < id; }); + if (it != id_map.begin()) { + --it; + *m_move_id += it->second - it->first; + } + } - const Vec3f position = m_result.moves.back().position; + // Returns the index of the move erased from the list, if any. + std::optional update(float height) { + if (!m_move_id.has_value() || !m_custom_gcode_per_print_z_id.has_value()) + return std::nullopt; - GCodeProcessorResult::MoveVertex& move = m_result.moves.emplace_back(m_result.moves[*m_move_id]); + const Vec3f position = m_result.moves.back().position; + const size_t erased = *m_move_id; + + GCodeProcessorResult::MoveVertex& move = m_result.moves.emplace_back(m_result.moves[erased]); move.position = position; move.height = height; - m_result.moves.erase(m_result.moves.begin() + *m_move_id); + m_result.moves.erase(m_result.moves.begin() + erased); m_result.custom_gcode_per_print_z[*m_custom_gcode_per_print_z_id].print_z = position.z(); reset(); + return erased; } void reset() { @@ -1189,6 +1229,10 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; AxisCoords m_start_position; // mm AxisCoords m_end_position; // mm AxisCoords m_origin; // mm + std::array m_axis_position_known { false, false, false }; + std::array m_axis_origin_known { true, true, true }; + bool m_processing_homing_move { false }; + ExclusionVolumePathChecker m_exclusion_volume_path_checker; CachedPosition m_cached_position; bool m_wiping; bool m_flushing; // mark a section with real flush @@ -1338,6 +1382,15 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; static unsigned int s_result_id; public: + struct PositionState + { + Vec3d position { Vec3d::Zero() }; + std::array axis_known { false, false, false }; + + bool has_known_xy() const { return axis_known[X] && axis_known[Y]; } + bool has_known_z() const { return axis_known[Z]; } + }; + GCodeProcessor(); void init_filament_maps_and_nozzle_type_when_import_only_gcode(); // Reprocessing an already-generated g-code (from-previous / imported g-code) does not rebuild @@ -1355,6 +1408,7 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; const std::vector &filament_map, const std::vector>& unprintable_filament_types ); void apply_config(const PrintConfig& config); + void configure_exclusion_volume_path_check(const PrintConfig &config); void set_print(Print* print) { m_print = print; } // Locates extrusions in the objects and bodies it numbers, those objects listed beforehand. void set_mass_locator(MassLocator locator, std::vector objects) @@ -1381,6 +1435,7 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; const GCodeProcessorResult& get_result() const { return m_result; } GCodeProcessorResult& result() { return m_result; } GCodeProcessorResult&& extract_result() { return std::move(m_result); } + PositionState get_current_position() const; // Load a G-code into a stand-alone G-code viewer. // throws CanceledException through print->throw_if_canceled() (sent by the caller as callback). @@ -1439,6 +1494,9 @@ inline constexpr float DEFAULT_FILAMENT_DENSITY = 1.245f; void process_G1(const std::array, 4>& axes = { std::nullopt, std::nullopt, std::nullopt, std::nullopt }, const std::optional& feedrate = std::nullopt, G1DiscretizationOrigin origin = G1DiscretizationOrigin::G1, const std::optional& remaining_internal_g1_lines = std::nullopt); + void update_position_known_from_move(const std::array, 4> &axes, G1DiscretizationOrigin origin); + void update_position_known_from_move(const GCodeReader::GCodeLine &line); + void update_exclusion_volume_path_check_result(); // Arc Move void process_G2_G3(const GCodeReader::GCodeLine& line, bool clockwise); diff --git a/src/libslic3r/GCode/TimelapsePosPicker.cpp b/src/libslic3r/GCode/TimelapsePosPicker.cpp index 84b6677b94..2c18895d9a 100644 --- a/src/libslic3r/GCode/TimelapsePosPicker.cpp +++ b/src/libslic3r/GCode/TimelapsePosPicker.cpp @@ -98,9 +98,10 @@ namespace Slic3r { m_plate_height = unscale_(bed_bbox.max.y()); m_plate_width = unscale_(bed_bbox.max.x()); - Polygon bed_exclude_area; - for (size_t idx = 0; idx < config.bed_exclude_area.values.size(); ++idx) - bed_exclude_area.points.emplace_back(coord_t(scale_(config.bed_exclude_area.values[idx].x())), coord_t(scale_(config.bed_exclude_area.values[idx].y()))); + // Timelapse positions are selected in the bed plane. Use the resolved + // bed-level footprints instead of the legacy flat point array, which + // cannot represent multiple or per-nozzle exclusion polygons. + const Polygons bed_exclude_areas = get_bed_excluded_area(config); Point base_wp_pt = print->get_fake_wipe_tower().pos.cast(); base_wp_pt = Point{ scale_(base_wp_pt.x()),scale_(base_wp_pt.y()) }; @@ -120,7 +121,7 @@ namespace Slic3r { wipe_tower_area = expand_object_projection(wipe_tower_area, m_print_seq == PrintSequence::ByObject); for (size_t idx = 0; idx < extruder_count; ++idx) { - ExPolygons printable_area = diff_ex(diff(m_bed_polygon, bed_exclude_area), { wipe_tower_area }); + ExPolygons printable_area = diff_ex(diff(Polygons{ m_bed_polygon }, bed_exclude_areas), { wipe_tower_area }); if (idx < config.extruder_printable_area.size()) { Polygon extruder_printable_area; for (size_t j = 0; j < config.extruder_printable_area.values[idx].size(); ++j) @@ -681,4 +682,4 @@ namespace Slic3r { return true; } -} \ No newline at end of file +} diff --git a/src/libslic3r/GCode/WipeTower.cpp b/src/libslic3r/GCode/WipeTower.cpp index b72e924da4..0e57c41804 100644 --- a/src/libslic3r/GCode/WipeTower.cpp +++ b/src/libslic3r/GCode/WipeTower.cpp @@ -2003,7 +2003,7 @@ WipeTower::WipeTower(const PrintConfig& config, int plate_idx, Vec3d plate_origi m_flat_ironing(config.prime_tower_flat_ironing.value), m_enable_tower_interface_features(config.enable_tower_interface_features.value), m_physical_extruder_map(config.physical_extruder_map.values), - m_enable_arc_fitting(config.enable_arc_fitting.value) + m_enable_arc_fitting(config.enable_arc_fitting.value == ArcFittingMode::Enabled) // Orca: has_filament_switcher is a device-set dynamic key, not a PrintConfig member; // it is pushed in from Print via set_has_filament_switcher() instead of read here. { diff --git a/src/libslic3r/GCode/WipeTower2.cpp b/src/libslic3r/GCode/WipeTower2.cpp index 21556e65ba..83729a72a1 100644 --- a/src/libslic3r/GCode/WipeTower2.cpp +++ b/src/libslic3r/GCode/WipeTower2.cpp @@ -1062,7 +1062,7 @@ WipeTower2::WipeTower2(const PrintConfig& config, const PrintRegionConfig& defau m_perimeter_speed(default_region_config.inner_wall_speed.get_at(get_extruder_index(config, (unsigned int)initial_tool))), m_current_tool(initial_tool), wipe_volumes(wiping_matrix), m_wipe_tower_max_purge_speed(float(config.wipe_tower_max_purge_speed)), - m_enable_arc_fitting(config.enable_arc_fitting), + m_enable_arc_fitting(config.enable_arc_fitting.value == ArcFittingMode::Enabled), m_used_fillet(config.wipe_tower_fillet_wall), m_rib_width(config.wipe_tower_rib_width), m_extra_rib_length(config.wipe_tower_extra_rib_length), diff --git a/src/libslic3r/GCodeWriter.cpp b/src/libslic3r/GCodeWriter.cpp index 805e6e2f52..4eed23d7d8 100644 --- a/src/libslic3r/GCodeWriter.cpp +++ b/src/libslic3r/GCodeWriter.cpp @@ -1140,6 +1140,19 @@ std::string GCodeWriter::travel_to_xyz(const Vec3d &point, const std::string &co return out_string; } +std::pair GCodeWriter::planned_travel_z(const Vec3d &point, const bool force_z) const +{ + double destination_z = point.z(); + if (std::abs(m_to_lift) > EPSILON) { + if ((!this->is_current_position_clear() || m_pos != point) && + m_to_lift + m_pos.z() > point.z()) + destination_z = m_to_lift + m_pos.z(); + } else if (!force_z && !this->will_move_z(point.z())) { + destination_z = m_pos.z(); + } + return { m_pos.z(), destination_z }; +} + std::string GCodeWriter::travel_to_z(double z, const std::string &comment, bool force) { /* If target Z is lower than current Z but higher than nominal Z @@ -1202,7 +1215,7 @@ std::string GCodeWriter::_spiral_travel_to_z(double z, const Vec2d &ij_offset, c : this->config.travel_speed.get_at(m_cached_extruder_idx); } - if (!this->config.enable_arc_fitting) { // Orca: if arc fitting is disabled, approximate the arc with small linear segments + if (this->config.enable_arc_fitting.value == ArcFittingMode::Disabled) { // Orca: if arc fitting is disabled, approximate the arc with small linear segments const double z_start = m_pos(2); // starting Z height const double px = m_pos(0) - m_x_offset; // take plate offset into consideration diff --git a/src/libslic3r/GCodeWriter.hpp b/src/libslic3r/GCodeWriter.hpp index fcbd68b282..02562fa651 100644 --- a/src/libslic3r/GCodeWriter.hpp +++ b/src/libslic3r/GCodeWriter.hpp @@ -97,6 +97,9 @@ public: double get_current_speed() const { return m_current_speed;} std::string travel_to_xy(const Vec2d &point, const std::string &comment = std::string()); std::string travel_to_xyz(const Vec3d &point, const std::string &comment = std::string(), bool force_z = false); + // Physical Z range which travel_to_xyz() will emit without mutating writer state. + // This includes an existing lift or a pending lazy lift. + std::pair planned_travel_z(const Vec3d &point, bool force_z = false) const; std::string travel_to_z(double z, const std::string &comment = std::string(), bool force = false); bool will_move_z(double z) const; std::string extrude_to_xy(const Vec2d &point, double dE, const std::string &comment = std::string(), bool force_no_extrusion = false); diff --git a/src/libslic3r/LayOnFace.cpp b/src/libslic3r/LayOnFace.cpp index a66139a17b..f567645eb7 100644 --- a/src/libslic3r/LayOnFace.cpp +++ b/src/libslic3r/LayOnFace.cpp @@ -213,13 +213,29 @@ int find_plane_at_point(const std::vector &planes, const Transfo return -1; } +Transform3d lay_on_face_rotation(const Vec3d &normal, const Transform3d &instance_matrix_no_offset) +{ + // Normal in instance coordinates: a normal transforms by the inverse transpose. + const Vec3d tnormal = (instance_matrix_no_offset.matrix().block(0, 0, 3, 3).inverse().transpose() * normal).normalized(); + const Vec3d down = -Vec3d::UnitZ(); + + // A face already pointing straight up needs a half turn, and every horizontal axis does + // that equally well. setFromTwoVectors() resolves the choice through an SVD whose null + // space is the whole XY plane, so the axis follows rounding noise and the object lands at + // an arbitrary angle in the plate plane. Turn it over about X instead, which keeps the + // footprint the object already had. + if (tnormal.dot(down) < -1. + 1e-9) + return Transform3d(Eigen::AngleAxisd(PI, Vec3d::UnitX())); + + return Transform3d(Eigen::Quaterniond().setFromTwoVectors(tnormal, down)); +} + void lay_on_face(ModelObject &object, size_t instance_idx, const Vec3d &normal) { ModelInstance &instance = *object.instances[instance_idx]; const Geometry::Transformation &trafo = instance.get_transformation(); - // Same rotation as Selection::flattening_rotate(): turn the transformed normal to point down. - const Vec3d tnormal = trafo.get_matrix().matrix().block(0, 0, 3, 3).inverse().transpose() * normal; - const Transform3d rotation = Transform3d(Eigen::Quaterniond().setFromTwoVectors(tnormal, -Vec3d::UnitZ())); + // Same rotation as Selection::flattening_rotate(), which the gizmo uses. + const Transform3d rotation = lay_on_face_rotation(normal, trafo.get_matrix_no_offset()); instance.set_transformation(Geometry::Transformation(trafo.get_offset_matrix() * rotation * trafo.get_matrix_no_offset())); // Drop this instance only: ensure_on_bed() skips instances without auto_drop and measures the first instance. object.translate_instance(instance_idx, -object.instance_bounding_box(instance_idx).min.z() * Vec3d::UnitZ()); diff --git a/src/libslic3r/LayOnFace.hpp b/src/libslic3r/LayOnFace.hpp index 6a9242e5c6..c02c9f6eeb 100644 --- a/src/libslic3r/LayOnFace.hpp +++ b/src/libslic3r/LayOnFace.hpp @@ -46,4 +46,10 @@ int find_plane_at_point(const std::vector &planes, const Transfo // the gizmo applies, then drops the instance so its lowest point is at z = 0. void lay_on_face(ModelObject &object, size_t instance_idx, const Vec3d &normal); +// The rotation that turns `normal` (object coordinates) to point down, given the instance's +// rotation, scale and mirror. A face that already points straight up is turned over about X: +// the axis setFromTwoVectors() picks there is arbitrary, and it lands the object at a random +// angle in the plate plane. +Transform3d lay_on_face_rotation(const Vec3d &normal, const Transform3d &instance_matrix_no_offset); + } // namespace Slic3r diff --git a/src/libslic3r/Layer.cpp b/src/libslic3r/Layer.cpp index 8e58a5e671..849b57e4b3 100644 --- a/src/libslic3r/Layer.cpp +++ b/src/libslic3r/Layer.cpp @@ -380,7 +380,7 @@ void Layer::simplify_support_path(ExtrusionPath * path) { const auto &print_config = this->object()->print()->config(); const bool spiral_mode = print_config.spiral_mode; - const bool enable_arc_fitting = print_config.enable_arc_fitting; + const bool enable_arc_fitting = print_config.enable_arc_fitting.value == ArcFittingMode::Enabled; const auto scaled_resolution = scaled(print_config.resolution.value); if (enable_arc_fitting && @@ -395,7 +395,7 @@ void Layer::simplify_support_multi_path(ExtrusionMultiPath* multipath) { const auto &print_config = this->object()->print()->config(); const bool spiral_mode = print_config.spiral_mode; - const bool enable_arc_fitting = print_config.enable_arc_fitting; + const bool enable_arc_fitting = print_config.enable_arc_fitting.value == ArcFittingMode::Enabled; const auto scaled_resolution = scaled(print_config.resolution.value); for (size_t i = 0; i < multipath->paths.size(); ++i) { @@ -412,7 +412,7 @@ void Layer::simplify_support_loop(ExtrusionLoop* loop) { const auto &print_config = this->object()->print()->config(); const bool spiral_mode = print_config.spiral_mode; - const bool enable_arc_fitting = print_config.enable_arc_fitting; + const bool enable_arc_fitting = print_config.enable_arc_fitting.value == ArcFittingMode::Enabled; const auto scaled_resolution = scaled(print_config.resolution.value); for (size_t i = 0; i < loop->paths.size(); ++i) { diff --git a/src/libslic3r/LayerRegion.cpp b/src/libslic3r/LayerRegion.cpp index eef3f90c87..74ef2b7494 100644 --- a/src/libslic3r/LayerRegion.cpp +++ b/src/libslic3r/LayerRegion.cpp @@ -1101,16 +1101,13 @@ void LayerRegion::simplify_entity_collection(ExtrusionEntityCollection* entity_c void LayerRegion::simplify_path(ExtrusionPath* path) { const auto &print_config = this->layer()->object()->print()->config(); - const bool spiral_mode = print_config.spiral_mode; - const bool enable_arc_fitting = print_config.enable_arc_fitting; + const ArcFittingMode arc_fitting = print_config.enable_arc_fitting.value; + const bool is_sparse_infill = path->role() == erInternalInfill; const auto scaled_resolution = scaled(print_config.resolution.value); - if (enable_arc_fitting && - !spiral_mode) { - if (path->role() == erInternalInfill) - path->simplify_by_fitting_arc(SCALED_SPARSE_INFILL_RESOLUTION); - else - path->simplify_by_fitting_arc(scaled_resolution); + if (!print_config.spiral_mode && + (arc_fitting == ArcFittingMode::Enabled || (arc_fitting == ArcFittingMode::SparseInfill && is_sparse_infill))) { + path->simplify_by_fitting_arc(is_sparse_infill ? SCALED_SPARSE_INFILL_RESOLUTION : scaled_resolution); } else { path->simplify(scaled_resolution); } @@ -1118,42 +1115,14 @@ void LayerRegion::simplify_path(ExtrusionPath* path) void LayerRegion::simplify_multi_path(ExtrusionMultiPath* multipath) { - const auto &print_config = this->layer()->object()->print()->config(); - const bool spiral_mode = print_config.spiral_mode; - const bool enable_arc_fitting = print_config.enable_arc_fitting; - const auto scaled_resolution = scaled(print_config.resolution.value); - - for (size_t i = 0; i < multipath->paths.size(); ++i) { - if (enable_arc_fitting && - !spiral_mode) { - if (multipath->paths[i].role() == erInternalInfill) - multipath->paths[i].simplify_by_fitting_arc(SCALED_SPARSE_INFILL_RESOLUTION); - else - multipath->paths[i].simplify_by_fitting_arc(scaled_resolution); - } else { - multipath->paths[i].simplify(scaled_resolution); - } - } + for (ExtrusionPath &path : multipath->paths) + this->simplify_path(&path); } void LayerRegion::simplify_loop(ExtrusionLoop* loop) { - const auto &print_config = this->layer()->object()->print()->config(); - const bool spiral_mode = print_config.spiral_mode; - const bool enable_arc_fitting = print_config.enable_arc_fitting; - const auto scaled_resolution = scaled(print_config.resolution.value); - - for (size_t i = 0; i < loop->paths.size(); ++i) { - if (enable_arc_fitting && - !spiral_mode) { - if (loop->paths[i].role() == erInternalInfill) - loop->paths[i].simplify_by_fitting_arc(SCALED_SPARSE_INFILL_RESOLUTION); - else - loop->paths[i].simplify_by_fitting_arc(scaled_resolution); - } else { - loop->paths[i].simplify(scaled_resolution); - } - } + for (ExtrusionPath &path : loop->paths) + this->simplify_path(&path); } } diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index aea1b2be36..c4cff42a64 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -17,6 +17,7 @@ #include "SLA/SupportPoint.hpp" #include "TextureDisplacement.hpp" #include "libslic3r.h" +#include "AABBTreeIndirect.hpp" #include "BuildVolume.hpp" #include "TexturePainting.hpp" #include "Format/AssimpImport.hpp" @@ -29,6 +30,7 @@ #include "TriangleMeshSlicer.hpp" #include "TriangleSelector.hpp" #include "MaterialType.hpp" +#include "Tesselate.hpp" #include "MeshRepair.hpp" #include "Format/AMF.hpp" @@ -39,6 +41,7 @@ #include "FaceDetector.hpp" #include "libslic3r/Geometry/ConvexHull.hpp" +#include "ClipperUtils.hpp" #include #include @@ -61,6 +64,7 @@ #include "SVG.hpp" #include +#include #include #include #include @@ -3241,6 +3245,9 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf //auto print_config = print.config(); //printSpeedMap.bed_poly.points = get_bed_shape(*(wxGetApp().plater()->config())); printSpeedMap.bed_poly.points = get_bed_shape(config); + // Collision volumes are additive to the legacy bed keep-out. Preserve the + // established printable-bed polygon so bed-edge and legacy-area brim + // clipping continue to work when collision volumes are also configured. Pointfs excluse_area_points = print_config.bed_exclude_area.values; Polygons exclude_polys; Polygon exclude_poly; @@ -3252,7 +3259,8 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf exclude_poly.points.clear(); } } - printSpeedMap.bed_poly = diff({ printSpeedMap.bed_poly }, exclude_polys)[0]; + if (!exclude_polys.empty()) + printSpeedMap.bed_poly = diff({ printSpeedMap.bed_poly }, exclude_polys)[0]; } // find temperature of heatend and bed and matierial of an given extruder @@ -3548,6 +3556,316 @@ Polygon ModelInstance::convex_hull_2d() return convex_hull; } +namespace { + +struct ExclusionPrismFootprintTriangle +{ + std::array vertices; + Vec2d min = Vec2d::Zero(); + Vec2d max = Vec2d::Zero(); +}; + +static double cross_2d(const Vec2d &a, const Vec2d &b) +{ + return a.x() * b.y() - a.y() * b.x(); +} + +template +static std::vector clip_polygon_by_signed_distance(const std::vector &input, DistanceFn distance) +{ + constexpr double clip_epsilon = 1e-8; + constexpr double duplicate_epsilon_sq = 1e-16; + + std::vector output; + if (input.empty()) + return output; + + auto append_point = [&output](const Vec3d &point) { + if (output.empty() || (output.back() - point).squaredNorm() > duplicate_epsilon_sq) + output.emplace_back(point); + }; + + Vec3d prev = input.back(); + double prev_distance = distance(prev); + bool prev_inside = prev_distance >= -clip_epsilon; + for (const Vec3d &curr : input) { + const double curr_distance = distance(curr); + const bool curr_inside = curr_distance >= -clip_epsilon; + + if (curr_inside != prev_inside) { + const double denom = prev_distance - curr_distance; + if (std::abs(denom) > clip_epsilon) { + const double t = prev_distance / denom; + append_point(prev + t * (curr - prev)); + } + } + if (curr_inside) + append_point(curr); + + prev = curr; + prev_distance = curr_distance; + prev_inside = curr_inside; + } + + if (output.size() > 1 && (output.front() - output.back()).squaredNorm() <= duplicate_epsilon_sq) + output.pop_back(); + + return output; +} + +static std::vector triangulated_prism_footprints(const Polygon &polygon) +{ + std::vector out; + if (polygon.points.size() < 3) + return out; + + ExPolygon expolygon; + expolygon.contour = polygon; + expolygon.contour.make_counter_clockwise(); + + std::vector triangles = triangulate_expolygon_2d(expolygon, NORMALS_UP); + if (triangles.empty()) { + triangles.reserve((polygon.points.size() - 2) * 3); + const Vec2d first(unscale(polygon.points.front().x()), unscale(polygon.points.front().y())); + for (size_t i = 1; i + 1 < polygon.points.size(); ++i) { + triangles.emplace_back(first); + triangles.emplace_back(unscale(polygon.points[i].x()), unscale(polygon.points[i].y())); + triangles.emplace_back(unscale(polygon.points[i + 1].x()), unscale(polygon.points[i + 1].y())); + } + } + + out.reserve(triangles.size() / 3); + for (size_t i = 0; i + 2 < triangles.size(); i += 3) { + ExclusionPrismFootprintTriangle tri; + tri.vertices = { triangles[i], triangles[i + 1], triangles[i + 2] }; + + const double area = cross_2d(tri.vertices[1] - tri.vertices[0], tri.vertices[2] - tri.vertices[0]); + if (std::abs(area) <= EPSILON) + continue; + if (area < 0.0) + std::swap(tri.vertices[1], tri.vertices[2]); + + tri.min = tri.vertices[0].cwiseMin(tri.vertices[1]).cwiseMin(tri.vertices[2]); + tri.max = tri.vertices[0].cwiseMax(tri.vertices[1]).cwiseMax(tri.vertices[2]); + out.emplace_back(std::move(tri)); + } + + return out; +} + +static bool triangle_bbox_intersects_prism_footprint(const Vec3d &p0, const Vec3d &p1, const Vec3d &p2, const ExclusionPrismFootprintTriangle &footprint) +{ + constexpr double bbox_epsilon = 1e-8; + const double tri_min_x = std::min({ p0.x(), p1.x(), p2.x() }); + const double tri_max_x = std::max({ p0.x(), p1.x(), p2.x() }); + const double tri_min_y = std::min({ p0.y(), p1.y(), p2.y() }); + const double tri_max_y = std::max({ p0.y(), p1.y(), p2.y() }); + + return tri_max_x >= footprint.min.x() - bbox_epsilon && + tri_min_x <= footprint.max.x() + bbox_epsilon && + tri_max_y >= footprint.min.y() - bbox_epsilon && + tri_min_y <= footprint.max.y() + bbox_epsilon; +} + +static std::vector clip_model_triangle_to_prism( + const Vec3d &p0, + const Vec3d &p1, + const Vec3d &p2, + const double z_min, + const double z_max, + const ExclusionPrismFootprintTriangle &footprint) +{ + std::vector clipped = { p0, p1, p2 }; + clipped = clip_polygon_by_signed_distance(clipped, [z_min](const Vec3d &p) { return p.z() - z_min; }); + clipped = clip_polygon_by_signed_distance(clipped, [z_max](const Vec3d &p) { return z_max - p.z(); }); + + for (size_t i = 0; i < footprint.vertices.size() && clipped.size() >= 3; ++i) { + const Vec2d &a = footprint.vertices[i]; + const Vec2d &b = footprint.vertices[(i + 1) % footprint.vertices.size()]; + const Vec2d edge = b - a; + clipped = clip_polygon_by_signed_distance(clipped, [a, edge](const Vec3d &p) { + return cross_2d(edge, Vec2d(p.x() - a.x(), p.y() - a.y())); + }); + } + + return clipped; +} + +static double polygon_3d_area2(const std::vector &polygon) +{ + if (polygon.size() < 3) + return 0.0; + + Vec3d normal = Vec3d::Zero(); + for (size_t i = 1; i + 1 < polygon.size(); ++i) + normal += (polygon[i] - polygon.front()).cross(polygon[i + 1] - polygon.front()); + return normal.norm(); +} + +static void append_clipped_polygon(indexed_triangle_set &out, const std::vector &polygon) +{ + if (polygon.size() < 3) + return; + + // Do not reserve exact capacity here. This helper may be called for many + // clipped fragments, so let std::vector grow amortized through emplace_back. + const int base = int(out.vertices.size()); + for (const Vec3d &point : polygon) + out.vertices.emplace_back(point.cast()); + + for (size_t i = 1; i + 1 < polygon.size(); ++i) { + stl_triangle_vertex_indices tri; + tri << base, base + int(i), base + int(i + 1); + out.indices.emplace_back(tri); + } +} + +static bool mesh_contains_point_linear(const indexed_triangle_set &its, const Vec3d &point) +{ + constexpr double ray_epsilon = 1e-6; + const Vec3d ray_direction = Vec3d::UnitX(); + double nearest_hit_distance = std::numeric_limits::infinity(); + size_t nearest_face = size_t(-1); + + for (size_t face_id = 0; face_id < its.indices.size(); ++face_id) { + const stl_triangle_vertex_indices &face = its.indices[face_id]; + double distance; + double u; + double v; + if (AABBTreeIndirect::detail::intersect_triangle( + point, ray_direction, + its.vertices[face[0]], its.vertices[face[1]], its.vertices[face[2]], + distance, u, v, ray_epsilon) && + distance > 0.0 && distance < nearest_hit_distance) { + nearest_hit_distance = distance; + nearest_face = face_id; + } + } + + // This matches AABBMesh::hit_result::is_inside(): for a consistently + // oriented closed mesh, the nearest face points along a ray leaving it. + return nearest_face != size_t(-1) && + its_unnormalized_normal(its, nearest_face).cast().dot(ray_direction) > 0.0; +} + +} // namespace + +bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh) const +{ + // With no output mesh this is a fast yes/no test and returns on the first + // hit. With an output mesh it collects all clipped fragments for the red + // GUI intersection preview. + if (intersection_mesh != nullptr) + intersection_mesh->clear(); + + if (region.polygon.points.size() < 3) + return false; + + double z_min = region.z_min; + double z_max = region.z_max; + if (z_min > z_max) + std::swap(z_min, z_max); + if (z_max <= z_min + EPSILON) + return false; + + const std::vector footprints = triangulated_prism_footprints(region.polygon); + if (footprints.empty()) + return false; + + bool intersects = false; + const ModelObject *model_object = get_object(); + const Transform3d instance_matrix = get_matrix(); + + for (const ModelVolume *volume : model_object->volumes) { + if (! volume->is_model_part()) + continue; + + const indexed_triangle_set &its = volume->mesh().its; + if (its.vertices.empty() || its.indices.empty()) + continue; + + const Transform3d volume_matrix = instance_matrix * volume->get_matrix(); + bool volume_surface_intersects = false; + for (const stl_triangle_vertex_indices &face : its.indices) { + const Vec3d p0 = volume_matrix * its.vertices[face[0]].cast(); + const Vec3d p1 = volume_matrix * its.vertices[face[1]].cast(); + const Vec3d p2 = volume_matrix * its.vertices[face[2]].cast(); + + const double tri_min_z = std::min({ p0.z(), p1.z(), p2.z() }); + const double tri_max_z = std::max({ p0.z(), p1.z(), p2.z() }); + if (tri_max_z < z_min || tri_min_z > z_max) + continue; + + for (const ExclusionPrismFootprintTriangle &footprint : footprints) { + if (! triangle_bbox_intersects_prism_footprint(p0, p1, p2, footprint)) + continue; + + std::vector clipped = clip_model_triangle_to_prism(p0, p1, p2, z_min, z_max, footprint); + if (polygon_3d_area2(clipped) <= 1e-8) + continue; + + volume_surface_intersects = true; + intersects = true; + if (intersection_mesh == nullptr) + return true; + + append_clipped_polygon(*intersection_mesh, clipped); + } + } + + if (!volume_surface_intersects && !intersects) { + // Surface clipping cannot detect a prism wholly enclosed by a + // solid. In that topology, with no boundary crossing, one point + // inside the connected prism is sufficient to test containment. + const ExclusionPrismFootprintTriangle &footprint = footprints.front(); + const Vec2d probe_xy = (footprint.vertices[0] + footprint.vertices[1] + footprint.vertices[2]) / 3.0; + const Vec3d probe_world(probe_xy.x(), probe_xy.y(), z_min + 0.5 * (z_max - z_min)); + const Vec3d probe_local = volume_matrix.inverse() * probe_world; + + // A linear ray scan keeps this one-off fallback O(n) without + // adding ray tests to the usual surface-intersection path. + if (volume->mesh().bounding_box().contains(probe_local) && mesh_contains_point_linear(its, probe_local)) { + intersects = true; + if (intersection_mesh == nullptr) + return true; + } + } + } + + return intersects; +} + +bool ModelInstance::intersects_bed_exclude_regions( + const std::vector ®ions, + indexed_triangle_set *intersection_mesh) const +{ + if (intersection_mesh != nullptr) + intersection_mesh->clear(); + if (regions.empty()) + return false; + + const Polygon hull = const_cast(this)->convex_hull_2d(); + bool intersects = false; + for (const BedExcludeRegion ®ion : regions) { + if (intersection(Polygons{ region.polygon }, Polygons{ hull }).empty()) + continue; + + if (intersection_mesh == nullptr) { + if (intersects_bed_exclude_region(region)) + return true; + continue; + } + + indexed_triangle_set region_intersection; + if (intersects_bed_exclude_region(region, ®ion_intersection)) { + intersects = true; + if (!region_intersection.empty()) + its_merge(*intersection_mesh, region_intersection); + } + } + return intersects; +} + //BBS: invalidate instance's convex_hull_2d void ModelInstance::invalidate_convex_hull_2d() { diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index ea0a02cbe0..6d9797ff67 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -1519,6 +1519,8 @@ public: double get_auto_brim_width() const; // BBS Polygon convex_hull_2d(); + bool intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh = nullptr) const; + bool intersects_bed_exclude_regions(const std::vector ®ions, indexed_triangle_set *intersection_mesh = nullptr) const; void invalidate_convex_hull_2d(); // Getting the input polygon for arrange diff --git a/src/libslic3r/ModelArrange.cpp b/src/libslic3r/ModelArrange.cpp index c5c952577c..3db5d38258 100644 --- a/src/libslic3r/ModelArrange.cpp +++ b/src/libslic3r/ModelArrange.cpp @@ -192,8 +192,11 @@ ArrangePolygon get_instance_arrange_poly(ModelInstance* instance, const Slic3r:: ap.has_tree_support = true; } - auto size = obj->instance_convex_hull_bounding_box(instance).size(); - ap.height = size.z(); + const BoundingBoxf3 bbox = obj->instance_convex_hull_bounding_box(instance); + ap.height = bbox.size().z(); + ap.z_min = bbox.min.z(); + ap.z_max = bbox.max.z(); + ap.has_z_range = bbox.defined; ap.name = obj->name; return ap; } diff --git a/src/libslic3r/MultiMaterialSegmentation.cpp b/src/libslic3r/MultiMaterialSegmentation.cpp index 507d997f1d..4c32c7380a 100644 --- a/src/libslic3r/MultiMaterialSegmentation.cpp +++ b/src/libslic3r/MultiMaterialSegmentation.cpp @@ -1928,6 +1928,7 @@ static void remove_multiple_edges_in_vertices(MMU_Graph &graph, const std::vecto } +namespace { // Finds the islands (layer ExPolygons) a region piece overlaps. A top or bottom region is projected from the neighbouring // layers and may reach past the island it belongs to, or over several islands. class IslandLocator @@ -1987,6 +1988,7 @@ private: coord_t m_cell_w = 1, m_cell_h = 1; std::vector> m_grid; }; +} // namespace static std::vector> merge_segmented_layers(const std::vector &input_expolygons, const std::vector> &segmented_regions, diff --git a/src/libslic3r/PerimeterGenerator.cpp b/src/libslic3r/PerimeterGenerator.cpp index 219b6b2551..42963a4575 100644 --- a/src/libslic3r/PerimeterGenerator.cpp +++ b/src/libslic3r/PerimeterGenerator.cpp @@ -1527,7 +1527,7 @@ void PerimeterGenerator::process_classic() process_no_bridge(all_surfaces, perimeter_spacing, ext_perimeter_width); // BBS: don't simplify too much which influence arc fitting when export gcode if arc_fitting is enabled - double surface_simplify_resolution = (print_config->enable_arc_fitting && !this->has_fuzzy_skin) ? 0.2 * m_scaled_resolution : m_scaled_resolution; + double surface_simplify_resolution = (print_config->enable_arc_fitting.value == ArcFittingMode::Enabled && !this->has_fuzzy_skin) ? 0.2 * m_scaled_resolution : m_scaled_resolution; //BBS: reorder the surface to reduce the travel time ExPolygons surface_exp; for (const Surface &surface : all_surfaces) @@ -2577,7 +2577,7 @@ void PerimeterGenerator::process_arachne() process_no_bridge(all_surfaces, perimeter_spacing, ext_perimeter_width); // BBS: don't simplify too much which influence arc fitting when export gcode if arc_fitting is enabled - double surface_simplify_resolution = (print_config->enable_arc_fitting && !this->has_fuzzy_skin) ? 0.2 * m_scaled_resolution : m_scaled_resolution; + double surface_simplify_resolution = (print_config->enable_arc_fitting.value == ArcFittingMode::Enabled && !this->has_fuzzy_skin) ? 0.2 * m_scaled_resolution : m_scaled_resolution; // ORCA: neither one-wall option has a surface to act on without the shell behind it, see // has_top_shell_layers() / has_bottom_shell_layers(). Gated here so every use below - including the // topmost and first layers - sees the same answer. diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index 81b78ec092..40a3385371 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1575,6 +1575,7 @@ static std::vector s_Preset_printer_options { "belt_frame_tilt_decouple", "belt_frame_tilt_angle", "belt_support_floor_offset", "enable_belt_purge_tower", + "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", "gcode_flavor", "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", "single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode", diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 78e6ad4277..38c250c0ac 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -61,6 +61,7 @@ #include "BoundingBox.hpp" #include "Brim.hpp" #include "ClipperUtils.hpp" +#include "ExclusionVolumeGeometry.hpp" #include "Extruder.hpp" #include "FilamentMixer.hpp" #include "Flow.hpp" @@ -87,6 +88,7 @@ #include #include #include +#include #include #include #include @@ -127,6 +129,98 @@ template class PrintState; PrintRegion::PrintRegion(const PrintRegionConfig &config) : PrintRegion(config, config.hash()) {} PrintRegion::PrintRegion(PrintRegionConfig &&config) : PrintRegion(std::move(config), config.hash()) {} +static std::vector translated_bed_exclusion_volumes(const Print &print) +{ + std::vector regions = get_bed_excluded_regions(print.config()); + const Point print_origin(scale_(print.get_plate_origin().x()), scale_(print.get_plate_origin().y())); + + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(print_origin); + + return regions; +} + +static std::vector> translated_bed_exclusion_volumes_by_extruder(const Print &print) +{ + std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); + const Point print_origin(scale_(print.get_plate_origin().x()), scale_(print.get_plate_origin().y())); + for (std::vector ®ions : regions_by_extruder) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(print_origin); + return regions_by_extruder; +} + +struct BedExclusionCollision +{ + size_t extruder_id; + bool collision_volume; +}; + +static bool intersects_bed_exclusion_purpose( + const ModelInstance &instance, + const std::vector ®ions, + const bool collision_volume) +{ + return std::any_of(regions.begin(), regions.end(), [&](const BedExcludeRegion ®ion) { + return region.is_collision_volume() == collision_volume && + instance.intersects_bed_exclude_region(region); + }); +} + +static std::optional colliding_bed_exclusion( + const Print &print, + const PrintObject &print_object, + const ModelInstance &instance, + const std::vector> ®ions_by_extruder) +{ + if (regions_by_extruder.empty()) + return std::nullopt; + + // The legacy area is shared by every nozzle. Report it with Orca's + // established wording even when opt-in collision volumes coexist. + if (intersects_bed_exclusion_purpose(instance, regions_by_extruder.front(), false)) + return BedExclusionCollision{ 0, false }; + + const bool automatic = is_auto_filament_map_mode(print.get_filament_map_mode()); + if (automatic && print.is_BBL_printer()) { + // Bambu automatic grouping owns the concrete filament assignment and + // the config starts with a non-authoritative [1, 1, ...] seed. Its + // geometric-unprintable input steers individual filaments away from + // colliding nozzles; validation only blocks an object when no nozzle + // can print it. + std::optional first_collision; + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + if (!intersects_bed_exclusion_purpose(instance, regions_by_extruder[extruder_id], true)) + return std::nullopt; + if (!first_collision.has_value()) + first_collision = extruder_id; + } + return first_collision.has_value() ? + std::optional(BedExclusionCollision{ *first_collision, true }) : std::nullopt; + } + + for (const unsigned int filament_id : print_object.printing_extruders()) { + const int resolved_extruder = bed_exclusion_extruder_for_filament( + filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), + true, regions_by_extruder.size()); + if (resolved_extruder < 0) + continue; + const size_t extruder_id = size_t(resolved_extruder); + if (intersects_bed_exclusion_purpose(instance, regions_by_extruder[extruder_id], true)) + return BedExclusionCollision{ extruder_id, true }; + } + return std::nullopt; +} + +static Polygons full_height_bed_exclusion_polygons(const std::vector ®ions) +{ + Polygons out; + for (const BedExcludeRegion ®ion : regions) + if (! region.has_z_range) + out.emplace_back(region.polygon); + return out; +} + //BBS // ORCA: Now this is a parameter //float Print::min_skirt_length = 0; @@ -187,8 +281,6 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "reduce_crossing_wall", "max_travel_detour_distance", "printable_area", - //BBS: add bed_exclude_area - "bed_exclude_area", "thumbnail_size", "before_layer_change_gcode", "enable_pressure_advance", @@ -212,7 +304,6 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "extruder_clearance_radius", "nozzle_height", "extruder_colour", - "extruder_offset", "filament_flow_ratio", "reduce_fan_stop_start_freq", "dont_slow_down_outer_wall", @@ -337,13 +428,27 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n }; static std::unordered_set steps_ignore; + static const std::unordered_set steps_exclusion_geometry = { + "bed_exclude_area", + "bed_exclude_volumes", + "bed_exclude_volume_mode", + "extruder_bed_exclude_volumes", + "extruder_offset" + }; std::vector steps; std::vector osteps; bool invalidated = false; for (const t_config_option_key &opt_key : opt_keys) { - if (steps_gcode.find(opt_key) != steps_gcode.end()) { + if (steps_exclusion_geometry.find(opt_key) != steps_exclusion_geometry.end()) { + // Exclusions are consumed while generating brims, support, tree + // support and wipe-tower geometry, not only during final export. + steps.emplace_back(psWipeTower); + steps.emplace_back(psSkirtBrim); + osteps.emplace_back(posSupportMaterial); + osteps.emplace_back(posSimplifySupportPath); + } else if (steps_gcode.find(opt_key) != steps_gcode.end()) { // These options only affect G-code export or they are just notes without influence on the generated G-code, // so there is nothing to invalidate. steps.emplace_back(psGCodeExport); @@ -787,10 +892,8 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print { StringObjectException single_object_exception; const auto& print_config = print.config(); - Polygons exclude_polys = get_bed_excluded_area(print_config); const Vec3d print_origin = print.get_plate_origin(); - std::for_each(exclude_polys.begin(), exclude_polys.end(), - [&print_origin](Polygon& p) { p.translate(scale_(print_origin.x()), scale_(print_origin.y())); }); + const std::vector> exclusion_volumes = translated_bed_exclusion_volumes_by_extruder(print); struct print_instance_info { @@ -841,22 +944,24 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print // Convert the shift from the PrintObject's coordinates into ModelObject's coordinates by removing the centering offset. convex_hull.translate(instance.shift - print_object->center_offset()); } - convex_hull_no_offset.translate(instance.shift - print_object->center_offset()); - //juedge the exclude area - if (!intersection(exclude_polys, convex_hull_no_offset).empty()) { + const std::optional exclusion_collision = colliding_bed_exclusion( + print, *print_object, *instance.model_instance, exclusion_volumes); + if (exclusion_collision.has_value()) { + const std::string collision_message = !exclusion_collision->collision_volume ? + (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % instance.model_instance->get_object()->name).str() : + is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? + (boost::format(L("%1% intersects collision volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects a collision volume for extruder %2%.")) % instance.model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); if (single_object_exception.string.empty()) { - single_object_exception.string = (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); + single_object_exception.string = collision_message; // single_object_exception.object = instance.model_instance->get_object(); //ORCA: Pass ModelInstance instead of ModelObject single_object_exception.object = instance.model_instance; } else { - single_object_exception.string += "\n"+(boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); + single_object_exception.string += "\n" + collision_message; single_object_exception.object = nullptr; } - //if (polygons) { - // intersecting_idxs.emplace_back(convex_hulls_other.size()); - //} } // if output needed, collect indices (inside convex_hulls_other) of intersecting hulls @@ -1480,10 +1585,9 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, return {}; const auto& print_config = print.config(); - Polygons exclude_polys = get_bed_excluded_area(print_config); const Vec3d print_origin = print.get_plate_origin(); - std::for_each(exclude_polys.begin(), exclude_polys.end(), - [&print_origin](Polygon& p) { p.translate(scale_(print_origin.x()), scale_(print_origin.y())); }); + const std::vector> exclusion_volumes = translated_bed_exclusion_volumes_by_extruder(print); + const Polygons prime_tower_exclude_polys = full_height_bed_exclusion_polygons(translated_bed_exclusion_volumes(print)); Pointfs wrapping_detection_area = print_config.wrapping_exclude_area.values; Polygon wrapping_poly; @@ -1503,14 +1607,6 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, inst->model_instance->get_scaling_factor(), inst->model_instance->get_mirror())); volume_hull.translate(inst->shift - inst->print_object->center_offset()); - if (!intersection(exclude_polys, volume_hull).empty()) { - // return {inst->model_instance->get_object()->name + L(" is too close to exclusion area, there may be collisions when printing.") + "\n", - // inst->model_instance->get_object()}; - //ORCA: Pass ModelInstance instead of ModelObject - return {(boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % inst->model_instance->get_object()->name).str() + "\n", - inst->model_instance}; - } - if (print_config.enable_wrapping_detection.value && !intersection(wrapping_poly, volume_hull).empty()) { // return {inst->model_instance->get_object()->name + L(" is too close to clumping detection area, there may be collisions when printing.") + "\n", // inst->model_instance->get_object()}; @@ -1520,6 +1616,15 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, } current_instance_hulls.emplace_back(volume_hull); } + if (const std::optional exclusion_collision = colliding_bed_exclusion( + print, *inst->print_object, *inst->model_instance, exclusion_volumes); exclusion_collision.has_value()) { + const std::string message = !exclusion_collision->collision_volume ? + (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % inst->model_instance->get_object()->name).str() : + is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? + (boost::format(L("%1% intersects collision volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects a collision volume for extruder %2%.")) % inst->model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); + return {message + "\n", inst->model_instance}; + } if (!intersection(convex_hulls_other, current_instance_hulls).empty()) { if (warning) { @@ -1603,13 +1708,13 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, warning->string += L("Prime tower is too close to others, and collisions may be caused.\n"); } } - if (!intersection(exclude_polys, tower_polys_checked).empty()) { + if (!intersection(prime_tower_exclude_polys, tower_polys_checked).empty()) { return {L("Prime tower is too close to an exclusion area, and collisions will be caused.\n")}; } if (print_config.enable_wrapping_detection.value && !intersection({wrapping_poly}, tower_polys_checked).empty()) { return {L("Prime tower is too close to the clumping detection area, and collisions will be caused.\n")}; } - if (warning && !intersection(exclude_polys, tower_polys_estimated).empty()) { + if (warning && !intersection(prime_tower_exclude_polys, tower_polys_estimated).empty()) { warning->string += L("Prime tower is too close to an exclusion area. There may be collisions when printing.") + "\n"; } if (warning && print_config.enable_wrapping_detection.value && !intersection({wrapping_poly}, tower_polys_estimated).empty()) { @@ -3724,7 +3829,11 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) // Orca: Build both the old object-keyed brim map and the per-instance // maps used by skirt/brim groups. m_brimMap.clear(); + m_brimFilamentMap.clear(); m_brimMapByInstance.clear(); + for (const auto& [object_id, filament] : objPrintVec) + if (filament > 0) + m_brimFilamentMap.emplace(object_id, filament - 1); m_first_layer_convex_hull.points.clear(); if (this->has_brim()) { Polygons islands_area; @@ -4152,7 +4261,22 @@ void Print::_make_skirt() } } - auto make_brims_for_skirt_brim_group = [this](const std::vector& group_instances) { + std::vector> brim_exclusion_regions; + if (has_bed_exclude_volumes(m_config)) { + brim_exclusion_regions = translated_bed_exclusion_volumes_by_extruder(*this); + for (std::vector ®ions : brim_exclusion_regions) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } + const bool has_brim_exclusions = std::any_of( + brim_exclusion_regions.begin(), brim_exclusion_regions.end(), + [](const std::vector ®ions) { return !regions.empty(); }); + const bool has_nozzle_specific_brim_exclusions = has_brim_exclusions && + active_bed_exclude_volume_mode(m_config) != BedExcludeVolumeMode::Shared; + + auto make_brims_for_skirt_brim_group = + [this, &brim_exclusion_regions, has_nozzle_specific_brim_exclusions] + (const std::vector& group_instances) { std::vector brims; std::vector brim_instances; for (const ObjectInstanceID& instance : group_instances) { @@ -4161,10 +4285,31 @@ void Print::_make_skirt() brim_instances.push_back(instance); } + auto brim_filament = [this](const ObjectInstanceID& instance) -> std::optional { + const auto it = m_brimFilamentMap.find(instance.object_id); + return it == m_brimFilamentMap.end() ? std::nullopt : + std::optional(it->second); + }; + auto compatible_brim_nozzles = + [this, &brim_filament, &brim_exclusion_regions, has_nozzle_specific_brim_exclusions] + (const ObjectInstanceID& first, const ObjectInstanceID& second) { + if (!has_nozzle_specific_brim_exclusions) + return true; + const std::optional first_filament = brim_filament(first); + const std::optional second_filament = brim_filament(second); + return first_filament.has_value() && second_filament.has_value() && + bed_exclusion_physical_extruders( + *this, { *first_filament, *second_filament }, + brim_exclusion_regions.size(), 0).size() == 1; + }; + const bool combine_group_brims = m_config.combine_brims && brim_instances.size() > 1; if (!combine_group_brims) { - for (const ObjectInstanceID& instance : brim_instances) - brims.push_back({ m_brimMapByInstance.at(instance), { instance } }); + for (const ObjectInstanceID& instance : brim_instances) { + const std::optional filament = brim_filament(instance); + if (filament.has_value()) + brims.push_back({ m_brimMapByInstance.at(instance), { instance }, *filament }); + } return brims; } @@ -4192,6 +4337,7 @@ void Print::_make_skirt() for (size_t j = i + 1; j < brim_instances.size(); ++j) { const auto area_j = m_objectBrimAreasByInstance.find(brim_instances[j]); if (area_j != m_objectBrimAreasByInstance.end() && + compatible_brim_nozzles(brim_instances[i], brim_instances[j]) && !intersection_ex(offset_ex(area_i->second, brim_contact_distance, jtRound, SCALED_RESOLUTION), area_j->second).empty()) unite_brims(i, j); } @@ -4202,9 +4348,12 @@ void Print::_make_skirt() combined_brim_ids[find_brim_parent(i)].push_back(brim_instances[i]); for (const auto& [_, instances] : combined_brim_ids) { + const std::optional filament = brim_filament(instances.front()); + if (!filament.has_value()) + continue; if (instances.size() == 1) { const ObjectInstanceID& instance = instances.front(); - brims.push_back({ m_brimMapByInstance.at(instance), { instance } }); + brims.push_back({ m_brimMapByInstance.at(instance), { instance }, *filament }); continue; } @@ -4216,8 +4365,26 @@ void Print::_make_skirt() const float brim_cleanup_delta = std::max(scaled_resolution, float(SCALED_EPSILON)); combined_area = offset2_ex(combined_area, brim_cleanup_delta, -brim_cleanup_delta, jtRound, scaled_resolution); + // The group has one known physical nozzle. Clip after union and + // cleanup so the geometry consumed by path generation remains + // valid for the exact filament recorded on the combined brim. + const std::vector physical_extruders = bed_exclusion_physical_extruders( + *this, { *filament }, brim_exclusion_regions.size(), 0); + const coord_t width_spacing_delta = std::max( + 0, brim_flow().scaled_width() - brim_flow().scaled_spacing()); + const coord_t exclusion_clearance = + (width_spacing_delta + 1) / 2 + coord_t(SCALED_EPSILON); + const ExPolygons exclusions = active_bed_exclusion_footprints( + brim_exclusion_regions, physical_extruders, 0.0, + std::max(0.0, skirt_first_layer_height()), Point(0, 0), exclusion_clearance); + if (!exclusions.empty()) + combined_area = diff_ex(combined_area, exclusions); + if (combined_area.empty()) + continue; + Polygons islands_area; - brims.push_back({ makeBrimInfillFromPlateCoordinates(combined_area, *this, islands_area), instances }); + brims.push_back({ makeBrimInfillFromPlateCoordinates(combined_area, *this, islands_area), + instances, *filament }); } return brims; @@ -5542,6 +5709,7 @@ void Print::export_gcode_from_previous_file(const std::string& file, GCodeProces // (via ensure_nozzle_group_result), so the multi-nozzle send/monitor mapping survives here. if (result != nullptr && result->nozzle_group_result) processor.initialize_from_context(result->nozzle_group_result); + processor.configure_exclusion_volume_path_check(this->config()); //processor.enable_producers(true); processor.process_file(file); diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index b36349c587..8d214da02a 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -516,6 +516,7 @@ public: // returns 0-based indices of extruders used to print the object (without brim, support and other helper extrusions) std::vector object_extruders() const; + std::vector printing_extruders() const; // Called by make_perimeters() void slice(); @@ -1156,6 +1157,8 @@ public: struct Brim { ExtrusionEntityCollection brim; std::vector instances; + // Zero-based logical filament selected when the brim was planned. + unsigned int filament_id { unsigned(-1) }; }; ExtrusionEntityCollection skirt; @@ -1511,6 +1514,8 @@ private: bool m_has_shared_per_object_skirt { false }; // Orca: Object-keyed brim paths kept for existing code. std::map m_brimMap; + // Zero-based logical filament selected for each object's brim. + std::map m_brimFilamentMap; // Orca: Actual brim paths keyed by object instance. std::map m_brimMapByInstance; // Orca: Translated brim areas keyed by instance, used to find touching brims. diff --git a/src/libslic3r/PrintBase.hpp b/src/libslic3r/PrintBase.hpp index 7e2b17e48f..f3c40102f8 100644 --- a/src/libslic3r/PrintBase.hpp +++ b/src/libslic3r/PrintBase.hpp @@ -70,6 +70,7 @@ public: SlicingNeedSupportOn, SlicingEmptyGcodeLayers, SlicingGcodeOverlap, + SlicingExclusionVolumeToolpath, SlicingPreciseSeamWarning }; diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 91261690fd..164bdece3b 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -10,21 +10,23 @@ #include "FilamentMixer.hpp" #include "MaterialType.hpp" #include "I18N.hpp" -#include "enum_bitmask.hpp" +#include "LocalesUtils.hpp" #include "format.hpp" #include "GCode/Thumbnails.hpp" +#include +#include +#include +#include +#include "enum_bitmask.hpp" #include #include -#include #include #include #include -#include #include #include "libslic3r.h" #include -#include #include #include #include @@ -33,6 +35,8 @@ #include #include #include +#include +#include #include #include #include @@ -248,6 +252,14 @@ static t_config_enum_values s_keys_map_PowerLossRecoveryMode { }; CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(PowerLossRecoveryMode) +// Orca +static t_config_enum_values s_keys_map_ArcFittingMode { + { "disabled", int(ArcFittingMode::Disabled) }, + { "enabled", int(ArcFittingMode::Enabled) }, + { "sparse_infill", int(ArcFittingMode::SparseInfill) } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(ArcFittingMode) + static t_config_enum_values s_keys_map_CenterOfSurfacePattern{ {"each_surface", int(CenterOfSurfacePattern::Each_Surface)}, {"each_model", int(CenterOfSurfacePattern::Each_Model)}, @@ -727,6 +739,13 @@ static const t_config_enum_values s_keys_map_FilamentMapMode = { }; CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(FilamentMapMode) +static const t_config_enum_values s_keys_map_BedExcludeVolumeMode = { + { "shared", int(BedExcludeVolumeMode::Shared) }, + { "toolhead_offset", int(BedExcludeVolumeMode::ToolheadOffset) }, + { "per_extruder", int(BedExcludeVolumeMode::PerExtruder) } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(BedExcludeVolumeMode) + // IMEX: keep the legacy hyphenated wire strings so existing presets / 3MFs // deserialize unchanged after the coString -> coEnum migration. static const t_config_enum_values s_keys_map_ImexToolLayout = { @@ -1035,11 +1054,38 @@ void PrintConfigDef::init_common_params() def = this->add("bed_exclude_area", coPoints); def->label = L("Excluded bed area"); def->tooltip = L("Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. " - "The area is expressed as polygon by points in following format: \"XxY, XxY, ...\""); + "The area is expressed as a polygon in the format \"XxY, XxY, ...\". It constrains material and model placement, " + "but allows machine travel. Configure toolhead collision volumes separately for G-code checking and travel avoidance."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionPoints{ Vec2d(0, 0) }); + def = this->add("bed_exclude_volumes", coString); + def->label = L("Toolhead collision volumes"); + def->tooltip = L("Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. " + "Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. " + "Separate multiple volumes with \"|\". These volumes are additional to the excluded bed area. " + "Automatic arrangement conservatively uses the bounding box of a non-convex volume."); + def->mode = comAdvanced; + def->gui_type = ConfigOptionDef::GUIType::one_string; + def->set_default_value(new ConfigOptionString()); + + def = this->add("bed_exclude_volume_mode", coEnum); + def->label = L("Collision volume behavior"); + def->tooltip = L("Choose whether all nozzles use the same collision volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, select each extruder on the Extruder page to configure its volumes."); + def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); + def->enum_values = { "shared", "toolhead_offset", "per_extruder" }; + def->enum_labels = { L("Shared"), L("Toolhead-relative (nozzle offsets)"), L("Individual per extruder") }; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + + def = this->add("extruder_bed_exclude_volumes", coStrings); + def->label = L("Extruder collision volumes"); + def->tooltip = L("Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared collision volumes. Leave empty for no collision volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume."); + def->mode = comAdvanced; + def->gui_type = ConfigOptionDef::GUIType::one_string; + def->set_default_value(new ConfigOptionStrings{ "" }); + def = this->add("bed_custom_texture", coString); def->label = L("Bed custom texture"); def->mode = comAdvanced; @@ -4363,16 +4409,25 @@ void PrintConfigDef::init_fff_params() def->set_default_value(new ConfigOptionBool(0)); // BBS - def = this->add("enable_arc_fitting", coBool); + def = this->add("enable_arc_fitting", coEnum); def->label = L("Arc fitting"); - def->tooltip = L("Enable this to get a G-code file which has G2 and G3 moves. " - "The fitting tolerance is same as the resolution.\n\n" - "Note: For Klipper machines, this option is recommended to be disabled. Klipper does not benefit from " - "arc commands as these are split again into line segments by the firmware. This results in a reduction " - "in surface quality as line segments are converted to arcs by the slicer and then back to line segments " - "by the firmware."); + def->tooltip = L("Fit G2 and G3 arc moves to the toolpaths. Walls and surfaces are fitted within the resolution, while " + "sparse infill, supports and the wipe tower use fixed tolerances.\n" + " - Disabled: only straight G1 moves are used.\n" + " - Enabled: arcs are fitted to all toolpaths.\n" + " - Sparse infill only: arcs are fitted to the sparse infill only, which shortens the G-code of " + "curved infill patterns without affecting the walls and surfaces.\n\n" + "Note: For Klipper machines, Disabled is recommended. Klipper splits arcs back into line segments, " + "which lowers the surface quality and can increase the print time."); + def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); + def->enum_values.push_back("disabled"); + def->enum_values.push_back("enabled"); + def->enum_values.push_back("sparse_infill"); + def->enum_labels.push_back(L("Disabled")); + def->enum_labels.push_back(L("Enabled")); + def->enum_labels.push_back(L("Sparse infill only")); def->mode = comAdvanced; - def->set_default_value(new ConfigOptionBool(0)); + def->set_default_value(new ConfigOptionEnum(ArcFittingMode::Disabled)); // BBS def = this->add("gcode_add_line_number", coBool); def->label = L("Add line number"); @@ -9795,6 +9850,13 @@ void PrintConfigDef::handle_legacy(t_config_option_key &opt_key, std::string &va value = "disable"; } } + else if (opt_key == "enable_arc_fitting") { + if (value == "1" || boost::iequals(value, "true")) { + value = "enabled"; + } else if (value == "0" || boost::iequals(value, "false")) { + value = "disabled"; + } + } else if(opt_key == "ensure_vertical_shell_thickness") { if(value == "1") { value = "ensure_all"; @@ -10131,6 +10193,7 @@ std::set printer_extruder_options = { "nozzle_diameter", "default_nozzle_volume_type", "extruder_printable_area", + "extruder_bed_exclude_volumes", "extruder_printable_height", "min_layer_height", "max_layer_height", @@ -12375,6 +12438,25 @@ std::map validate(const FullPrintConfig &cfg, bool und break; } + const bool collision_volumes_enabled = has_bed_exclude_volumes(cfg); + if (cfg.bed_exclude_volume_mode.value != BedExcludeVolumeMode::PerExtruder && + !cfg.bed_exclude_volumes.value.empty() && + !is_valid_bed_exclude_volumes_string(cfg.bed_exclude_volumes.value, cfg.printable_height.value)) { + error_message.emplace("bed_exclude_volumes", L("Invalid collision volume definition.")); + } + if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::ToolheadOffset && + cfg.extruder_offset.size() < cfg.nozzle_diameter.size()) { + error_message.emplace("extruder_offset", L("A nozzle offset is required for every extruder when toolhead-relative collision volumes are enabled.")); + } + if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::PerExtruder) { + for (const std::string &entry : cfg.extruder_bed_exclude_volumes.values) { + if (!is_valid_bed_exclude_volumes_string(entry, cfg.printable_height.value)) { + error_message.emplace("extruder_bed_exclude_volumes", L("Invalid per-extruder collision volume definition.")); + break; + } + } + } + // --perimeters if (cfg.wall_loops.value < 0) { error_message.emplace("wall_loops", _u8L("invalid value ") + std::to_string(cfg.wall_loops.value)); @@ -13756,31 +13838,513 @@ Points get_bed_shape(const PrintConfig &cfg, bool use_share) Points get_bed_shape(const SLAPrinterConfig &cfg) { return to_points(make_counter_clockwise(cfg.printable_area.values)); } -Polygons get_bed_excluded_area(const PrintConfig& cfg) +namespace { + +static bool looks_like_bed_exclusion_volume_syntax(const std::string &value) { - const Pointfs exclude_area_points = cfg.bed_exclude_area.values; + return value.find('|') != std::string::npos || (value.find("..") != std::string::npos && value.find(';') != std::string::npos); +} - // Belt printer: project exclusion zone points from the belt surface to machine-frame XY. - // On the belt surface Z=0, so the in-plane axis foreshortens by cos(tilt). The tilt - // axis decides which bed axis foreshortens: tilt about X (belt along Y) scales Y, - // tilt about Y (belt along X) scales X. Derived from belt_slice_rotation. - const bool is_belt = cfg.belt_printer.value; - const auto tilt = BeltTransformPipeline::physical_tilt( - cfg.belt_slice_rotation.value, cfg.belt_slice_rotation_angle.value); - const double cos_x = is_belt ? std::cos(Geometry::deg2rad(tilt.tilt_x_deg)) : 1.0; // foreshortens Y - const double cos_y = is_belt ? std::cos(Geometry::deg2rad(tilt.tilt_y_deg)) : 1.0; // foreshortens X +static bool parse_double_token(const std::string &text, double &out) +{ + std::string token = text; + boost::trim(token); + if (token.empty()) + return false; - Polygon exclude_poly; - for (int i = 0; i < exclude_area_points.size(); i++) { - auto pt = exclude_area_points[i]; - double x = is_belt ? pt.x() * cos_y : pt.x(); - double y = is_belt ? pt.y() * cos_x : pt.y(); - exclude_poly.points.emplace_back(scale_(x), scale_(y)); + size_t parsed = 0; + out = string_to_double_decimal_point(token, &parsed); + return parsed == token.size() && std::isfinite(out); +} + +static bool parse_z_range_token( + const std::string &token_in, + const double printable_height, + double &z_min, + double &z_max, + bool &has_z) +{ + std::string token = token_in; + boost::trim(token); + if (token.empty()) + return false; + + size_t range_pos = token.find(".."); + if (range_pos == std::string::npos) + return false; + + std::string min_token = token.substr(0, range_pos); + std::string max_token = token.substr(range_pos + 2); + boost::trim(min_token); + boost::trim(max_token); + + double parsed_min = 0.0; + double parsed_max = printable_height; + if (! min_token.empty() && ! parse_double_token(min_token, parsed_min)) + return false; + if (! max_token.empty() && ! parse_double_token(max_token, parsed_max)) + return false; + + z_min = std::clamp(parsed_min, 0.0, printable_height); + z_max = std::clamp(parsed_max, 0.0, printable_height); + has_z = true; + // A range wholly outside the printable height clamps to a plane, which is + // not a volume and must not participate in conservative unknown-Z checks. + return z_min < z_max; +} + +static std::optional parse_exclude_polygon_points(const std::string &points_str) +{ + Pointfs points; + std::vector point_tokens; + boost::split(point_tokens, points_str, boost::is_any_of(",")); + points.reserve(point_tokens.size()); + for (std::string point_token : point_tokens) { + boost::trim(point_token); + const size_t separator = point_token.find('x'); + if (separator == std::string::npos || point_token.find('x', separator + 1) != std::string::npos) + return std::nullopt; + + double x = 0.0; + double y = 0.0; + if (!parse_double_token(point_token.substr(0, separator), x) || + !parse_double_token(point_token.substr(separator + 1), y) || + !std::isfinite(x) || !std::isfinite(y)) + return std::nullopt; + points.emplace_back(x, y); + } + if (points.size() < 3) + return std::nullopt; + + Polygon polygon; + polygon.points.reserve(points.size()); + for (const Vec2d &pt : points) + polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + if (polygon.area() == 0.0) + return std::nullopt; + polygon.make_counter_clockwise(); + return polygon; +} + +static void append_legacy_bed_exclude_regions( + std::vector &out, + const Pointfs &legacy_points, + const double printable_height) +{ + if (legacy_points.size() < 3) + return; + + Polygon polygon; + polygon.points.reserve(legacy_points.size()); + for (const Vec2d &pt : legacy_points) + polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + polygon.make_counter_clockwise(); + + out.push_back({ std::move(polygon), 0.0, printable_height, + BedExcludeRegion::Purpose::MaterialKeepout, false }); +} + +static void append_bed_exclusion_volume_regions( + std::vector &out, + const std::string ®ion_specs_raw, + const double printable_height) +{ + std::vector region_specs; + boost::split(region_specs, region_specs_raw, boost::is_any_of("|\n")); + + for (const std::string &spec_raw : region_specs) { + std::string spec = spec_raw; + boost::trim(spec); + if (spec.empty()) + continue; + + std::vector fields; + boost::split(fields, spec, boost::is_any_of(";")); + + double z_min = 0.0; + double z_max = printable_height; + bool has_z_range = false; + std::string points_field; + bool invalid_z = false; + + for (std::string field : fields) { + boost::trim(field); + if (field.empty()) + continue; + + bool parsed_z_range = parse_z_range_token(field, printable_height, z_min, z_max, has_z_range); + if (parsed_z_range) + continue; + + if (field.find("..") != std::string::npos && field.find('x') == std::string::npos) { + invalid_z = true; + break; + } + + if (boost::algorithm::istarts_with(field, "points=")) + field = field.substr(std::string("points=").size()); + else if (boost::algorithm::istarts_with(field, "polygon=")) + field = field.substr(std::string("polygon=").size()); + + points_field = field; + } + + if (invalid_z) + continue; + + if (! has_z_range) { + z_min = 0.0; + z_max = printable_height; + } + + if (z_min >= z_max) + continue; + + std::optional polygon = parse_exclude_polygon_points(points_field); + if (! polygon) + continue; + + out.push_back({ std::move(*polygon), z_min, z_max, + BedExcludeRegion::Purpose::CollisionVolume, has_z_range }); + } +} + +static bool has_nonempty_string(const std::string &value) +{ + return std::any_of(value.begin(), value.end(), [](const char c) { return !std::isspace(static_cast(c)); }); +} + +static bool collision_volumes_configured( + const std::string &shared_specs, + const BedExcludeVolumeMode mode, + const std::vector &per_extruder_specs) +{ + if (mode == BedExcludeVolumeMode::PerExtruder) + return std::any_of(per_extruder_specs.begin(), per_extruder_specs.end(), has_nonempty_string); + return has_nonempty_string(shared_specs); +} + +static std::vector parse_master_bed_excluded_regions( + const Pointfs &legacy_points, + const std::string &shared_specs, + const bool use_collision_volumes, + const BedExcludeVolumeMode mode, + const double printable_height) +{ + std::vector regions; + const double height = std::max(0.0, printable_height); + // Legacy excluded areas remain a shared material/placement keep-out even + // when collision volumes are configured. Collision volumes add constraints; + // they do not silently remove the printer profile's established area. + append_legacy_bed_exclude_regions(regions, legacy_points, height); + if (use_collision_volumes && mode != BedExcludeVolumeMode::PerExtruder) + append_bed_exclusion_volume_regions(regions, shared_specs, height); + return regions; +} + +static void project_bed_material_keepouts(std::vector ®ions, const ConfigBase &cfg) +{ + const auto *belt = cfg.option("belt_printer"); + if (belt == nullptr || !belt->value) + return; + + const auto *axis = cfg.option>("belt_slice_rotation"); + const auto *angle = cfg.option("belt_slice_rotation_angle"); + if (axis == nullptr || angle == nullptr) + return; + + const auto tilt = BeltTransformPipeline::physical_tilt(axis->value, angle->value); + const double cos_x = std::cos(Geometry::deg2rad(tilt.tilt_x_deg)); + const double cos_y = std::cos(Geometry::deg2rad(tilt.tilt_y_deg)); + // Resolve bed-surface coordinates once, before any placement or tower + // consumer sees them. Collision volumes already use model coordinates. + for (BedExcludeRegion ®ion : regions) + if (!region.is_collision_volume()) + for (Point &point : region.polygon.points) + point = Point(scale_(unscale(point.x()) * cos_y), scale_(unscale(point.y()) * cos_x)); +} + +static std::vector resolve_bed_excluded_regions( + const std::vector &master_regions, + const BedExcludeVolumeMode mode, + const std::vector &per_extruder_specs, + const std::vector &extruder_offsets, + const size_t reference_extruder, + const size_t extruder_id, + const double printable_height) +{ + if (mode == BedExcludeVolumeMode::Shared) + return master_regions; + + if (mode == BedExcludeVolumeMode::PerExtruder) { + std::vector regions = master_regions; + if (extruder_id < per_extruder_specs.size()) + append_bed_exclusion_volume_regions( + regions, per_extruder_specs[extruder_id], std::max(0.0, printable_height)); + return regions; } - exclude_poly.make_counter_clockwise(); + std::vector regions = master_regions; + if (extruder_id >= extruder_offsets.size() || extruder_offsets.empty()) + return regions; - return {exclude_poly}; + const size_t clamped_reference = std::min(reference_extruder, extruder_offsets.size() - 1); + // A model-space point is emitted as model_position - extruder_offset. Therefore a + // carriage/toolhead obstacle described through the reference nozzle appears in another + // nozzle's model space translated by (other_offset - reference_offset). + const Vec2d delta = extruder_offsets[extruder_id] - extruder_offsets[clamped_reference]; + const Point translation(scale_(delta.x()), scale_(delta.y())); + for (BedExcludeRegion ®ion : regions) { + // Toolhead-relative offsets apply only to opt-in collision volumes. + // A legacy material keep-out is bed-fixed and shared by every nozzle. + if (region.is_collision_volume()) + region.polygon.translate(translation); + } + return regions; +} + +static size_t bed_exclusion_extruder_count( + const size_t nozzle_count, + const size_t offset_count, + const size_t per_extruder_count) +{ + return std::max(1, std::max({ nozzle_count, offset_count, per_extruder_count })); +} + +static std::vector flatten_bed_excluded_regions( + const BedExcludeVolumeMode mode, + std::vector> regions_by_extruder) +{ + if (regions_by_extruder.empty()) + return {}; + if (mode == BedExcludeVolumeMode::Shared) + return std::move(regions_by_extruder.front()); + + std::vector flattened; + // A shared legacy area is present in every resolved nozzle group so object + // validation sees it for every tool. Flatten it only once, while retaining + // every nozzle-specific collision volume. + bool material_keepout_added = false; + for (std::vector ®ions : regions_by_extruder) { + for (BedExcludeRegion ®ion : regions) { + if (!region.is_collision_volume()) { + if (material_keepout_added) + continue; + material_keepout_added = true; + } + flattened.emplace_back(std::move(region)); + } + } + return flattened; +} + +} // namespace + +int bed_exclusion_extruder_for_filament( + const size_t filament_id, const std::vector &configured_map, const FilamentMapMode map_mode, + const bool is_bambu, const bool automatic_map_resolved, const size_t extruder_count) +{ + if (extruder_count == 0) + return -1; + + const bool automatic = is_auto_filament_map_mode(map_mode); + if (automatic && is_bambu && !automatic_map_resolved) + return -1; + + // Generic multi-tool printers use filament ids as tool ids. Their global + // filament_map still carries the Bambu grouping seed [1, 1, ...], which is + // not a meaningful assignment for these machines. + if (automatic && !is_bambu && filament_id < extruder_count) + return int(filament_id); + + if (filament_id < configured_map.size() && configured_map[filament_id] > 0 && + size_t(configured_map[filament_id]) <= extruder_count) + return configured_map[filament_id] - 1; + + return filament_id < extruder_count ? int(filament_id) : -1; +} + +std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg) +{ + const ConfigOptionFloat *height_option = cfg.opt("printable_height"); + const double printable_height = height_option != nullptr ? height_option->value : 0.0; + const ConfigOptionPoints *legacy_option = cfg.opt("bed_exclude_area"); + const ConfigOptionString *shared_option = cfg.opt("bed_exclude_volumes"); + const BedExcludeVolumeMode configured_mode = cfg.has("bed_exclude_volume_mode") ? + cfg.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + const ConfigOptionStrings *per_extruder_option = cfg.opt("extruder_bed_exclude_volumes"); + const ConfigOptionPoints *offset_option = cfg.opt("extruder_offset"); + const ConfigOptionFloats *nozzle_option = cfg.opt("nozzle_diameter"); + const ConfigOptionInt *reference_option = cfg.opt("master_extruder_id"); + + const Pointfs legacy_points = legacy_option != nullptr ? legacy_option->values : Pointfs{}; + const std::string shared_specs = shared_option != nullptr ? shared_option->value : std::string{}; + const std::vector per_extruder_specs = per_extruder_option != nullptr ? per_extruder_option->values : std::vector{}; + const bool use_collision_volumes = collision_volumes_configured(shared_specs, configured_mode, per_extruder_specs); + const BedExcludeVolumeMode active_mode = use_collision_volumes ? configured_mode : BedExcludeVolumeMode::Shared; + std::vector master_regions = parse_master_bed_excluded_regions( + legacy_points, shared_specs, use_collision_volumes, active_mode, printable_height); + project_bed_material_keepouts(master_regions, cfg); + const std::vector offsets = offset_option != nullptr ? offset_option->values : std::vector{}; + const size_t count = bed_exclusion_extruder_count( + nozzle_option != nullptr ? nozzle_option->size() : 0, + offsets.size(), per_extruder_specs.size()); + const size_t reference = reference_option != nullptr && reference_option->value > 0 ? size_t(reference_option->value - 1) : 0; + + std::vector> result; + result.reserve(count); + for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) + result.emplace_back(resolve_bed_excluded_regions(master_regions, active_mode, per_extruder_specs, offsets, reference, extruder_id, printable_height)); + return result; +} + +std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg) +{ + const double printable_height = cfg.printable_height.value; + const bool use_collision_volumes = collision_volumes_configured( + cfg.bed_exclude_volumes.value, cfg.bed_exclude_volume_mode.value, + cfg.extruder_bed_exclude_volumes.values); + const BedExcludeVolumeMode active_mode = use_collision_volumes ? + cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; + std::vector master_regions = parse_master_bed_excluded_regions( + cfg.bed_exclude_area.values, cfg.bed_exclude_volumes.value, use_collision_volumes, + active_mode, printable_height); + project_bed_material_keepouts(master_regions, cfg); + const size_t count = bed_exclusion_extruder_count( + cfg.nozzle_diameter.size(), cfg.extruder_offset.size(), cfg.extruder_bed_exclude_volumes.size()); + const size_t reference = cfg.master_extruder_id.value > 0 ? size_t(cfg.master_extruder_id.value - 1) : 0; + + std::vector> result; + result.reserve(count); + for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) { + result.emplace_back(resolve_bed_excluded_regions( + master_regions, active_mode, cfg.extruder_bed_exclude_volumes.values, + cfg.extruder_offset.values, reference, extruder_id, printable_height)); + } + return result; +} + +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg, const size_t extruder_id) +{ + std::vector> regions = get_bed_excluded_regions_by_extruder(cfg); + return extruder_id < regions.size() ? std::move(regions[extruder_id]) : std::vector{}; +} + +std::vector get_bed_excluded_regions(const PrintConfig &cfg, const size_t extruder_id) +{ + std::vector> regions = get_bed_excluded_regions_by_extruder(cfg); + return extruder_id < regions.size() ? std::move(regions[extruder_id]) : std::vector{}; +} + +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg) +{ + return flatten_bed_excluded_regions(active_bed_exclude_volume_mode(cfg), get_bed_excluded_regions_by_extruder(cfg)); +} + +std::vector get_bed_excluded_regions(const PrintConfig &cfg) +{ + return flatten_bed_excluded_regions(active_bed_exclude_volume_mode(cfg), get_bed_excluded_regions_by_extruder(cfg)); +} + +bool is_bed_exclusion_volume_syntax(const std::string &value) +{ + return looks_like_bed_exclusion_volume_syntax(value); +} + +bool is_valid_bed_exclude_volumes_string(const std::string &value, const double printable_height) +{ + if (value.empty()) + return true; + + std::vector specs; + boost::split(specs, value, boost::is_any_of("|\n")); + bool found_nonempty = false; + for (std::string spec : specs) { + boost::trim(spec); + if (spec.empty()) + continue; + found_nonempty = true; + std::vector parsed; + append_bed_exclusion_volume_regions(parsed, spec, std::max(0.0, printable_height)); + if (parsed.size() != 1) + return false; + } + return found_nonempty; +} + +void append_bed_exclude_volumes(DynamicPrintConfig &config, const std::string &definition) +{ + if (definition.empty()) + return; + + const auto append = [&definition](const std::string ¤t) { + return current.empty() ? definition : current + '|' + definition; + }; + const BedExcludeVolumeMode mode = config.has("bed_exclude_volume_mode") ? + config.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + if (mode == BedExcludeVolumeMode::PerExtruder) { + const ConfigOptionStrings *current = config.option("extruder_bed_exclude_volumes"); + std::vector definitions = current != nullptr ? current->values : std::vector{}; + const ConfigOptionFloats *nozzles = config.option("nozzle_diameter"); + const size_t extruder_count = std::max(1, nozzles != nullptr ? nozzles->size() : 0); + definitions.resize(std::max(definitions.size(), extruder_count)); + for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) + definitions[extruder_id] = append(definitions[extruder_id]); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(std::move(definitions))); + return; + } + + const ConfigOptionString *current = config.option("bed_exclude_volumes"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString( + append(current != nullptr ? current->value : std::string{}))); +} + +bool has_bed_exclude_volumes(const DynamicPrintConfig &cfg) +{ + const ConfigOptionString *shared = cfg.opt("bed_exclude_volumes"); + const ConfigOptionStrings *per_extruder = cfg.opt("extruder_bed_exclude_volumes"); + const BedExcludeVolumeMode mode = cfg.has("bed_exclude_volume_mode") ? + cfg.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + return collision_volumes_configured( + shared != nullptr ? shared->value : std::string{}, mode, + per_extruder != nullptr ? per_extruder->values : std::vector{}); +} + +bool has_bed_exclude_volumes(const PrintConfig &cfg) +{ + return collision_volumes_configured( + cfg.bed_exclude_volumes.value, cfg.bed_exclude_volume_mode.value, + cfg.extruder_bed_exclude_volumes.values); +} + +BedExcludeVolumeMode active_bed_exclude_volume_mode(const DynamicPrintConfig &cfg) +{ + if (!has_bed_exclude_volumes(cfg) || !cfg.has("bed_exclude_volume_mode")) + return BedExcludeVolumeMode::Shared; + return cfg.opt_enum("bed_exclude_volume_mode"); +} + +BedExcludeVolumeMode active_bed_exclude_volume_mode(const PrintConfig &cfg) +{ + return has_bed_exclude_volumes(cfg) ? cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; +} + +Polygons get_bed_excluded_area(const PrintConfig& cfg) +{ + const std::vector regions = get_bed_excluded_regions(cfg); + Polygons excluded_polygons; + excluded_polygons.reserve(regions.size()); + + for (const BedExcludeRegion ®ion : regions) { + if (region.has_z_range && region.z_min > EPSILON) + continue; + if (region.z_max <= EPSILON) + continue; + + excluded_polygons.emplace_back(region.polygon); + } + + return excluded_polygons; } Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share) diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 55e82656f0..e712c4565f 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -234,6 +234,13 @@ enum class PowerLossRecoveryMode { Disable, }; +// Orca +enum class ArcFittingMode { + Disabled, + Enabled, + SparseInfill, +}; + // BBS enum class WallSequence { InnerOuter, @@ -630,6 +637,14 @@ enum FilamentMapMode { fmmDefault }; +// Defines how bed exclusion volumes are resolved for printers with multiple +// independently positioned nozzles/toolheads. +enum class BedExcludeVolumeMode { + Shared = 0, + ToolheadOffset, + PerExtruder +}; + // All auto modes are ordered before fmmManual (see the enum ordering note above). inline bool is_auto_filament_map_mode(FilamentMapMode mode) { return mode < fmmManual; @@ -815,6 +830,7 @@ CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(WipeTowerWallType) CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(PerimeterGeneratorType) CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(ToolChangeOrderingType) CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(PowerLossRecoveryMode) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(ArcFittingMode) CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(SurfaceFillOrder) CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(AdaptiveInfillMode) CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(AdaptiveInfillGradient) @@ -1685,7 +1701,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionString, printing_by_object_gcode)) ((ConfigOptionFloats, deretraction_speed)) //BBS - ((ConfigOptionBool, enable_arc_fitting)) + ((ConfigOptionEnum, enable_arc_fitting)) ((ConfigOptionString, machine_end_gcode)) ((ConfigOptionStrings, filament_end_gcode)) ((ConfigOptionFloatsNullable, filament_flow_ratio)) @@ -1973,6 +1989,9 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE( ((ConfigOptionStrings, parallel_printheads_bed_exclude_areas)) //BBS: add bed_exclude_area ((ConfigOptionPoints, bed_exclude_area)) + ((ConfigOptionString, bed_exclude_volumes)) + ((ConfigOptionEnum, bed_exclude_volume_mode)) + ((ConfigOptionStrings, extruder_bed_exclude_volumes)) ((ConfigOptionPoints, head_wrap_detect_zone)) // BBS ((ConfigOptionString, bed_custom_texture)) @@ -2521,6 +2540,42 @@ Polygon get_shared_poly(const std::vector& extruder_polys); Points get_bed_shape(const DynamicPrintConfig &cfg, bool use_share = true); Points get_bed_shape(const PrintConfig &cfg, bool use_share = false); Points get_bed_shape(const SLAPrinterConfig &cfg); +struct BedExcludeRegion { + enum class Purpose { + MaterialKeepout, + CollisionVolume + }; + + Polygon polygon; + double z_min { 0.0 }; + double z_max { 0.0 }; + Purpose purpose { Purpose::MaterialKeepout }; + bool has_z_range { false }; + + bool is_collision_volume() const { return purpose == Purpose::CollisionVolume; } +}; +std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg); +std::vector get_bed_excluded_regions(const PrintConfig& cfg); +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg, size_t extruder_id); +std::vector get_bed_excluded_regions(const PrintConfig &cfg, size_t extruder_id); +std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg); +std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg); +// Resolve the nozzle whose exclusion regions apply to a filament. Filament +// and return ids are 0-based. Returns -1 while Bambu automatic grouping has +// no concrete assignment. +int bed_exclusion_extruder_for_filament(size_t filament_id, const std::vector &configured_map, + FilamentMapMode map_mode, bool is_bambu, bool automatic_map_resolved, + size_t extruder_count); +bool is_bed_exclusion_volume_syntax(const std::string &value); +bool is_valid_bed_exclude_volumes_string(const std::string &value, double printable_height); +// Add shared definitions without replacing existing volumes or changing the +// configured multi-nozzle mode. In individual mode the new definitions are +// applied to every physical extruder. +void append_bed_exclude_volumes(DynamicPrintConfig &config, const std::string &definition); +bool has_bed_exclude_volumes(const DynamicPrintConfig &cfg); +bool has_bed_exclude_volumes(const PrintConfig &cfg); +BedExcludeVolumeMode active_bed_exclude_volume_mode(const DynamicPrintConfig &cfg); +BedExcludeVolumeMode active_bed_exclude_volume_mode(const PrintConfig &cfg); Slic3r::Polygons get_bed_excluded_area(const PrintConfig& cfg); Slic3r::Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share = false); bool has_skirt(const DynamicPrintConfig& cfg); diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index e48f8d71f1..6dd48e530d 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -354,6 +354,23 @@ std::vector> PrintObject::detect_extruder_geometric_unprintables() std::vector> geometric_unprintables(extruder_size); // the container to return + std::vector> exclusion_regions = get_bed_excluded_regions_by_extruder(m_print->config()); + exclusion_regions.resize(extruder_size); + const Point plate_origin(scale_(m_print->get_plate_origin().x()), scale_(m_print->get_plate_origin().y())); + for (std::vector ®ions : exclusion_regions) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(plate_origin); + + const std::vector used_filaments = printing_extruders(); + for (size_t extruder_id = 0; extruder_id < exclusion_regions.size(); ++extruder_id) { + const bool collision = std::any_of(m_instances.begin(), m_instances.end(), [&](const PrintInstance &instance) { + return instance.model_instance != nullptr && + instance.model_instance->intersects_bed_exclude_regions(exclusion_regions[extruder_id]); + }); + if (collision) + geometric_unprintables[extruder_id].insert(used_filaments.begin(), used_filaments.end()); + } + std::vector printable_height_per_extruder = m_print->config().extruder_printable_height.values; assert(printable_height_per_extruder.size() == extruder_size); @@ -3039,6 +3056,32 @@ template void debug_draw(std::string name, const T& a, const T& b, c } #endif +// Whether a fill surface of the layer with the given id prints at full density, by the density Fill.cpp gives its type, once +// bridge_over_infill() and combine_infill() have run. +static bool prints_dense(const Surface &surface, const PrintRegionConfig ®ion_config, const PrintObjectConfig &object_config, size_t layer_id) +{ + switch (surface.surface_type) { + case stInternal: return region_config.sparse_infill_density.value == 100; + case stTop: return region_config.top_surface_density.value == 100; + case stBottom: return region_config.bottom_surface_density.value == 100; + case stBottomBridge: return region_config.bridge_density.value == 100; + case stInternalSolid: + // Elephant foot compensation thins it on the layers just above the first, and combining infill leaves voids below + // the top layer of each group. + if (region_config.infill_combination.value || + (object_config.elefant_foot_layers_density.value < 100 && layer_id > 0 && + layer_id <= size_t(object_config.elefant_foot_compensation_layers.value))) + return false; + // Where it lies over sparse infill, bridge_over_infill() turns it into an internal bridge. + [[fallthrough]]; + case stInternalBridge: + case stSecondInternalBridge: + case stInternalAfterExternalBridge: + return region_config.bridge_density.value == 100 && object_config.internal_bridge_density.value == 100; + default: return false; + } +} + // This method applies bridge flow to the first internal solid layer above sparse infill. void PrintObject::bridge_over_infill() { @@ -3088,6 +3131,9 @@ void PrintObject::bridge_over_infill() // unsupported area will serve as a filter for polygons worth bridging. Polygons unsupported_area; Polygons lower_layer_solids; + // Whether every fill surface of the lower layer prints at full density, which the early-out below needs. Kept + // apart from the unchanged rule for what counts as a solid to expand. + bool dense_below = true; for (const LayerRegion *region : layer->lower_layer->regions()) { Polygons fill_polys = to_polygons(region->fill_expolygons); // initially consider the whole layer unsupported, but also gather solid layers to later cut off supported parts @@ -3097,6 +3143,7 @@ void PrintObject::bridge_over_infill() Polygons p = to_polygons(surface.expolygon); lower_layer_solids.insert(lower_layer_solids.end(), p.begin(), p.end()); } + dense_below = dense_below && prints_dense(surface, region->region().config(), po->config(), layer->lower_layer->id()); } } unsupported_area = closing(unsupported_area, float(SCALED_EPSILON)); @@ -3110,10 +3157,15 @@ void PrintObject::bridge_over_infill() // By expanding the lower layer solids, we avoid making bridges from the tiny internal overhangs that are (very likely) supported by previous layer solids // NOTE that we cannot filter out polygons worth bridging by their area, because sometimes there is a very small internal island that will grow into large hole lower_layer_solids = shrink(lower_layer_solids, 1 * spacing); // first remove thin regions that will not support anything - lower_layer_solids = expand(lower_layer_solids, (1 + expansion_multiplier) * spacing); // then expand back (opening), and further for parts supported by internal solids // By shrinking the unsupported area, we avoid making bridges from narrow ensuring region along perimeters. unsupported_area = shrink(unsupported_area, expansion_multiplier * spacing); - unsupported_area = diff(unsupported_area, lower_layer_solids); + // Then expand the solids back (opening), and further for parts supported by internal solids. Over a lower layer + // printed at full density the expansion nearly always covers everything, which diff_expanded() proves at a + // fraction of the cost. Where Clipper's own offset decimation folds a sliver of solid thinner than about 0.01 + // of the reach, about 16 µm here, its result may differ from the full expansion's; that is accepted. + const float reach = float((1 + expansion_multiplier) * spacing); + unsupported_area = dense_below ? diff_expanded(unsupported_area, lower_layer_solids, reach) : + diff(unsupported_area, expand(lower_layer_solids, reach)); for (const LayerRegion *region : layer->regions()) { SurfacesPtr region_internal_solids = region->fill_surfaces.filter_by_type(stInternalSolid); @@ -4526,6 +4578,24 @@ std::vector PrintObject::object_extruders() const return extruders; } +std::vector PrintObject::printing_extruders() const +{ + std::vector extruders = object_extruders(); + if (has_support_material()) { + const size_t filament_count = print()->config().filament_diameter.size(); + auto append_fixed_filament = [&](const int filament_id) { + if (filament_id > 0) + extruders.emplace_back(std::min(size_t(filament_id - 1), filament_count > 0 ? filament_count - 1 : 0)); + }; + append_fixed_filament(config().support_filament.value); + append_fixed_filament(config().support_interface_filament.value); + } + if (extruders.empty()) + extruders.emplace_back(0); + sort_remove_duplicates(extruders); + return extruders; +} + bool PrintObject::update_layer_height_profile(const ModelObject &model_object, const SlicingParameters &slicing_parameters, std::vector &layer_height_profile) { bool updated = false; diff --git a/src/libslic3r/Support/SupportCommon.cpp b/src/libslic3r/Support/SupportCommon.cpp index dddbfcf189..0cca31adca 100644 --- a/src/libslic3r/Support/SupportCommon.cpp +++ b/src/libslic3r/Support/SupportCommon.cpp @@ -1,4 +1,5 @@ #include "../ClipperUtils.hpp" +#include "../ExclusionVolumeGeometry.hpp" #include "../ClipperZUtils.hpp" #include "../ExtrusionEntityCollection.hpp" #include "../Layer.hpp" @@ -55,6 +56,132 @@ namespace Slic3r { +namespace { + +int object_layer_id_at_z(const PrintObject &object, const coordf_t print_z) +{ + const ConstLayerPtrsAdaptor layers = object.layers(); + if (layers.empty()) + return -1; + const auto it = std::lower_bound(layers.begin(), layers.end(), print_z - EPSILON, + [](const Layer *layer, const coordf_t z) { return layer->print_z < z; }); + return int(it == layers.end() ? layers.size() - 1 : size_t(it - layers.begin())); +} + +bool support_layer_uses_interface_material(const SupportGeneratorLayer &layer) +{ + return one_of(layer.layer_type, { + SupporLayerType::RaftInterface, + SupporLayerType::BottomContact, + SupporLayerType::BottomInterface, + SupporLayerType::TopContact, + SupporLayerType::TopInterface }); +} + +void trim_polygons(Polygons &polygons, const Polygons &excluded) +{ + if (!polygons.empty() && !excluded.empty()) + polygons = diff(polygons, excluded, ApplySafetyOffset::Yes); +} + +} // namespace + +std::vector support_exclusion_filaments( + const PrintObject &object, + const bool interface_material) +{ + const int configured = interface_material ? object.config().support_interface_filament.value : + object.config().support_filament.value; + if (configured > 0) + return { unsigned(configured - 1) }; + + // "Current filament" is assigned during tool ordering, not from the + // supported object. It may therefore use a filament from another object, + // or one selected for flush-into-support, on any particular layer. + return object.print() == nullptr ? object.object_extruders() : object.print()->extruders(false); +} + +std::vector support_exclusion_areas_for_layers( + const PrintObject &object, + const std::vector> &layer_z_ranges, + const bool interface_material) +{ + std::vector result(layer_z_ranges.size()); + if (layer_z_ranges.empty() || object.print() == nullptr) + return result; + + const Print &print = *object.print(); + // Preserve established support output for legacy bed-exclude areas. Support + // avoidance is an opt-in property of explicit collision volumes. + if (!has_bed_exclude_volumes(print.config())) + return result; + + std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(print.config()); + for (std::vector ®ions : regions_by_extruder) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + if (regions_by_extruder.empty() || + std::all_of(regions_by_extruder.begin(), regions_by_extruder.end(), + [](const std::vector ®ions) { return regions.empty(); })) + return result; + + const std::vector filaments = support_exclusion_filaments(object, interface_material); + for (size_t idx = 0; idx < layer_z_ranges.size(); ++idx) { + const auto [z_min, z_max] = layer_z_ranges[idx]; + const int layer_id = object_layer_id_at_z(object, z_max); + const std::vector physical_extruders = bed_exclusion_physical_extruders( + print, filaments, regions_by_extruder.size(), layer_id); + result[idx] = to_polygons(active_bed_exclusion_footprints_for_object( + object, regions_by_extruder, physical_extruders, z_min, z_max, coord_t(SCALED_EPSILON))); + } + return result; +} + +void trim_support_layers_by_exclusion_volumes( + const PrintObject &object, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers) +{ + SupportGeneratorLayersPtr layers; + layers.reserve(raft_layers.size() + bottom_contacts.size() + top_contacts.size() + + intermediate_layers.size() + interface_layers.size() + base_interface_layers.size()); + for (const SupportGeneratorLayersPtr *source : { + &raft_layers, &bottom_contacts, &top_contacts, &intermediate_layers, + &interface_layers, &base_interface_layers }) + append(layers, *source); + std::sort(layers.begin(), layers.end()); + layers.erase(std::unique(layers.begin(), layers.end()), layers.end()); + + for (const bool interface_material : { false, true }) { + SupportGeneratorLayersPtr selected; + std::vector> z_ranges; + for (SupportGeneratorLayer *layer : layers) { + if (layer != nullptr && support_layer_uses_interface_material(*layer) == interface_material) { + selected.emplace_back(layer); + z_ranges.emplace_back(layer->bottom_print_z(), layer->print_z); + } + } + + const std::vector excluded = + support_exclusion_areas_for_layers(object, z_ranges, interface_material); + for (size_t idx = 0; idx < selected.size(); ++idx) { + SupportGeneratorLayer &layer = *selected[idx]; + trim_polygons(layer.polygons, excluded[idx]); + if (layer.contact_polygons) + trim_polygons(*layer.contact_polygons, excluded[idx]); + if (layer.overhang_polygons) + trim_polygons(*layer.overhang_polygons, excluded[idx]); + if (layer.enforcer_polygons) + trim_polygons(*layer.enforcer_polygons, excluded[idx]); + } + } +} + // how much we extend support around the actual contact area //FIXME this should be dependent on the nozzle diameter! #define SUPPORT_MATERIAL_MARGIN 1.5 diff --git a/src/libslic3r/Support/SupportCommon.hpp b/src/libslic3r/Support/SupportCommon.hpp index ca91ecc5ae..f50c2d7a6c 100644 --- a/src/libslic3r/Support/SupportCommon.hpp +++ b/src/libslic3r/Support/SupportCommon.hpp @@ -56,6 +56,32 @@ void tree_supports_generate_paths(ExtrusionEntitiesPtr &dst, const Polygons &pol void fill_expolygons_with_sheath_generate_paths( ExtrusionEntitiesPtr &dst, const Polygons &polygons, Fill *filler, float density, ExtrusionRole role, const Flow &flow, const SupportParameters& support_params, bool with_sheath, bool no_sort); +// Return every logical filament which may be selected for this support role. +// An explicit assignment has one result; "current filament" is intentionally +// print-wide because Orca resolves it later while ordering tools and wiping. +std::vector support_exclusion_filaments( + const PrintObject &object, + bool interface_material); + +// Build conservative, object-local exclusion masks for generated support. +// `interface_material` selects the support-interface filament; false selects +// the base support filament. Each pair describes the actual extrusion slab. +std::vector support_exclusion_areas_for_layers( + const PrintObject &object, + const std::vector> &layer_z_ranges, + bool interface_material); + +// Remove exclusion volumes from every support and raft polygon category before +// SupportLayer installation and toolpath generation. +void trim_support_layers_by_exclusion_volumes( + const PrintObject &object, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers); + // returns sorted layers SupportGeneratorLayersPtr generate_support_layers( PrintObject &object, diff --git a/src/libslic3r/Support/SupportMaterial.cpp b/src/libslic3r/Support/SupportMaterial.cpp index 8ac9172bfd..54a1de8a2c 100644 --- a/src/libslic3r/Support/SupportMaterial.cpp +++ b/src/libslic3r/Support/SupportMaterial.cpp @@ -553,6 +553,10 @@ void PrintObjectSupportMaterial::generate(PrintObject &object) BOOST_LOG_TRIVIAL(info) << "Support generator - Creating layers"; + trim_support_layers_by_exclusion_volumes( + object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, + interface_layers, base_interface_layers); + // For debugging purposes, one may want to show only some of the support extrusions. // raft_layers.clear(); // bottom_contacts.clear(); diff --git a/src/libslic3r/Support/TreeModelVolumes.cpp b/src/libslic3r/Support/TreeModelVolumes.cpp index 33d379c2b5..6ecf735a0e 100644 --- a/src/libslic3r/Support/TreeModelVolumes.cpp +++ b/src/libslic3r/Support/TreeModelVolumes.cpp @@ -192,22 +192,18 @@ TreeModelVolumes::TreeModelVolumes( } }); } - if (! additional_excluded_areas.empty()) { - tbb::parallel_for(tbb::blocked_range(0, m_anti_overhang.size()), - [&](const tbb::blocked_range &range) { - for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { - if (layer_idx < coord_t(additional_excluded_areas.size())) - append(m_anti_overhang[layer_idx], additional_excluded_areas[layer_idx]); - // if (SUPPORT_TREE_AVOID_SUPPORT_BLOCKER) - // append(m_anti_overhang[layer_idx], storage.support.supportLayers[layer_idx].anti_overhang); - //FIXME block wipe tower - // if (storage.primeTower.enabled) - // append(m_anti_overhang[layer_idx], layer_idx == 0 ? storage.primeTower.outer_poly_first_layer : storage.primeTower.outer_poly); - m_anti_overhang[layer_idx] = union_(m_anti_overhang[layer_idx]); - } - }); - } #endif + + if (!additional_excluded_areas.empty()) { + m_anti_overhang.resize(std::max(m_anti_overhang.size(), additional_excluded_areas.size())); + tbb::parallel_for(tbb::blocked_range(0, additional_excluded_areas.size()), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++layer_idx) { + append(m_anti_overhang[layer_idx], additional_excluded_areas[layer_idx]); + m_anti_overhang[layer_idx] = union_(m_anti_overhang[layer_idx]); + } + }); + } } void TreeModelVolumes::precalculate(const PrintObject& print_object, const coord_t max_layer, std::function throw_on_cancel) @@ -488,7 +484,8 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex if (calculate_placable) data_placeable.allocate(data.begin(), data.end()); - for (size_t outline_idx : layer_outline_indices) + for (size_t outline_pos = 0; outline_pos < layer_outline_indices.size(); ++outline_pos) { + const size_t outline_idx = layer_outline_indices[outline_pos]; if (const std::vector &outlines = m_layer_outlines[outline_idx].second; ! outlines.empty()) { const TreeSupportMeshGroupSettings &settings = m_layer_outlines[outline_idx].first; const coord_t layer_height = settings.layer_height; @@ -525,7 +522,7 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex }); // 2) Sum over top / bottom ranges. - const bool processing_last_mesh = outline_idx == layer_outline_indices.back(); + const bool processing_last_mesh = outline_pos + 1 == layer_outline_indices.size(); tbb::parallel_for(tbb::blocked_range(data.begin(), data.end()), [&collision_areas_offsetted, &outlines, &machine_border = m_machine_border, &anti_overhang = m_anti_overhang, radius, xy_distance, z_distance_bottom_layers, z_distance_top_layers, min_resolution = m_min_resolution, &data, processing_last_mesh, &throw_on_cancel] @@ -624,6 +621,7 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex // Calculating just the collision areas. } } + } #ifdef SLIC3R_TREESUPPORTS_PROGRESS { std::lock_guard critical_section(*m_critical_progress); diff --git a/src/libslic3r/Support/TreeSupport3D.cpp b/src/libslic3r/Support/TreeSupport3D.cpp index ef267fba68..e2bd31eadd 100644 --- a/src/libslic3r/Support/TreeSupport3D.cpp +++ b/src/libslic3r/Support/TreeSupport3D.cpp @@ -3485,12 +3485,41 @@ static void generate_support_areas(Print &print, TreeSupport* tree_support, cons m_progress_offset = counter == 0 ? 0 : TREE_PROGRESS_TOTAL * (double(counter) * m_progress_multiplier); #endif // SLIC3R_TREESUPPORT_PROGRESS PrintObject &print_object = *print.get_object(processing.second.front()); + const size_t num_raft_layers_for_exclusions = config.raft_layers.size(); + std::vector> tree_layer_z_ranges; + tree_layer_z_ranges.reserve(num_raft_layers_for_exclusions + print_object.layer_count()); + coordf_t previous_z = 0.; + for (const coordf_t print_z : config.raft_layers) { + tree_layer_z_ranges.emplace_back(previous_z, print_z); + previous_z = print_z; + } + for (const Layer *layer : print_object.layers()) { + tree_layer_z_ranges.emplace_back(layer->print_z - layer->height, layer->print_z); + } + // A tree is one continuous structure while "current filament" may + // alternate between base and interface nozzles from layer to layer. + // Planning against both masks prevents a locally valid layer from + // forcing a branch through another possible nozzle's exclusion volume. + std::vector exclusion_areas = + support_exclusion_areas_for_layers(print_object, tree_layer_z_ranges, false); + const bool tree_uses_interface_material = !config.raft_layers.empty() || + print_object.config().support_interface_top_layers.value > 0 || + number_of_support_interface_bottom_layers(print_object.config()) > 0; + if (tree_uses_interface_material) { + const std::vector interface_exclusion_areas = + support_exclusion_areas_for_layers(print_object, tree_layer_z_ranges, true); + for (size_t layer_idx = 0; layer_idx < exclusion_areas.size(); ++layer_idx) { + append(exclusion_areas[layer_idx], interface_exclusion_areas[layer_idx]); + exclusion_areas[layer_idx] = union_(exclusion_areas[layer_idx]); + } + } + // Generator for model collision, avoidance and internal guide volumes. TreeModelVolumes volumes{ print_object, build_volume, config.maximum_move_distance, config.maximum_move_distance_slow, processing.second.front(), #ifdef SLIC3R_TREESUPPORTS_PROGRESS m_progress_multiplier, m_progress_offset, #endif // SLIC3R_TREESUPPORTS_PROGRESS - /* additional_excluded_areas */{} }; + exclusion_areas }; //FIXME generating overhangs just for the first mesh of the group. assert(processing.second.size() == 1); @@ -3638,6 +3667,9 @@ static void generate_support_areas(Print &print, TreeSupport* tree_support, cons // Produce the support G-code. SupportGeneratorLayersPtr raft_layers = generate_raft_base(print_object, support_params, print_object.slicing_parameters(), top_contacts, interface_layers, base_interface_layers, intermediate_layers, layer_storage); + trim_support_layers_by_exclusion_volumes( + print_object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, + interface_layers, base_interface_layers); SupportGeneratorLayersPtr layers_sorted = generate_support_layers(print_object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, interface_layers, base_interface_layers); // BBS: This is a hack to avoid the support being generated outside the bed area. See #4769. diff --git a/src/libslic3r/TextureDisplacement.cpp b/src/libslic3r/TextureDisplacement.cpp index 26e8726a72..074eb69db6 100644 --- a/src/libslic3r/TextureDisplacement.cpp +++ b/src/libslic3r/TextureDisplacement.cpp @@ -2724,7 +2724,8 @@ indexed_triangle_set build_texture_displacement_v2(const indexed_triangle_set bool flip_normals, BakeStageRecorder *debug, TextureBakeStats *stats, - const std::vector *model_uv) + const std::vector *model_uv, + float resting_drop) { HeightFieldSampler combined = make_combined_displacement_sampler(mesh, layers, facets_data, model_uv); if (!combined) @@ -2871,6 +2872,9 @@ indexed_triangle_set build_texture_displacement_v2(const indexed_triangle_set bounds.min = bounds.min.cwiseMin(v); bounds.max = bounds.max.cwiseMax(v); } + // The bottom the pipeline clamps and snaps to is the plane the whole object rests on, not this + // part's own: a part held off the plate by another keeps the relief on its underside. + bounds.min.z() -= resting_drop; const auto sample = [&combined](const Vec3f &pos, const Vec3f &, const Vec3f &blend_normal) { // The blend normal chooses the projection; the move itself is along the smooth normal, which @@ -3030,7 +3034,8 @@ static indexed_triangle_set build_texture_displacement_in_place( bool flip_normals, BakeStageRecorder *debug, TextureBakeStats *stats, - const std::vector *model_uv) + const std::vector *model_uv, + float resting_drop) { // The classic path moves the vertices the mesh already has, so there is no budget to report on. (void) stats; @@ -3067,7 +3072,7 @@ static indexed_triangle_set build_texture_displacement_in_place( if (options.pipeline_v2) return build_texture_displacement_v2(mesh, layers, facets_data, options, progress, color, flip_normals, - debug, stats, model_uv); + debug, stats, model_uv, resting_drop); // Layers are combined in slot order, like stacked layers in an image editor: each one folds its // own displacement into the running total via its blend mode (see TextureBlendMode). @@ -3399,10 +3404,12 @@ static indexed_triangle_set build_texture_displacement_in_place( if (!any_displacement) return mesh; - // The model's own resting plane, taken before anything moves - see the clamp after smoothing. + // The plane the model rests on, taken before anything moves - see the clamp after smoothing. That + // is this mesh's own bottom, lowered to the object's when another part of it sits lower. float resting_z = std::numeric_limits::max(); for (const Vec3f &v : mesh.vertices) resting_z = std::min(resting_z, v.z()); + resting_z -= resting_drop; size_t moved_count = 0; for (size_t vi = 0; vi < mesh.vertices.size(); ++vi) @@ -3494,17 +3501,20 @@ indexed_triangle_set build_texture_displacement(const indexed_triangle_set const Transform3d &volume_to_world, BakeStageRecorder *debug, TextureBakeStats *stats, - const std::vector *model_uv) + const std::vector *model_uv, + const Vec3d *texture_anchor, + float resting_drop) { // An untransformed volume on an untransformed instance is by far the common case, and the round // trip costs two matrix multiplies per vertex on a mesh that can carry millions of them - so take // the identity out of the way rather than paying for it. // The texture is projected in the bake frame - world orientation and scale, anchored at the - // volume's origin (see texture_displacement_bake_frame()). - const Transform3d frame = texture_displacement_bake_frame(volume_to_world); + // texture's anchor (see texture_displacement_bake_frame()). + const Transform3d frame = texture_anchor != nullptr ? texture_displacement_bake_frame(volume_to_world, *texture_anchor) : + texture_displacement_bake_frame(volume_to_world); if (frame.matrix().isApprox(Transform3d::Identity().matrix())) return build_texture_displacement_in_place(base_mesh, layers, facets_data, options, progress, color, - false, debug, stats, model_uv); + false, debug, stats, model_uv, resting_drop); const Transform3d to_local = frame.inverse(); // A mirroring placement leaves the positions correct but every winding-derived normal pointing @@ -3520,8 +3530,8 @@ indexed_triangle_set build_texture_displacement(const indexed_triangle_set const size_t debug_mark = (debug != nullptr) ? debug->mark() : 0; // The UV channel rides along untouched: a uv is a coordinate in the texture, not on the model, so // the frame the mesh is measured in does not reach it. - indexed_triangle_set out = build_texture_displacement_in_place(world, layers, facets_data, options, - progress, color, mirrored, debug, stats, model_uv); + indexed_triangle_set out = build_texture_displacement_in_place(world, layers, facets_data, options, progress, + color, mirrored, debug, stats, model_uv, resting_drop); // Everything the bake recorded is in world millimetres, like `out` itself. The debug view draws in // the volume's local frame, so the stages are brought back the same way the result is. if (debug != nullptr) @@ -3568,13 +3578,18 @@ void texture_displacement_patch_frame(const indexed_triangle_set &patch, const s (an.y() <= an.x() && an.y() <= an.z()) ? Vec3f::UnitY() : Vec3f::UnitZ(); } +Transform3d texture_displacement_bake_frame(const Transform3d &volume_to_world, const Vec3d &anchor) +{ + // World orientation and scale, but the origin moved onto the model: the texture then rides with + // the model when it is moved about the plate (and a single, untiled stamp starts on the model + // rather than at the plate's corner), while a tile is still `tiling_scale` printed millimetres + // whatever the instance's scale. + return Eigen::Translation3d(-anchor) * volume_to_world; +} + Transform3d texture_displacement_bake_frame(const Transform3d &volume_to_world) { - // World orientation and scale, but the origin moved to where the volume's own origin sits: the - // texture then rides with the model when it is moved about the plate (and a single, untiled stamp - // starts on the model rather than at the plate's corner), while a tile is still `tiling_scale` - // printed millimetres whatever the instance's scale. - return Eigen::Translation3d(-volume_to_world.translation()) * volume_to_world; + return texture_displacement_bake_frame(volume_to_world, volume_to_world.translation()); } Transform3d texture_displacement_volume_to_world(const ModelVolume &volume) diff --git a/src/libslic3r/TextureDisplacement.hpp b/src/libslic3r/TextureDisplacement.hpp index 919dfad654..89450270eb 100644 --- a/src/libslic3r/TextureDisplacement.hpp +++ b/src/libslic3r/TextureDisplacement.hpp @@ -1040,14 +1040,26 @@ indexed_triangle_set build_texture_displacement(const indexed_triangle_set // When given, receives what the bake spent. TextureBakeStats *stats = nullptr, // The model's own UV channel; see above. - const std::vector *model_uv = nullptr); + const std::vector *model_uv = nullptr, + // The world point the texture is anchored at, null for + // the volume's own origin. Every part of a multibody + // object passes the same point, so the pattern runs on + // across them. See texture_displacement_bake_frame(). + const Vec3d *texture_anchor = nullptr, + // How far the object's lowest point lies below this + // volume's own, in mm. Relief is kept above the plane + // the whole object rests on, so a part held off the + // plate by another keeps the relief on its underside. + float resting_drop = 0.f); // `volume`'s mesh coordinates -> world millimetres: its first instance's transform times its own. // The mesh is shared by every instance, so a multi-instance object can only be baked for one of // them; the first is what the gizmo edits against. Identity when the volume has no object yet. Transform3d texture_displacement_volume_to_world(const ModelVolume &volume); -// The frame the bake and the previews project the texture in: `volume_to_world` with its translation -// removed, i.e. world orientation and scale about the volume's own origin. See build_texture_displacement(). +// The frame the bake and the previews project the texture in: world orientation and scale, with the +// world point `anchor` as its origin. See build_texture_displacement(). +Transform3d texture_displacement_bake_frame(const Transform3d &volume_to_world, const Vec3d &anchor); +// Anchored at the volume's own origin, which is where a single-part object's texture sits. Transform3d texture_displacement_bake_frame(const Transform3d &volume_to_world); // Area-weighted vertex normals of `its` - the directions the bake both projects and displaces along. diff --git a/src/slic3r/GUI/3DScene.cpp b/src/slic3r/GUI/3DScene.cpp index 3895275a33..071663b851 100644 --- a/src/slic3r/GUI/3DScene.cpp +++ b/src/slic3r/GUI/3DScene.cpp @@ -58,6 +58,8 @@ #include #include +#include + #include #include @@ -1454,10 +1456,31 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo BuildVolume plate_build_volume(pp_bed_shape, build_volume.printable_height(), build_volume.extruder_areas(), build_volume.extruder_heights()); const std::vector& exclude_areas = curr_plate->get_exclude_areas(); + const DynamicPrintConfig *plater_config = GUI::wxGetApp().plater()->config(); + std::vector> exclusion_regions; + // Legacy bed-exclude areas retain Orca's existing 2D presentation. The + // per-extruder 3D state is needed only after collision volumes are enabled. + if (has_bed_exclude_volumes(*plater_config)) { + exclusion_regions = get_bed_excluded_regions_by_extruder(*plater_config); + // The native BuildVolume path below already presents the shared legacy + // area. Merge only opt-in collision volumes into nozzle-specific state. + for (std::vector ®ions : exclusion_regions) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } + const Vec3d plate_origin = curr_plate->get_origin(); + const Point exclusion_offset(scale_(plate_origin.x()), scale_(plate_origin.y())); + for (std::vector ®ions : exclusion_regions) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(exclusion_offset); + std::map>> objects_unprintable_filaments; - int extruder_count = build_volume.get_extruder_area_count(); + const DynamicPrintConfig &plate_project_config = GUI::wxGetApp().preset_bundle->project_config; + const int build_volume_extruder_count = build_volume.get_extruder_area_count(); + const int extruder_count = std::max(build_volume_extruder_count, int(exclusion_regions.size())); std::vector> unprintable_filament_ids(extruder_count, std::set()); std::set partly_objects_set; + std::map, std::vector> instance_inside_exclusion_regions; const ModelObjectPtrs &model_objects = model.objects; for (GLVolume* volume : this->volumes) { @@ -1472,7 +1495,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo //FIXME this test does not evaluate collision of a build volume bounding box with non-convex objects. const BoundingBoxf3& bb = volume_bbox(*volume); state = plate_build_volume.volume_state_bbox(bb); - if ((state == BuildVolume::ObjectState::Inside) && (extruder_count > 1)) + if ((state == BuildVolume::ObjectState::Inside) && (build_volume_extruder_count > 1)) { state = plate_build_volume.check_volume_bbox_state_with_extruder_areas(bb, inside_extruders); } @@ -1486,7 +1509,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo const indexed_triangle_set& convex_mesh_it = volume_convex_mesh(*volume).its; const Transform3f trafo = volume->world_matrix().cast(); state = plate_build_volume.object_state(convex_mesh_it, trafo, volume_sinking(*volume)); - if ((state == BuildVolume::ObjectState::Inside) && (extruder_count > 1)) + if ((state == BuildVolume::ObjectState::Inside) && (build_volume_extruder_count > 1)) { state = plate_build_volume.check_object_state_with_extruder_areas(convex_mesh_it, trafo, inside_extruders); } @@ -1499,12 +1522,52 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo } assert(state != BuildVolume::ObjectState::Below); + // Preserve Orca's native printable-area result separately. + // Exclusion collisions have current-map semantics and must not + // leak into the later "unprintable on every possible nozzle" + // aggregation used by automatic printable-area assignment. + const std::vector printable_area_inside_extruders = inside_extruders; + + // Newer Orca resolves live multi-nozzle placement through this + // per-extruder state vector. Merge exclusion-volume collisions + // into the same source of truth instead of relying only on the + // legacy PartPlate::check_outside() path. + if ((state == BuildVolume::ObjectState::Inside || state == BuildVolume::ObjectState::Limited) && + volume->object_idx() >= 0 && volume->object_idx() < int(model_objects.size()) && + volume->instance_idx() >= 0 && + volume->instance_idx() < int(model_objects[volume->object_idx()]->instances.size())) { + inside_extruders.resize(extruder_count, true); + + const std::pair instance_key{ volume->object_idx(), volume->instance_idx() }; + auto [cache_it, inserted] = instance_inside_exclusion_regions.emplace( + instance_key, std::vector(extruder_count, true)); + if (inserted) { + const ModelInstance *instance = model_objects[volume->object_idx()]->instances[volume->instance_idx()]; + for (size_t extruder_id = 0; extruder_id < exclusion_regions.size(); ++extruder_id) { + if (instance->intersects_bed_exclude_regions(exclusion_regions[extruder_id])) + cache_it->second[extruder_id] = false; + } + } + + bool exclusion_limited = false; + for (size_t extruder_id = 0; extruder_id < cache_it->second.size(); ++extruder_id) { + if (!cache_it->second[extruder_id]) { + inside_extruders[extruder_id] = false; + exclusion_limited = true; + } + } + + if (exclusion_limited && state == BuildVolume::ObjectState::Inside) + state = extruder_count > 1 ? BuildVolume::ObjectState::Limited : BuildVolume::ObjectState::Colliding; + + } + if (state == BuildVolume::ObjectState::Limited) { //unprintable_filament_ids.resize(inside_extruders.size()); ModelObject *model_object = model_objects[volume->object_idx()]; ModelVolume *model_volume = model_object->volumes[volume->volume_idx()]; - for (size_t i = 0; i < inside_extruders.size(); ++i) { - if (!inside_extruders[i]) { + for (size_t i = 0; i < printable_area_inside_extruders.size(); ++i) { + if (!printable_area_inside_extruders[i]) { std::vector filaments = model_volume->get_extruders(); unprintable_filament_ids[i].insert(filaments.begin(), filaments.end()); if (object_results) { @@ -1579,8 +1642,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo //check per-object error for extruder areas if (object_results && (extruder_count > 1)) { - const auto& project_config = Slic3r::GUI::wxGetApp().preset_bundle->project_config; - object_results->mode = curr_plate->get_real_filament_map_mode(project_config); + object_results->mode = curr_plate->get_real_filament_map_mode(plate_project_config); if (object_results->mode < FilamentMapMode::fmmManual) { std::vector conflict_filament_vector; @@ -1642,8 +1704,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo else { std::set conflict_filaments_set; - const auto& project_config = Slic3r::GUI::wxGetApp().preset_bundle->project_config; - std::vector filament_maps = curr_plate->get_real_filament_maps(project_config); + std::vector filament_maps = curr_plate->get_real_filament_maps(plate_project_config); for (auto& object_map: objects_unprintable_filaments) { ModelObject *model_object = object_map.first; @@ -1658,7 +1719,8 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo for (int filament: filaments_set) { - if (filament_maps[filament - 1] == extruder_id) + if (filament > 0 && size_t(filament) <= filament_maps.size() && + filament_maps[filament - 1] == extruder_id) { object_filament_info.manual_filaments.emplace(filament, extruder_id); object_results->filament_maps[filament] = extruder_id; @@ -1675,6 +1737,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo object_results->filaments = std::vector(conflict_filaments_set.begin(), conflict_filaments_set.end()); } } + } /*for (GLVolume* volume : this->volumes) diff --git a/src/slic3r/GUI/3DScene.hpp b/src/slic3r/GUI/3DScene.hpp index d7ff4168c8..ac31946c80 100644 --- a/src/slic3r/GUI/3DScene.hpp +++ b/src/slic3r/GUI/3DScene.hpp @@ -69,7 +69,7 @@ enum ModelInstanceEPrintVolumeState : unsigned char; using ModelObjectPtrs = std::vector; struct ObjectFilamentInfo { - ModelObject* object; + ModelObject* object { nullptr }; std::map manual_filaments; //manual mode: filament id -> extruder id can not be printed std::vector auto_filaments; //auto mode: filaments in all extruder's outside area diff --git a/src/slic3r/GUI/ActionRegistry.cpp b/src/slic3r/GUI/ActionRegistry.cpp index 6956423bc6..011381b33e 100644 --- a/src/slic3r/GUI/ActionRegistry.cpp +++ b/src/slic3r/GUI/ActionRegistry.cpp @@ -3,9 +3,11 @@ #include "GUI.hpp" #include "GUI_App.hpp" #include "I18N.hpp" +#include "ImGuiWrapper.hpp" #include "MainFrame.hpp" #include "NativeCommands.hpp" #include "Notebook.hpp" +#include "NotificationManager.hpp" #include "OptionsGroup.hpp" #include "Plater.hpp" #include "SettingsIndex.hpp" @@ -99,6 +101,45 @@ std::string find_loaded_source_name(PluginManager& manager, const std::string& p return plugin_key; } +// Translates a Script capability outcome into the action layer's result vocabulary. Shared by +// the synchronous run path and the async completion notification. +AppActionRunResult script_outcome_to_action_result(const ScriptCompletion& completion) +{ + // Cancelled by PluginManager (unload/shutdown): expected termination, nothing to show. + if (completion.cancelled) + return {}; + + if (!completion.error.empty()) + return {AppActionRunResult::Level::Error, from_u8(completion.error)}; + + const ExecutionResult& result = completion.result; + const bool skipped = result.status == PluginResult::Skipped; + const wxString fallback = skipped ? _L("Script plugin skipped.") : _L("Script plugin finished."); + return {skipped ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Success, + result.message.empty() ? fallback : from_u8(result.message)}; +} + +// Surfaces the eventual outcome of an async script launched from the speed dial. That launch +// already returned (the UI was not blocked), so the finish is reported as a notification. A +// cancellation is silent. +void notify_script_outcome(const ScriptCompletion& completion) +{ + if (completion.cancelled) + return; + if (wxTheApp == nullptr || wxGetApp().is_closing()) + return; + + Plater* plater = wxGetApp().plater(); + if (plater == nullptr || wxGetApp().imgui() == nullptr || !wxGetApp().imgui()->display_initialized()) + return; + + const AppActionRunResult action_result = script_outcome_to_action_result(completion); + const auto level = action_result.level == AppActionRunResult::Level::Error + ? NotificationManager::NotificationLevel::ErrorNotificationLevel + : NotificationManager::NotificationLevel::RegularNotificationLevel; + plater->get_notification_manager()->push_notification(NotificationType::CustomNotification, level, into_u8(action_result.message)); +} + // A runnable script capability exposed as a speed-dial action. source_key = plugin_key // (identity), so a plugin display-name change does not re-key the action. struct PluginScriptAction : AppAction @@ -124,15 +165,36 @@ struct PluginScriptAction : AppAction AppActionRunResult run(const std::string& /*param*/) const override { - std::string error; - const ExecutionResult result = PluginManager::instance().run_script_capability(plugin_key, capability, error); - if (!error.empty()) - return {AppActionRunResult::Level::Error, from_u8(error)}; + struct Outcome + { + bool async = false; + bool completed = false; + AppActionRunResult result; + }; + auto outcome = std::make_shared(); - const bool skipped = result.status == PluginResult::Skipped; - const wxString fallback = skipped ? _L("Script plugin skipped.") : _L("Script plugin finished."); - return {skipped ? AppActionRunResult::Level::Info : AppActionRunResult::Level::Success, - result.message.empty() ? fallback : from_u8(result.message)}; + auto on_done = [outcome](const ScriptCompletion& completion) { + outcome->result = script_outcome_to_action_result(completion); + outcome->completed = true; + if (outcome->async) + notify_script_outcome(completion); + }; + + const PluginManager::ScriptLaunchResult launch = PluginManager::instance().launch_script_capability(plugin_key, capability, on_done); + if (launch.launched_async) { + // The completion is delivered on this (GUI) thread once the (sync or async) invocation + // finishes, so marking `async` here cannot race with on_done. The speed dial has already + // shown a result by then; the final outcome arrives as a notification (a cancellation is + // silent). + outcome->async = true; + if (outcome->completed) + return outcome->result; + return {AppActionRunResult::Level::Info, _L("Script plugin started.")}; + } + + // The launch failed inline; on_done produced the (error) result. + on_done(launch.outcome); + return outcome->result; } }; diff --git a/src/slic3r/GUI/CAD/SketchInlineEditor.hpp b/src/slic3r/GUI/CAD/SketchInlineEditor.hpp index 677e74b3a0..1721066cd8 100644 --- a/src/slic3r/GUI/CAD/SketchInlineEditor.hpp +++ b/src/slic3r/GUI/CAD/SketchInlineEditor.hpp @@ -68,8 +68,8 @@ public: // (nothing further) <- the canvas has nothing to redraw, so it stops // // This canvas repaints ON DEMAND. ImGui decides whether it wants the keyboard at the END of a - // frame, from the active item, and GLCanvas3D::on_char only calls render() when - // update_key_data() says ImGui wants it. No frames -> WantTextInput never turns on -> no + // frame, from the active item, and GLCanvas3D::on_char only calls render() when ImGui + // wants or claims the key. No frames -> WantTextInput never turns on -> no // render on a keystroke -> still no frames. The characters sit in ImGui's queue and the field // looks exactly as deaf as the window it replaced. One repaint per frame while it is open // breaks the circle. diff --git a/src/slic3r/GUI/CalibrationWizard.cpp b/src/slic3r/GUI/CalibrationWizard.cpp index 5d287942ba..912973828c 100644 --- a/src/slic3r/GUI/CalibrationWizard.cpp +++ b/src/slic3r/GUI/CalibrationWizard.cpp @@ -435,7 +435,7 @@ void CalibrationWizard::cache_preset_info(MachineObject *obj, float nozzle_dia, if (obj->is_multi_extruders()) { int ams_id, slot_id, tray_id; get_tray_ams_and_slot_id(curr_obj, result.tray_id, ams_id, slot_id, tray_id); - result.extruder_id = preset_page->get_extruder_id(ams_id); + result.extruder_id = preset_page->get_extruder_id_by_tray_id(result.tray_id); result.nozzle_diameter = preset_page->get_nozzle_diameter(result.extruder_id); } else { @@ -753,7 +753,7 @@ void PressureAdvanceWizard::on_cali_start() X1CCalibInfos::X1CCalibInfo calib_info; get_tray_ams_and_slot_id(curr_obj, item.first, calib_info.ams_id, calib_info.slot_id, calib_info.tray_id); - calib_info.extruder_id = preset_page->get_extruder_id(calib_info.ams_id); + calib_info.extruder_id = preset_page->get_extruder_id_by_tray_id(item.first); calib_info.extruder_type = preset_page->get_extruder_type(calib_info.extruder_id); calib_info.nozzle_volume_type = preset_page->get_nozzle_volume_type(calib_info.extruder_id); calib_info.nozzle_diameter = preset_page->get_nozzle_diameter(calib_info.extruder_id); @@ -792,7 +792,7 @@ void PressureAdvanceWizard::on_cali_start() CalibInfo calib_info; calib_info.dev_id = curr_obj->get_dev_id(); get_tray_ams_and_slot_id(curr_obj, selected_filaments.begin()->first, calib_info.ams_id, calib_info.slot_id, selected_tray_id); - calib_info.extruder_id = preset_page->get_extruder_id(calib_info.ams_id); + calib_info.extruder_id = preset_page->get_extruder_id_by_tray_id(selected_filaments.begin()->first); calib_info.extruder_type = preset_page->get_extruder_type(calib_info.extruder_id); calib_info.nozzle_volume_type = preset_page->get_nozzle_volume_type(calib_info.extruder_id); calib_info.nozzle_diameter = preset_page->get_nozzle_diameter(calib_info.extruder_id); @@ -877,7 +877,7 @@ void PressureAdvanceWizard::on_cali_start() calib_info.dev_id = curr_obj->get_dev_id(); get_tray_ams_and_slot_id(curr_obj, item.first, calib_info.ams_id, calib_info.slot_id, selected_tray_id); calib_info.index = preset_page->get_index_by_tray_id(item.first); - calib_info.extruder_id = preset_page->get_extruder_id(calib_info.ams_id); + calib_info.extruder_id = preset_page->get_extruder_id_by_tray_id(item.first); calib_info.nozzle_diameter = preset_page->get_nozzle_diameter(calib_info.extruder_id); calib_info.extruder_type = preset_page->get_extruder_type(calib_info.extruder_id); calib_info.nozzle_volume_type = preset_page->get_nozzle_volume_type(calib_info.extruder_id); @@ -1252,7 +1252,7 @@ void FlowRateWizard::on_cali_start(CaliPresetStage stage, float cali_value, Flow X1CCalibInfos::X1CCalibInfo calib_info; calib_info.tray_id = item.first; get_tray_ams_and_slot_id(curr_obj, item.first, calib_info.ams_id, calib_info.slot_id, calib_info.tray_id); - calib_info.extruder_id = preset_page->get_extruder_id(calib_info.ams_id); + calib_info.extruder_id = preset_page->get_extruder_id_by_tray_id(item.first); calib_info.extruder_type = preset_page->get_extruder_type(calib_info.extruder_id); calib_info.nozzle_volume_type = preset_page->get_nozzle_volume_type(calib_info.extruder_id); calib_info.nozzle_diameter = preset_page->get_nozzle_diameter(calib_info.extruder_id); @@ -1308,7 +1308,15 @@ void FlowRateWizard::on_cali_start(CaliPresetStage stage, float cali_value, Flow int selected_tray_id = 0; get_tray_ams_and_slot_id(curr_obj, selected_filaments.begin()->first, calib_info.ams_id, calib_info.slot_id, selected_tray_id); calib_info.select_ams = std::to_string(selected_tray_id); - calib_info.extruder_id = preset_page->get_extruder_id(calib_info.ams_id); + calib_info.extruder_id = preset_page->get_extruder_id_by_tray_id(selected_filaments.begin()->first); + if (from_page == FlowRatioCaliSource::FROM_COARSE_PAGE) { + // The fine pass must run on the extruder the coarse pass used. The cache records it; + // the preset page's selection may have changed or been reset since. + const auto cached = get_cached_selected_filament_for_multi_extruder(curr_obj); + const auto it = cached.find(selected_filaments.begin()->first); + if (it != cached.end()) + calib_info.extruder_id = it->second.extruder_id; + } calib_info.extruder_type = preset_page->get_extruder_type(calib_info.extruder_id); calib_info.nozzle_volume_type = preset_page->get_nozzle_volume_type(calib_info.extruder_id); calib_info.nozzle_diameter = preset_page->get_nozzle_diameter(calib_info.extruder_id); @@ -1724,7 +1732,7 @@ void MaxVolumetricSpeedWizard::on_cali_start() int selected_tray_id = 0; get_tray_ams_and_slot_id(curr_obj, selected_filaments.begin()->first, calib_info.ams_id, calib_info.slot_id, selected_tray_id); calib_info.select_ams = std::to_string(selected_tray_id); - calib_info.extruder_id = preset_page->get_extruder_id(calib_info.ams_id); + calib_info.extruder_id = preset_page->get_extruder_id_by_tray_id(selected_filaments.begin()->first); calib_info.extruder_type = preset_page->get_extruder_type(calib_info.extruder_id); calib_info.nozzle_volume_type = preset_page->get_nozzle_volume_type(calib_info.extruder_id); calib_info.nozzle_diameter = preset_page->get_nozzle_diameter(calib_info.extruder_id); diff --git a/src/slic3r/GUI/CalibrationWizardPresetPage.cpp b/src/slic3r/GUI/CalibrationWizardPresetPage.cpp index 754d3457cb..673026159e 100644 --- a/src/slic3r/GUI/CalibrationWizardPresetPage.cpp +++ b/src/slic3r/GUI/CalibrationWizardPresetPage.cpp @@ -587,8 +587,23 @@ void CalibrationPresetPage::on_sys_color_changed() m_ams_sync_button->msw_rescale(); } -int CalibrationPresetPage::get_extruder_id(int ams_id) +int CalibrationPresetPage::get_extruder_id_by_tray_id(int tray_id) { + // An AMS behind a Filament Track Switch feeds both extruders, so the extruder is the one + // whose panel the filament was selected in. + if (curr_obj && curr_obj->is_multi_extruders()) { + for (FilamentComboBox *fcb : get_selected_filament_combobox()) { + if (fcb->get_tray_id() != tray_id) + continue; + const bool is_deputy = std::find(m_deputy_filament_comboBox_list.begin(), m_deputy_filament_comboBox_list.end(), fcb) != + m_deputy_filament_comboBox_list.end(); + return is_deputy ? DEPUTY_EXTRUDER_ID : MAIN_EXTRUDER_ID; + } + } + + int ams_id = tray_id / 4, slot_id, unused_tray_id; + if (curr_obj) + get_tray_ams_and_slot_id(curr_obj, tray_id, ams_id, slot_id, unused_tray_id); if (m_ams_id_to_extruder_id_map.find(ams_id) != m_ams_id_to_extruder_id_map.end()) { return m_ams_id_to_extruder_id_map[ams_id]; } @@ -866,6 +881,18 @@ static void fill_nozzle_volume_combo(ComboBox *combo) select_nozzle_volume(combo, NozzleVolumeType::nvtStandard); } +static DynamicPrintConfig empty_tray_config() +{ + DynamicPrintConfig config; + config.set_key_value("filament_id", new ConfigOptionStrings{""}); + config.set_key_value("tag_uid", new ConfigOptionStrings{""}); + config.set_key_value("filament_type", new ConfigOptionStrings{""}); + config.set_key_value("tray_name", new ConfigOptionStrings{""}); + config.set_key_value("filament_colour", new ConfigOptionStrings{""}); + config.set_key_value("filament_exist", new ConfigOptionBools{false}); + return config; +} + void CalibrationPresetPage::init_selection_values() { // init nozzle diameter and nozzle volume @@ -2272,27 +2299,36 @@ void CalibrationPresetPage::sync_ams_info(MachineObject* obj) } } - // init virtual tray info - if (full_filament_ams_list.find(VIRTUAL_TRAY_MAIN_ID) != full_filament_ams_list.end()) { - filament_ams_list[VIRTUAL_TRAY_MAIN_ID] = full_filament_ams_list[VIRTUAL_TRAY_MAIN_ID]; - } + // init virtual tray info. With a Filament Track Switch installed the external spools feed + // through the switch, so they can't be calibrated as their own trays. + if (obj->GetFilaSwitch()->IsInstalled()) { + filament_ams_list[VIRTUAL_TRAY_MAIN_ID] = empty_tray_config(); + filament_ams_list[VIRTUAL_TRAY_DEPUTY_ID] = empty_tray_config(); + } else { + if (full_filament_ams_list.find(VIRTUAL_TRAY_MAIN_ID) != full_filament_ams_list.end()) { + filament_ams_list[VIRTUAL_TRAY_MAIN_ID] = full_filament_ams_list[VIRTUAL_TRAY_MAIN_ID]; + } - if (full_filament_ams_list.find(VIRTUAL_TRAY_DEPUTY_ID) != full_filament_ams_list.end()) { - filament_ams_list[VIRTUAL_TRAY_DEPUTY_ID] = full_filament_ams_list[VIRTUAL_TRAY_DEPUTY_ID]; + if (full_filament_ams_list.find(VIRTUAL_TRAY_DEPUTY_ID) != full_filament_ams_list.end()) { + filament_ams_list[VIRTUAL_TRAY_DEPUTY_ID] = full_filament_ams_list[VIRTUAL_TRAY_DEPUTY_ID]; + } } // update filament from panel, display only obj has ams // update multi ams panel, display only obj has multi ams if (obj->HasAms()) { if (obj->is_multi_extruders()) { + // An AMS behind a Filament Track Switch is bound to both extruders and appears in both panels. bool main_done = false; bool deputy_done = false; for (auto &ams_item : obj->GetFilaSystem()->GetAmsList()) { - if (ams_item.second->GetExtruderId() == 0 && !main_done) { - update_multi_extruder_filament_combobox(ams_item.second->GetAmsId(), ams_item.second->GetExtruderId()); + const auto &extruder_set = ams_item.second->GetBindedExtruderSet(); + if (!main_done && extruder_set.count(MAIN_EXTRUDER_ID) != 0) { + update_multi_extruder_filament_combobox(ams_item.second->GetAmsId(), MAIN_EXTRUDER_ID); main_done = true; - } else if (ams_item.second->GetExtruderId() == 1 && !deputy_done) { - update_multi_extruder_filament_combobox(ams_item.second->GetAmsId(), ams_item.second->GetExtruderId()); + } + if (!deputy_done && extruder_set.count(DEPUTY_EXTRUDER_ID) != 0) { + update_multi_extruder_filament_combobox(ams_item.second->GetAmsId(), DEPUTY_EXTRUDER_ID); deputy_done = true; } } @@ -2333,10 +2369,11 @@ void CalibrationPresetPage::sync_ams_info(MachineObject* obj) if (ams->second->IsExist() && info.parse_ams_info(obj, ams->second, obj->GetFilaSystem()->IsDetectRemainEnabled(), obj->is_support_ams_humidity)) { ams_info.push_back(info); - if (info.nozzle_id == 0) { - main_ams_info.push_back(info); - } else { - deputy_ams_info.push_back(info); + for (int extruder_id : ams->second->GetBindedExtruderSet()) { + if (extruder_id == MAIN_EXTRUDER_ID) + main_ams_info.push_back(info); + else + deputy_ams_info.push_back(info); } } m_ams_id_to_extruder_id_map[stoi(info.ams_id)] = info.nozzle_id; @@ -2584,13 +2621,7 @@ void CalibrationPresetPage::update_multi_extruder_filament_combobox(const std::s } } - DynamicPrintConfig empty_config; - empty_config.set_key_value("filament_id", new ConfigOptionStrings{""}); - empty_config.set_key_value("tag_uid", new ConfigOptionStrings{""}); - empty_config.set_key_value("filament_type", new ConfigOptionStrings{""}); - empty_config.set_key_value("tray_name", new ConfigOptionStrings{""}); - empty_config.set_key_value("filament_colour", new ConfigOptionStrings{""}); - empty_config.set_key_value("filament_exist", new ConfigOptionBools{false}); + DynamicPrintConfig empty_config = empty_tray_config(); if (filament_ams_list.empty()) return; diff --git a/src/slic3r/GUI/CalibrationWizardPresetPage.hpp b/src/slic3r/GUI/CalibrationWizardPresetPage.hpp index 1ad2a2e1e1..27753baf26 100644 --- a/src/slic3r/GUI/CalibrationWizardPresetPage.hpp +++ b/src/slic3r/GUI/CalibrationWizardPresetPage.hpp @@ -251,7 +251,7 @@ public: void msw_rescale() override; void on_sys_color_changed() override; - int get_extruder_id(int ams_id); + int get_extruder_id_by_tray_id(int tray_id); float get_nozzle_diameter(int extruder_id) const; NozzleVolumeType get_nozzle_volume_type(int extruder_id) const; ExtruderType get_extruder_type(int extruder_id) const; diff --git a/src/slic3r/GUI/ConfigManipulation.cpp b/src/slic3r/GUI/ConfigManipulation.cpp index a03f63c737..9af9a4309f 100644 --- a/src/slic3r/GUI/ConfigManipulation.cpp +++ b/src/slic3r/GUI/ConfigManipulation.cpp @@ -807,7 +807,7 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in toggle_field("enable_arc_fitting", !have_volumetric_extrusion_rate_slope && !is_belt_printer); toggle_line("max_volumetric_extrusion_rate_slope_segment_length", have_volumetric_extrusion_rate_slope); toggle_line("extrusion_rate_smoothing_external_perimeter_only", have_volumetric_extrusion_rate_slope); - if(have_volumetric_extrusion_rate_slope) config->set_key_value("enable_arc_fitting", new ConfigOptionBool(false)); + if(have_volumetric_extrusion_rate_slope) config->set_key_value("enable_arc_fitting", new ConfigOptionEnum(ArcFittingMode::Disabled)); if(have_volumetric_extrusion_rate_slope_segment_length < 0.5) { DynamicPrintConfig new_conf = *config; new_conf.set_key_value("max_volumetric_extrusion_rate_slope_segment_length", new ConfigOptionFloat(1)); diff --git a/src/slic3r/GUI/ConfigValueFormatter.cpp b/src/slic3r/GUI/ConfigValueFormatter.cpp index 8536e6731d..58f219a9ed 100644 --- a/src/slic3r/GUI/ConfigValueFormatter.cpp +++ b/src/slic3r/GUI/ConfigValueFormatter.cpp @@ -242,7 +242,7 @@ wxString get_string_value(const std::string& opt_key, const DynamicPrintConfig& return get_thumbnails_string(points.values); } else if (pure_key == "bed_exclude_area") { - return get_thumbnails_string(config.option(pure_key)->values); + return from_u8(config.option(pure_key)->serialize()); } else if (pure_key == "head_wrap_detect_zone") { return get_thumbnails_string(config.option(pure_key)->values); diff --git a/src/slic3r/GUI/ConfigWizard.cpp b/src/slic3r/GUI/ConfigWizard.cpp index 5d14f8162e..d04e3f718a 100644 --- a/src/slic3r/GUI/ConfigWizard.cpp +++ b/src/slic3r/GUI/ConfigWizard.cpp @@ -2671,7 +2671,8 @@ ConfigWizard::ConfigWizard(wxWindow *parent) p->load_vendors(); //BBS: add bed exclude areas p->custom_config.reset(DynamicPrintConfig::new_from_defaults_keys({ - "gcode_flavor", "printable_area", "bed_exclude_area", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" + "gcode_flavor", "printable_area", "bed_exclude_area", "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", + "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" //, "nozzle_temperature", "bed_temperature" })); diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index f2ae0490d9..55c491f811 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -733,6 +733,14 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true m_value = into_u8(str); } break; + } else if (m_opt.opt_key == "bed_exclude_volumes" || m_opt.opt_key == "extruder_bed_exclude_volumes") { + const std::string definition = into_u8(str); + if (!is_valid_bed_exclude_volumes_string(definition, std::numeric_limits::max())) { + show_error(m_parent, _L("Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + const std::string old_value = m_value.empty() ? std::string{} : boost::any_cast(m_value); + set_value(from_u8(old_value), true); + break; + } } else if (m_opt.opt_key == "extra_solid_infills") { std::string ustr(str.utf8_string()); // New rule: accept either interval form (N or N#K) or explicit list (e.g. 1,7,9), with optional quotes. @@ -784,11 +792,18 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true case coPoints: { std::vector out_values; str.Replace(" ", wxEmptyString, true); + const bool bed_exclusion_volume_syntax = m_opt_id == "bed_exclude_area" && + (str.Find("|") != wxNOT_FOUND || (str.Find("..") != wxNOT_FOUND && str.Find(";") != wxNOT_FOUND)); + if (bed_exclusion_volume_syntax) { + // Leave volume validation and the copy prompt to the printer tab. + m_value = into_u8(str); + break; + } if (!str.IsEmpty()) { bool invalid_val = false; - wxStringTokenizer thumbnails(str, ","); - while (thumbnails.HasMoreTokens()) { - wxString token = thumbnails.GetNextToken(); + wxStringTokenizer points(str, ","); + while (points.HasMoreTokens()) { + wxString token = points.GetNextToken(); double x, y; wxStringTokenizer thumbnail(token, "x"); if (thumbnail.HasMoreTokens()) { @@ -807,10 +822,11 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true if (invalid_val) { wxString text_value; - if (!m_value.empty()) + if (!m_value.empty() && boost::any_cast>(&m_value) != nullptr) text_value = get_thumbnails_string(boost::any_cast>(m_value)); set_value(text_value, true); - show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""),"XxY, XxY, ..." )); + show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""), "XxY, XxY, ...")); + break; } } diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 50ba576736..2f72a8e976 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -1886,27 +1886,31 @@ static std::pair construct_extruder_unprintable_error(ObjectFilament auto mode = object_result.mode; for (auto& obj_filament : object_result.object_filaments) { + bool found_left = false; + bool found_right = false; + if (mode == FilamentMapMode::fmmManual) { for (auto& elem : obj_filament.manual_filaments) { - bool found_left = false, found_right = false; - int filamnet_id = elem.first; int extruder_id = elem.second; - if (extruder_id == 1 && !found_left) { + if (extruder_id == 1) { found_left = true; - left_unprintable_objects.emplace_back(obj_filament); } - if (extruder_id == 2 && !found_right) { + if (extruder_id == 2) { found_right = true; - right_unprintable_objects.emplace_back(obj_filament); } } } else { if (!obj_filament.auto_filaments.empty()) { - left_unprintable_objects.emplace_back(obj_filament); - right_unprintable_objects.emplace_back(obj_filament); + found_left = true; + found_right = true; } } + + if (found_left) + left_unprintable_objects.emplace_back(obj_filament); + if (found_right) + right_unprintable_objects.emplace_back(obj_filament); } Preset &preset = GUI::wxGetApp().preset_bundle->printers.get_edited_preset(); @@ -1942,7 +1946,7 @@ static std::pair construct_extruder_unprintable_error(ObjectFilament model_prefix = (boost::format(_u8L("The position or size of some models exceeds the %s's printable range.")) % nozzle_name).str(); else model_prefix = (boost::format(_u8L("The position or size of the model %s exceeds the %s's printable range.")) - %object_result.object_filaments.front().object->name % nozzle_name).str(); + %unprintable_objs.front().object->name % nozzle_name).str(); tips[idx] += model_prefix; tips[idx] += (boost::format(_u8L(" Please check and adjust the part's position or size to fit the printable range:\n"))).str(); @@ -2813,7 +2817,6 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) // Design tab: replace the plate's corner-origin grid with the origin-centred CAD grid. _render_cad_grid(camera.get_view_matrix(), camera.get_projection_matrix()); m_frame_profiler.mark("plates"); - //BBS: add outline logic // Depth pass for object-on-object and self shadows; consumed by the gouraud shader below. _render_shadows(camera.get_view_matrix(), camera.get_projection_matrix()); @@ -2821,6 +2824,14 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) _render_objects(GLVolumeCollection::ERenderType::Opaque, !m_gizmos.is_running()); _render_below_plate_volumes(); m_frame_profiler.mark("objects"); + // Collision previews follow the same visibility rule as the bed. + const bool show_exclusion_intersections = m_show_bed && + (!m_main_toolbar.is_enabled() || + (gizmo_type != GLGizmosManager::FdmSupports && gizmo_type != GLGizmosManager::Seam && + gizmo_type != GLGizmosManager::MmSegmentation && gizmo_type != GLGizmosManager::FuzzySkin)); + if (show_exclusion_intersections) + wxGetApp().plater()->get_partplate_list().render_exclusion_volume_intersections( + camera.get_view_matrix(), camera.get_projection_matrix()); _render_sla_slices(); _render_selection(); _render_objects(GLVolumeCollection::ERenderType::Transparent, !m_gizmos.is_running()); @@ -3888,6 +3899,8 @@ void GLCanvas3D::bind_event_handlers() // The key-up that would commit a keyboard edit goes to whatever took the focus. if (m_selection_edit.kind != SelectionEdit::None) finish_selection_edit(); + release_held_modifiers(); + wxGetApp().imgui()->forget_key_claims(); ImGui::SetWindowFocus(nullptr); render(); evt.Skip(); @@ -4021,11 +4034,12 @@ void GLCanvas3D::on_char(wxKeyEvent& evt) // see include/wx/defs.h enum wxKeyCode int keyCode = evt.GetKeyCode(); - auto imgui = wxGetApp().imgui(); - if (imgui->update_key_data(evt)) { + auto imgui = wxGetApp().imgui(); + const bool imgui_claimed = imgui->claim_key_event(evt); + if (imgui->update_key_data(evt) || imgui_claimed) render(); + if (imgui_claimed) return; - } // Design tab: Delete, Esc, Ctrl+Z/Y and F are NOT handled here. DesignPanel's CHAR_HOOK owns // them (one route per key, whatever holds focus) and only lets a key through to this canvas @@ -4316,20 +4330,35 @@ static bool key_repeats(int key) static void key_released(int key) { s_keys_down.erase(key); } +void GLCanvas3D::release_held_modifiers() +{ + for (const int key : { WXK_SHIFT, WXK_CONTROL, WXK_ALT }) { + if (s_keys_down.count(key) == 0) + continue; + wxKeyEvent release(wxEVT_KEY_UP); + release.m_keyCode = key; + on_key(release); + } +} + void GLCanvas3D::on_key(wxKeyEvent& evt) { - const int keyCode = evt.GetKeyCode(); + auto imgui = wxGetApp().imgui(); + const int keyCode = evt.GetKeyCode(); + const bool imgui_claimed = imgui->claim_key_event(evt); if (evt.GetEventType() == wxEVT_KEY_DOWN) m_key_down = { keyCode, key_repeats(keyCode) }; else if (evt.GetEventType() == wxEVT_KEY_UP) key_released(keyCode); const bool alt_wheel_released = evt.GetEventType() == wxEVT_KEY_UP && keyCode == WXK_ALT && std::exchange(m_alt_wheel_used, false); - auto imgui = wxGetApp().imgui(); - if (imgui->update_key_data(evt)) + // ImGui closes a popup on Esc only through keyboard navigation, which is off. + if (imgui_claimed && evt.GetEventType() == wxEVT_KEY_DOWN && keyCode == WXK_ESCAPE) + imgui->close_top_popup(); + if (imgui->update_key_data(evt) || imgui_claimed) render(); - else + if (!imgui_claimed) { // Before the gizmos and the selection, which Esc also closes. if (evt.GetEventType() == wxEVT_KEY_DOWN && keyCode == WXK_ESCAPE && std::exchange(m_section_view->panel_open, false)) { @@ -4871,6 +4900,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) // It should be detection of volume change // Not only detection of some modifiers !!! if (evt.Dragging()) { + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->clear_exclusion_volume_intersections(); GLGizmosManager::EType c = m_gizmos.get_current_type(); if (current_printer_technology() == ptFFF && (fff_print()->config().print_sequence == PrintSequence::ByObject)) { @@ -5099,6 +5130,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) if (!m_mouse.drag.move_requires_threshold) { m_mouse.dragging = true; + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->clear_exclusion_volume_intersections(); Vec3d cur_pos = m_mouse.drag.start_position_3D; // we do not want to translate objects if the user just clicked on an object while pressing shift to remove it from the selection and then drag if (m_selection.contains_volume(get_first_hover_volume_idx())) { @@ -6205,6 +6238,13 @@ void GLCanvas3D::set_cursor(ECursorType type) void GLCanvas3D::mouse_up_cleanup() { + // Both direct dragging and gizmo manipulation clear the expensive red + // exclusion-intersection mesh while moving. Gizmo drags do not always set + // m_mouse.dragging, so every completed mouse operation must allow the + // cached preview to restore/recompute that mesh. + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->invalidate_exclusion_volume_preview(); + m_moving = false; m_camera_movement = false; m_mouse.drag.move_volume_idx = -1; diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 5acbba39a1..ce537643bd 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -1275,6 +1275,8 @@ public: void on_idle(wxIdleEvent& evt); void on_char(wxKeyEvent& evt); void on_key(wxKeyEvent& evt); + // Sends a key-up for each modifier still held, whose own key-up is sent to the window that takes the focus. + void release_held_modifiers(); // Runs the Plater/Preview shortcut bound to chord, swallowing auto-repeats of one-shot // shortcuts; false when nothing is bound. bool handle_shortcut(const KeyChord& chord); diff --git a/src/slic3r/GUI/GUI.cpp b/src/slic3r/GUI/GUI.cpp index e376bfc097..b7e41dac98 100644 --- a/src/slic3r/GUI/GUI.cpp +++ b/src/slic3r/GUI/GUI.cpp @@ -263,8 +263,18 @@ void change_opt_value(DynamicPrintConfig& config, const t_config_option_key& opt } break; case coPoints:{ + if (opt_key == "bed_exclude_area" && boost::any_cast(&value) != nullptr) { + // Tab handles pasted volume syntax after this callback. Do not + // deserialize it as points: failure would erase the saved area + // before the user can accept or cancel the copy operation. + break; + } if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" ) { config.option(opt_key)->values = boost::any_cast>(value); + if (opt_key == "bed_exclude_area") { + ConfigOptionPoints normalized(boost::any_cast>(value)); + config.option(opt_key)->deserialize(normalized.serialize()); + } break; } auto vec_new = std::make_unique(boost::any_cast(value)); diff --git a/src/slic3r/GUI/Gizmos/GLGizmoAlignment.cpp b/src/slic3r/GUI/Gizmos/GLGizmoAlignment.cpp index 96b85215a1..3e70763181 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoAlignment.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoAlignment.cpp @@ -19,6 +19,37 @@ namespace Slic3r { namespace GUI { +namespace { + +// Maps world coordinates into the frame whose axes are the columns of basis. +Transform3d world_to_frame(const Matrix3d &basis) +{ + Transform3d trafo = Transform3d::Identity(); + trafo.linear() = basis.transpose(); + return trafo; +} + +// Model parts of an instance, as ModelObject::instance_bounding_box() or instance_convex_hull_bounding_box() takes them. +BoundingBoxf3 instance_box_in_frame(const ModelObject &object, const ModelInstance &instance, const Transform3d &to_frame, bool convex_hull) +{ + BoundingBoxf3 box; + const Transform3d inst_matrix = to_frame * instance.get_transformation().get_matrix(); + for (const ModelVolume *v : object.volumes) { + if (!v->is_model_part()) + continue; + const Transform3d matrix = inst_matrix * v->get_matrix(); + box.merge(convex_hull ? v->get_convex_hull().transformed_bounding_box(matrix) : v->mesh().transformed_bounding_box(matrix)); + } + return box; +} + +BoundingBoxf3 volume_box_in_frame(const GLVolume &volume, const Matrix3d &basis) +{ + return volume.transformed_convex_hull_bounding_box(world_to_frame(basis) * volume.world_matrix()); +} + +} // namespace + GLGizmoAlignment::GLGizmoAlignment(GLCanvas3D& canvas) : m_canvas(canvas) { } @@ -106,9 +137,10 @@ bool GLGizmoAlignment::align_to_center(AlignType type,bool align_parent) { std::string type_str = type == AlignType::CENTER_X ? "X" : (type == AlignType::CENTER_Y ? "Y" : "Z"); std::string operation_name = type == AlignType::CENTER_X ? "X Center" : (type == AlignType::CENTER_Y ? "Y Center" : "Z Center"); + const Matrix3d basis = reference_basis(align_parent); double selection_center = 0.f; if (align_parent) { - BoundingBoxf3 parent_box = get_parent_box(); + BoundingBoxf3 parent_box = get_parent_box(basis); selection_center = get_current_coord(operation_name, parent_box); // Handle multiple volume selection @@ -119,18 +151,18 @@ bool GLGizmoAlignment::align_to_center(AlignType type,bool align_parent) get_selection().setup_cache(); - BoundingBoxf3 selection_bbox = get_items_box(); + BoundingBoxf3 selection_bbox = get_items_box(basis); double current_coord = get_current_coord(operation_name, selection_bbox); Vec3d displacement = generate_displacement(operation_name, selection_center - current_coord); // Move the selected volumes together so that their collective bounding box is centered in the parent for (const GLVolume *volume : get_selected_part_volumes()) { - get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), displacement, false); + get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), basis * displacement, false); } finish_operation(true); return true; } BoundingBoxf3 big_bb; - auto objects = get_selected_objects_info(big_bb); + auto objects = get_selected_objects_info(big_bb, basis); if (objects.empty()) return false; // Handle multiple objects or parts selection @@ -143,7 +175,7 @@ bool GLGizmoAlignment::align_to_center(AlignType type,bool align_parent) Vec3d displacement = generate_displacement(operation_name, selection_center - current_coord); // Multiple objects: use selection bounding box for alignment for (const auto &obj : objects) { - apply_transformation(obj.object_idx, obj.instance_idx, displacement); + apply_transformation(obj.object_idx, obj.instance_idx, basis * displacement); } finish_operation(); @@ -157,23 +189,23 @@ bool GLGizmoAlignment::align_to_center(AlignType type,bool align_parent) get_selection().setup_cache(); - BoundingBoxf3 selection_bbox = get_items_box(); + BoundingBoxf3 selection_bbox = get_items_box(basis); selection_center = get_current_coord(operation_name, selection_bbox); // Move each part to align to the center of their collective bounding box for (const GLVolume *volume : get_selected_part_volumes()) { - auto temp_box = volume->transformed_convex_hull_bounding_box(); + auto temp_box = volume_box_in_frame(*volume, basis); double current = get_current_coord(operation_name, temp_box); double offset = selection_center - current; Vec3d displacement = generate_displacement(operation_name, offset); - get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), displacement, false); + get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), basis * displacement, false); } finish_operation(true); return true; } BoundingBoxf3 big_bb; - auto objects = get_selected_objects_info(big_bb); + auto objects = get_selected_objects_info(big_bb, basis); if (objects.empty()) return false; // Handle multiple instances selection_center = get_current_coord(operation_name, big_bb); @@ -188,7 +220,7 @@ bool GLGizmoAlignment::align_to_center(AlignType type,bool align_parent) BoundingBoxf3 temp_bbox = obj.bbox; double current_coord = get_current_coord(operation_name, temp_bbox); Vec3d displacement = generate_displacement(operation_name, selection_center - current_coord); - apply_transformation(obj.object_idx, obj.instance_idx, displacement); + apply_transformation(obj.object_idx, obj.instance_idx, basis * displacement); } finish_operation(); return true; @@ -244,9 +276,10 @@ bool GLGizmoAlignment::distribute_z() template bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFunc set_coord, const std::string &operation_name ,bool align_parent) { + const Matrix3d basis = reference_basis(align_parent); if (align_parent) { // Find reference coordinate - BoundingBoxf3 parent_box = get_parent_box(); + BoundingBoxf3 parent_box = get_parent_box(basis); double reference_coord = get_current_coord(operation_name, parent_box); // Handle parts selection differently if (is_parts_selection(true)) { @@ -259,12 +292,12 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun const std::vector volumes = get_selected_part_volumes(); if (volumes.empty()) return false; - BoundingBoxf3 selection_bbox = get_items_box(); + BoundingBoxf3 selection_bbox = get_items_box(basis); double current_coord = get_current_coord(operation_name, selection_bbox); Vec3d displacement = generate_displacement(operation_name, reference_coord - current_coord); for (const GLVolume *volume : volumes) { if (displacement.norm() > 1e-6) { - get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), displacement, false); + get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), basis * displacement, false); } } @@ -274,7 +307,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun // Handle objects selection (original logic) BoundingBoxf3 big_bb; - auto objects = get_selected_objects_info(big_bb); + auto objects = get_selected_objects_info(big_bb, basis); if (objects.empty()) return false; if (!take_snapshot("align to parent node " + operation_name)) { return false; } @@ -286,7 +319,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun for (const auto &obj : objects) { if (displacement.norm() > 1e-6) { - apply_transformation(obj.object_idx, obj.instance_idx, displacement); + apply_transformation(obj.object_idx, obj.instance_idx, basis * displacement); } } @@ -309,7 +342,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun bool first = true; for (const GLVolume* volume : volumes) { - BoundingBoxf3 bbox = volume->transformed_convex_hull_bounding_box(); + BoundingBoxf3 bbox = volume_box_in_frame(*volume, basis); double coord = 0.0; if (operation_name.find("X Max") != std::string::npos) { @@ -339,7 +372,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun } for (const GLVolume* volume : volumes) { - BoundingBoxf3 bbox = volume->transformed_convex_hull_bounding_box(); + BoundingBoxf3 bbox = volume_box_in_frame(*volume, basis); double current_coord = 0.0; if (operation_name.find("X Max") != std::string::npos) { @@ -367,7 +400,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun } if (displacement.norm() > 1e-6) { - get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), displacement, false); + get_selection().translate(volume->object_idx(), volume->instance_idx(), volume->volume_idx(), basis * displacement, false); } } @@ -377,7 +410,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun // Handle objects selection (original logic) BoundingBoxf3 big_bb; - auto objects = get_selected_objects_info(big_bb); + auto objects = get_selected_objects_info(big_bb, basis); if (objects.empty()) return false; if (!take_snapshot(operation_name)) { @@ -402,7 +435,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun set_coord(displacement, reference_coord, current_coord); if (displacement.norm() > 1e-6) { - apply_transformation(obj.object_idx, obj.instance_idx, displacement); + apply_transformation(obj.object_idx, obj.instance_idx, basis * displacement); } } @@ -413,6 +446,7 @@ bool GLGizmoAlignment::align_objects_generic(GetCoordFunc get_coord, SetCoordFun template bool GLGizmoAlignment::distribute_objects_generic(GetCoordFunc get_coord, int axis, const std::string& operation_name) { + const Matrix3d basis = reference_basis(false); if (is_parts_selection(false)) { const std::vector volumes = get_selected_part_volumes(); if (volumes.size() < 3) return false; @@ -425,7 +459,7 @@ bool GLGizmoAlignment::distribute_objects_generic(GetCoordFunc get_coord, int ax std::vector entries; entries.reserve(volumes.size()); for (const GLVolume* v : volumes) { - BoundingBoxf3 bbox = v->transformed_convex_hull_bounding_box(); + BoundingBoxf3 bbox = volume_box_in_frame(*v, basis); Vec3d c = bbox.center(); double coord = (axis == 0 ? c.x() : axis == 1 ? c.y() : c.z()); entries.push_back({v, coord}); @@ -433,9 +467,9 @@ bool GLGizmoAlignment::distribute_objects_generic(GetCoordFunc get_coord, int ax std::sort(entries.begin(), entries.end(), [](const VolEntry& a, const VolEntry& b){ return a.coord < b.coord; }); - BoundingBoxf3 selection_bbox = get_items_box(); - BoundingBoxf3 left_bbox = entries.front().v->transformed_convex_hull_bounding_box(); - BoundingBoxf3 right_bbox = entries.back().v->transformed_convex_hull_bounding_box(); + BoundingBoxf3 selection_bbox = get_items_box(basis); + BoundingBoxf3 left_bbox = volume_box_in_frame(*entries.front().v, basis); + BoundingBoxf3 right_bbox = volume_box_in_frame(*entries.back().v, basis); auto axis_extent = [&](const BoundingBoxf3 &bb) { return (axis == 0 ? (bb.max.x() - bb.min.x()) : axis == 1 ? (bb.max.y() - bb.min.y()) : (bb.max.z() - bb.min.z())); }; double left_width = axis_extent(left_bbox); double right_width = axis_extent(right_bbox); @@ -454,7 +488,7 @@ bool GLGizmoAlignment::distribute_objects_generic(GetCoordFunc get_coord, int ax Vec3d displacement = Vec3d::Zero(); displacement[axis] = offset; const GLVolume *v = entries[i].v; - get_selection().translate(v->object_idx(), v->instance_idx(), v->volume_idx(), displacement, false); + get_selection().translate(v->object_idx(), v->instance_idx(), v->volume_idx(), basis * displacement, false); } } @@ -462,7 +496,7 @@ bool GLGizmoAlignment::distribute_objects_generic(GetCoordFunc get_coord, int ax return true; } BoundingBoxf3 big_bb; - auto objects = get_selected_objects_info(big_bb); + auto objects = get_selected_objects_info(big_bb, basis); if (objects.size() < 3) return false; if (!take_snapshot(operation_name)) { @@ -488,7 +522,7 @@ bool GLGizmoAlignment::distribute_objects_generic(GetCoordFunc get_coord, int ax if (std::abs(offset) > 1e-6) { Vec3d displacement = Vec3d::Zero(); displacement[axis] = offset; - apply_transformation(objects[i].object_idx, objects[i].instance_idx, displacement); + apply_transformation(objects[i].object_idx, objects[i].instance_idx, basis * displacement); } } @@ -544,13 +578,27 @@ Vec3d GLGizmoAlignment::generate_displacement(std::string operation_name, double return displacement; } -std::vector GLGizmoAlignment::get_selected_objects_info(BoundingBoxf3 &big_bb) const +Matrix3d GLGizmoAlignment::reference_basis(bool align_parent) const +{ + // Plate alignment stays on the world axes. + const Selection &selection = get_selection(); + if (!m_object_cs || selection.is_empty() || (align_parent && !is_parts_selection(true))) + return Matrix3d::Identity(); + + // The instance of the first selected volume, as the Move gizmo's object coordinate system does. + auto transformation = selection.get_first_volume()->get_instance_transformation(); + transformation.reset_scaling_factor(); + return transformation.get_matrix_no_offset().linear(); +} + +std::vector GLGizmoAlignment::get_selected_objects_info(BoundingBoxf3 &big_bb, const Matrix3d &basis) const { std::vector objects; Selection& selection = get_selection(); if (selection.is_empty()) return objects; + const Transform3d to_frame = world_to_frame(basis); const auto& content = selection.get_content(); for (const auto& obj_it : content) { for (const auto& inst_idx : obj_it.second) { @@ -559,7 +607,7 @@ std::vector GLGizmoAlignment::get_selected_objects if (obj_idx >= 0 && obj_idx < selection.get_model()->objects.size()) { ModelObject* object = selection.get_model()->objects[obj_idx]; if (inst_idx >= 0 && inst_idx < object->instances.size()) { - BoundingBoxf3 bbox = object->instance_bounding_box(inst_idx); + BoundingBoxf3 bbox = instance_box_in_frame(*object, *object->instances[inst_idx], to_frame, false); big_bb.merge(bbox); objects.emplace_back(obj_idx, inst_idx, bbox); } @@ -602,22 +650,24 @@ std::vector GLGizmoAlignment::get_selected_part_volumes() cons return volumes; } -BoundingBoxf3 GLGizmoAlignment::get_items_box() const +BoundingBoxf3 GLGizmoAlignment::get_items_box(const Matrix3d &basis) const { BoundingBoxf3 box; if (is_parts_selection(false)) { for (const GLVolume *volume : get_selected_part_volumes()) - box.merge(volume->transformed_convex_hull_bounding_box()); + box.merge(volume_box_in_frame(*volume, basis)); } else - get_selected_objects_info(box); + get_selected_objects_info(box, basis); return box; } -BoundingBoxf3 GLGizmoAlignment::get_parent_box() const +BoundingBoxf3 GLGizmoAlignment::get_parent_box(const Matrix3d &basis) const { const Selection &selection = get_selection(); - if (is_parts_selection(true)) - return selection.get_model()->objects[selection.get_object_idx()]->instance_convex_hull_bounding_box(selection.get_instance_idx()); + if (is_parts_selection(true)) { + const ModelObject *object = selection.get_model()->objects[selection.get_object_idx()]; + return instance_box_in_frame(*object, *object->instances[selection.get_instance_idx()], world_to_frame(basis), true); + } // can_align() requires every selected instance on one plate, so the first one gives the plate. BoundingBoxf3 box; @@ -629,7 +679,7 @@ BoundingBoxf3 GLGizmoAlignment::get_parent_box() const if (plate == nullptr) break; BoundingBoxf3 instances_box; - get_selected_objects_info(instances_box); + get_selected_objects_info(instances_box, Matrix3d::Identity()); box = plate->get_plate_box(); box.max.z() = instances_box.max.z(); // Keep the aligned objects off the plate edge. @@ -714,4 +764,4 @@ size_t GLGizmoAlignment::get_items_count(AlignType type, bool align_parent, std: } } // namespace GUI -} // namespace Slic3r \ No newline at end of file +} // namespace Slic3r diff --git a/src/slic3r/GUI/Gizmos/GLGizmoAlignment.hpp b/src/slic3r/GUI/Gizmos/GLGizmoAlignment.hpp index daca519034..30db673dfd 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoAlignment.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoAlignment.hpp @@ -62,7 +62,13 @@ public: bool can_align(AlignType type, bool align_parent = false) const; bool can_distribute(AlignType type) const; - std::vector get_selected_objects_info(BoundingBoxf3 &big_bb) const; + // Object coordinate system: operations align along the axes of the selection's instance instead of the world axes. + void set_object_cs(bool flag) { m_object_cs = flag; } + // Rotation whose columns are the axes an operation aligns along. Plate alignment always uses the world axes. + Matrix3d reference_basis(bool align_parent) const; + + // Boxes and displacements inside the operations are in the frame of the basis from reference_basis(). + std::vector get_selected_objects_info(BoundingBoxf3 &big_bb, const Matrix3d &basis) const; double get_current_coord(std::string operation_name, BoundingBoxf3 &bbox); Vec3d generate_displacement(std::string operation_name, double offset); @@ -72,16 +78,17 @@ public: // The volumes a parts operation moves: the selected volumes, or only the model parts when a whole instance is // selected. Empty for a cut object, whose parts must keep their place. std::vector get_selected_part_volumes() const; - // World bounding box of the items an operation moves, the reference of every non-parent operation. - BoundingBoxf3 get_items_box() const; - // World bounding box aligned to with align_parent: the instance of a parts selection, or the plate holding the + // Bounding box of the items an operation moves, the reference of every non-parent operation. + BoundingBoxf3 get_items_box(const Matrix3d &basis) const; + // Bounding box aligned to with align_parent: the instance of a parts selection, or the plate holding the // selected instances, up to their top. - BoundingBoxf3 get_parent_box() const; + BoundingBoxf3 get_parent_box(const Matrix3d &basis) const; // Number of items the operation would move, or 0 when it cannot move them; why_not then gets the reason, if any. size_t get_items_count(AlignType type, bool align_parent, std::string *why_not = nullptr) const; private: GLCanvas3D& m_canvas; + bool m_object_cs{false}; template bool align_objects_generic(GetCoordFunc get_coord, SetCoordFunc set_coord, const std::string &operation_name, bool align_parent = false); diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp index 6968e81c7e..22629570cb 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMove.cpp @@ -110,8 +110,8 @@ bool GLGizmoMove3D::on_is_activable() const void GLGizmoMove3D::on_set_state() { if (get_state() == On) { - m_last_selected_obejct_idx = -1; - m_last_selected_volume_idx = -1; + m_last_selected_obejct_idx = -2; + m_last_selected_volume_idx = -2; change_cs_by_selection(); } if (m_object_manipulation) @@ -355,13 +355,17 @@ void GLGizmoMove3D::render_align_preview() if (m_object_manipulation == nullptr || m_object_manipulation->get_hovered_align_type() == AlignType::NONE) return; - // The box the hovered operation aligns to, in world coordinates like the operation itself. - const AlignType type = m_object_manipulation->get_hovered_align_type(); - const GLGizmoAlignment &helper = m_object_manipulation->get_alignment_helper(); - const BoundingBoxf3 box = m_object_manipulation->get_align_to_parent() ? helper.get_parent_box() : helper.get_items_box(); + // The box the hovered operation aligns to, in the frame the operation aligns along. + const AlignType type = m_object_manipulation->get_hovered_align_type(); + const GLGizmoAlignment &helper = m_object_manipulation->get_alignment_helper(); + const bool to_parent = m_object_manipulation->get_align_to_parent(); + const Matrix3d basis = helper.reference_basis(to_parent); + const BoundingBoxf3 box = to_parent ? helper.get_parent_box(basis) : helper.get_items_box(basis); if (!box.defined) return; - m_parent.get_selection().render_bounding_box(box, {0.0f, 150.0f / 255.0f, 136.0f / 255.0f}, m_parent.get_scale()); + Transform3d basis_trafo = Transform3d::Identity(); + basis_trafo.linear() = basis; + m_parent.get_selection().render_bounding_box(box, basis_trafo, {0.0f, 150.0f / 255.0f, 136.0f / 255.0f}, m_parent.get_scale()); GLShaderProgram* shader = wxGetApp().get_shader("flat"); if (shader == nullptr) @@ -427,7 +431,7 @@ void GLGizmoMove3D::render_align_preview() for (double position : positions) { plane_center[axis] = position; plane_matrix.translation() = plane_center; - shader->set_uniform("view_model_matrix", camera.get_view_matrix() * plane_matrix); + shader->set_uniform("view_model_matrix", camera.get_view_matrix() * basis_trafo * plane_matrix); m_align_plane.render(); } shader->stop_using(); @@ -437,7 +441,7 @@ void GLGizmoMove3D::render_align_preview() } void GLGizmoMove3D::change_cs_by_selection() { - int obejct_idx, volume_idx; + int obejct_idx = -1, volume_idx = -1; ModelVolume *model_volume = m_parent.get_selection().get_selected_single_volume(obejct_idx, volume_idx); if (m_last_selected_obejct_idx == obejct_idx && m_last_selected_volume_idx == volume_idx) { return; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMove.hpp b/src/slic3r/GUI/Gizmos/GLGizmoMove.hpp index 3eb5522156..5d6a3317df 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMove.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMove.hpp @@ -81,7 +81,8 @@ private: void render_align_preview(); void change_cs_by_selection(); //cs mean Coordinate System private: - int m_last_selected_obejct_idx, m_last_selected_volume_idx; + // -1 is a selection without a single volume; -2 is no selection seen yet. + int m_last_selected_obejct_idx{-2}, m_last_selected_volume_idx{-2}; }; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp index 388b04312d..6c540fa9d2 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp @@ -114,6 +114,11 @@ Vec3f GLGizmoPainterBase::get_tilt_up_direction() const } void GLGizmoPainterBase::render_triangles(const Selection& selection, const ModelVolume* skip) const +{ + render_triangles(selection, skip == nullptr ? std::vector{} : std::vector{skip}); +} + +void GLGizmoPainterBase::render_triangles(const Selection& selection, const std::vector& skip) const { auto* shader = wxGetApp().get_shader("mm_gouraud"); if (!shader) @@ -135,7 +140,7 @@ void GLGizmoPainterBase::render_triangles(const Selection& selection, const Mode continue; ++mesh_id; - if (mv == skip) + if (std::find(skip.begin(), skip.end(), mv) != skip.end()) continue; Transform3d trafo_matrix; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp index 96871ae5dc..9695606417 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp @@ -235,6 +235,10 @@ public: protected: // Draws every model part's selector, except `skip`'s when given. virtual void render_triangles(const Selection& selection, const ModelVolume* skip = nullptr) const; + // The same, skipping every part in `skip`. A gizmo can have a preview standing in for more than one + // model part at a time - the texture-displacement gizmo previews every painted part of a multibody + // object - and drawing those parts' selectors over it would bury the preview under a flat surface. + void render_triangles(const Selection& selection, const std::vector& skip) const; void render_cursor(); void render_cursor_circle(); void render_cursor_sphere(const Transform3d& trafo) const; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp b/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp index 4842f93f34..e0609d5660 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoScale.cpp @@ -185,8 +185,8 @@ bool GLGizmoScale3D::on_is_activable() const void GLGizmoScale3D::on_set_state() { if (get_state() == On) { - m_last_selected_obejct_idx = -1; - m_last_selected_volume_idx = -1; + m_last_selected_obejct_idx = -2; + m_last_selected_volume_idx = -2; change_cs_by_selection(); } } @@ -302,7 +302,7 @@ void GLGizmoScale3D::update_grabbers_data() void GLGizmoScale3D::change_cs_by_selection() { - int obejct_idx, volume_idx; + int obejct_idx = -1, volume_idx = -1; ModelVolume *model_volume = m_parent.get_selection().get_selected_single_volume(obejct_idx, volume_idx); if (m_last_selected_obejct_idx == obejct_idx && m_last_selected_volume_idx == volume_idx) { return; } m_last_selected_obejct_idx = obejct_idx; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoScale.hpp b/src/slic3r/GUI/Gizmos/GLGizmoScale.hpp index d830b9f36a..3a91a5fa62 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoScale.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoScale.hpp @@ -110,7 +110,8 @@ private: void update_grabbers_data(); void change_cs_by_selection(); // cs mean Coordinate System private: - int m_last_selected_obejct_idx, m_last_selected_volume_idx; + // -1 is a selection without a single volume; -2 is no selection seen yet. + int m_last_selected_obejct_idx{-2}, m_last_selected_volume_idx{-2}; }; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp index 7f0019f86b..adc9982a80 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.cpp @@ -7,6 +7,7 @@ #include "ColorSpaceConvert.hpp" #include "libslic3r/AABBTreeIndirect.hpp" +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Color.hpp" #include "libslic3r/FilamentMixer.hpp" #include "libslic3r/PresetBundle.hpp" @@ -26,6 +27,7 @@ #include "slic3r/GUI/GuiColor.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/MainFrame.hpp" // wxGetApp().mainframe, as the projector window's parent +#include "slic3r/GUI/MeshUtils.hpp" #include "slic3r/GUI/MsgDialog.hpp" #include "slic3r/GUI/OpenGLManager.hpp" #include "slic3r/GUI/Plater.hpp" @@ -580,6 +582,7 @@ void GLGizmoTextureDisplacement::on_shutdown() { m_parent.toggle_model_objects_visibility(true); m_preview_glmodel.reset(); + m_part_previews.clear(); m_shaded_preview_glmodel.reset(); m_paint_overlay_glmodel.reset(); m_paint_overlay_dirty = false; @@ -705,8 +708,7 @@ void GLGizmoTextureDisplacement::render_painter_gizmo() // why those two modes looked like they did nothing. Leave it out and let the undisplaced volume show // through instead (toggle_model_objects_visibility below) - that one *is* coincident with the // overlay, which is what the offset assumes, and it is the surface whose mapping is being inspected. - const bool use_true_preview = !use_shaded && m_uv_check_mode == UVCheckMode::None && - m_preview_glmodel.is_initialized(); + const bool use_true_preview = !use_shaded && m_uv_check_mode == UVCheckMode::None && has_true_preview(); // In Checker/Distortion mode the UV-check overlay *is* the surface visualization the user is // looking at, so the opaque paint-selection highlight must not be drawn on top of it - same // reasoning as skipping it for the shaded preview (see bug #12). Without this the painted area @@ -717,10 +719,23 @@ void GLGizmoTextureDisplacement::render_painter_gizmo() // put it back. Getting this wrong leaves an invisible model, so it is decided once, here, rather // than per branch below. ModelVolume *mv = texture_volume(); + // The parts a preview is standing in for, and whose real volumes therefore have to be hidden and + // whose selectors must not be drawn over it. The shaded view only ever shades the layer stack's own + // part; the true-displacement view covers every painted part of a multibody object. + std::vector previewed; + if (use_shaded && mv != nullptr) { + previewed.push_back(mv); + } else if (use_true_preview) { + if (mv != nullptr && m_preview_glmodel.is_initialized()) + previewed.push_back(mv); + for (const std::unique_ptr &preview : m_part_previews) + if (const ModelVolume *part = preview_part(*preview); part != nullptr) + previewed.push_back(part); + } m_parent.toggle_model_objects_visibility(true); - if ((use_shaded || use_true_preview) && mv != nullptr) + for (const ModelVolume *volume : previewed) m_parent.toggle_model_objects_visibility(false, m_c->selection_info()->model_object(), - m_c->selection_info()->get_active_instance(), mv); + m_c->selection_info()->get_active_instance(), volume); // Over a preview, the paint feedback - the selectors' highlight in the Normal view, the tint in both - // is drawn only while a mouse button is down: during a stroke, a fill click included. Between strokes @@ -734,14 +749,15 @@ void GLGizmoTextureDisplacement::render_painter_gizmo() if (use_shaded) { render_shaded_preview_mesh(); // The shaded mesh is the textured volume alone, so the other model parts are still the selectors' to draw. - render_triangles(selection, mv); + render_triangles(selection, previewed); textured_selector_drawn = false; } else if (use_true_preview) { render_preview_mesh(); glsafe(::glEnable(GL_POLYGON_OFFSET_FILL)); glsafe(::glPolygonOffset(-1.0f, -1.0f)); - // Without paint feedback, only the other model parts: render_preview_mesh() draws the textured one. - render_triangles(selection, paint_feedback ? nullptr : mv); + // Without paint feedback, only the parts with no preview over them: render_preview_mesh() draws + // the rest. + render_triangles(selection, paint_feedback ? std::vector{} : previewed); glsafe(::glDisable(GL_POLYGON_OFFSET_FILL)); textured_selector_drawn = paint_feedback; } else { @@ -1239,36 +1255,61 @@ void GLGizmoTextureDisplacement::render_seam_overlay() void GLGizmoTextureDisplacement::render_preview_mesh() { const ModelObject *mo = m_c->selection_info()->model_object(); - const ModelVolume *mv = texture_volume(); - if (mo == nullptr || mv == nullptr) + if (mo == nullptr) return; - const Selection &selection = m_parent.get_selection(); - const Transform3d trafo_matrix = mo->instances[selection.get_instance_idx()]->get_transformation().get_matrix() * mv->get_matrix(); - auto *shader = wxGetApp().get_shader("gouraud_light"); if (shader == nullptr) return; + + const Selection &selection = m_parent.get_selection(); + const Transform3d instance_matrix = mo->instances[selection.get_instance_idx()]->get_transformation().get_matrix(); + const Camera &camera = wxGetApp().plater()->get_camera(); + const Transform3d &view_matrix = camera.get_view_matrix(); + shader->start_using(); - const Camera &camera = wxGetApp().plater()->get_camera(); - const Transform3d &view_matrix = camera.get_view_matrix(); - shader->set_uniform("view_model_matrix", view_matrix * trafo_matrix); - shader->set_uniform("projection_matrix", camera.get_projection_matrix()); - const Matrix3d view_normal_matrix = view_matrix.matrix().block(0, 0, 3, 3) * trafo_matrix.matrix().block(0, 0, 3, 3).inverse().transpose(); - shader->set_uniform("view_normal_matrix", view_normal_matrix); - if (m_preview_color_runs.empty()) { - m_preview_glmodel.render(); - } else { - // set_color() writes the uniform the shader reads, so one call per group is all the - // per-triangle colour this needs. - for (const PreviewColorRun &run : m_preview_color_runs) { - m_preview_glmodel.set_color(run.color); - m_preview_glmodel.render(run.range, shader); + // Each part is drawn through its own matrix: a multibody object's parts sit in different places + // inside the object, so one matrix for all of them would pile every preview onto the first part. + const auto draw = [&](const ModelVolume &volume, GLModel &model, const std::vector &runs) { + if (!model.is_initialized()) + return; + const Transform3d trafo_matrix = instance_matrix * volume.get_matrix(); + shader->set_uniform("view_model_matrix", view_matrix * trafo_matrix); + shader->set_uniform("projection_matrix", camera.get_projection_matrix()); + const Matrix3d view_normal_matrix = view_matrix.matrix().block(0, 0, 3, 3) * + trafo_matrix.matrix().block(0, 0, 3, 3).inverse().transpose(); + shader->set_uniform("view_normal_matrix", view_normal_matrix); + if (runs.empty()) { + model.render(); + } else { + // set_color() writes the uniform the shader reads, so one call per group is all the + // per-triangle colour this needs. + for (const PreviewColorRun &run : runs) { + model.set_color(run.color); + model.render(run.range, shader); + } } - } + }; + + if (const ModelVolume *owner = texture_volume(); owner != nullptr) + draw(*owner, m_preview_glmodel, m_preview_color_runs); + for (const std::unique_ptr &preview : m_part_previews) + if (const ModelVolume *part = preview_part(*preview); part != nullptr) + draw(*part, preview->glmodel, preview->color_runs); shader->stop_using(); } +const ModelVolume *GLGizmoTextureDisplacement::preview_part(const PartPreview &preview) const +{ + const ModelObject *mo = m_c->selection_info()->model_object(); + if (mo == nullptr) + return nullptr; + for (const ModelVolume *mv : mo->volumes) + if (mv->id() == preview.volume_id) + return mv; + return nullptr; // the part was removed, or its mesh replaced, since the preview was built +} + float GLGizmoTextureDisplacement::layer_texture_aspect(const TextureDisplacementLayer &layer) { // decode_height_texture() is cached on the image_data allocation, so this is a hash lookup rather @@ -2362,8 +2403,9 @@ void GLGizmoTextureDisplacement::rebuild_preview() return; const ModelVolume *mv = texture_volume(); - if (mv == nullptr || !mv->is_texture_displacement_painted()) { + if (mv == nullptr || !any_part_painted()) { m_preview_glmodel.reset(); + m_part_previews.clear(); m_preview_its = indexed_triangle_set{}; // no displaced mesh; wireframe falls back to the base m_preview_job_pending = false; refresh_wireframe(); @@ -2384,14 +2426,44 @@ void GLGizmoTextureDisplacement::rebuild_preview() queue_preview_job(); } +indexed_triangle_set GLGizmoTextureDisplacement::group_preview_by_color(const indexed_triangle_set &its, + const std::vector &triangle_color, + const std::vector &entry_colors, + std::vector &runs) +{ + runs.clear(); + if (triangle_color.size() != its.indices.size() || entry_colors.empty()) + return its; + + indexed_triangle_set sorted; + sorted.vertices = its.vertices; + sorted.indices.reserve(its.indices.size()); + for (int want = 0; want <= int(entry_colors.size()); ++want) { + const size_t first = sorted.indices.size(); + for (size_t i = 0; i < its.indices.size(); ++i) + if (int(triangle_color[i]) == want) + sorted.indices.push_back(its.indices[i]); + if (sorted.indices.size() == first) + continue; + runs.push_back({ { first * 3, sorted.indices.size() * 3 }, + want == 0 ? GLVolume::NEUTRAL_COLOR : entry_colors[size_t(want - 1)] }); + } + return sorted; +} + void GLGizmoTextureDisplacement::queue_preview_job() { // A job in flight when the gizmo closes still runs its completion handler, which would otherwise // happily queue the follow-up run it was holding - against a gizmo nobody is looking at any more. if (m_state != On) return; - const ModelVolume *mv = texture_volume(); - if (mv == nullptr || !mv->is_texture_displacement_painted()) + const ModelVolume *owner = texture_volume(); + if (owner == nullptr) + return; + // Every painted part, so the preview shows the whole of what Bake will do rather than its first + // part - the same set bake() displaces. + const std::vector parts = painted_parts(); + if (parts.empty()) return; // One in flight at a time; everything requested meanwhile collapses into a single follow-up run @@ -2404,22 +2476,39 @@ void GLGizmoTextureDisplacement::queue_preview_job() const uint64_t generation = m_preview_generation->load(); TextureDisplacementPreviewInput input; - input.base_mesh = mv->mesh().its; - input.layers = mv->texture_displacement_layers; - input.options = mv->texture_displacement_options; - // The preview is looked at, not printed or sliced: skip the simplification and the repair that - // follows it, which are most of the one-run pipeline's time. The relief is the same. - if (input.options.pipeline_v2) - input.options.v2_max_triangles_k = 0; - input.volume_to_world = texture_displacement_volume_to_world(*mv); - if (mv->has_texture_uv()) - input.model_uv = mv->texture_uv; - for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) - input.facets_data[size_t(i)] = mv->texture_displacement_facet(i).get_data(); // Captured here rather than read in the handler: the palette is main-thread state, and the preview // has to be grouped against the same palette it was computed with, not whatever it is by the time - // the result lands. - input.color = color_settings_for(*mv); + // the result lands. Read off the layer stack's own part, since that is where the stack lives. + input.color = color_settings_for(*owner); + input.volumes.reserve(parts.size()); + // Which part each result belongs to, so the handler can tell the layer stack's own preview - the one + // the overlays and the wireframe are keyed to - from the rest. + std::vector part_ids; + part_ids.reserve(parts.size()); + const Vec3d anchor = texture_anchor(); + const std::vector drops = resting_drops(parts); + for (size_t i = 0; i < parts.size(); ++i) { + const ModelVolume *part = parts[i]; + TextureDisplacementPreviewVolume entry; + entry.base_mesh = part->mesh().its; + entry.layers = layers_for_part(*part); + entry.options = owner->texture_displacement_options; + // The preview is looked at, not printed or sliced: skip the simplification and the repair that + // follows it, which are most of the one-run pipeline's time. The relief is the same. + if (entry.options.pipeline_v2) + entry.options.v2_max_triangles_k = 0; + entry.volume_to_world = texture_displacement_volume_to_world(*part); + entry.texture_anchor = anchor; + entry.resting_drop = drops[i]; + if (part->has_texture_uv()) + entry.model_uv = part->texture_uv; + for (int slot = 0; slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++slot) + entry.facets_data[size_t(slot)] = part->texture_displacement_facet(slot).get_data(); + input.volumes.push_back(std::move(entry)); + part_ids.push_back(part->id()); + } + const ObjectID owner_id = owner->id(); + // The result names a palette entry per triangle (index + 1), so these are the colours to draw it in: // a single filament's own, or for a mix the colour its slot will show once a bake creates it. std::vector entry_colors; @@ -2430,43 +2519,52 @@ void GLGizmoTextureDisplacement::queue_preview_job() m_preview_job_running = true; auto &worker = wxGetApp().plater()->get_ui_job_worker(); queue_job(worker, std::make_unique(std::move(input), generation, m_preview_generation, - [this, entry_colors](TextureDisplacementPreviewResult result, uint64_t result_generation) { - indexed_triangle_set its = std::move(result.mesh); + [this, entry_colors, part_ids, owner_id](std::vector results, + uint64_t result_generation) { m_preview_job_running = false; if (result_generation != m_preview_generation->load()) { // Superseded while this was computing (it will have aborted early and come back // empty). Whatever the newest state is, it still needs a run. m_preview_job_pending = true; - } else if (its.indices.empty()) { + } else if (results.empty()) { // Aborted or cancelled rather than finished - the handler runs on every outcome so // the in-flight latch above always clears. Keep whatever preview is already on screen // rather than blanking it; there is no new result to show, not a new empty one. } else { + // A finished run carries the whole object, so it replaces the previous one outright: a + // part that is no longer painted must lose its preview, or its flat volume would stay + // hidden behind geometry from before. m_preview_glmodel.reset(); m_preview_color_runs.clear(); - if (result.triangle_color.size() == its.indices.size() && !entry_colors.empty()) { - indexed_triangle_set sorted; - sorted.vertices = its.vertices; - sorted.indices.reserve(its.indices.size()); - for (int want = 0; want <= int(entry_colors.size()); ++want) { - const size_t first = sorted.indices.size(); - for (size_t i = 0; i < its.indices.size(); ++i) - if (int(result.triangle_color[i]) == want) - sorted.indices.push_back(its.indices[i]); - if (sorted.indices.size() == first) - continue; - m_preview_color_runs.push_back( - { { first * 3, sorted.indices.size() * 3 }, - want == 0 ? GLVolume::NEUTRAL_COLOR : entry_colors[size_t(want - 1)] }); + m_preview_its = indexed_triangle_set{}; + m_part_previews.clear(); + + for (size_t i = 0; i < results.size() && i < part_ids.size(); ++i) { + indexed_triangle_set its = std::move(results[i].mesh); + if (its.indices.empty()) + continue; // this part's layers moved nothing; its own volume is drawn instead + + std::vector runs; + indexed_triangle_set grouped = + group_preview_by_color(its, results[i].triangle_color, entry_colors, runs); + + if (part_ids[i] == owner_id) { + m_preview_color_runs = std::move(runs); + m_preview_glmodel.init_from(grouped); + m_preview_glmodel.set_color(GLVolume::NEUTRAL_COLOR); + // Keep the displaced mesh so the wireframe overlay can be drawn on the raised + // surface actually shown in the true-displacement view. + m_preview_its = std::move(its); + } else { + auto preview = std::make_unique(); + preview->volume_id = part_ids[i]; + preview->color_runs = std::move(runs); + preview->glmodel.init_from(grouped); + preview->glmodel.set_color(GLVolume::NEUTRAL_COLOR); + m_part_previews.push_back(std::move(preview)); } - m_preview_glmodel.init_from(sorted); - } else { - m_preview_glmodel.init_from(its); } - m_preview_glmodel.set_color(GLVolume::NEUTRAL_COLOR); - // Keep the displaced mesh so the wireframe overlay can be drawn on it (the - // true-displacement view), then refresh the wireframe from it. - m_preview_its = std::move(its); + refresh_wireframe(); // The paint tint rides the displaced surface in this view, so it follows the new mesh. m_paint_overlay_dirty = true; @@ -3702,6 +3800,82 @@ const ModelVolume* GLGizmoTextureDisplacement::texture_volume() const return const_cast(this)->texture_volume(); } +std::vector GLGizmoTextureDisplacement::texture_parts() +{ + std::vector out; + ModelObject *mo = m_c->selection_info()->model_object(); + if (mo == nullptr) + return out; + for (ModelVolume *mv : mo->volumes) + if (mv->is_model_part()) + out.push_back(mv); + return out; +} + +std::vector GLGizmoTextureDisplacement::painted_parts() +{ + std::vector out; + for (ModelVolume *mv : texture_parts()) + if (mv->is_texture_displacement_painted()) + out.push_back(mv); + return out; +} + +bool GLGizmoTextureDisplacement::any_part_painted() const +{ + for (const ModelVolume *mv : const_cast(this)->texture_parts()) + if (mv->is_texture_displacement_painted()) + return true; + return false; +} + +std::vector GLGizmoTextureDisplacement::layers_for_part(const ModelVolume &part) const +{ + const ModelVolume *owner = texture_volume(); + if (owner == nullptr) + return {}; + std::vector out = owner->texture_displacement_layers; + if (&part == owner) + return out; + for (TextureDisplacementLayer &layer : out) { + layer.lscm_seam_edges.clear(); + layer.islands.clear(); + layer.island_groups.clear(); + layer.lscm_uv_overrides.clear(); + } + return out; +} + +Vec3d GLGizmoTextureDisplacement::texture_anchor() const +{ + const ModelVolume *owner = texture_volume(); + return owner != nullptr ? Vec3d(texture_displacement_volume_to_world(*owner).translation()) : Vec3d::Zero(); +} + +std::vector GLGizmoTextureDisplacement::resting_drops(const std::vector &parts) +{ + const auto bottom = [](const ModelVolume &part) { + return part.mesh().transformed_bounding_box(texture_displacement_volume_to_world(part)).min.z(); + }; + // Each part's bottom is measured the same way as the object's, so the lowest part's drop is exactly + // 0 and a single-part object bakes against its own bottom as it always has. + double object_bottom = std::numeric_limits::max(); + for (const ModelVolume *part : texture_parts()) + object_bottom = std::min(object_bottom, bottom(*part)); + std::vector out; + out.reserve(parts.size()); + for (const ModelVolume *part : parts) + out.push_back(float(bottom(*part) - object_bottom)); + return out; +} + +Transform3d GLGizmoTextureDisplacement::prepare_texture_frame(const ModelVolume &part) +{ + if (texture_parts().size() < 2) + return Transform3d::Identity(); + return texture_displacement_bake_frame(texture_displacement_volume_to_world(part), texture_anchor()); +} + void GLGizmoTextureDisplacement::update_model_object() { store_panel_state(); @@ -4982,7 +5156,10 @@ void GLGizmoTextureDisplacement::remove_texture_layer(int slot) [slot](const TextureDisplacementLayer &l) { return l.slot == slot; }), layers.end()); if (slot >= 0 && slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS)) { - mv->texture_displacement_facet(slot).reset(); + // Every model part: paint left in the slot on another part would still bake, and the next layer + // added reuses the slot. + for (ModelVolume *part : texture_parts()) + part->texture_displacement_facet(slot).reset(); m_thumbnails[size_t(slot)].reset(); m_thumbnail_source[size_t(slot)].reset(); m_layer_expanded[size_t(slot)] = false; @@ -5073,25 +5250,19 @@ void GLGizmoTextureDisplacement::move_texture_layer(int slot, int to_index) int GLGizmoTextureDisplacement::select_visible_faces(const std::array *uv_clip) { - ModelVolume *mv = texture_volume(); - ModelObject *mo = m_c->selection_info()->model_object(); - const int idx = texture_volume_raycaster_index(); - if (mv == nullptr || mo == nullptr || idx < 0 || idx >= int(m_triangle_selectors.size())) + const ModelVolume *owner = texture_volume(); + ModelObject *mo = m_c->selection_info()->model_object(); + // Every model part, at its selector's and its raycaster's index (see texture_parts()): what is in + // view gets painted whichever part it belongs to, and one part can hide another. + const std::vector parts = texture_parts(); + const std::vector raycasters = m_c->raycaster()->raycasters(); + if (owner == nullptr || mo == nullptr || parts.size() > m_triangle_selectors.size() || parts.size() > raycasters.size()) return 0; - const indexed_triangle_set &its = mv->mesh().its; - if (its.indices.empty()) - return 0; - - const Selection &selection = m_parent.get_selection(); - const Geometry::Transformation trafo(mo->instances[selection.get_instance_idx()]->get_transformation().get_matrix() * - mv->get_matrix()); - const Transform3d &to_world = trafo.get_matrix(); - const Camera &camera = wxGetApp().plater()->get_camera(); - - // Normals transform by the inverse transpose, not by the matrix itself - with a non-uniform - // scale the two differ, and using the wrong one flips the facing test on the scaled axes. - const Matrix3d normal_matrix = to_world.matrix().block<3, 3>(0, 0).inverse().transpose(); + const Selection &selection = m_parent.get_selection(); + const Transform3d instance = mo->instances[selection.get_instance_idx()]->get_transformation().get_matrix(); + const Transform3d owner_to_world = instance * owner->get_matrix(); + const Camera &camera = wxGetApp().plater()->get_camera(); // Pass 1 (cheap): drop back-facing triangles. Under perspective the view direction varies across // the model, so it is taken per triangle from the eye to the centroid; under an orthographic @@ -5101,69 +5272,109 @@ int GLGizmoTextureDisplacement::select_visible_faces(const std::array const bool ortho = camera.get_type() == Camera::EType::Ortho; const Vec3d fwd = camera.get_dir_forward(); - std::vector centroids; // world coords, what get_unobscured_idxs() expects - std::vector front_facing; // parallel: which facet each centroid came from - centroids.reserve(its.indices.size() / 2); - front_facing.reserve(its.indices.size() / 2); + std::vector trafos; + std::vector> centroids(parts.size()); // world coords, what get_unobscured_idxs() expects + std::vector> front_facing(parts.size()); // parallel: which facet each centroid came from + trafos.reserve(parts.size()); + for (size_t p = 0; p < parts.size(); ++p) { + const ModelVolume &part = *parts[p]; + const indexed_triangle_set &its = part.mesh().its; + trafos.emplace_back(instance * part.get_matrix()); + const Transform3d &to_world = trafos.back().get_matrix(); + // The projection frame maps the owner's local coordinates (see apply_projection_frame()), so + // another part's centroids are brought into them before the clip test. + const Transform3d to_owner = (&part == owner) ? Transform3d::Identity() : Transform3d(owner_to_world.inverse() * to_world); - for (size_t f = 0; f < its.indices.size(); ++f) { - const stl_triangle_vertex_indices &tri = its.indices[f]; - const Vec3d a = its.vertices[tri[0]].cast(); - const Vec3d b = its.vertices[tri[1]].cast(); - const Vec3d c = its.vertices[tri[2]].cast(); - const Vec3d n_world = normal_matrix * (b - a).cross(c - a); - if (n_world.squaredNorm() < 1e-20) - continue; // degenerate triangle: no meaningful normal, so no meaningful facing test - const Vec3d centroid_local = (a + b + c) / 3.0; - const Vec3d centroid_world = to_world * centroid_local; - const Vec3d view_dir = ortho ? fwd : Vec3d(centroid_world - eye); - if (n_world.dot(view_dir) >= 0.0) - continue; // facing away from the camera + // Normals transform by the inverse transpose, not by the matrix itself - with a non-uniform + // scale the two differ, and using the wrong one flips the facing test on the scaled axes. + const Matrix3d normal_matrix = to_world.matrix().block<3, 3>(0, 0).inverse().transpose(); - // Clip to the projection frame before the raycast, not after: outside the frame the texture - // samples to nothing anyway, so those facets would only be painted to no effect - and this - // is also what keeps the ray queries proportional to the framed area instead of the model. - if (uv_clip != nullptr) { - Vec2f uv; - if (!project_uv_projective(*uv_clip, centroid_local.cast(), uv)) - continue; // behind the projector - if (uv.x() < 0.f || uv.x() > 1.f || uv.y() < 0.f || uv.y() > 1.f) - continue; + centroids[p].reserve(its.indices.size() / 2); + front_facing[p].reserve(its.indices.size() / 2); + for (size_t f = 0; f < its.indices.size(); ++f) { + const stl_triangle_vertex_indices &tri = its.indices[f]; + const Vec3d a = its.vertices[tri[0]].cast(); + const Vec3d b = its.vertices[tri[1]].cast(); + const Vec3d c = its.vertices[tri[2]].cast(); + const Vec3d n_world = normal_matrix * (b - a).cross(c - a); + if (n_world.squaredNorm() < 1e-20) + continue; // degenerate triangle: no meaningful normal, so no meaningful facing test + const Vec3d centroid_local = (a + b + c) / 3.0; + const Vec3d centroid_world = to_world * centroid_local; + const Vec3d view_dir = ortho ? fwd : Vec3d(centroid_world - eye); + if (n_world.dot(view_dir) >= 0.0) + continue; // facing away from the camera + + // Clip to the projection frame before the raycast, not after: outside the frame the texture + // samples to nothing anyway, so those facets would only be painted to no effect - and this + // is also what keeps the ray queries proportional to the framed area instead of the model. + if (uv_clip != nullptr) { + Vec2f uv; + if (!project_uv_projective(*uv_clip, (to_owner * centroid_local).cast(), uv)) + continue; // behind the projector + if (uv.x() < 0.f || uv.x() > 1.f || uv.y() < 0.f || uv.y() > 1.f) + continue; + } + centroids[p].emplace_back(centroid_world.cast()); + front_facing[p].push_back(unsigned(f)); } - centroids.emplace_back(centroid_world.cast()); - front_facing.push_back(unsigned(f)); } - if (centroids.empty()) - return 0; // Pass 2 (the expensive one): a real ray query per surviving centroid, so geometry in front of a // front-facing triangle correctly hides it - the far inner wall of a cup is front-facing but not - // visible. This is why the whole thing is click-driven rather than live. - std::vector unobscured; + // visible. This is why the whole thing is click-driven rather than live. Each raycaster only sees + // its own part's mesh, so a centroid has to be clear of every one of them; its own part goes first, + // since that is what hides most of them. + size_t visible = 0; { wxBusyCursor wait; - unobscured = m_c->raycaster()->raycasters()[size_t(idx)]->get_unobscured_idxs( - trafo, camera, centroids, m_c->object_clipper()->get_clipping_plane()); + const ClippingPlane *clipping_plane = m_c->object_clipper()->get_clipping_plane(); + for (size_t p = 0; p < parts.size(); ++p) { + std::vector &points = centroids[p]; + std::vector &facets = front_facing[p]; + const auto keep_unobscured_by = [&](size_t q) { + const std::vector clear = raycasters[q]->get_unobscured_idxs(trafos[q], camera, points, clipping_plane); + std::vector kept_points; + std::vector kept_facets; + kept_points.reserve(clear.size()); + kept_facets.reserve(clear.size()); + for (unsigned i : clear) { + kept_points.push_back(points[i]); + kept_facets.push_back(facets[i]); + } + points = std::move(kept_points); + facets = std::move(kept_facets); + }; + if (!points.empty()) + keep_unobscured_by(p); + for (size_t q = 0; q < parts.size() && !points.empty(); ++q) + if (q != p) + keep_unobscured_by(q); + visible += facets.size(); + } } - if (unobscured.empty()) + if (visible == 0) return 0; Plater::TakeSnapshot snapshot(wxGetApp().plater(), _u8L("Select visible faces for texture displacement"), UndoRedo::SnapshotType::GizmoAction); - // Replaces the layer's paint rather than adding to it: the checkbox means "project onto what I - // can see", so a second capture from a new angle should not leave the previous angle painted. + // Replaces the layer's paint rather than adding to it, on every part including those nothing was + // visible on: the checkbox means "project onto what I can see", so a second capture from a new + // angle should not leave the previous angle painted. // TriangleSelectorGUI, not the TriangleSelector base: request_update_render_data() is declared on // the GUI subclass, so binding to the base here would drop it. - TriangleSelectorGUI &selector = *m_triangle_selectors[size_t(idx)]; - selector.reset(); - for (unsigned i : unobscured) - selector.set_facet(int(front_facing[i]), EnforcerBlockerType::ENFORCER); - selector.request_update_render_data(true); + for (size_t p = 0; p < parts.size(); ++p) { + TriangleSelectorGUI &selector = *m_triangle_selectors[p]; + selector.reset(); + for (unsigned f : front_facing[p]) + selector.set_facet(int(f), EnforcerBlockerType::ENFORCER); + selector.request_update_render_data(true); + } update_model_object(); m_parent.set_as_dirty(); - return int(unobscured.size()); + return int(visible); } void GLGizmoTextureDisplacement::select_whole_model() @@ -5190,27 +5401,31 @@ void GLGizmoTextureDisplacement::select_whole_model() void GLGizmoTextureDisplacement::subdivide_model() { - ModelVolume *mv = texture_volume(); ModelObject *mo = m_c->selection_info()->model_object(); - if (mv == nullptr || mo == nullptr || m_subdivide_count < 1) + // Every model part, like the remesh: this is a plain mesh operation on the object, and a part left + // coarse is a part no height map can raise relief on. + const std::vector parts = texture_parts(); + if (mo == nullptr || parts.empty() || m_subdivide_count < 1) return; // 0 passes means "no subdivision" - don't take a snapshot for a no-op Plater *plater = wxGetApp().plater(); Plater::TakeSnapshot snapshot(plater, _u8L("Subdivide model for texture displacement"), UndoRedo::SnapshotType::GizmoAction); - // Same save/replace/restore-painting dance GLGizmoSimplify uses when it re-tessellates a - // volume's mesh: supported/seam/mmu/fuzzy-skin masks get remapped onto the new triangles, - // texture-displacement doesn't (no remap support for it yet) and is dropped instead of being - // left referring to triangle indices that no longer mean the same thing. - std::optional saved_painting = mv->save_painting(); + for (ModelVolume *mv : parts) { + // Same save/replace/restore-painting dance GLGizmoSimplify uses when it re-tessellates a + // volume's mesh: supported/seam/mmu/fuzzy-skin masks get remapped onto the new triangles, + // texture-displacement doesn't (no remap support for it yet) and is dropped instead of being + // left referring to triangle indices that no longer mean the same thing. + std::optional saved_painting = mv->save_painting(); - // max_edge_length 0 means "no triangle is ever small enough", so every non-degenerate edge is - // split on each of the m_subdivide_count passes - i.e. a plain "subdivide the whole mesh N times". - TriangleMesh new_mesh(subdivide_mesh_uniform(mv->mesh().its, 0.f, m_subdivide_count)); - mv->set_mesh(std::move(new_mesh)); - mv->set_new_unique_id(); - mv->calculate_convex_hull(); - mv->restore_painting(saved_painting); + // max_edge_length 0 means "no triangle is ever small enough", so every non-degenerate edge is + // split on each of the m_subdivide_count passes - i.e. a plain "subdivide the whole mesh N times". + TriangleMesh new_mesh(subdivide_mesh_uniform(mv->mesh().its, 0.f, m_subdivide_count)); + mv->set_mesh(std::move(new_mesh)); + mv->set_new_unique_id(); + mv->calculate_convex_hull(); + mv->restore_painting(saved_painting); + } if (ObjectList *obj_list = wxGetApp().obj_list()) { const ModelObjectPtrs &objs = plater->model().objects; @@ -5855,13 +6070,35 @@ ColorQuantizeFn GLGizmoTextureDisplacement::make_palette_quantizer(const std::ve TextureDisplacementPrepareResult GLGizmoTextureDisplacement::prepare_mesh( const indexed_triangle_set &base, const TextureDisplacementFacetsData &masks, const std::vector &layers, const std::vector &model_uv, - const TextureDisplacementPrepareParams ¶ms, + const Transform3d &texture_frame, const TextureDisplacementPrepareParams ¶ms, const TextureColorSettings &color_settings, const DisplacementProgressFn &progress, BakeStageRecorder *debug) { TextureDisplacementPrepareResult out; const auto report = [&progress](int pct) { return !progress || progress(pct); }; + // The samplers are built over a copy of the current mesh moved into `texture_frame`, and queried + // with points and normals mapped across, so the stages below go on measuring the mesh itself. + const bool framed = !texture_frame.matrix().isApprox(Transform3d::Identity().matrix()); + const Matrix3d frame_normal = texture_frame.linear().inverse().transpose(); + indexed_triangle_set framed_mesh; + const auto mesh_to_sample = [&](const indexed_triangle_set &its) -> const indexed_triangle_set & { + if (!framed) + return its; + framed_mesh = its; + for (Vec3f &v : framed_mesh.vertices) + v = (texture_frame * v.cast()).cast(); + return framed_mesh; + }; + const auto sample_in_frame = [&](auto sampler) -> decltype(sampler) { + if (!framed || !sampler) + return sampler; + return [sampler, frame = texture_frame, frame_normal](const Vec3f &pos, const Vec3f &normal) { + return sampler((frame * pos.cast()).cast(), + (frame_normal * normal.cast()).normalized().cast()); + }; + }; + // Stage capture for the debug view. Timed from the end of the previous stage, so the capture - // a copy plus an edge scan - never lands inside the measurement it reports. auto stage_clock = std::chrono::steady_clock::now(); @@ -5937,17 +6174,20 @@ TextureDisplacementPrepareResult GLGizmoTextureDisplacement::prepare_mesh( // length baseline alone. const std::vector uv_stage = uv_now(); const std::vector *uv_ptr = uv_stage.empty() ? nullptr : &uv_stage; + const indexed_triangle_set &sampled = mesh_to_sample(mesh.its); HeightFieldSampler sampler; if (params.subdiv_feature) - sampler = make_combined_displacement_sampler(mesh.its, layers, current, uv_ptr); + sampler = sample_in_frame(make_combined_displacement_sampler(sampled, layers, current, uv_ptr)); // Colour boundaries need triangles of their own - the chord test cannot see them, since // the height field is perfectly smooth across a change of filament. ColorFieldSampler color; // A flat-colour layer is matched against single filaments only, as the bake does, so its // boundaries are refined where the bake will actually change filament. if (params.subdiv_color_edge_mm > 0.f && !color_settings.empty()) - color = make_combined_color_sampler(mesh.its, layers, current, make_palette_quantizer(color_settings.palette), - make_palette_quantizer(color_settings.palette_pure), uv_ptr); + color = sample_in_frame(make_combined_color_sampler(sampled, layers, current, + make_palette_quantizer(color_settings.palette), + make_palette_quantizer(color_settings.palette_pure), + uv_ptr)); // The refinement follows perceived colour: a mix is one colour here, however the slicer // interleaves its filaments layer by layer. // "Min edge" is a feature-mode control (it is the floor the curvature test refines down @@ -6008,8 +6248,8 @@ TextureDisplacementPrepareResult GLGizmoTextureDisplacement::prepare_mesh( cut_region[i] = (region[size_t(source[i])] & REFINE_PAINTED) ? 1 : 0; const std::vector uv_refined = uv_now(); const HeightFieldSampler refined_sampler = - make_combined_displacement_sampler(mesh.its, layers, current, - uv_refined.empty() ? nullptr : &uv_refined); + sample_in_frame(make_combined_displacement_sampler(mesh_to_sample(mesh.its), layers, current, + uv_refined.empty() ? nullptr : &uv_refined)); std::vector cut_source; size_t cuts = 0; indexed_triangle_set cut = cut_mesh_at_steps(mesh.its, cut_region, refined_sampler, @@ -6047,7 +6287,7 @@ void GLGizmoTextureDisplacement::subdivide_model_adaptive() update_model_object(); // flush any in-progress stroke into the committed masks first - if (!mv->is_texture_displacement_painted()) { + if (!any_part_painted()) { show_error(nullptr, _u8L("Paint the area you want to subdivide first - adaptive subdivision only " "refines where you have painted.")); return; @@ -6209,7 +6449,8 @@ void GLGizmoTextureDisplacement::remesh_model() params.remesh_sharp_deg = m_remesh_keep_sharp_edges ? m_remesh_sharp_angle_deg : 0.f; queue_prepare(params, _u8L("Remesh model for texture displacement"), /* then_bake */ false, _u8L("Remeshing did not change the model. It may be non-manifold (open edges or edges " - "shared by more than two triangles), or the target edge length may already be met.")); + "shared by more than two triangles), or the target edge length may already be met."), + PrepareScope::AllParts); } void GLGizmoTextureDisplacement::rebuild_subdivide_preview() @@ -6360,23 +6601,35 @@ GLTexture *GLGizmoTextureDisplacement::get_layer_height_texture(const TextureDis void GLGizmoTextureDisplacement::bake(bool own_snapshot) { - ModelVolume *mv = texture_volume(); - if (!mv || m_bake_in_progress) + ModelVolume *owner = texture_volume(); + if (owner == nullptr || m_bake_in_progress) return; // Make sure the currently active layer's in-progress edits are flushed into the model before // baking, otherwise the most recent, not-yet-committed strokes would be silently skipped. update_model_object(); - if (!mv->is_texture_displacement_painted()) { + // Every painted part, not only the one holding the layer stack: the brush paints across all of + // them (see update_model_object()), so baking one would leave the user's paint on the others + // untouched and their geometry flat. + const std::vector parts = painted_parts(); + if (parts.empty()) { show_error(nullptr, _u8L("Nothing is painted, there is nothing to bake.")); return; } + const Vec3d anchor = texture_anchor(); + const std::vector drops = resting_drops(parts); + std::vector volumes; + volumes.reserve(parts.size()); + for (size_t i = 0; i < parts.size(); ++i) + volumes.push_back(texture_displacement_bake_volume(*parts[i], layers_for_part(*parts[i]), + owner->texture_displacement_options, anchor, drops[i])); + m_bake_in_progress = true; - queue_texture_displacement_bake(*mv, color_settings_for(*mv), [this]() { + queue_texture_displacement_bake(std::move(volumes), color_settings_for(*owner), [this]() { m_bake_in_progress = false; - // Baking replaces the volume's mesh (new id, new topology) without changing the object's + // Baking replaces each baked part's mesh (new id, new topology) without changing the object's // id or volume count, so GLGizmoPainterBase::data_changed()'s usual change-detection never // notices it needs to reload - do it explicitly here, otherwise the gizmo keeps painting // and rendering against the stale, pre-bake TriangleSelectorPatch until the object is @@ -6448,7 +6701,7 @@ void GLGizmoTextureDisplacement::bake_standard() return; update_model_object(); // flush the active layer's in-progress strokes before anything reads them - if (!mv->is_texture_displacement_painted()) { + if (!any_part_painted()) { show_error(nullptr, _u8L("Nothing is painted, there is nothing to bake.")); return; } @@ -6520,7 +6773,8 @@ void GLGizmoTextureDisplacement::run_stage_debug() m_debug_in_progress = true; queue_texture_displacement_debug( - *mv, color_settings_for(*mv), params, run_prepare, m_debug_check_topology, + *mv, color_settings_for(*mv), params, prepare_texture_frame(*mv), resting_drops({mv}).front(), run_prepare, + m_debug_check_topology, [this](std::vector stages) { m_debug_in_progress = false; if (!stages.empty()) { @@ -6548,6 +6802,9 @@ void GLGizmoTextureDisplacement::show_debug_stage(int index) m_use_shaded_preview = false; m_preview_color_runs.clear(); m_preview_glmodel.reset(); + // The stage is a capture of one part's run, so the other parts go back to being drawn as themselves + // rather than keeping a live preview the captured stages say nothing about. + m_part_previews.clear(); indexed_triangle_set its; its.vertices = stage.mesh.vertices; @@ -6669,23 +6926,36 @@ void GLGizmoTextureDisplacement::render_debug_stage_panel(ModelVolume *mv) void GLGizmoTextureDisplacement::queue_prepare(const TextureDisplacementPrepareParams ¶ms, const std::string &snapshot_name, bool then_bake, - const std::string &unchanged_msg) + const std::string &unchanged_msg, PrepareScope scope) { - ModelVolume *mv = texture_volume(); - if (mv == nullptr || m_prepare_in_progress || m_bake_in_progress) + ModelVolume *owner = texture_volume(); + if (owner == nullptr || m_prepare_in_progress || m_bake_in_progress) + return; + + // Preparing only the layer stack's own part would hand the displacement a coarse mesh everywhere + // else - a height map can only move vertices that already exist, so on a multibody object that is + // the difference between relief and a flat face. See PrepareScope for which parts that means. + const std::vector parts = scope == PrepareScope::AllParts ? texture_parts() : painted_parts(); + if (parts.empty()) return; TextureDisplacementPrepareInput input; - input.volume_id = mv->id(); - input.base_mesh = mv->mesh().its; - input.masks = facets_data_of(*mv); - input.layers = mv->texture_displacement_layers; input.params = params; input.snapshot_name = snapshot_name; - if (mv->has_texture_uv()) - input.model_uv = mv->texture_uv; + input.volumes.reserve(parts.size()); + for (const ModelVolume *part : parts) { + TextureDisplacementPrepareVolume entry; + entry.volume_id = part->id(); + entry.base_mesh = part->mesh().its; + entry.masks = facets_data_of(*part); + entry.layers = layers_for_part(*part); + if (part->has_texture_uv()) + entry.model_uv = part->texture_uv; + entry.texture_frame = prepare_texture_frame(*part); + input.volumes.push_back(std::move(entry)); + } if (params.subdiv_color_edge_mm > 0.f) - input.color = color_settings_for(*mv); + input.color = color_settings_for(*owner); m_prepare_in_progress = true; queue_texture_displacement_prepare(std::move(input), [this, then_bake, unchanged_msg]( @@ -8399,9 +8669,20 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float const float footer_top = ImGui::GetCursorScreenPos().y; ImGui::Separator(); { - const float x0 = ImGui::GetCursorPosX(); - const int base_k = mv != nullptr ? int((mv->mesh().facets_count() + 500) / 1000) : 0; - const bool v2 = mv != nullptr && mv->texture_displacement_options.pipeline_v2; + const float x0 = ImGui::GetCursorPosX(); + // Over every part the bake will act on, not just the one holding the layer stack, so the count + // the footer quotes is the count Bake is actually working with on a multibody object. Before + // anything is painted there is nothing to bake yet, and the whole object is the honest estimate. + size_t base_facets = 0; + { + std::vector counted = painted_parts(); + if (counted.empty()) + counted = texture_parts(); + for (const ModelVolume *part : counted) + base_facets += part->mesh().facets_count(); + } + const int base_k = int((base_facets + 500) / 1000); + const bool v2 = mv != nullptr && mv->texture_displacement_options.pipeline_v2; // The triangle budget is the one subdivision control Standard mode keeps: its right value depends on // the part rather than on the recipe (a big model, or a fine texture, simply needs more of them), and @@ -8534,7 +8815,9 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float ImGui::SameLine(x0 + panel_w - button_w * 2 - style.ItemSpacing.x); - const bool can_bake = !busy && mv != nullptr && mv->is_texture_displacement_painted(); + // Read before Close below, which releases the selection any_part_painted() finds the parts through. + const bool painted = mv != nullptr && any_part_painted(); + const bool can_bake = !busy && painted; const std::string bake_label = m_prepare_in_progress ? _u8L("Preparing...") : m_bake_in_progress ? _u8L("Baking...") : into_u8(m_desc.at("bake")); @@ -8554,7 +8837,7 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float m_imgui->pop_bold_font(); GLGizmoUtils::pop_orca_button_style(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) - panel_tooltip(mv != nullptr && !mv->is_texture_displacement_painted() ? + panel_tooltip(mv != nullptr && !painted ? (m_seam_edit_mode ? _u8L("Nothing is painted yet. The UV editor's seam tool is on, so " "strokes on the model mark seams instead of painting - turn " "it off in the pane to paint.") : @@ -8580,8 +8863,8 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float // What Bake will produce, and which layers it will skip. if (mv != nullptr) { const std::string base_count = base_k > 0 ? Slic3r::format(_u8L("%1% k"), base_k) : - std::to_string(mv->mesh().facets_count()); - const unsigned base_n = base_k > 0 ? unsigned(base_k) * 1000 : unsigned(mv->mesh().facets_count()); + std::to_string(base_facets); + const unsigned base_n = base_k > 0 ? unsigned(base_k) * 1000 : unsigned(base_facets); const unsigned result_n = unsigned(base_k + m_subdivide_budget_k) * 1000; // TRN %1% is a triangle count, either exact or rounded to thousands such as "120 k". std::string note = v2 ? Slic3r::format(into_u8(_L_PLURAL("Model: %1% triangle - the bake refines to the resolution above, up to its budget", @@ -8591,7 +8874,7 @@ void GLGizmoTextureDisplacement::on_render_input_window(float x, float y, float "Bake moves existing vertices - the model stays at %1% triangles", base_n)), base_count) : Slic3r::format(into_u8(_L_PLURAL("Bake result up to ~%1% k triangle", "Bake result up to ~%1% k triangles", result_n)), base_k + m_subdivide_budget_k); - if (mv->is_texture_displacement_painted()) { + if (painted) { std::vector skipped; for (const TextureDisplacementLayer &l : mv->texture_displacement_layers) if (!slot_painted(l.slot)) diff --git a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp index 22d8b417c7..873d90ff69 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp @@ -15,6 +15,7 @@ #include #include #include "libslic3r/Color.hpp" +#include "libslic3r/ObjectID.hpp" #include #include "libslic3r/TriangleSelector.hpp" #include "libslic3r/TriangleMesh.hpp" @@ -69,6 +70,14 @@ public: // to the samplers so a ModelUV layer drives // the refinement through its own layout. const std::vector &model_uv, + // `base`'s coordinates -> the frame the bake + // samples the texture in, so the refinement + // follows the texture the bake will apply. + // Only the sampling moves into it: the mesh, + // and every length in `params`, stay in + // `base`'s own coordinates. Identity samples + // there as well. + const Transform3d &texture_frame, const TextureDisplacementPrepareParams ¶ms, const TextureColorSettings &color_settings, const DisplacementProgressFn &progress, @@ -185,6 +194,35 @@ public: ColorRGBA color; }; std::vector m_preview_color_runs; + + // The displaced preview of each painted model part *other* than the one owning the layer stack. That + // part keeps m_preview_glmodel and m_preview_its, which the paint overlays, the wireframe and the UV + // and seam editors are all keyed to; the remaining parts of a multibody object only need their + // geometry drawn, so that is all this holds. Built by the same preview job, one entry per part. + // + // Held behind unique_ptr because GLModel owns GPU buffers and has no move constructor: a vector of + // them by value would copy the handles on reallocation and free them twice. + struct PartPreview + { + ObjectID volume_id; + GLModel glmodel; + std::vector color_runs; + }; + std::vector> m_part_previews; + // The part `preview` was built for, or nullptr if it has gone away or had its mesh replaced since - + // in which case that part's own volume is drawn instead of a preview that no longer describes it. + const ModelVolume *preview_part(const PartPreview &preview) const; + // Whether the true-displacement view has anything to draw. Asking m_preview_glmodel alone would + // hide the real volumes behind an empty preview whenever only another part is painted. + bool has_true_preview() const { return m_preview_glmodel.is_initialized() || !m_part_previews.empty(); } + // The preview mesh as it is uploaded: when the run reported a palette entry per triangle, the index + // buffer is reordered so that each palette colour becomes one contiguous draw range (returned in + // `runs`); otherwise `its` is handed back unchanged and `runs` stays empty. Only the index buffer is + // permuted, never the vertices - see PreviewColorRun. + static indexed_triangle_set group_preview_by_color(const indexed_triangle_set &its, + const std::vector &triangle_color, + const std::vector &entry_colors, + std::vector &runs); // True if any of the volume's layers would actually colour something: colour turned on, and a // texture that has colour to give. What decides whether a palette is captured into a job at all, // and so whether the colour criterion and the mmu write ever run. @@ -258,12 +296,46 @@ private: void on_shutdown() override; PainterGizmoType get_painter_type() const override; - // Phase 1 restricts the texture layer list to the first model-part volume of the current - // object (the common single-volume case); multi-part objects only get texture layers on - // their first part until a later phase. Returns nullptr if there is no model part. + // The model part that owns the object's texture layer stack, its options, and the unwrap the UV and + // seam editors work on: the first model part of the current object. Those are object-wide settings + // kept on one part rather than copied onto all of them. Returns nullptr if there is no model part. + // + // This is *not* the set of parts a bake acts on - see painted_parts(). Reading the layer stack and + // baking are different questions, and answering the second one with this is what made texture + // displacement ignore every part of a multibody object but the first. ModelVolume* texture_volume(); const ModelVolume* texture_volume() const; + // Every model part of the current object, in the object's own volume order - which is also the + // order update_from_model_object() builds m_triangle_selectors in, so index i here is selector i. + std::vector texture_parts(); + // The parts a bake or a preview acts on: those of texture_parts() carrying paint in at least one + // slot. Empty when nothing is painted anywhere on the object, which is what the Bake button and its + // "nothing is painted" check test. + std::vector painted_parts(); + bool any_part_painted() const; + + // The object's layer stack as it applies to `part`. The stack itself lives on texture_volume(), but + // four of each layer's fields index *that* part's mesh and the chart ids of *its* unwrap - the LSCM + // seam edges, the island placements, their join groups and the per-vertex uv overrides. Carried onto + // another part they would address triangles and charts that have nothing to do with it, so they are + // dropped and that part unwraps on its own. Everything else - the image, depth, tiling, projection + // method, blend mode, colour - applies unchanged, since every part is baked in the one texture frame + // anchored at texture_anchor(); that is what lets one stack texture a whole multibody object. + std::vector layers_for_part(const ModelVolume &part) const; + // The world point the object's texture is anchored at: texture_volume()'s origin. Every part is + // baked and previewed in the frame anchored there (see texture_displacement_bake_frame()), so a + // tiled pattern runs on across the parts and a view projection lands where it was aimed on each. + Vec3d texture_anchor() const; + // For each of `parts`, at the same index: how far the object's lowest point lies below that part's + // own, in mm - what its bake lowers its resting plane by, so every part is clamped against the one + // plane the object rests on. 0 for the lowest part, and so for a single-part object. + std::vector resting_drops(const std::vector &parts); + // Where prepare_mesh() samples `part`'s texture: the frame its bake samples in when the object has + // several model parts, so they are all refined for one continuous texture. A single-part object + // keeps the identity, the frame it has always been refined in. + Transform3d prepare_texture_frame(const ModelVolume &part); + void add_texture_layer(); void remove_texture_layer(int slot); // Moves the layer in `slot` to position `to_index` of the slot-ordered stack (an insertion index, @@ -310,8 +382,14 @@ private: // - `unchanged_msg`, when not empty, is shown if the run had nothing to do. Standard's Bake passes // nothing: a mesh that already meets the criteria is not an error there, it just goes straight // on to the displacement. + // - `scope` is which of the object's model parts to prepare. Anything feeding a displacement + // prepares exactly the parts that displacement will move; a plain Remesh is a mesh operation on + // the object and takes all of them, so painting the rest of a multibody object afterwards has a + // dense enough mesh to show relief on. + enum class PrepareScope { PaintedParts, AllParts }; void queue_prepare(const TextureDisplacementPrepareParams ¶ms, const std::string &snapshot_name, - bool then_bake, const std::string &unchanged_msg); + bool then_bake, const std::string &unchanged_msg, + PrepareScope scope = PrepareScope::PaintedParts); // Set from queue_prepare() until its job's result has been committed. Distinct from // m_bake_in_progress because Standard's Bake sets both in turn, and because every button that would // read or replace the mesh has to stay disabled for the whole of it. @@ -351,14 +429,14 @@ private: // volume's slot among them, or -1 if it has none (no selection, or the lists disagree). int texture_volume_raycaster_index() const; - // Paints exactly the facets currently visible from the camera onto the active layer, replacing - // whatever that layer had painted. "Visible" is two tests: the facet faces the camera, and its - // centroid is not hidden behind other geometry (a real raycast, so a concave part's far inner - // wall is correctly excluded). When `uv_clip` is given (the projection frame's matrix), facets - // whose centroid falls outside the frame's uv unit square are skipped first - which both clips - // the selection to the frame and spares the raycast for everything outside it. Costs one ray - // query per surviving facet, so it is a one-shot action, never a per-frame one. Returns the - // number of facets selected. + // Paints exactly the facets currently visible from the camera onto the active layer, on every model + // part, replacing whatever that layer had painted on each. "Visible" is two tests: the facet faces + // the camera, and its centroid is not hidden behind other geometry of any part (a real raycast, so + // a concave part's far inner wall is correctly excluded). When `uv_clip` is given (the projection + // frame's matrix), facets whose centroid falls outside the frame's uv unit square are skipped first + // - which both clips the selection to the frame and spares the raycast for everything outside it. + // Costs one ray query per surviving facet and part, so it is a one-shot action, never a per-frame + // one. Returns the number of facets selected. int select_visible_faces(const std::array *uv_clip = nullptr); // When set, "Capture current view" also re-selects the visible faces, so the viewpoint the diff --git a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp index 427eac8b9c..9e17c2a015 100644 --- a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp +++ b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.cpp @@ -748,7 +748,8 @@ void GizmoObjectManipulation::set_init_rotation(const Geometry::Transformation & void GizmoObjectManipulation::reset_align_state() { m_hovered_align_type = GLGizmoAlignment::AlignType::NONE; - m_align_to_parent = !m_alignment_helper.can_align(GLGizmoAlignment::AlignType::X_MIN); + m_can_align_within = m_alignment_helper.can_align(GLGizmoAlignment::AlignType::X_MIN); + m_align_to_parent = !m_can_align_within; } void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, std::string window_name, float x, float y, float bottom_limit) @@ -924,7 +925,7 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, } if (!focued_on_text) m_glcanvas.handle_sidebar_focus_event("", false); - // Align and distribute along the world axes, within the selection or to the object or plate holding it. + // Align and distribute along the coordinate system of the panel, within the selection or to the object or plate holding it. using AlignType = GLGizmoAlignment::AlignType; const bool old_align_to_parent = m_align_to_parent; AlignType hovered_align_type = AlignType::NONE; @@ -932,6 +933,7 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing(); + m_alignment_helper.set_object_cs(is_instance_coordinates()); // Each row is row_height tall, separated by ItemSpacing.y. Every control is centered vertically in its row. const float row_y = ImGui::GetCursorPosY(); @@ -954,7 +956,13 @@ void GizmoObjectManipulation::do_render_move_window(ImGuiWrapper *imgui_wrapper, _u8L("Selection"), m_alignment_helper.is_parts_selection(true) ? _u8L("Object") : _u8L("Plate") }; - if (!m_alignment_helper.can_align(AlignType::X_MIN)) { + // Selecting enough items to align within them makes that the default, as when the tool opens. + const bool can_align_within = m_alignment_helper.can_align(AlignType::X_MIN); + if (can_align_within != m_can_align_within) { + m_can_align_within = can_align_within; + m_align_to_parent = !can_align_within; + } + if (!can_align_within) { align_modes.erase(align_modes.begin()); m_align_to_parent = true; } diff --git a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp index 7452884146..e69ed2be3a 100644 --- a/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp +++ b/src/slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp @@ -188,6 +188,8 @@ private: GLGizmoAlignment::AlignType m_hovered_align_type{GLGizmoAlignment::AlignType::NONE}; // Align to the object or plate holding the selection rather than within the selection. bool m_align_to_parent{false}; + // Whether the selection can align within itself, tracked to detect when the selection crosses that threshold. + bool m_can_align_within{false}; // Contains all shortcuts in the format of {shortcut, description}, e.g. {alt + _L("Left mouse button"), _L("Part_selection")} std::vector> m_shortcuts_move; diff --git a/src/slic3r/GUI/ImGuiWrapper.cpp b/src/slic3r/GUI/ImGuiWrapper.cpp index 080e85ad4e..b37b99f783 100644 --- a/src/slic3r/GUI/ImGuiWrapper.cpp +++ b/src/slic3r/GUI/ImGuiWrapper.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include "libslic3r/Technologies.hpp" @@ -506,6 +505,11 @@ bool ImGuiWrapper::update_mouse_data(wxMouseEvent& evt) io.MouseDown[0] = evt.LeftIsDown(); io.MouseDown[1] = evt.RightIsDown(); io.MouseDown[2] = evt.MiddleIsDown(); + // Replaces a modifier left held when its key-up was sent to another window. + io.KeyCtrl = evt.ControlDown(); + io.KeyShift = evt.ShiftDown(); + io.KeyAlt = evt.AltDown(); + io.KeySuper = evt.MetaDown(); // Only a vertical wheel event with a direction is a wheel step. A macOS trackpad reports sideways motion // as separate horizontal events, and its wheel events often carry a rotation of 0: wx truncates the // sub-pixel deltas to whole ones and passes on events with no delta at all. Read as vertical steps, @@ -588,16 +592,6 @@ void ImGuiWrapper::new_frame() // synchronize key states // when the application loses the focus it may happen that the key up event is not processed - // synchronize modifier keys - constexpr std::array, 3> imgui_mod_keys{ - std::make_pair(ImGuiKeyModFlags_Ctrl, WXK_CONTROL), - std::make_pair(ImGuiKeyModFlags_Shift, WXK_SHIFT), - std::make_pair(ImGuiKeyModFlags_Alt, WXK_ALT) }; - for (const std::pair& key : imgui_mod_keys) { - if ((io.KeyMods & key.first) != 0 && !wxGetKeyState(key.second)) - io.KeyMods &= ~key.first; - } - // Not sure if it is neccessary // values from 33 to 126 are reserved for the standard ASCII characters for (size_t i = 33; i <= 126; ++i) { @@ -2137,18 +2131,41 @@ bool ImGuiWrapper::want_any_input() const bool ImGuiWrapper::text_input_active() const { - const ImGuiID id = ImGui::GetActiveID(); - return id != 0 && ImGui::GetInputTextState(id) != nullptr; + // An active InputText requests text input in each frame that draws it, and NewFrame() moves the + // request into io.WantTextInput. + const ImGuiContext& g = *ImGui::GetCurrentContext(); + return g.WithinFrameScope ? g.IO.WantTextInput : g.WantTextInputNextFrame == 1; +} + +// A popup stays on the popup stack while its canvas is hidden, so it counts only if the last finished frame +// drew it, which NewFrame() moves from Active to WasActive. +static bool drawn_last_frame(const ImGuiWindow* popup) +{ + return popup != nullptr && (ImGui::GetCurrentContext()->WithinFrameScope ? popup->WasActive : popup->Active); } bool ImGuiWrapper::modal_popup_open() const { - // A modal stays on the popup stack while its canvas is hidden, so it counts only if the last finished - // frame drew it, which NewFrame() moves from Active to WasActive. - const ImGuiWindow* modal = ImGui::GetTopMostPopupModal(); - if (modal == nullptr) - return false; - return ImGui::GetCurrentContext()->WithinFrameScope ? modal->WasActive : modal->Active; + return drawn_last_frame(ImGui::GetTopMostPopupModal()); +} + +bool ImGuiWrapper::popup_open() const +{ + const ImVector& stack = ImGui::GetCurrentContext()->OpenPopupStack; + return std::any_of(stack.begin(), stack.end(), [](const ImGuiPopupData& popup) { return drawn_last_frame(popup.Window); }); +} + +void ImGuiWrapper::close_top_popup() +{ + const ImVector& stack = ImGui::GetCurrentContext()->OpenPopupStack; + for (int level = stack.Size - 1; level >= 0; --level) { + const ImGuiWindow* popup = stack[level].Window; + if (!drawn_last_frame(popup)) + continue; + if ((popup->Flags & ImGuiWindowFlags_Modal) == 0) + ImGui::ClosePopupToLevel(level, true); + return; + } } bool ImGuiWrapper::owns_key(const KeyChord& chord) const @@ -2156,6 +2173,39 @@ bool ImGuiWrapper::owns_key(const KeyChord& chord) const return modal_popup_open() || (chord.edits_text() && text_input_active()); } +bool ImGuiWrapper::item_held() const +{ + return ImGui::GetIO().MouseDown[0] && ImGui::GetActiveID() != 0; +} + +bool ImGuiWrapper::owns_keyboard() const +{ + return popup_open() || item_held() || text_input_active(); +} + +bool ImGuiWrapper::claim_key_event(const wxKeyEvent& evt) +{ + const bool claimed = owns_keyboard(); + const int key = evt.GetKeyCode(); + if (evt.GetEventType() == wxEVT_KEY_DOWN) { + m_char_claim = m_key_claims.try_emplace(key, claimed).first->second; + return *m_char_claim; + } + if (evt.GetEventType() == wxEVT_KEY_UP) { + m_char_claim.reset(); + if (const auto press = m_key_claims.extract(key)) + return press.mapped(); + return claimed; + } + return std::exchange(m_char_claim, std::nullopt).value_or(claimed); +} + +void ImGuiWrapper::forget_key_claims() +{ + m_key_claims.clear(); + m_char_claim.reset(); +} + ImFontAtlasCustomRect* ImGuiWrapper::GetTextureCustomRect(const wchar_t& tex_id) { auto item = m_custom_glyph_rects_ids.find(tex_id); diff --git a/src/slic3r/GUI/ImGuiWrapper.hpp b/src/slic3r/GUI/ImGuiWrapper.hpp index 6b5487bb5f..e4b8dabd77 100644 --- a/src/slic3r/GUI/ImGuiWrapper.hpp +++ b/src/slic3r/GUI/ImGuiWrapper.hpp @@ -73,6 +73,10 @@ class ImGuiWrapper #endif // ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT std::map m_custom_glyph_rects_ids; std::string m_clipboard_text; + // Keys held down, each with whether ImGui claimed its press. + std::map m_key_claims; + // Whether ImGui claimed the last key-down, for the char event that follows it. + std::optional m_char_claim; public: struct LastSliderStatus { @@ -224,8 +228,21 @@ public: bool text_input_active() const; // True while an ImGui modal popup is on screen. bool modal_popup_open() const; + // True while any ImGui popup is on screen, modal or not. + bool popup_open() const; + // Closes the topmost popup on screen unless it is a modal, which handles Esc itself. + void close_top_popup(); // True for every key while a modal is open, and for text-editing keys while an InputText is active. bool owns_key(const KeyChord& chord) const; + // True while the left mouse button holds an ImGui item, such as a slider being dragged. + bool item_held() const; + // True while a popup is open, an item is held or an InputText is active. + bool owns_keyboard() const; + // Returns owns_keyboard() as of the key's key-down, so its repeats, char event and release get the + // same answer. Call it once per event. + bool claim_key_event(const wxKeyEvent& evt); + // Drops the record of held keys, whose key-ups are sent to the window that takes the focus. + void forget_key_claims(); // Optional inputs are used for set up value inside of an optional, with default value // diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.cpp b/src/slic3r/GUI/Jobs/ArrangeJob.cpp index 1ba99bf1b1..fd4fdee4ed 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.cpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.cpp @@ -50,6 +50,58 @@ namespace Slic3r { namespace GUI { using ArrangePolygon = arrangement::ArrangePolygon; +void set_arrange_polygon_bed_exclusion_extruders(ArrangePolygon &polygon, const ModelObject &object, + const PartPlate &plate, const DynamicPrintConfig &config) +{ + polygon.bed_exclusion_extruder_ids.clear(); + if (active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared) + return; + + const ConfigOptionFloats *nozzle_diameters = config.opt("nozzle_diameter"); + const size_t extruder_count = nozzle_diameters != nullptr ? nozzle_diameters->size() : 0; + if (extruder_count == 0) + return; + + PresetBundle *preset_bundle = wxGetApp().preset_bundle; + if (preset_bundle == nullptr) + return; + + const DynamicPrintConfig &project_config = preset_bundle->project_config; + // Automatic Bambu mapping may be recalculated after arrangement or differ + // between destination plates. Leave it unresolved so every nozzle volume + // is checked rather than embedding a temporary assignment in the item. + if (preset_bundle->is_bbl_vendor() && + is_auto_filament_map_mode(plate.get_real_filament_map_mode(project_config))) + return; + + std::set extruder_ids; + for (const auto &mapping : plate.get_object_filament_extruders(object, project_config, extruder_count)) + extruder_ids.emplace(int(mapping.second)); + polygon.bed_exclusion_extruder_ids.assign(extruder_ids.begin(), extruder_ids.end()); +} + +static void set_arrange_polygon_bed_exclusion_extruders_for_all_plates(ArrangePolygon &polygon, + const ModelObject &object, + PartPlateList &plate_list, + const DynamicPrintConfig &config) +{ + polygon.bed_exclusion_extruder_ids.clear(); + if (active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared) + return; + + std::set extruder_ids; + for (int plate_index = 0; plate_index < plate_list.get_plate_count(); ++plate_index) { + ArrangePolygon mapped = polygon; + set_arrange_polygon_bed_exclusion_extruders(mapped, object, *plate_list.get_plate(plate_index), config); + if (mapped.bed_exclusion_extruder_ids.empty()) { + polygon.bed_exclusion_extruder_ids.clear(); + return; + } + extruder_ids.insert(mapped.bed_exclusion_extruder_ids.begin(), mapped.bed_exclusion_extruder_ids.end()); + } + polygon.bed_exclusion_extruder_ids.assign(extruder_ids.begin(), extruder_ids.end()); +} + // Cache the wti info class WipeTower: public GLCanvas3D::WipeTowerInfo { public: @@ -194,11 +246,14 @@ void ArrangeJob::clear_input() current_plate_index = 0; } -ArrangePolygon ArrangeJob::prepare_arrange_polygon(void* model_instance) +ArrangePolygon ArrangeJob::prepare_arrange_polygon(void *model_instance, const PartPlate *mapping_plate) { ModelInstance* instance = (ModelInstance*)model_instance; const Slic3r::DynamicPrintConfig& config = wxGetApp().preset_bundle->full_config(); - return get_instance_arrange_poly(instance, config); + ArrangePolygon polygon = get_instance_arrange_poly(instance, config); + if (mapping_plate != nullptr) + set_arrange_polygon_bed_exclusion_extruders(polygon, *instance->get_object(), *mapping_plate, config); + return polygon; } void ArrangeJob::prepare_selected() { @@ -234,6 +289,8 @@ void ArrangeJob::prepare_selected() { for (size_t i = 0; i < inst_sel.size(); ++i) { ModelInstance* mi = mo->instances[i]; ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[i]); + set_arrange_polygon_bed_exclusion_extruders_for_all_plates( + ap, *mo, plate_list, wxGetApp().preset_bundle->full_config()); //BBS: partplate_list preprocess //remove the locked plate's instances, neither in selected, nor in un-selected bool locked = plate_list.preprocess_arrange_polygon(oidx, i, ap, inst_sel[i]); @@ -309,6 +366,8 @@ void ArrangeJob::prepare_all() { for (size_t i = 0; i < mo->instances.size(); ++i) { ModelInstance * mi = mo->instances[i]; ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[i]); + set_arrange_polygon_bed_exclusion_extruders_for_all_plates( + ap, *mo, plate_list, wxGetApp().preset_bundle->full_config()); //BBS: partplate_list preprocess //remove the locked plate's instances, neither in selected, nor in un-selected bool locked = plate_list.preprocess_arrange_polygon(oidx, i, ap, true); @@ -350,7 +409,7 @@ void ArrangeJob::prepare_all() { bool enable_wrapping = current_config.option("enable_wrapping_detection")->value; // add the virtual object into unselect list if has - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping, MAX_NUM_PLATES); + plate_list.preprocess_exclude_areas(m_unselected, wxGetApp().preset_bundle->full_config(), enable_wrapping, MAX_NUM_PLATES); prepare_belt_regions(MAX_NUM_PLATES); } @@ -503,7 +562,7 @@ void ArrangeJob::prepare_partplate() { for (size_t inst_idx = 0; inst_idx < mo->instances.size(); ++inst_idx) { bool in_plate = plate->contain_instance(oidx, inst_idx) || plate->intersect_instance(oidx, inst_idx); - ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[inst_idx]); + ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[inst_idx], plate); ArrangePolygons& cont = mo->instances[inst_idx]->printable ? (in_plate ? m_selected : m_unselected) : @@ -534,7 +593,8 @@ void ArrangeJob::prepare_partplate() { bool enable_wrapping = current_config.option("enable_wrapping_detection")->value; // add the virtual object into unselect list if has - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping, current_plate_index + 1); + plate_list.preprocess_exclude_areas( + m_unselected, wxGetApp().preset_bundle->full_config(), enable_wrapping, current_plate_index + 1); prepare_belt_regions(current_plate_index + 1); } @@ -686,7 +746,7 @@ void ArrangeJob::process(Ctl &ctl) imex.add_keep_outs(m_unselected); bool enable_wrapping = global_config.option("enable_wrapping_detection")->value; - partplate_list.preprocess_exclude_areas(params.excluded_regions, enable_wrapping, 1, scale_(1)); + partplate_list.preprocess_exclude_areas(params.excluded_regions, global_config, enable_wrapping, 1, scale_(1)); BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << bedpts[0].transpose() << ", " << bedpts[1].transpose() << ", " << bedpts[2].transpose() << ", " << bedpts[3].transpose(); @@ -771,6 +831,17 @@ void ArrangeJob::finalize(bool canceled, std::exception_ptr &eptr) { if (canceled || eptr) return; + // Nothing could be placed: leave the plates and the instances exactly as they were. + // Rebuilding the plates would only re-home the instances by their bounds, which moves + // a too large item to whichever plate it happens to reach over. + const bool nothing_arranged = !m_selected.empty() && + std::all_of(m_selected.begin(), m_selected.end(), [](const ArrangePolygon &ap) { return !ap.is_arranged(); }); + if (nothing_arranged) { + m_plater->get_notification_manager()->close_notification_of_type(NotificationType::ArrangeOngoing); + m_plater->m_arrange_running.store(false); + return; + } + // Unprintable items go to the last virtual bed int beds = 0; @@ -870,12 +941,13 @@ void ArrangeJob::finalize(bool canceled, std::exception_ptr &eptr) { } m_plater->get_notification_manager()->close_notification_of_type(NotificationType::ArrangeOngoing); - //BBS: reload all objects due to arrange + //BBS: reload all objects due to arrange. Plates are never recycled here: arranging + // must not remove a plate the user created, even when the arrange left it empty. if (only_on_partplate) { - plate_list.rebuild_plates_after_arrangement(!only_on_partplate, true, current_plate_index); + plate_list.rebuild_plates_after_arrangement(false, true, current_plate_index); } else { - plate_list.rebuild_plates_after_arrangement(!only_on_partplate, true); + plate_list.rebuild_plates_after_arrangement(false, true); } // unlock the plates we just locked diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.hpp b/src/slic3r/GUI/Jobs/ArrangeJob.hpp index a31b65cea3..4383174f56 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.hpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.hpp @@ -16,10 +16,17 @@ namespace Slic3r { class ModelInstance; +class ModelObject; namespace GUI { class Plater; +class PartPlate; + +void set_arrange_polygon_bed_exclusion_extruders(arrangement::ArrangePolygon &polygon, + const ModelObject &object, + const PartPlate &plate, + const DynamicPrintConfig &config); class ArrangeJob : public Job { @@ -71,7 +78,7 @@ class ArrangeJob : public Job void prepare_belt_regions(int num_plates); void prepare_imex_zones(); - ArrangePolygon prepare_arrange_polygon(void* instance); + ArrangePolygon prepare_arrange_polygon(void *instance, const PartPlate *mapping_plate = nullptr); protected: diff --git a/src/slic3r/GUI/Jobs/FillBedJob.cpp b/src/slic3r/GUI/Jobs/FillBedJob.cpp index 4b4936e4ef..f3da5e631b 100644 --- a/src/slic3r/GUI/Jobs/FillBedJob.cpp +++ b/src/slic3r/GUI/Jobs/FillBedJob.cpp @@ -79,6 +79,7 @@ void FillBedJob::prepare() bool selected = (oidx == m_object_idx); ArrangePolygon ap = get_instance_arrange_poly(mo->instances[inst_idx], global_config); + set_arrange_polygon_bed_exclusion_extruders(ap, *mo, *plate, global_config); BoundingBox ap_bb = ap.transformed_poly().contour.bounding_box(); ap.name = mo->name; @@ -146,8 +147,8 @@ void FillBedJob::prepare() bool enable_wrapping = global_config.option("enable_wrapping_detection")->value; //add the virtual object into unselect list if has double scaled_exclusion_gap = scale_(1); - plate_list.preprocess_exclude_areas(params.excluded_regions, enable_wrapping, 1, scaled_exclusion_gap); - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping); + plate_list.preprocess_exclude_areas(params.excluded_regions, global_config, enable_wrapping, 1, scaled_exclusion_gap); + plate_list.preprocess_exclude_areas(m_unselected, global_config, enable_wrapping); m_bedpts = get_bed_shape(*m_plater->config()); @@ -173,11 +174,14 @@ void FillBedJob::prepare() auto polys = offset_ex(m_selected.front().poly, params.min_obj_distance / 2); ExPolygon poly = polys.empty() ? m_selected.front().poly : polys.front(); double poly_area = poly.area() / sc; + const ArrangePolygon &fill_template = m_selected.front(); double unsel_area = std::accumulate(m_unselected.begin(), m_unselected.end(), 0., - [cur_plate_index](double s, const auto &ap) { + [cur_plate_index, &fill_template](double s, const auto &ap) { //BBS: m_unselected instance is in the same partplate - return s + (ap.bed_idx == cur_plate_index) * ap.poly.area(); + const bool exclusion_applies = !ap.is_bed_exclusion || + bed_exclusion_applies(fill_template, ap); + return s + (ap.bed_idx == cur_plate_index && exclusion_applies) * ap.poly.area(); //return s + (ap.bed_idx == 0) * ap.poly.area(); }) / sc; @@ -192,36 +196,24 @@ void FillBedJob::prepare() //sel_id = std::max(sel_id, 0); ModelInstance *mi = model_object->instances[sel_id]; ArrangePolygon template_ap = get_instance_arrange_poly(mi, global_config); + set_arrange_polygon_bed_exclusion_extruders(template_ap, *model_object, *plate, global_config); - int obj_idx; - double offset_base, offset; - bool was_one_instance; - if (m_instances) { - obj_idx = m_plater->get_selected_object_idx(); - offset_base = m_plater->canvas3D()->get_size_proportional_to_max_bed_size(0.05); - offset = offset_base; - was_one_instance = model_object->instances.size()==1; - } - - for (int i = 0; i < needed_items; ++i, offset += offset_base) { + for (int i = 0; i < needed_items; ++i) { ArrangePolygon ap = template_ap; ap.poly = m_selected.front().poly; ap.bed_idx = PartPlateList::MAX_PLATES_COUNT; ap.itemid = -1; - ap.setter = [this, offset](const ArrangePolygon &p) { + ap.setter = [this, mi](const ArrangePolygon &p) { ModelObject *mo = m_plater->model().objects[m_object_idx]; - ModelObject *obj; if (m_instances) { - ModelInstance* model_instance = mo->instances.back(); - Vec3d offset_vec = model_instance->get_offset() + Vec3d(offset, offset, 0.0); - mo->add_instance(offset_vec, model_instance->get_scaling_factor(), model_instance->get_rotation(), model_instance->get_mirror()); - obj = mo; + ModelInstance *new_instance = mo->add_instance(*mi); + new_instance->apply_arrange_result(p.translation.cast(), p.rotation); } else { ModelObject* newObj = m_plater->model().add_object(*mo); newObj->name = mo->name +" "+ std::to_string(p.itemid); - obj = newObj; + for (ModelInstance *new_instance : newObj->instances) + new_instance->apply_arrange_result(p.translation.cast(), p.rotation); } - for (ModelInstance *newInst : obj->instances) { newInst->apply_arrange_result(p.translation.cast(), p.rotation); } //m_plater->sidebar().obj_list()->paste_objects_into_list({m_plater->model().objects.size()-1}); }; m_selected.emplace_back(ap); @@ -248,7 +240,6 @@ void FillBedJob::process(Ctl &ctl) if (m_object_idx == -1 || m_selected.empty()) return; update_arrange_params(params, m_plater->config(), m_selected); - m_bedpts = get_shrink_bedpts(m_plater->config(), params); auto &partplate_list = m_plater->get_partplate_list(); auto &print = wxGetApp().plater()->get_partplate_list().get_current_fff_print(); @@ -260,6 +251,8 @@ void FillBedJob::process(Ctl &ctl) update_selected_items_inflation(m_selected, m_plater->config(), params); update_unselected_items_inflation(m_unselected, m_plater->config(), params); + // After the inflation, which may give back part of the bed margin. + m_bedpts = get_shrink_bedpts(m_plater->config(), params); bool do_stop = false; params.stopcondition = [&ctl, &do_stop]() { @@ -278,21 +271,65 @@ void FillBedJob::process(Ctl &ctl) // final align用的是凸包,在有fixed item的情况下可能找到的参考点位置是错的,这里就不做了。见STUDIO-3265 params.do_final_align = !is_bbl; - if (m_selected.size() > 100){ + if (m_selected.size() > 100) { // too many items, just find grid empty cells to put them - Vec2f step = unscaled(get_extents(m_selected.front().poly).size()) + Vec2f(m_selected.front().brim_width, m_selected.front().brim_width); - std::vector empty_cells = Plater::get_empty_cells(step); - size_t n=std::min(m_selected.size(), empty_cells.size()); - for (size_t i = 0; i < n; i++) { - m_selected[i].translation = scaled(empty_cells[i]); - m_selected[i].bed_idx= 0; + std::vector occupied_boxes; + for (const ArrangePolygon &fixed : m_unselected) { + if (fixed.bed_idx != 0 || fixed.is_extrusion_cali_object) + continue; + + if (fixed.is_bed_exclusion) { + const bool relevant = std::any_of( + m_selected.begin(), m_selected.end(), [&fixed](const ArrangePolygon &item) { + return bed_exclusion_applies(item, fixed); + }); + if (!relevant) + continue; + } + + BoundingBox bbox = get_extents(fixed.transformed_poly()); + bbox.offset(std::max(0, fixed.inflation)); + occupied_boxes.emplace_back(unscale(bbox.min), unscale(bbox.max)); } - for (size_t i = n; i < m_selected.size(); i++) { - m_selected[i].bed_idx = -1; + + // Fill the remaining space without disturbing instances which are + // already placed. Besides matching the meaning of "Fill bed", this + // also prevents candidates rejected by the grid from remaining under + // newly placed copies at their old positions. + const Vec3d plate_origin = partplate_list.get_curr_plate()->get_origin(); + for (const ArrangePolygon &existing : m_selected) { + if (existing.priority == 0 || existing.bed_idx != 0) + continue; + + BoundingBox bbox = get_extents(existing.transformed_poly()); + bbox.offset(std::max(0, existing.inflation)); + BoundingBoxf local_box(unscale(bbox.min), unscale(bbox.max)); + local_box.translate(Vec2d(-plate_origin.x(), -plate_origin.y())); + occupied_boxes.emplace_back(std::move(local_box)); } - } - else + + const Vec2f step = unscaled(get_extents(m_selected.front().poly).size()) + + Vec2f(m_selected.front().brim_width, m_selected.front().brim_width); + const bool has_conditional_exclusions = has_bed_exclusion_regions(m_unselected); + const std::vector empty_cells = + Plater::get_empty_cells(step, occupied_boxes, !has_conditional_exclusions); + + size_t cell_index = 0; + for (ArrangePolygon &item : m_selected) { + if (item.priority != 0) + continue; + + if (cell_index < empty_cells.size()) { + item.translation = scaled(empty_cells[cell_index++]); + item.bed_idx = 0; + } else { + item.bed_idx = arrangement::UNARRANGED; + } + } + + } else { arrangement::arrange(m_selected, m_unselected, m_bedpts, params); + } // finalize just here. ctl.update_status(100, ctl.was_canceled() ? @@ -357,6 +394,17 @@ void FillBedJob::finalize(bool canceled, std::exception_ptr &eptr) obj_list->update_printable_state(i, 0); } + if (m_instances && model_object->instances.size() > inst_cnt) { + const size_t new_instance_count = model_object->instances.size() - inst_cnt; + // Match the normal add-instance flow: update the scene before the + // object tree starts referring to the newly created instances. + m_plater->update(); + // A single-instance object has no instance children in the object + // tree yet, so the first refresh must add the original as well. + obj_list->increase_object_instances( + m_object_idx, inst_cnt == 1 ? new_instance_count + 1 : new_instance_count); + } + BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": paste_objects_into_list"; /*for (ArrangePolygon& ap : m_selected) { @@ -367,10 +415,9 @@ void FillBedJob::finalize(bool canceled, std::exception_ptr &eptr) //model_object->ensure_on_bed(); //BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": model_object->ensure_on_bed()"; - if (m_instances) {// && wxGetApp().app_config->get("auto_arrange") == "true") { - m_plater->set_prepare_state(Job::PREPARE_STATE_MENU); - m_plater->arrange(); - } + // FillBedJob has already computed and validated the final positions. + // The instance tree is synchronized above, so rerunning the general + // arranger here would only risk discarding a valid fill result. m_plater->update(); { diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.cpp b/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.cpp index 72363e4393..ef3a49b8f7 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.cpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.cpp @@ -6,6 +6,7 @@ #include #include #include "libslic3r/TextureDisplacement.hpp" +#include "libslic3r/Point.hpp" #include #include #include @@ -50,6 +51,9 @@ void TextureDisplacementBakeJob::process(Ctl &ctl) // bake, which on a subdivided mesh can run for several seconds. // Colour, when any layer asks for it, is computed in the same pass as the displacement: both need // the same per-layer projection and UV work, and doing it twice would double the expensive part. + // + // The quantizers are built once for the whole job rather than per part: each fills a colour lookup + // cube that costs tens of milliseconds, and the palette is the object's, not the part's. TextureColorRequest color_request; TextureColorRequest *color = nullptr; if (!m_input.color.empty()) { @@ -57,27 +61,38 @@ void TextureDisplacementBakeJob::process(Ctl &ctl) if (!m_input.color.palette_pure.empty()) color_request.quantize_pure = GLGizmoTextureDisplacement::make_palette_quantizer(m_input.color.palette_pure); color_request.despeckle_passes = m_input.color.despeckle_passes; - color_request.out_triangle = &m_triangle_color; if (color_request.quantize) color = &color_request; } + // Each part gets its own slice of the 1..100 range, in order, so one progress bar covers the whole + // bake however many parts it displaces. + const size_t count = m_input.volumes.size(); + m_results.resize(count); int last_reported = 1; - m_result = TriangleMesh(build_texture_displacement( - m_input.base_mesh, m_input.layers, m_input.facets_data, m_input.options, - [&ctl, &status, &last_reported](int percent) { - if (ctl.was_canceled()) - return false; - // The notification repaints (and wakes the idle loop) on every call, so only push a - // message when the displayed integer percentage actually moves. - if (percent > last_reported) { - last_reported = percent; - ctl.update_status(percent, status); - } - return true; - }, - color, m_input.volume_to_world, nullptr, &m_stats, - m_input.model_uv.empty() ? nullptr : &m_input.model_uv)); + for (size_t i = 0; i < count; ++i) { + const TextureDisplacementBakeVolume &volume = m_input.volumes[i]; + if (color != nullptr) + color_request.out_triangle = &m_results[i].triangle_color; + m_results[i].mesh = TriangleMesh(build_texture_displacement( + volume.base_mesh, volume.layers, volume.facets_data, volume.options, + [&ctl, &status, &last_reported, i, count](int percent) { + if (ctl.was_canceled()) + return false; + // The notification repaints (and wakes the idle loop) on every call, so only push a + // message when the displayed integer percentage actually moves. + const int overall = int((i * 100 + size_t(std::max(0, percent))) / count); + if (overall > last_reported) { + last_reported = overall; + ctl.update_status(overall, status); + } + return true; + }, + color, volume.volume_to_world, nullptr, &m_results[i].stats, + volume.model_uv.empty() ? nullptr : &volume.model_uv, &volume.texture_anchor, volume.resting_drop)); + if (ctl.was_canceled()) + break; + } // Always finish at 100: this is what closes the notification. Reported even on cancel, where // build_texture_displacement() returns an empty mesh and finalize() commits nothing. @@ -92,147 +107,184 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept ~OnExit() { if (fn) fn(); } } on_exit{m_on_finished}; - if (canceled || eptr || m_result.empty()) + if (canceled || eptr) return; // A bake that moved nothing - no layer could be sampled, or every sample was zero - must not be // committed: committing is what clears the baked layers' paint, so the user would see the painted // region simply vanish with no relief in its place and no idea why. Keep the paint and say so. - { - const indexed_triangle_set &out = m_result.its; - bool unchanged = out.indices.size() == m_input.base_mesh.indices.size() && - out.vertices.size() == m_input.base_mesh.vertices.size(); - for (size_t i = 0; unchanged && i < out.vertices.size(); ++i) - unchanged = (out.vertices[i] - m_input.base_mesh.vertices[i]).cwiseAbs().maxCoeff() < 1e-5f; - if (unchanged) { - show_error(nullptr, _u8L("The bake produced no displacement, so nothing was changed and the paint was kept. " - "Check that the painted layer has a texture and a non-zero depth.")); - return; - } + // Judged per part, because on a multibody object only some parts may carry a layer that displaces; + // the ones that did move are committed and the rest are left exactly as they were. + const auto moved = [this](size_t i) { + const TriangleMesh &result = m_results[i].mesh; + if (result.empty()) + return false; + const indexed_triangle_set &out = result.its; + const indexed_triangle_set &base = m_input.volumes[i].base_mesh; + bool unchanged = out.indices.size() == base.indices.size() && out.vertices.size() == base.vertices.size(); + for (size_t v = 0; unchanged && v < out.vertices.size(); ++v) + unchanged = (out.vertices[v] - base.vertices[v]).cwiseAbs().maxCoeff() < 1e-5f; + return !unchanged; + }; + + std::vector to_commit; + for (size_t i = 0; i < m_results.size(); ++i) + if (moved(i)) + to_commit.push_back(i); + if (to_commit.empty()) { + show_error(nullptr, _u8L("The bake produced no displacement, so nothing was changed and the paint was kept. " + "Check that the painted layer has a texture and a non-zero depth.")); + return; } Plater *plater = wxGetApp().plater(); - const auto commit = [this, plater]() { - ModelVolume *volume = get_model_volume(m_input.volume_id, plater->model().objects); - if (volume == nullptr) - return; - - // The filament each palette entry prints in. This is where a mix becomes a mixed filament slot, - // and only a mix the bake actually painted with: the preview never creates one, so the project - // gains only the slots this result needs. Done before anything below names them - adding a slot - // runs ModelVolume::update_extruder_count(), which clamps paint above the old filament count. + // The filament each palette entry prints in. This is where a mix becomes a mixed filament slot, + // and only a mix the bake actually painted with: the preview never creates one, so the project + // gains only the slots this result needs. Decided once for the whole bake, over the entries every + // part used between them, so the same mix cannot end up in two slots. Done before anything below + // names them - adding a slot runs ModelVolume::update_extruder_count(), which clamps paint above + // the old filament count. + const auto filaments_for_palette = [this, plater, &to_commit]() { + // palette_filaments() only cares *which* entries appear, so the union of the parts' entries + // stands in for their concatenated per-triangle colours. + std::vector seen(m_input.color.palette.size() + 1, 0); + std::vector used; + for (const size_t i : to_commit) + for (const uint8_t entry : m_results[i].triangle_color) + if (entry > 0 && size_t(entry) < seen.size() && !seen[size_t(entry)]) { + seen[size_t(entry)] = 1; + used.push_back(entry); + } Sidebar &sidebar = plater->sidebar(); - const std::vector filament_of = GLGizmoTextureDisplacement::palette_filaments( - m_input.color.palette, m_triangle_color, [&sidebar](const PrintableColor &mix) { + return GLGizmoTextureDisplacement::palette_filaments( + m_input.color.palette, used, [&sidebar](const PrintableColor &mix) { return sidebar.ensure_mixed_filament({ unsigned(mix.a + 1), unsigned(mix.b + 1) }, { mix.a_percent(), 100 - mix.a_percent() }); }); + }; - // Whether the bake replaced the triangles or only moved the vertices it was given. The classic - // path is topology-preserving by contract, so every per-triangle annotation on the volume still - // means what it did; the default pipeline refines, cuts and simplifies, so none of them do. - // Both are checked: the flag is what the bake promised, the count is what it delivered. Only - // the triangles matter - the annotations are per facet and reference no vertex index - so a - // vertex count that changed on its own (the bake compacts unreferenced vertices away) is not a - // reason to remap anything. - const bool topology_changed = m_input.options.pipeline_v2 || - m_result.its.indices.size() != m_input.base_mesh.indices.size(); + const auto commit = [this, plater, &to_commit, &filaments_for_palette]() { + const std::vector filament_of = filaments_for_palette(); + ModelObject *object = nullptr; - // Carry the volume's existing paint - the model's own colours above all - across that rebuild. - // Without it a bake left the mmu_segmentation_facets bitstream pointing at a triangle set that - // no longer existed, which is what scrambled the colours of an imported coloured model even - // with colour switched off on every layer and nothing in the bake that was meant to touch them. - // - // transfer_facet_paint() rather than ModelVolume::restore_painting(): the latter's remap wants - // a target triangle overlapping the source paint to within 0.01 mm, which the baked surface is - // nowhere near - it has moved by the relief depth. Nothing to do when the topology is intact: - // triangle i is still triangle i, so the paint is already exactly right and carrying it at all - // could only lose detail. - std::array before; - if (topology_changed) { - before[0] = volume->supported_facets.get_data(); - before[1] = volume->seam_facets.get_data(); - before[2] = volume->mmu_segmentation_facets.get_data(); - before[3] = volume->fuzzy_skin_facets.get_data(); - } + for (const size_t i : to_commit) { + ModelVolume *volume = get_model_volume(m_input.volumes[i].volume_id, plater->model().objects); + // The lookup doubles as a staleness check: anything that replaces a volume's mesh also gives it + // a new id, so a part replaced since this bake started - by an undo, another bake, or a + // boolean - simply fails to find its volume and is skipped. + if (volume == nullptr) + continue; + const TextureDisplacementBakeVolume &input = m_input.volumes[i]; + const std::vector &triangle_color = m_results[i].triangle_color; - volume->set_mesh(std::move(m_result)); - volume->set_new_unique_id(); - volume->calculate_convex_hull(); + // Whether the bake replaced the triangles or only moved the vertices it was given. The classic + // path is topology-preserving by contract, so every per-triangle annotation on the volume still + // means what it did; the default pipeline refines, cuts and simplifies, so none of them do. + // Both are checked: the flag is what the bake promised, the count is what it delivered. Only + // the triangles matter - the annotations are per facet and reference no vertex index - so a + // vertex count that changed on its own (the bake compacts unreferenced vertices away) is not a + // reason to remap anything. + const bool topology_changed = input.options.pipeline_v2 || + m_results[i].mesh.its.indices.size() != input.base_mesh.indices.size(); - if (topology_changed) { - const std::array target{ &volume->supported_facets, &volume->seam_facets, - &volume->mmu_segmentation_facets, - &volume->fuzzy_skin_facets }; - for (size_t ch = 0; ch < target.size(); ++ch) { - const std::vector state = - transfer_facet_paint(m_input.base_mesh, before[ch], volume->mesh().its); - // Nothing was painted in this channel, or there is nothing to paint it onto: either - // way the annotation must not keep describing the mesh that is gone. - if (state.empty()) { - target[ch]->reset(); - continue; - } - TriangleSelector selector(volume->mesh()); - bool any = false; - for (size_t i = 0; i < state.size(); ++i) - if (state[i] != 0) { - selector.set_facet(int(i), EnforcerBlockerType(state[i])); - any = true; + // Carry the volume's existing paint - the model's own colours above all - across that rebuild. + // Without it a bake left the mmu_segmentation_facets bitstream pointing at a triangle set that + // no longer existed, which is what scrambled the colours of an imported coloured model even + // with colour switched off on every layer and nothing in the bake that was meant to touch them. + // + // transfer_facet_paint() rather than ModelVolume::restore_painting(): the latter's remap wants + // a target triangle overlapping the source paint to within 0.01 mm, which the baked surface is + // nowhere near - it has moved by the relief depth. Nothing to do when the topology is intact: + // triangle i is still triangle i, so the paint is already exactly right and carrying it at all + // could only lose detail. + std::array before; + if (topology_changed) { + before[0] = volume->supported_facets.get_data(); + before[1] = volume->seam_facets.get_data(); + before[2] = volume->mmu_segmentation_facets.get_data(); + before[3] = volume->fuzzy_skin_facets.get_data(); + } + + volume->set_mesh(std::move(m_results[i].mesh)); + volume->set_new_unique_id(); + volume->calculate_convex_hull(); + + if (topology_changed) { + const std::array target{ &volume->supported_facets, &volume->seam_facets, + &volume->mmu_segmentation_facets, + &volume->fuzzy_skin_facets }; + for (size_t ch = 0; ch < target.size(); ++ch) { + const std::vector state = + transfer_facet_paint(input.base_mesh, before[ch], volume->mesh().its); + // Nothing was painted in this channel, or there is nothing to paint it onto: either + // way the annotation must not keep describing the mesh that is gone. + if (state.empty()) { + target[ch]->reset(); + continue; } - if (any) - target[ch]->set(selector); - else - target[ch]->reset(); + TriangleSelector selector(volume->mesh()); + bool any = false; + for (size_t t = 0; t < state.size(); ++t) + if (state[t] != 0) { + selector.set_facet(int(t), EnforcerBlockerType(state[t])); + any = true; + } + if (any) + target[ch]->set(selector); + else + target[ch]->reset(); + } } - } - // Colour lands in mmu_segmentation_facets, merged *over* whatever is already painted there - // rather than replacing it: a triangle the texture does not colour keeps its existing filament, - // and one the user never painted at all stays at NONE, which already means "the volume's own - // filament". That is what confines the effect to the painted area without having to invent a - // colour for everything outside it. What was already painted is whatever the transfer above - // left in the annotation, so this bake's colour lands on top of it rather than instead of it. - if (!m_triangle_color.empty() && m_triangle_color.size() == volume->mesh().its.indices.size()) { - TriangleSelector selector(volume->mesh()); - const TriangleSelector::TriangleSplittingData &existing = volume->mmu_segmentation_facets.get_data(); - if (!existing.bitstream.empty()) - selector.deserialize(existing, false); - for (size_t i = 0; i < m_triangle_color.size(); ++i) { - const size_t entry = size_t(m_triangle_color[i]); - if (entry > 0 && entry <= filament_of.size() && filament_of[entry - 1] >= 0) - selector.set_facet(int(i), EnforcerBlockerType(filament_of[entry - 1] + 1)); + // Colour lands in mmu_segmentation_facets, merged *over* whatever is already painted there + // rather than replacing it: a triangle the texture does not colour keeps its existing filament, + // and one the user never painted at all stays at NONE, which already means "the volume's own + // filament". That is what confines the effect to the painted area without having to invent a + // colour for everything outside it. What was already painted is whatever the transfer above + // left in the annotation, so this bake's colour lands on top of it rather than instead of it. + if (!triangle_color.empty() && triangle_color.size() == volume->mesh().its.indices.size()) { + TriangleSelector selector(volume->mesh()); + const TriangleSelector::TriangleSplittingData &existing = volume->mmu_segmentation_facets.get_data(); + if (!existing.bitstream.empty()) + selector.deserialize(existing, false); + for (size_t t = 0; t < triangle_color.size(); ++t) { + const size_t entry = size_t(triangle_color[t]); + if (entry > 0 && entry <= filament_of.size() && filament_of[entry - 1] >= 0) + selector.set_facet(int(t), EnforcerBlockerType(filament_of[entry - 1] + 1)); + } + volume->mmu_segmentation_facets.set(selector); } - volume->mmu_segmentation_facets.set(selector); + + // Clear the paint mask of every layer that was actually baked so a repeat bake (or the paint + // overlay) doesn't act on triangles that no longer represent the same unbaked surface. The + // texture layer definitions themselves are left untouched so the user can keep sculpting with + // the same textures. + // + // A mask the bake did *not* consume only still means what it did if the topology is unchanged, + // which is true of the classic path (it moves existing vertices) but not of the one-run + // pipeline, which rebuilds and then simplifies the mesh. A mask left behind against the old + // topology is exactly what makes the gizmo reload an empty selector over a non-empty mask and + // then erase it on the next flush - see GLGizmoTextureDisplacement::update_from_model_object(). + for (int slot = 0; slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++slot) { + const auto it = std::find_if(input.layers.begin(), input.layers.end(), + [slot](const TextureDisplacementLayer &l) { return l.slot == slot; }); + if (topology_changed || (it != input.layers.end() && !it->empty())) + volume->texture_displacement_facet(slot).reset(); + } + + // The model's own UV channel. Resampled onto a rebuilt mesh from the surface the bake started + // from: a displaced vertex came from its foot point on that surface, which is the position its + // uv belongs to - so no distance limit, the relief depth is exactly how far it has moved. + if (!input.model_uv.empty()) + volume->texture_uv = topology_changed ? transfer_uv_channel(input.base_mesh, input.model_uv, + volume->mesh().its) : + input.model_uv; + + if (object == nullptr) + object = volume->get_object(); } - // Clear the paint mask of every layer that was actually baked so a repeat bake (or the paint - // overlay) doesn't act on triangles that no longer represent the same unbaked surface. The - // texture layer definitions themselves are left untouched so the user can keep sculpting with - // the same textures. - // - // A mask the bake did *not* consume only still means what it did if the topology is unchanged, - // which is true of the classic path (it moves existing vertices) but not of the one-run - // pipeline, which rebuilds and then simplifies the mesh. A mask left behind against the old - // topology is exactly what makes the gizmo reload an empty selector over a non-empty mask and - // then erase it on the next flush - see GLGizmoTextureDisplacement::update_from_model_object(). - for (int slot = 0; slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++slot) { - const auto it = std::find_if(m_input.layers.begin(), m_input.layers.end(), - [slot](const TextureDisplacementLayer &l) { return l.slot == slot; }); - if (topology_changed || (it != m_input.layers.end() && !it->empty())) - volume->texture_displacement_facet(slot).reset(); - } - - // The model's own UV channel. Resampled onto a rebuilt mesh from the surface the bake started - // from: a displaced vertex came from its foot point on that surface, which is the position its - // uv belongs to - so no distance limit, the relief depth is exactly how far it has moved. - if (!m_input.model_uv.empty()) - volume->texture_uv = topology_changed ? transfer_uv_channel(m_input.base_mesh, m_input.model_uv, - volume->mesh().its) : - m_input.model_uv; - - ModelObject *object = volume->get_object(); if (object == nullptr) return; @@ -261,8 +313,15 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept // The refinement went finer than the budget could keep: the simplification had to take detail back // out to fit, so what was baked carries less of the texture than the resolution asked for. Said // here, with the numbers, because it is the only place that knows them - and not as an error - // dialog: the result is a usable mesh, just not the one the settings described. - if (m_stats.budget_limited) { + // dialog: the result is a usable mesh, just not the one the settings described. Summed over the + // parts that hit it, since the budget is spent per part and one message is enough. + size_t refined = 0, budget = 0; + for (const size_t i : to_commit) + if (m_results[i].stats.budget_limited) { + refined += m_results[i].stats.triangles_refined; + budget += m_results[i].stats.triangles_budget; + } + if (refined > 0) { // Thousands under a million, so a small budget is not reported as "0.1 M". const auto count = [](size_t n) { return n >= 1000000 ? Slic3r::format("%1$.1f M", double(n) / 1000000.) : @@ -272,26 +331,39 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept NotificationType::CustomNotification, NotificationManager::NotificationLevel::WarningNotificationLevel, Slic3r::format(_u8L("The triangle budget limited the detail: this resolution needs %1% triangles, " "the budget kept %2%. Raise Budget or use a coarser Resolution for the full detail."), - count(m_stats.triangles_refined), count(m_stats.triangles_budget))); + count(refined), count(budget))); } } -void queue_texture_displacement_bake(const ModelVolume &volume, const TextureColorSettings &color, +TextureDisplacementBakeVolume texture_displacement_bake_volume(const ModelVolume &volume, + const std::vector &layers, + const TextureDisplacementOptions &options, + const Vec3d &texture_anchor, + float resting_drop) +{ + TextureDisplacementBakeVolume out; + out.volume_id = volume.id(); + out.base_mesh = volume.mesh().its; + out.layers = layers; + out.options = options; + out.volume_to_world = texture_displacement_volume_to_world(volume); + out.texture_anchor = texture_anchor; + out.resting_drop = resting_drop; + if (volume.has_texture_uv()) + out.model_uv = volume.texture_uv; + for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) + out.facets_data[size_t(i)] = volume.texture_displacement_facet(i).get_data(); + return out; +} + +void queue_texture_displacement_bake(std::vector volumes, + const TextureColorSettings &color, std::function on_finished, bool take_snapshot) { TextureDisplacementBakeInput input; + input.volumes = std::move(volumes); input.color = color; input.take_snapshot = take_snapshot; - input.volume_id = volume.id(); - input.base_mesh = volume.mesh().its; - if (volume.has_texture_uv()) - input.model_uv = volume.texture_uv; - input.layers = volume.texture_displacement_layers; - input.options = volume.texture_displacement_options; - input.volume_to_world = texture_displacement_volume_to_world(volume); - for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) - input.facets_data[size_t(i)] = volume.texture_displacement_facet(i).get_data(); - auto &worker = wxGetApp().plater()->get_ui_job_worker(); queue_job(worker, std::make_unique(std::move(input), std::move(on_finished))); diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.hpp b/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.hpp index 5e1a586736..dc611910bf 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.hpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementBakeJob.hpp @@ -17,10 +17,11 @@ namespace Slic3r { class ModelVolume; } namespace Slic3r::GUI { -// Everything process() needs, captured by value on the main thread when the job is queued so the -// worker thread never touches the live Model concurrently with the UI (mirrors how EmbossJob's -// DataBase is captured before process() runs). -struct TextureDisplacementBakeInput +// One model part's share of a bake: its own mesh, its own paint masks and UV channel, and the layer +// stack to displace it by. Captured by value on the main thread when the job is queued so the worker +// thread never touches the live Model concurrently with the UI (mirrors how EmbossJob's DataBase is +// captured before process() runs). +struct TextureDisplacementBakeVolume { ObjectID volume_id; indexed_triangle_set base_mesh; @@ -30,22 +31,38 @@ struct TextureDisplacementBakeInput // Mesh coordinates -> world millimetres. Captured here with everything else so the worker never // reaches back into the live Model for it. See build_texture_displacement(). Transform3d volume_to_world = Transform3d::Identity(); - // Captured on the main thread. Empty unless some layer is colouring, in which case the bake also - // writes the volume's mmu_segmentation_facets - the same per-triangle filament assignment the MMU - // paint gizmo writes - alongside the displaced geometry. - TextureColorSettings color; - // The volume's own UV channel (ModelVolume::texture_uv), empty when it has none: what a ModelUV + // The part's own UV channel (ModelVolume::texture_uv), empty when it has none: what a ModelUV // layer maps through, and what the commit puts back on the baked mesh. std::vector model_uv; + // Where the part sits in its object: the world point the object's texture is anchored at, and how + // far the object's lowest point lies below the part's own. See build_texture_displacement(). + Vec3d texture_anchor = Vec3d::Zero(); + float resting_drop = 0.f; +}; + +struct TextureDisplacementBakeInput +{ + // Every model part the bake acts on, in the object's own volume order. An object made of several + // parts carries one entry per part the paint actually reaches: the layer stack is the object's, + // but each part is displaced through its own mesh, its own masks and its own UV channel. Baking + // only the first part is what made texture displacement silently ignore every other body of a + // multibody object. + std::vector volumes; + // Captured on the main thread, and shared by every part: the palette comes from the project's + // filaments and from the layer stack, neither of which is per part. Empty unless some layer is + // colouring, in which case the bake also writes each part's mmu_segmentation_facets - the same + // per-triangle filament assignment the MMU paint gizmo writes - alongside the displaced geometry. + TextureColorSettings color; // Whether this job pushes its own undo step when it commits. False when the caller has already // taken one that is meant to cover the displacement as well - Standard mode's Bake, which remeshes // and subdivides first and has to undo as a single action. - bool take_snapshot = true; + bool take_snapshot = true; }; -// Bakes a volume's painted texture-displacement layers into real mesh geometry in the background, +// Bakes an object's painted texture-displacement layers into real mesh geometry in the background, // then commits the result on the main thread - mirrors EmbossJob's UpdateJob/update_volume() -// bake-and-commit pattern (see EmbossJob.cpp). +// bake-and-commit pattern (see EmbossJob.cpp). Every part is displaced in the one job and committed +// under the one undo step, so a multibody object undoes as a single action. class TextureDisplacementBakeJob : public Job { public: @@ -55,24 +72,41 @@ public: void finalize(bool canceled, std::exception_ptr &eptr) override; private: + // What the bake produced for one part of m_input.volumes, at the same index. + struct VolumeResult + { + TriangleMesh mesh; + // Per triangle of `mesh`: the palette entry to print it in, as its index + 1 (0 = leave + // alone). Empty unless a layer asked for colour. See TextureColorRequest; finalize() turns + // these into filaments. + std::vector triangle_color; + // What the bake spent, for the message it leaves behind when the budget capped the detail. + TextureBakeStats stats; + }; + TextureDisplacementBakeInput m_input; - TriangleMesh m_result; - // What the bake spent, for the message it leaves behind when the budget capped the detail. - TextureBakeStats m_stats; - // Per triangle of m_result: the palette entry to print it in, as its index + 1 (0 = leave alone). - // Empty unless a layer asked for colour. See TextureColorRequest; finalize() turns these into - // filaments. - std::vector m_triangle_color; + std::vector m_results; std::function m_on_finished; }; -// Captures `volume`'s current mesh/layers/paint data and queues a TextureDisplacementBakeJob on -// the app's UI job worker. `on_finished` is always called once the job settles (success, failure, -// or cancellation), so the caller can clear its own "bake in progress" UI state. Must be called -// from the main thread. -void queue_texture_displacement_bake(const ModelVolume &volume, const TextureColorSettings &color, +// Captures each of `volumes`' current mesh/layers/paint data and queues a single +// TextureDisplacementBakeJob on the app's UI job worker. `on_finished` is always called once the job +// settles (success, failure, or cancellation), so the caller can clear its own "bake in progress" UI +// state. Must be called from the main thread. +void queue_texture_displacement_bake(std::vector volumes, + const TextureColorSettings &color, std::function on_finished, bool take_snapshot = true); +// `volume`'s share of a bake, read off the live Model. `layers`, `options`, `texture_anchor` and +// `resting_drop` are passed in rather than taken from `volume` because they belong to the object, not +// to the part: every part of a multibody object is displaced by the same stack, in the same texture +// frame and against the same plate (see GLGizmoTextureDisplacement::layers_for_part()). +TextureDisplacementBakeVolume texture_displacement_bake_volume(const ModelVolume &volume, + const std::vector &layers, + const TextureDisplacementOptions &options, + const Vec3d &texture_anchor, + float resting_drop); + } // namespace Slic3r::GUI #endif // slic3r_TextureDisplacementBakeJob_hpp_ diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.cpp b/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.cpp index eb4eec036f..0ef72a2f03 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.cpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.cpp @@ -60,8 +60,8 @@ void TextureDisplacementDebugJob::process(Ctl &ctl) // experimental pipeline refines as part of the bake and has nothing to prepare. if (m_input.run_prepare && !m_input.options.pipeline_v2) { const TextureDisplacementPrepareResult prepared = - GLGizmoTextureDisplacement::prepare_mesh(mesh, masks, m_input.layers, uv, m_input.prepare_params, - m_input.color, + GLGizmoTextureDisplacement::prepare_mesh(mesh, masks, m_input.layers, uv, m_input.prepare_texture_frame, + m_input.prepare_params, m_input.color, // Preparation is roughly half the run; the bake // takes the progress bar from there. [&report](int pct) { return report(1 + pct / 2); }, @@ -86,7 +86,8 @@ void TextureDisplacementDebugJob::process(Ctl &ctl) build_texture_displacement(mesh, m_input.layers, masks, m_input.options, [&report](int pct) { return report(50 + pct / 2); }, /* color */ nullptr, m_input.volume_to_world, &recorder, /* stats */ nullptr, - uv.empty() ? nullptr : &uv); + uv.empty() ? nullptr : &uv, /* texture_anchor: the volume's own origin */ nullptr, + m_input.resting_drop); m_stages = recorder.take(); ctl.update_status(100, status); // always finish at 100: this is what closes the notification @@ -106,6 +107,7 @@ void TextureDisplacementDebugJob::finalize(bool canceled, std::exception_ptr &ep void queue_texture_displacement_debug(const ModelVolume &volume, const TextureColorSettings &color, const TextureDisplacementPrepareParams &prepare_params, + const Transform3d &prepare_texture_frame, float resting_drop, bool run_prepare, bool check_topology, std::function)> on_finished) { @@ -119,6 +121,8 @@ void queue_texture_displacement_debug(const ModelVolume &volume, const TextureCo input.check_topology = check_topology; input.color = color; input.volume_to_world = texture_displacement_volume_to_world(volume); + input.prepare_texture_frame = prepare_texture_frame; + input.resting_drop = resting_drop; if (volume.has_texture_uv()) input.model_uv = volume.texture_uv; for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.hpp b/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.hpp index 981a17773f..251f2cbccf 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.hpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementDebugJob.hpp @@ -44,6 +44,11 @@ struct TextureDisplacementDebugInput // Mesh coordinates -> world millimetres, as the bake gets it. The captured stages are brought // back into mesh coordinates before they are handed over, so the gizmo can draw them directly. Transform3d volume_to_world = Transform3d::Identity(); + // Where the preparation samples the texture, and how far below the volume's own bottom its object + // rests - both as the bake and its preparation get them (see TextureDisplacementPrepareVolume and + // TextureDisplacementBakeVolume). + Transform3d prepare_texture_frame = Transform3d::Identity(); + float resting_drop = 0.f; // Only the quantizer is used, and only by the refinement's colour criterion - the debug run // produces no colour of its own. TextureColorSettings color; @@ -79,6 +84,7 @@ private: // caller can clear its own in-progress state. Must be called from the main thread. void queue_texture_displacement_debug(const ModelVolume &volume, const TextureColorSettings &color, const TextureDisplacementPrepareParams &prepare_params, + const Transform3d &prepare_texture_frame, float resting_drop, bool run_prepare, bool check_topology, std::function)> on_finished); diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.cpp b/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.cpp index 6c582d3746..5c19e6b450 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.cpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/Jobs/Worker.hpp" @@ -44,18 +45,29 @@ void TextureDisplacementPrepareJob::process(Ctl &ctl) // once it reaches 100%, and below that it shows Cancel, which is wired through here. Reporting is // throttled to whole percentage points because every call repaints the notification and wakes the // idle loop. + // Each part gets its own slice of the range, in order, so one bar covers them all. + const size_t count = m_input.volumes.size(); + m_results.resize(count); int last_reported = 1; - m_result = GLGizmoTextureDisplacement::prepare_mesh(m_input.base_mesh, m_input.masks, m_input.layers, - m_input.model_uv, m_input.params, m_input.color, - [&ctl, &status, &last_reported](int percent) { - if (ctl.was_canceled()) - return false; - if (percent > last_reported) { - last_reported = percent; - ctl.update_status(percent, status); - } - return true; - }); + for (size_t i = 0; i < count; ++i) { + const TextureDisplacementPrepareVolume &volume = m_input.volumes[i]; + m_results[i] = GLGizmoTextureDisplacement::prepare_mesh(volume.base_mesh, volume.masks, volume.layers, + volume.model_uv, volume.texture_frame, + m_input.params, m_input.color, + [&ctl, &status, &last_reported, i, count](int percent) { + if (ctl.was_canceled()) + return false; + const int overall = + int((i * 100 + size_t(std::max(0, percent))) / count); + if (overall > last_reported) { + last_reported = overall; + ctl.update_status(overall, status); + } + return true; + }); + if (ctl.was_canceled()) + break; + } ctl.update_status(100, status); // always finish at 100: this is what closes the notification } @@ -72,44 +84,56 @@ void TextureDisplacementPrepareJob::finalize(bool canceled, std::exception_ptr & if (canceled || eptr) return; - if (m_result.paint_lost) { - outcome = TextureDisplacementPrepareOutcome::PaintLost; - return; + // One part losing its paint stops the whole prepare, exactly as it stops a single-part one: the + // promise is that a prepare which cannot carry the paint changes nothing, and committing the other + // parts would break it halfway. The message that follows tells the user to remesh by hand instead. + for (const TextureDisplacementPrepareResult &result : m_results) + if (result.paint_lost) { + outcome = TextureDisplacementPrepareOutcome::PaintLost; + return; + } + + Plater *plater = wxGetApp().plater(); + + // Resolved before the snapshot is opened, so a run whose parts have all gone away leaves no empty + // undo step behind. The lookup doubles as the staleness check: anything that replaces a volume's + // mesh also gives it a new id (set_new_unique_id()), so a prepare computed from a mesh that has + // since been replaced - by an undo, another bake, or a boolean - simply fails to find its volume. + std::vector> to_commit; + for (size_t i = 0; i < m_results.size(); ++i) { + if (m_results[i].mesh.indices.empty()) + continue; + if (ModelVolume *volume = get_model_volume(m_input.volumes[i].volume_id, plater->model().objects); + volume != nullptr && volume->get_object() != nullptr) + to_commit.emplace_back(i, volume); } - if (m_result.mesh.indices.empty()) { + if (to_commit.empty()) { + // Nothing needed doing anywhere, which is not an error - every mesh already met the criteria. outcome = TextureDisplacementPrepareOutcome::Unchanged; return; } - Plater *plater = wxGetApp().plater(); - ModelVolume *volume = get_model_volume(m_input.volume_id, plater->model().objects); - // The lookup doubles as a staleness check: anything that replaces a volume's mesh also gives it a - // new id (set_new_unique_id()), so a prepare computed from a mesh that has since been replaced - - // by an undo, another bake, or a boolean - simply fails to find its volume and commits nothing. - if (volume == nullptr) - return; - ModelObject *object = volume->get_object(); - if (object == nullptr) - return; - + ModelObject *object = to_commit.front().second->get_object(); { Plater::TakeSnapshot snapshot(plater, m_input.snapshot_name, UndoRedo::SnapshotType::GizmoAction); - // The four standard paint channels ride across on ModelVolume's own spatial remap. The eight - // texture-displacement masks do not go through it - prepare_mesh() has already carried them, - // exactly, from the source triangles the refinement records - so they are put back after - // restore_painting(), which resets every extra facet before remapping the channels it knows. - std::optional saved_painting = volume->save_painting(); - volume->set_mesh(TriangleMesh(std::move(m_result.mesh))); - volume->set_new_unique_id(); - volume->calculate_convex_hull(); - volume->restore_painting(saved_painting); - for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) - volume->texture_displacement_facet(i).set_data(std::move(m_result.masks[size_t(i)])); - // The model's own UV channel, resampled onto the new mesh by the run. Also put back after - // restore_painting(), which resets it along with the extra facets for the same reason: it is - // indexed by triangle and the triangles have changed. - volume->texture_uv = std::move(m_result.uv); + for (const auto &[i, volume] : to_commit) { + // The four standard paint channels ride across on ModelVolume's own spatial remap. The eight + // texture-displacement masks do not go through it - prepare_mesh() has already carried them, + // exactly, from the source triangles the refinement records - so they are put back after + // restore_painting(), which resets every extra facet before remapping the channels it knows. + std::optional saved_painting = volume->save_painting(); + volume->set_mesh(TriangleMesh(std::move(m_results[i].mesh))); + volume->set_new_unique_id(); + volume->calculate_convex_hull(); + volume->restore_painting(saved_painting); + for (int slot = 0; slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++slot) + volume->texture_displacement_facet(slot).set_data(std::move(m_results[i].masks[size_t(slot)])); + // The model's own UV channel, resampled onto the new mesh by the run. Also put back after + // restore_painting(), which resets it along with the extra facets for the same reason: it is + // indexed by triangle and the triangles have changed. + volume->texture_uv = std::move(m_results[i].uv); + } if (ObjectList *obj_list = wxGetApp().obj_list()) { const ModelObjectPtrs &objs = plater->model().objects; diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.hpp b/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.hpp index a07bf63ae9..1565e54f83 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.hpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementPrepareJob.hpp @@ -31,36 +31,50 @@ namespace Slic3r::GUI { // this job adds is the worker thread, the progress notification with its Cancel button, and the commit. enum class TextureDisplacementPrepareOutcome { - Committed, // the volume now carries the prepared mesh and the paint carried onto it - Unchanged, // nothing needed doing - the mesh already met the criteria; the model was not touched - PaintLost, // the remesh landed but no layer's paint survived it, so nothing was committed - Failed, // cancelled, threw, or the volume went away while the job ran + Committed, // the parts now carry the prepared mesh and the paint carried onto it + Unchanged, // nothing needed doing - the meshes already met the criteria; the model was not touched + PaintLost, // a remesh landed but no layer's paint survived it, so nothing was committed + Failed, // cancelled, threw, or the volumes went away while the job ran }; -struct TextureDisplacementPrepareInput +// One model part's share of a prepare. As with the bake, `layers` belongs to the object rather than to +// the part (see GLGizmoTextureDisplacement::layers_for_part()). +struct TextureDisplacementPrepareVolume { ObjectID volume_id; indexed_triangle_set base_mesh; TextureDisplacementFacetsData masks; std::vector layers; - TextureDisplacementPrepareParams params; - // Captured on the main thread. Empty when no layer is colouring, in which case the refinement - // skips the colour criterion entirely. Only the *quantizer* is used here: refinement follows - // perceived colour, never the interleaving that realises a mix. - TextureColorSettings color; - // The volume's own UV channel (ModelVolume::texture_uv), empty when it has none. prepare_mesh() + // The part's own UV channel (ModelVolume::texture_uv), empty when it has none. prepare_mesh() // resamples it onto the mesh it produces, and the commit puts it back - like the masks, it is // indexed by triangle and so cannot survive the stages on its own. std::vector model_uv; + // Where prepare_mesh() samples the texture: the bake frame shared by every part of a multibody + // object, so each part is refined for the texture the bake will put on it. Identity, the part's own + // coordinates, for a single-part object. + Transform3d texture_frame = Transform3d::Identity(); +}; + +struct TextureDisplacementPrepareInput +{ + // Every model part to prepare, in the object's own volume order - the same parts the bake that + // follows will displace, so a multibody object is refined everywhere its paint reaches rather than + // only on its first part. + std::vector volumes; + TextureDisplacementPrepareParams params; + // Captured on the main thread. Empty when no layer is colouring, in which case the refinement + // skips the colour criterion entirely. Only the *quantizer* is used here: refinement follows + // perceived colour, never the interleaving that realises a mix. + TextureColorSettings color; // The undo step the commit opens. Standard mode's Bake names it after the bake, because the // displacement job that follows commits into this same step rather than pushing its own. - std::string snapshot_name; + std::string snapshot_name; }; class TextureDisplacementPrepareJob : public Job { TextureDisplacementPrepareInput m_input; - TextureDisplacementPrepareResult m_result; + std::vector m_results; std::function m_on_finished; public: diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.cpp b/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.cpp index 32b88aa951..ee17d11c8e 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.cpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.cpp @@ -1,19 +1,22 @@ #include "TextureDisplacementPreviewJob.hpp" #include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp" +#include #include #include #include #include #include +#include #include "libslic3r/TextureDisplacement.hpp" #include namespace Slic3r::GUI { -TextureDisplacementPreviewJob::TextureDisplacementPreviewJob(TextureDisplacementPreviewInput &&input, uint64_t generation, - std::shared_ptr> current_generation, - std::function on_finished) +TextureDisplacementPreviewJob::TextureDisplacementPreviewJob( + TextureDisplacementPreviewInput &&input, uint64_t generation, + std::shared_ptr> current_generation, + std::function, uint64_t)> on_finished) : m_input(std::move(input)), m_generation(generation), m_current_generation(std::move(current_generation)), m_on_finished(std::move(on_finished)) { @@ -26,6 +29,9 @@ void TextureDisplacementPreviewJob::process(Ctl &ctl) // Only ever touches m_input (captured by value before this job was queued) and local state - // never the live Model - so this is safe to run concurrently with the UI thread. + // + // The quantizers are built once for the whole run: the palette is the object's, not the part's, + // and each one fills a colour lookup cube that costs tens of milliseconds. TextureColorRequest color_request; TextureColorRequest *color = nullptr; if (!m_input.color.empty()) { @@ -33,23 +39,32 @@ void TextureDisplacementPreviewJob::process(Ctl &ctl) if (!m_input.color.palette_pure.empty()) color_request.quantize_pure = GLGizmoTextureDisplacement::make_palette_quantizer(m_input.color.palette_pure); color_request.despeckle_passes = m_input.color.despeckle_passes; - color_request.out_triangle = &m_result.triangle_color; if (color_request.quantize) color = &color_request; } - m_result.mesh = build_texture_displacement(m_input.base_mesh, m_input.layers, m_input.facets_data, - m_input.options, - [this, &ctl](int) { - // Bail the moment this preview stops being the current - // one; build_texture_displacement() then returns an - // empty mesh and finalize() drops it. - return !ctl.was_canceled() && - (!m_current_generation || - m_current_generation->load() == m_generation); - }, - color, m_input.volume_to_world, nullptr, nullptr, - m_input.model_uv.empty() ? nullptr : &m_input.model_uv); + // Bail the moment this preview stops being the current one: build_texture_displacement() then + // returns an empty mesh, and finalize() drops the whole run rather than showing half of it. + const auto still_wanted = [this, &ctl](int) { + return !ctl.was_canceled() && + (!m_current_generation || m_current_generation->load() == m_generation); + }; + + m_results.resize(m_input.volumes.size()); + for (size_t i = 0; i < m_input.volumes.size(); ++i) { + const TextureDisplacementPreviewVolume &volume = m_input.volumes[i]; + if (color != nullptr) + color_request.out_triangle = &m_results[i].triangle_color; + m_results[i].mesh = build_texture_displacement(volume.base_mesh, volume.layers, volume.facets_data, + volume.options, still_wanted, color, volume.volume_to_world, + nullptr, nullptr, + volume.model_uv.empty() ? nullptr : &volume.model_uv, + &volume.texture_anchor, volume.resting_drop); + if (!still_wanted(0)) { + m_results.clear(); + return; + } + } } void TextureDisplacementPreviewJob::finalize(bool canceled, std::exception_ptr &eptr) @@ -62,9 +77,9 @@ void TextureDisplacementPreviewJob::finalize(bool canceled, std::exception_ptr & // was ever queued again for the rest of the session. An empty result is the caller's signal that // nothing usable came back; it already handles that. if (canceled || eptr) - m_on_finished(TextureDisplacementPreviewResult{}, m_generation); + m_on_finished({}, m_generation); else - m_on_finished(std::move(m_result), m_generation); + m_on_finished(std::move(m_results), m_generation); } } // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.hpp b/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.hpp index 7f7941e828..c8ef0fb168 100644 --- a/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.hpp +++ b/src/slic3r/GUI/Jobs/TextureDisplacementPreviewJob.hpp @@ -15,9 +15,9 @@ namespace Slic3r::GUI { -// Everything process() needs, captured by value on the main thread when the job is queued - -// mirrors TextureDisplacementBakeInput, but a preview never writes back to the Model. -struct TextureDisplacementPreviewInput +// One model part's share of a preview. Captured by value on the main thread when the job is queued - +// mirrors TextureDisplacementBakeVolume, but a preview never writes back to the Model. +struct TextureDisplacementPreviewVolume { indexed_triangle_set base_mesh; std::vector layers; @@ -26,16 +26,26 @@ struct TextureDisplacementPreviewInput // Mesh coordinates -> world millimetres, so the preview is displaced in the same space the bake // is and the two cannot disagree. See build_texture_displacement(). Transform3d volume_to_world = Transform3d::Identity(); - // Empty unless a layer is colouring, in which case the preview reports the palette entry per - // triangle alongside the mesh, so the Normal view shows the colours the bake will produce. - TextureColorSettings color; - // The volume's own UV channel (ModelVolume::texture_uv), so a ModelUV layer previews through the - // same layout it will bake through. Empty when the volume has none. + // The part's own UV channel (ModelVolume::texture_uv), so a ModelUV layer previews through the + // same layout it will bake through. Empty when the part has none. std::vector model_uv; + // Where the part sits in its object, as TextureDisplacementBakeVolume has it. + Vec3d texture_anchor = Vec3d::Zero(); + float resting_drop = 0.f; }; -// A preview result: the displaced mesh, and - when the input carried a palette - one palette entry per -// triangle (its index + 1; 0 means "no colour from the texture"). +struct TextureDisplacementPreviewInput +{ + // The same parts the bake would displace, in the object's own volume order, so the preview shows + // the whole of what Bake will do on a multibody object rather than just its first part. + std::vector volumes; + // Empty unless a layer is colouring, in which case the preview reports the palette entry per + // triangle alongside the mesh, so the Normal view shows the colours the bake will produce. + TextureColorSettings color; +}; + +// A preview result for one part: the displaced mesh, and - when the input carried a palette - one +// palette entry per triangle (its index + 1; 0 means "no colour from the texture"). struct TextureDisplacementPreviewResult { indexed_triangle_set mesh; @@ -65,9 +75,12 @@ public: // already been superseded stops burning CPU instead of running to completion for a result that // will only be thrown away. That matters because the UI job worker runs one job at a time in FIFO // order: without it, a Bake queued behind a handful of stale previews waits for every one of them. + // + // `on_finished` receives one result per input part, at the same index - or an empty vector when + // the run was superseded, cancelled or threw. TextureDisplacementPreviewJob(TextureDisplacementPreviewInput &&input, uint64_t generation, std::shared_ptr> current_generation, - std::function on_finished); + std::function, uint64_t)> on_finished); void process(Ctl &ctl) override; void finalize(bool canceled, std::exception_ptr &eptr) override; @@ -76,8 +89,8 @@ private: TextureDisplacementPreviewInput m_input; uint64_t m_generation; std::shared_ptr> m_current_generation; - TextureDisplacementPreviewResult m_result; - std::function m_on_finished; + std::vector m_results; + std::function, uint64_t)> m_on_finished; }; } // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index c36a895a17..f9baeb2a12 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -909,6 +909,10 @@ bool MainFrame::handle_global_shortcut(const KeyChord& chord) m_plater->get_current_canvas3D()->post_event(SimpleEvent(wxEVT_PAINT)); } break; + case Shortcut::ShowCollisionVolumes: + if (m_plater && m_plater->is_view3D_shown() && m_plater->printer_technology() == ptFFF) + m_plater->show_collision_volumes(!m_plater->are_collision_volumes_shown()); + break; case Shortcut::ViewDefault: if (m_plater) { select_view("plate"); @@ -3132,12 +3136,15 @@ void MainFrame::init_menubar_as_editor() { editMenu = new wxMenu(); + // Feeds the key to ImGui instead when ImGui has the focused canvas's keyboard, since the menu + // handles its key equivalents before the canvas receives the key. auto handle_key_event = [](wxKeyEvent& evt) { - if (wxGetApp().imgui()->update_key_data(evt)) { - wxGetApp().plater()->get_current_canvas3D()->render(); - return true; - } - return false; + const ImGuiWrapper* imgui = focused_canvas_imgui(wxWindow::FindFocus()); + if (imgui == nullptr || !imgui->owns_keyboard()) + return false; + wxGetApp().imgui()->update_key_data(evt); + wxGetApp().plater()->get_current_canvas3D()->render(); + return true; }; #ifndef __APPLE__ // BBS undo @@ -3471,6 +3478,14 @@ void MainFrame::init_menubar_as_editor() [this]() { return m_plater->is_view3D_shown(); }, [this]() { return m_plater->are_view3D_labels_shown(); }, this); m_shortcut_menu_items.push_back({ show_labels, Shortcut::ShowLabels, _L("Show &Labels"), true }); + wxMenuItem* show_collision_volumes = append_menu_check_item( + viewMenu, wxID_ANY, shortcut_label(_L("Show all collision volumes"), Shortcut::ShowCollisionVolumes, true), + _L("Show the full height of every configured collision volume, including on an empty bed."), + [this](wxCommandEvent&) { m_plater->show_collision_volumes(!m_plater->are_collision_volumes_shown()); }, this, + [this]() { return m_plater->is_view3D_shown() && m_plater->printer_technology() == ptFFF; }, + [this]() { return m_plater->are_collision_volumes_shown(); }, this); + m_shortcut_menu_items.push_back({ show_collision_volumes, Shortcut::ShowCollisionVolumes, _L("Show all collision volumes"), true }); + append_menu_check_item(viewMenu, wxID_ANY, _L("Show &Overhang"), _L("Show object overhang highlight in 3D scene."), [this](wxCommandEvent &) { m_plater->show_view3D_overhang(!m_plater->is_view3D_overhang_shown()); diff --git a/src/slic3r/GUI/OptionsGroup.cpp b/src/slic3r/GUI/OptionsGroup.cpp index 8af4cfeef8..57cb7b4c52 100644 --- a/src/slic3r/GUI/OptionsGroup.cpp +++ b/src/slic3r/GUI/OptionsGroup.cpp @@ -1209,7 +1209,7 @@ boost::any ConfigOptionsGroup::get_config_value(const DynamicPrintConfig& config if (opt_key == "printable_area") ret = get_thumbnails_string(config.option(opt_key)->values); else if (opt_key == "bed_exclude_area") - ret = get_thumbnails_string(config.option(opt_key)->values); + ret = from_u8(config.option(opt_key)->serialize()); else if (opt_key == "wrapping_exclude_area") ret = get_thumbnails_string(config.option(opt_key)->values); else @@ -1320,7 +1320,7 @@ boost::any ConfigOptionsGroup::get_config_value2(const DynamicPrintConfig& confi if (opt_key == "printable_area") ret = get_thumbnails_string(config.option(opt_key)->values); else if (opt_key == "bed_exclude_area") - ret = get_thumbnails_string(config.option(opt_key)->values); + ret = from_u8(config.option(opt_key)->serialize()); else if (opt_key == "wrapping_exclude_area") ret = get_thumbnails_string(config.option(opt_key)->values); else @@ -1332,6 +1332,21 @@ boost::any ConfigOptionsGroup::get_config_value2(const DynamicPrintConfig& confi return ret; } +bool ConfigOptionsGroup::commit_config_value(const t_config_option_key& opt_key, int opt_index) +{ + if (m_config == nullptr) + return false; + + // m_opt_map is filled while the option lines are created, so it still resolves the option when + // the group's controls (and thus its fields) have not been built yet. + const std::string opt_id = option_id_in_map(m_opt_map, opt_key, opt_index); + if (opt_id.empty()) + return false; + + on_change_OG(opt_id, get_config_value2(*m_config, opt_key, opt_index)); + return true; +} + Field* ConfigOptionsGroup::get_fieldc(const t_config_option_key& opt_key, int opt_index) { Field* field = get_field(opt_key); diff --git a/src/slic3r/GUI/OptionsGroup.hpp b/src/slic3r/GUI/OptionsGroup.hpp index ae629f943e..bea4596e09 100644 --- a/src/slic3r/GUI/OptionsGroup.hpp +++ b/src/slic3r/GUI/OptionsGroup.hpp @@ -119,6 +119,37 @@ using column_t = std::function; using t_optionfield_map = std::map; using t_opt_map = std::map< std::string, std::pair >; +// The option id a group's option map holds for opt_key, and the index it carries. `opt_index` is +// an in/out parameter: a negative value asks for the option's single entry, an explicit one selects +// that index. Returns an empty string when the map does not own the option, or when a negative index +// matches several entries -- a vector option the GUI edits one index at a time, which has no single +// value to commit. A group fills the map while its option lines are created (OptionsGroup::append_line +// / ConfigOptionsGroup::get_option), so this resolves an option even before its controls (and its +// field) have been built. +inline std::string option_id_in_map(const t_opt_map& options, const t_config_option_key& opt_key, int& opt_index) +{ + if (opt_index >= 0) { + for (const auto& opt : options) { + if (opt.second.first == opt_key && opt.second.second == opt_index) { + opt_index = opt.second.second; + return opt.first; + } + } + return {}; + } + + std::string opt_id; + for (const auto& opt : options) { + if (opt.second.first != opt_key) + continue; + if (!opt_id.empty()) + return {}; // several entries: a vector option, not one value + opt_id = opt.first; + opt_index = opt.second.second; + } + return opt_id; +} + class OptionsGroup { public: const bool staticbox{true}; @@ -332,6 +363,15 @@ public: boost::any get_config_value(const DynamicPrintConfig& config, const std::string& opt_key, int opt_index = -1); // BBS: restore all pages in preset boost::any get_config_value2(const DynamicPrintConfig& config, const std::string& opt_key, int opt_index = -1); + // Re-run this group's committed-change path for one of its options without a widget event: + // build the option's value from the config this group edits (get_config_value2, the same form + // the option's field reports) and dispatch on_change_OG(), so the group's option-specific + // conversion (e.g. the printer_agent canonicalization) and its registered change handler run + // exactly as for a hand edit. The option map is filled while the option lines are created, so + // this resolves an option whose field is not built yet (a lazy page, or an option the GUI has + // no field for). Returns false when this group does not own the option, or when opt_index < 0 + // matches several entries (a vector option the GUI edits index by index has no single value). + bool commit_config_value(const t_config_option_key& opt_key, int opt_index = -1); Field* get_fieldc(const t_config_option_key& opt_key, int opt_index); std::pair get_custom_ctrl_with_blinking_ptr(const t_config_option_key& opt_key, int opt_index/* = -1*/); diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index 984323daff..f8de4fbfc9 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -76,6 +76,8 @@ #include "libslic3r/GCode/WipeTowerEstimate.hpp" #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/BoundingBox.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" +#include "libslic3r/Tesselate.hpp" #include "libslic3r/Geometry.hpp" #include "libslic3r/GCode/ThumbnailData.hpp" #include "libslic3r/IMEXHelpers.hpp" @@ -1467,6 +1469,144 @@ static bool init_model_from_lines(GLModel &model, const Lines3 &lines) return true; } +static ExPolygon expolygon_from_polygon(const Polygon &polygon) +{ + ExPolygon expolygon; + expolygon.contour = polygon; + expolygon.contour.make_counter_clockwise(); + return expolygon; +} + +static void append_expolygon_triangles(GLModel::Geometry &init_data, const ExPolygon &expolygon, float z) +{ + const std::vector triangles = triangulate_expolygon_2f(expolygon, NORMALS_UP); + if (triangles.empty() || triangles.size() % 3 != 0) + return; + + Vec2f min = triangles.front(); + Vec2f max = min; + for (const Vec2f &v : triangles) { + min = min.cwiseMin(v).eval(); + max = max.cwiseMax(v).eval(); + } + + const Vec2f size = max - min; + if (size.x() <= 0.0f || size.y() <= 0.0f) + return; + + Vec2f inv_size = size.cwiseInverse(); + inv_size.y() *= -1.0f; + + init_data.reserve_vertices(init_data.vertices_count() + triangles.size()); + init_data.reserve_indices(init_data.indices_count() + triangles.size()); + for (const Vec2f &v : triangles) { + init_data.add_vertex(Vec3f(v.x(), v.y(), z), (Vec2f)(v - min).cwiseProduct(inv_size).eval()); + const unsigned int vertices_counter = (unsigned int)init_data.vertices_count(); + if (vertices_counter % 3 == 0) + init_data.add_triangle(vertices_counter - 3, vertices_counter - 2, vertices_counter - 1); + } +} + +static bool init_model_from_polygons(GLModel &model, const Polygons &polygons, float z) +{ + model.reset(); + if (polygons.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3T2 }; + + for (const Polygon &polygon : polygons) { + if (polygon.points.size() < 3) + continue; + + append_expolygon_triangles(init_data, expolygon_from_polygon(polygon), z); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + +static bool init_model_from_expolygons(GLModel &model, const ExPolygons &expolygons, float z) +{ + model.reset(); + if (expolygons.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3T2 }; + + for (const ExPolygon &expolygon : expolygons) { + if (expolygon.contour.points.size() < 3) + continue; + + append_expolygon_triangles(init_data, expolygon, z); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + +struct ExclusionVolumePrismPreview +{ + Polygon footprint; + double z_min { 0.0 }; + double z_max { 0.0 }; +}; + +static bool init_exclusion_volume_prism_model(GLModel &model, const std::vector &prisms) +{ + model.reset(); + if (prisms.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3 }; + + for (const ExclusionVolumePrismPreview &prism : prisms) { + const Polygon &polygon = prism.footprint; + const float z_min = static_cast(prism.z_min); + const float z_max = static_cast(prism.z_max); + if (polygon.points.size() < 3 || z_max <= z_min) + continue; + + init_data.reserve_vertices(init_data.vertices_count() + 4 * polygon.points.size()); + init_data.reserve_indices(init_data.indices_count() + 6 * polygon.points.size()); + for (size_t i = 0; i < polygon.points.size(); ++i) { + const Point &p0 = polygon.points[i]; + const Point &p1 = polygon.points[(i + 1) % polygon.points.size()]; + + init_data.add_vertex(Vec3f(unscale(p0.x()), unscale(p0.y()), z_min)); + init_data.add_vertex(Vec3f(unscale(p1.x()), unscale(p1.y()), z_min)); + init_data.add_vertex(Vec3f(unscale(p1.x()), unscale(p1.y()), z_max)); + init_data.add_vertex(Vec3f(unscale(p0.x()), unscale(p0.y()), z_max)); + + const unsigned int base = (unsigned int)init_data.vertices_count() - 4; + init_data.add_triangle(base, base + 1, base + 2); + init_data.add_triangle(base, base + 2, base + 3); + } + + const ExPolygon expolygon = expolygon_from_polygon(polygon); + const std::vector triangles = triangulate_expolygon_2f(expolygon, NORMALS_UP); + init_data.reserve_vertices(init_data.vertices_count() + triangles.size()); + init_data.reserve_indices(init_data.indices_count() + triangles.size()); + const unsigned int cap_base = (unsigned int)init_data.vertices_count(); + for (const Vec2f &v : triangles) + init_data.add_vertex(Vec3f(v.x(), v.y(), z_max)); + for (size_t i = 0; i + 2 < triangles.size(); i += 3) + init_data.add_triangle(cap_base + (unsigned int)i, cap_base + (unsigned int)i + 1, cap_base + (unsigned int)i + 2); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + static void init_raycaster_from_model(PickingModel& model) { assert(model.mesh_raycaster == nullptr); @@ -1886,6 +2026,410 @@ void PartPlate::render_exclude_area(bool force_default_color) { glsafe(::glDepthMask(GL_TRUE)); } +double PartPlate::max_broad_phase_intersecting_object_height(const Polygons& regions) const +{ + if (m_model == nullptr) + return 0.0; + + double max_height = 0.0; + + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) + continue; + + ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) + continue; + + ModelInstance *instance = object->instances[instance_id]; + if (!instance->printable) + continue; + + Polygon hull = instance->convex_hull_2d(); + bool intersects_region = false; + for (const Polygon ®ion : regions) { + if (!intersection(Polygons{ region }, Polygons{ hull }).empty()) { + intersects_region = true; + break; + } + } + + if (!intersects_region) + continue; + + const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); + max_height = std::max(max_height, instance_box.max.z()); + } + + return max_height; +} + +std::string PartPlate::exclusion_volume_preview_cache_key(const std::vector ®ions) const +{ + std::ostringstream key; + key << std::setprecision(17); + key << "plate:" << m_origin.x() << ',' << m_origin.y() << ',' << m_height << ';'; + + key << "regions:" << regions.size() << ';'; + for (const BedExcludeRegion ®ion : regions) { + key << region.z_min << ".." << region.z_max << ':' + << int(region.purpose) << ':' << region.has_z_range << ':' + << region.polygon.points.size(); + for (const Point &point : region.polygon.points) + key << ',' << point.x() << 'x' << point.y(); + key << ';'; + } + + key << "instances:" << obj_to_instance_set.size() << ';'; + if (m_model != nullptr) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + key << obj_id << ':' << instance_id << ':'; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) { + key << "invalid;"; + continue; + } + + const ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) { + key << "invalid;"; + continue; + } + + const ModelInstance *instance = object->instances[instance_id]; + key << static_cast(object) << ':' << static_cast(instance) << ':' + << object->volumes.size() << ':' << instance->printable << ':'; + + const Transform3d instance_matrix = instance->get_matrix(); + for (int r = 0; r < int(instance_matrix.matrix().rows()); ++r) + for (int c = 0; c < int(instance_matrix.matrix().cols()); ++c) + key << instance_matrix.matrix()(r, c) << ','; + + for (const ModelVolume *volume : object->volumes) { + key << static_cast(volume) << ':'; + for (const int filament_id : volume->get_extruders()) + key << 'f' << filament_id << ','; + const Transform3d volume_matrix = volume->get_matrix(); + for (int r = 0; r < int(volume_matrix.matrix().rows()); ++r) + for (int c = 0; c < int(volume_matrix.matrix().cols()); ++c) + key << volume_matrix.matrix()(r, c) << ','; + } + key << ';'; + } + } + + return key.str(); +} + +void PartPlate::update_exclusion_volume_preview_models() +{ + if (!m_exclusion_volume_preview_dirty) + return; + m_exclusion_volume_preview_dirty = false; + + const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; + if (config == nullptr) { + m_exclusion_volume_preview_cache_key.clear(); + m_exclusion_volume_floor_triangles.reset(); + m_exclusion_volume_border_triangles.reset(); + m_extruder_exclusion_volume_borders.clear(); + m_active_exclusion_volume_prisms.reset(); + m_exclusion_volume_intersection_triangles.reset(); + m_exclusion_volume_intersections_cleared = false; + return; + } + + const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(*config); + std::vector regions; + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + if (mode == BedExcludeVolumeMode::Shared && extruder_id > 0) + break; + for (const BedExcludeRegion ®ion : regions_by_extruder[extruder_id]) { + if (!region.is_collision_volume() && extruder_id > 0) + continue; + regions.emplace_back(region); + } + } + // A coloured border communicates which physical nozzle owns a footprint. + // With only one nozzle the exclusion applies to every filament, so using + // the first filament colour would incorrectly imply material ownership. + const bool show_nozzle_ownership = + regions_by_extruder.size() > 1 && mode != BedExcludeVolumeMode::Shared; + std::ostringstream grouped_key; + const bool show_all_volumes = m_plater->are_collision_volumes_shown(); + grouped_key << exclusion_volume_preview_cache_key(regions) << "mode:" << int(mode) + << ";show_all:" << show_all_volumes << ";groups:"; + for (const std::vector &group : regions_by_extruder) + grouped_key << group.size() << ','; + const std::vector filament_colors = m_plater->get_extruder_colors_from_plater_config(); + std::vector preview_colors(regions_by_extruder.size()); + + // Use the same effective filament-to-nozzle policy as collision checks so + // the coloured border never implies a mapping the validator does not use. + const DynamicPrintConfig &project_config = wxGetApp().preset_bundle->project_config; + const std::vector filament_map = get_effective_exclusion_filament_maps( + project_config, filament_colors.size(), regions_by_extruder.size()); + grouped_key << "map:"; + for (const int extruder_id : filament_map) + grouped_key << extruder_id << ','; + grouped_key << ';'; + grouped_key << "object_maps:"; + if (m_model != nullptr) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int object_id = object_instance.first; + if (object_id < 0 || object_id >= int(m_model->objects.size())) + continue; + grouped_key << object_id << ':'; + for (const auto &[filament_id, extruder_id] : get_object_filament_extruders( + *m_model->objects[object_id], project_config, regions_by_extruder.size())) + grouped_key << filament_id << '>' << extruder_id << ','; + grouped_key << ';'; + } + } + for (size_t filament_id = 0; filament_id < filament_colors.size(); ++filament_id) { + const int mapped_extruder = filament_id < filament_map.size() ? filament_map[filament_id] - 1 : int(filament_id); + if (mapped_extruder >= 0 && size_t(mapped_extruder) < preview_colors.size() && preview_colors[mapped_extruder].empty()) + preview_colors[mapped_extruder] = filament_colors[filament_id]; + } + + if (const ConfigOptionStrings *extruder_colors = config->opt("extruder_colour"); + extruder_colors != nullptr) { + for (size_t extruder_id = 0; extruder_id < preview_colors.size() && extruder_id < extruder_colors->size(); ++extruder_id) + if (preview_colors[extruder_id].empty()) + preview_colors[extruder_id] = extruder_colors->values[extruder_id]; + } + for (const std::string &color : preview_colors) + grouped_key << color << ','; + const std::string cache_key = grouped_key.str(); + if (cache_key == m_exclusion_volume_preview_cache_key && !m_exclusion_volume_intersections_cleared) + return; + m_exclusion_volume_preview_cache_key = cache_key; + m_exclusion_volume_intersections_cleared = false; + + m_exclusion_volume_floor_triangles.reset(); + m_exclusion_volume_border_triangles.reset(); + m_extruder_exclusion_volume_borders.clear(); + m_active_exclusion_volume_prisms.reset(); + m_exclusion_volume_intersection_triangles.reset(); + + const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); + Polygons floor_regions; + ExPolygons border_regions; + const coord_t ribbon_width = scale_(1.6); + struct PreviewRegion { + BedExcludeRegion region; + Polygon footprint; + size_t extruder_id; + }; + std::vector preview_regions; + Polygons preview_footprints; + std::vector active_prisms; + + if (show_nozzle_ownership) { + static const std::array fallback_colors = { + ColorRGBA{ .18f, .52f, .95f, .92f }, ColorRGBA{ .95f, .35f, .22f, .92f }, + ColorRGBA{ .25f, .72f, .38f, .92f }, ColorRGBA{ .72f, .34f, .88f, .92f }, + ColorRGBA{ .95f, .68f, .16f, .92f }, ColorRGBA{ .18f, .76f, .78f, .92f } + }; + const coord_t tool_border_width = scale_(0.55); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + ColorRGBA color = fallback_colors[extruder_id % fallback_colors.size()]; + if (extruder_id < preview_colors.size()) { + ColorRGBA decoded; + if (decode_color(preview_colors[extruder_id], decoded)) { + color = decoded; + color.a(0.92f); + } + } + + for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + if (!region_src.is_collision_volume()) + continue; + Polygon footprint = region_src.polygon; + footprint.translate(plate_offset); + footprint.make_counter_clockwise(); + const Polygons inner = offset(Polygons{ footprint }, -tool_border_width, jtMiter, 2.0); + const ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(footprint) } : diff_ex(Polygons{ footprint }, inner); + auto model = std::make_unique(); + // Nozzle colours identify the bed footprint, not the volume's + // vertical position, so keep this border with the grey preview. + const float border_z = GROUND_Z + 0.026f; + if (init_model_from_expolygons(*model, border, border_z) && model->is_initialized()) + m_extruder_exclusion_volume_borders.emplace_back(std::move(model), color); + } + } + } + + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + // Shared regions are identical for every nozzle. Keeping one copy + // avoids duplicate floor, prism and intersection geometry. + if (mode == BedExcludeVolumeMode::Shared && extruder_id > 0) + break; + + for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + // The legacy area is shared and bed-fixed, even when nozzle-specific + // collision volumes are active. Keep only one preview copy. + if (!region_src.is_collision_volume() && extruder_id > 0) + continue; + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); + BedExcludeRegion translated_region = region_src; + translated_region.polygon = region; + preview_regions.push_back({ std::move(translated_region), region, extruder_id }); + preview_footprints.emplace_back(region); + + // Legacy polygons continue to use Orca's existing grey bed preview; + // the additional floor/ribbon belongs only to collision volumes. + if (region_src.is_collision_volume()) { + if (!region_src.has_z_range || region_src.z_min <= EPSILON) { + floor_regions.emplace_back(region); + } else { + const Polygons inner = offset(Polygons{ region }, -ribbon_width, jtMiter, 2.0); + ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(region) } : diff_ex(Polygons{ region }, inner); + border_regions.insert(border_regions.end(), border.begin(), border.end()); + } + } + } + } + + // Automatic previews stay limited to nearby objects. The View toggle lets + // profile authors inspect the complete configured height on an empty bed. + const double preview_height = show_all_volumes ? 0.0 : + max_broad_phase_intersecting_object_height(preview_footprints); + if (show_all_volumes || preview_height > EPSILON) { + for (const PreviewRegion &preview_region : preview_regions) { + const BedExcludeRegion ®ion_src = preview_region.region; + if (!region_src.is_collision_volume()) + continue; + const double z_min = region_src.has_z_range ? region_src.z_min : 0.0; + const double z_max = show_all_volumes ? region_src.z_max : std::min(region_src.z_max, preview_height); + if (z_max > z_min + EPSILON) + active_prisms.push_back({ preview_region.footprint, z_min, z_max }); + } + } + + indexed_triangle_set intersection_triangles; + if (m_model != nullptr && !preview_regions.empty()) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) + continue; + + ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) + continue; + + ModelInstance *instance = object->instances[instance_id]; + if (!instance->printable) + continue; + + std::set relevant_extruders; + if (mode != BedExcludeVolumeMode::Shared) { + for (const auto &mapping : get_object_filament_extruders( + *object, project_config, regions_by_extruder.size())) + relevant_extruders.emplace(mapping.second); + } + + Polygon hull = instance->convex_hull_2d(); + const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); + for (const PreviewRegion &preview_region : preview_regions) { + if (preview_region.region.is_collision_volume() && mode != BedExcludeVolumeMode::Shared && + relevant_extruders.find(preview_region.extruder_id) == relevant_extruders.end()) + continue; + + const BedExcludeRegion ®ion = preview_region.region; + if (intersection(Polygons{ preview_region.footprint }, Polygons{ hull }).empty()) + continue; + if (instance_box.max.z() < region.z_min || instance_box.min.z() > region.z_max) + continue; + + // The preview path intentionally requests the full clipped mesh. + // Boolean-only placement checks call this without an output mesh. + indexed_triangle_set region_intersections; + if (instance->intersects_bed_exclude_region(region, ®ion_intersections) && !region_intersections.empty()) + its_merge(intersection_triangles, region_intersections); + } + } + } + + if (!floor_regions.empty() && !init_model_from_polygons(m_exclusion_volume_floor_triangles, floor_regions, GROUND_Z + 0.01f)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create exclusion volume floor preview triangles\n"; + + if (!border_regions.empty() && !init_model_from_expolygons(m_exclusion_volume_border_triangles, border_regions, GROUND_Z + 0.018f)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create exclusion volume preview border\n"; + + if (!active_prisms.empty() && !init_exclusion_volume_prism_model(m_active_exclusion_volume_prisms, active_prisms)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create active exclusion volume preview prisms\n"; + + if (!intersection_triangles.empty()) + m_exclusion_volume_intersection_triangles.init_from(intersection_triangles); +} + +void PartPlate::render_exclusion_volume_previews(bool force_default_color) +{ + if (force_default_color) + return; + + update_exclusion_volume_preview_models(); + + const ColorRGBA floor_color = m_selected ? ColorRGBA{ .86f, .86f, .86f, .70f } : ColorRGBA{ .60f, .60f, .60f, .30f }; + const ColorRGBA ribbon_color{ .60f, .60f, .60f, .70f }; + const ColorRGBA prism_color{ .52f, .52f, .52f, .38f }; + + glsafe(::glDepthMask(GL_FALSE)); + + m_exclusion_volume_floor_triangles.set_color(floor_color); + m_exclusion_volume_floor_triangles.render(); + + m_exclusion_volume_border_triangles.set_color(ribbon_color); + m_exclusion_volume_border_triangles.render(); + + for (auto &colored_border : m_extruder_exclusion_volume_borders) { + colored_border.first->set_color(colored_border.second); + colored_border.first->render(); + } + + m_active_exclusion_volume_prisms.set_color(prism_color); + m_active_exclusion_volume_prisms.render(); + + glsafe(::glLineWidth(1.0f * m_scale_factor)); + glsafe(::glDepthMask(GL_TRUE)); +} + +void PartPlate::render_exclusion_volume_intersections() +{ + if (!m_exclusion_volume_intersection_triangles.is_initialized()) + return; + + const ColorRGBA intersection_color{ .68f, .02f, .02f, .58f }; + + glsafe(::glEnable(GL_POLYGON_OFFSET_FILL)); + glsafe(::glPolygonOffset(-1.0f, -1.0f)); + + m_exclusion_volume_intersection_triangles.set_color(intersection_color); + m_exclusion_volume_intersection_triangles.render(); + + glsafe(::glDisable(GL_POLYGON_OFFSET_FILL)); +} + +void PartPlate::clear_exclusion_volume_intersections() +{ + m_exclusion_volume_intersection_triangles.reset(); + m_exclusion_volume_intersections_cleared = true; +} + +void PartPlate::invalidate_exclusion_volume_preview() +{ + m_exclusion_volume_preview_dirty = true; +} + + /*void PartPlate::render_background_for_picking(const ColorRGBA render_color) const { unsigned int triangles_vcount = m_triangles.get_vertices_count(); @@ -2992,6 +3536,122 @@ int PartPlate::get_logical_extruder_by_filament_id(const DynamicConfig& g_config return filament_map[idx - 1] - 1; } +std::vector PartPlate::get_effective_exclusion_filament_maps( + const DynamicConfig &g_config, const size_t filament_count, const size_t extruder_count) const +{ + std::vector result(filament_count, 0); + if (extruder_count == 0) + return result; + + const std::vector configured_map = get_real_filament_maps(g_config); + const FilamentMapMode map_mode = get_real_filament_map_mode(g_config); + PresetBundle *preset_bundle = wxGetApp().preset_bundle; + const bool is_bambu = preset_bundle != nullptr && preset_bundle->is_bbl_vendor(); + const bool automatic = is_auto_filament_map_mode(map_mode); + const bool automatic_map_resolved = !automatic || !get_filament_maps().empty(); + for (size_t filament_id = 0; filament_id < filament_count; ++filament_id) { + const int extruder_id = bed_exclusion_extruder_for_filament( + filament_id, configured_map, map_mode, is_bambu, automatic_map_resolved, extruder_count); + if (extruder_id >= 0) + result[filament_id] = extruder_id + 1; + } + return result; +} + +std::map PartPlate::get_object_filament_extruders( + const ModelObject &object, const DynamicConfig &g_config, const size_t extruder_count) const +{ + std::set filament_ids; + const DynamicPrintConfig &process_config = wxGetApp().preset_bundle->prints.get_edited_preset().config; + const auto effective_option = [&object, &process_config](const char *key) -> const ConfigOption * { + if (const ConfigOption *option = object.config.option(key); option != nullptr) + return option; + return process_config.option(key); + }; + const auto effective_int = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr ? option->getInt() : 0; + }; + const auto effective_float = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr ? option->getFloat() : 0.0; + }; + const auto effective_bool = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr && option->getBool(); + }; + + const bool has_brim = effective_int("brim_type") != int(BrimType::btNoBrim) && effective_float("brim_width") > 0.0; + const int wall_loops = effective_int("wall_loops"); + const double sparse_infill_density = effective_float("sparse_infill_density"); + const int top_shell_layers = effective_int("top_shell_layers"); + const int bottom_shell_layers = effective_int("bottom_shell_layers"); + const std::array, 6> feature_filament_keys = { + std::pair{ "outer_wall_filament_id", wall_loops > 0 || has_brim }, + std::pair{ "inner_wall_filament_id", wall_loops > 1 }, + std::pair{ "sparse_infill_filament_id", sparse_infill_density > 0.0 }, + std::pair{ "internal_solid_filament_id", sparse_infill_density > 0.0 || top_shell_layers > 0 || bottom_shell_layers > 0 }, + std::pair{ "top_surface_filament_id", top_shell_layers > 0 }, + std::pair{ "bottom_surface_filament_id", bottom_shell_layers > 0 } + }; + auto collect_config_filaments = [&filament_ids, &feature_filament_keys](const DynamicConfig &config) { + for (const auto &[key, active] : feature_filament_keys) { + if (active) { + if (const ConfigOption *option = config.option(key); option != nullptr && option->getInt() > 0) + filament_ids.emplace(option->getInt()); + } + } + if (const ConfigOption *option = config.option("extruder"); option != nullptr && option->getInt() > 0) + filament_ids.emplace(option->getInt()); + }; + + for (const ModelVolume *volume : object.volumes) { + const std::vector volume_filaments = volume->get_extruders(); + filament_ids.insert(volume_filaments.begin(), volume_filaments.end()); + collect_config_filaments(volume->config.get()); + } + collect_config_filaments(object.config.get()); + for (const auto &layer_range : object.layer_config_ranges) + collect_config_filaments(layer_range.second.get()); + + // Process-level feature assignments also apply when the object has no + // override. This mirrors the relevant parts of PrintObject::printing_extruders() + // closely enough for an unsliced placement preview. + for (const auto &[key, active] : feature_filament_keys) { + if (active && !object.config.has(key) && process_config.has(key) && process_config.opt_int(key) > 0) + filament_ids.emplace(process_config.opt_int(key)); + } + + const bool has_support = effective_bool("enable_support") || effective_int("raft_layers") > 0; + if (has_support) { + const int support_filament = effective_int("support_filament"); + const int interface_filament = effective_int("support_interface_filament"); + if (support_filament > 0) + filament_ids.emplace(support_filament); + if (interface_filament > 0) + filament_ids.emplace(interface_filament); + } + + // Match Orca's normal fallback for an unassigned object. + if (filament_ids.empty()) + filament_ids.emplace(1); + + const size_t required_filament_count = filament_ids.empty() ? 0 : size_t(*filament_ids.rbegin()); + const std::vector filament_map = get_effective_exclusion_filament_maps( + g_config, required_filament_count, extruder_count); + std::map result; + for (const int filament_id : filament_ids) { + if (filament_id <= 0) + continue; + + const int mapped_extruder = size_t(filament_id) <= filament_map.size() && filament_map[filament_id - 1] > 0 ? + filament_map[filament_id - 1] - 1 : -1; + if (mapped_extruder >= 0 && size_t(mapped_extruder) < extruder_count) + result.emplace(filament_id, size_t(mapped_extruder)); + } + return result; +} + std::vector PartPlate::get_used_filaments() { std::vector used_filaments; @@ -3513,6 +4173,7 @@ void PartPlate::clear(bool clear_sliced_result) { obj_to_instance_set.clear(); instance_outside_set.clear(); + invalidate_exclusion_volume_preview(); if (clear_sliced_result) { m_ready_for_slice = true; update_slice_result_valid_state(false); @@ -3592,6 +4253,7 @@ void PartPlate::set_pos_and_size(Vec3d& origin, int width, int depth, double hei m_width = width; m_depth = depth; m_height = height; + invalidate_exclusion_volume_preview(); if (with_instance_move && m_plater) m_plater->mark_plate_toolbar_image_dirty(); @@ -3721,6 +4383,7 @@ void PartPlate::set_print(PrintBase* print, GCodeResult* result, int index) m_print_index = index; m_print->set_plate_origin(m_origin); + invalidate_exclusion_volume_preview(); return; } @@ -3841,7 +4504,14 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi ModelInstance* instance = object->instances[instance_id]; BoundingBoxf3 instance_box = bounding_box? *bounding_box: object->instance_convex_hull_bounding_box(instance_id); - Polygon hull = instance->convex_hull_2d(); + // Reuse the hull across exclusion and IMEX checks, but do not build it for + // instances rejected by the plate bounds or printers with no relevant zones. + std::optional instance_hull; + const auto get_instance_hull = [&]() -> const Polygon & { + if (!instance_hull) + instance_hull = instance->convex_hull_2d(); + return *instance_hull; + }; BoundingBoxf3 plate_box = get_plate_box(); this->open_belt_y(plate_box); if (instance_box.max.z() > plate_box.min.z()) @@ -3860,34 +4530,66 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi else if (plate_box.contains(instance_box)) { - if (m_exclude_bounding_box.size() > 0) - { - Polygon hull = instance->convex_hull_2d(); - int index; - for (index = 0; index < m_exclude_bounding_box.size(); index ++) - { - Polygon p = m_exclude_bounding_box[index].polygon(true); // instance convex hull is scaled, so we need to scale here - if (intersection({ p }, { hull }).empty() == false) - //if (m_exclude_bounding_box[index].intersects(instance_box)) - { - break; - } - } - if (index >= m_exclude_bounding_box.size()) - outside = false; - } - else - outside = false; + outside = false; + const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; + bool checked_config_regions = false; + if (config != nullptr) { + const std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(*config); + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); + // The legacy outside flag has no filament/nozzle context. Always + // check the shared legacy area here, but let the newer per-extruder + // pipeline handle nozzle-specific collision volumes. + const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); + const Polygon &hull = get_instance_hull(); + + const size_t groups_to_check = regions_by_extruder.empty() ? 0 : 1; + for (size_t group_id = 0; group_id < groups_to_check; ++group_id) { + const std::vector &extruder_regions = regions_by_extruder[group_id]; + for (const BedExcludeRegion ®ion_src : extruder_regions) { + if (mode != BedExcludeVolumeMode::Shared && region_src.is_collision_volume()) + continue; + checked_config_regions = true; + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); + + if (intersection(Polygons{ region }, Polygons{ hull }).empty()) + continue; + + if (instance_box.max.z() < region_src.z_min || instance_box.min.z() > region_src.z_max) + continue; + + BedExcludeRegion translated_region = region_src; + translated_region.polygon = std::move(region); + if (instance->intersects_bed_exclude_region(translated_region)) { + outside = true; + break; + } + } + if (outside) + break; + } + } + + if (!checked_config_regions && m_exclude_bounding_box.size() > 0) { + const Polygon &hull = get_instance_hull(); + for (const BoundingBoxf3 &exclude_box : m_exclude_bounding_box) { + Polygon p = exclude_box.polygon(true); // instance convex hull is scaled, so we need to scale here + if (!intersection({ p }, { hull }).empty()) { + outside = true; + break; + } + } + } } // IDEX/IQEX placement check (prepare-mode bounding-box test). // Block objects that overlap secondary (copy/mirror) zones or the carriage // danger strip at the primary zone boundary. Reuses the existing // outside=true → instance_outside_set → update_states() → blocks slicing path. - // Reuse the hull computed above: ModelInstance::convex_hull_2d() is NOT cached - // (Model.cpp has the validity guard commented out), so recomputing it here would - // cost every user a per-instance hull rebuild, including on non-IMEX printers. - if (!outside && imex_hull_violates(hull)) + if (!outside && (!m_imex_secondary_zone_boxes.empty() || !m_imex_collision_zones.empty()) && + imex_hull_violates(get_instance_hull())) outside = true; return outside; @@ -3953,6 +4655,7 @@ int PartPlate::add_instance(int obj_id, int instance_id, bool move_position, Bou std::pair pair(obj_id, instance_id); obj_to_instance_set.insert(pair); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": plate_id %1%, add instance obj_id %2%, instance_id %3%, move_position %4%") % m_plate_index % obj_id % instance_id % move_position; @@ -3995,6 +4698,7 @@ int PartPlate::remove_instance(int obj_id, int instance_id) it = obj_to_instance_set.find(std::pair(obj_id, instance_id)); if (it != obj_to_instance_set.end()) { obj_to_instance_set.erase(it); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(":plate_id %1%, found obj_id %2%, instance_id %3%") % m_plate_index % obj_id % instance_id; result = 0; } @@ -4054,6 +4758,7 @@ void PartPlate::translate_all_instance(Vec3d position) } } } + invalidate_exclusion_volume_preview(); return; } @@ -4088,6 +4793,7 @@ void PartPlate::duplicate_all_instance(unsigned int dup_count, bool need_skip, s for ( size_t new_instance_id = 0; new_instance_id < newObj->instances.size(); new_instance_id++ ) { obj_to_instance_set.emplace(std::pair(new_obj_id, new_instance_id)); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": duplicate object into plate: index_pair [%1%,%2%], obj_id %3%") % new_obj_id % new_instance_id % newObj->id().id; } } @@ -4131,6 +4837,7 @@ void PartPlate::update_instance_exclude_status(int obj_id, int instance_id, Boun std::set>::iterator it; outside = check_outside(obj_id, instance_id, bounding_box); + invalidate_exclusion_volume_preview(); it = instance_outside_set.find(std::pair(obj_id, instance_id)); if (it == instance_outside_set.end()) { @@ -4158,6 +4865,7 @@ void PartPlate::update_object_index(int obj_idx_removed, int obj_idx_max) } obj_to_instance_set.clear(); obj_to_instance_set = temp_set; + invalidate_exclusion_volume_preview(); //update the instance_outside_set temp_set.clear(); @@ -4413,6 +5121,8 @@ void PartPlate::generate_exclude_polygon(ExPolygon &exclude_polygon) bool PartPlate::set_shape(const Pointfs& shape, const Pointfs& exclude_areas, const std::vector& extruder_areas, const std::vector& extruder_heights, Vec2d position, float height_to_lid, float height_to_rod) { + invalidate_exclusion_volume_preview(); + Pointfs new_shape, new_exclude_areas; m_extruder_heights = extruder_heights; for (const Vec2d& p : shape) { @@ -4633,6 +5343,7 @@ void PartPlate::render(const Transform3d& view_matrix, const Transform3d& projec } render_wrapping_detection_area(force_background_color); } + render_exclusion_volume_previews(force_background_color); } render_height_limit(mode); @@ -5073,6 +5784,7 @@ void PartPlate::set_filament_map_mode(const FilamentMapMode& mode) clear_filament_map_mode(); else m_config.option>("filament_map_mode", true)->value = mode; + invalidate_exclusion_volume_preview(); } std::vector PartPlate::get_filament_maps() const @@ -5087,12 +5799,14 @@ std::vector PartPlate::get_filament_maps() const void PartPlate::set_filament_maps(const std::vector& f_maps) { m_config.option("filament_map", true)->values = f_maps; + invalidate_exclusion_volume_preview(); } void PartPlate::clear_filament_map() { if (m_config.has("filament_map")) m_config.erase("filament_map"); + invalidate_exclusion_volume_preview(); } std::vector PartPlate::get_filament_volume_maps() const @@ -5810,6 +6524,39 @@ void PartPlateList::update_plates() set_shapes(m_shape, m_exclude_areas, m_wrapping_exclude_areas, m_extruder_areas, m_extruder_heights, m_logo_texture_filename, m_height_to_lid, m_height_to_rod); } +void PartPlateList::invalidate_exclusion_volume_previews() +{ + for (PartPlate *plate : m_plate_list) + if (plate != nullptr) + plate->invalidate_exclusion_volume_preview(); +} + +void PartPlateList::render_exclusion_volume_intersections( + const Transform3d &view_matrix, + const Transform3d &projection_matrix) +{ + GLShaderProgram *shader = wxGetApp().get_shader("flat"); + if (shader == nullptr) + return; + + shader->start_using(); + shader->set_uniform("view_model_matrix", view_matrix); + shader->set_uniform("projection_matrix", projection_matrix); + + glsafe(::glEnable(GL_DEPTH_TEST)); + glsafe(::glEnable(GL_BLEND)); + glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); + glsafe(::glDepthMask(GL_FALSE)); + + for (PartPlate *plate : m_plate_list) + if (plate != nullptr) + plate->render_exclusion_volume_intersections(); + + glsafe(::glDepthMask(GL_TRUE)); + glsafe(::glDisable(GL_BLEND)); + shader->stop_using(); +} + int PartPlateList::create_plate(bool adjust_position) { PartPlate* plate = NULL; @@ -5918,6 +6665,7 @@ int PartPlateList::duplicate_plate(int index) // go over the instances and pair with the object for (size_t new_instance_id = 0; new_instance_id < object_copy->instances.size(); new_instance_id++){ new_plate->obj_to_instance_set.emplace(std::pair(new_obj_id, new_instance_id)); + new_plate->invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": duplicate object into plate: index_pair [%1%,%2%], obj_id %3%") % new_obj_id % new_instance_id % object_copy->id().id; } } @@ -6903,7 +7651,8 @@ bool PartPlateList::preprocess_arrange_polygon_other_locked(int obj_index, int i return locked; } -bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, bool enable_wrapping_detect, int num_plates, float inflation) +bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, const DynamicPrintConfig &config, + bool enable_wrapping_detect, int num_plates, float inflation) { bool added = false; @@ -6935,10 +7684,47 @@ bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unsel } added = true; } + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(config); + const bool use_resolved_regions = has_bed_exclude_volumes(config); - // excluded area - if (m_exclude_areas.size() > 0) - { + if (use_resolved_regions) { + const std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(config); + const size_t extruder_count = mode == BedExcludeVolumeMode::Shared ? + std::min(1, regions_by_extruder.size()) : regions_by_extruder.size(); + + for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) { + for (size_t region_id = 0; region_id < regions_by_extruder[extruder_id].size(); ++region_id) { + const BedExcludeRegion ®ion = regions_by_extruder[extruder_id][region_id]; + if (!region.is_collision_volume() || region.polygon.points.size() < 3 || + (region.has_z_range && region.z_max <= region.z_min + EPSILON)) + continue; + + for (int plate_idx = 0; plate_idx < num_plates; ++plate_idx) { + arrangement::ArrangePolygon blocker; + blocker.poly.contour = bed_exclusion_arrange_polygon(region.polygon); + blocker.translation = Vec2crd::Zero(); + blocker.rotation = 0.0; + blocker.is_virt_object = true; + blocker.is_bed_exclusion = true; + blocker.bed_exclusion_extruder_id = mode == BedExcludeVolumeMode::Shared ? -1 : int(extruder_id); + blocker.bed_idx = plate_idx; + blocker.height = std::max(0.0, region.z_max - region.z_min); + blocker.z_min = region.z_min; + blocker.z_max = region.z_max; + blocker.has_z_range = region.has_z_range; + blocker.name = "BedExclusionVolume" + std::to_string(extruder_id) + "_" + std::to_string(region_id); + blocker.inflation = inflation; + unselected.emplace_back(std::move(blocker)); + } + added = true; + } + } + } + + // Keep Orca's established legacy-area arrange obstacle alongside any + // explicit collision-volume blockers. The two settings are additive. + if (!m_exclude_areas.empty()) { //has exclude areas PartPlate *plate = m_plate_list[0]; @@ -7108,19 +7894,14 @@ void PartPlateList::postprocess_arrange_polygon(arrangement::ArrangePolygon& arr { BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": bed_idx %1%, selected %2%, translation(x) %3%, (y) %4%") % arrange_polygon.bed_idx % selected % unscale(arrange_polygon.translation(X)) % unscale(arrange_polygon.translation(Y)); + // UNARRANGED means the item could not be placed, so it has no bed to map onto and + // must be left where the user had it. Moving it to a virtual bed here would shift + // it off the plate, because no such plate is created for it afterwards. + if (arrange_polygon.bed_idx == arrangement::UNARRANGED) + return; + if ((selected) || (arrange_polygon.bed_idx != PartPlateList::MAX_PLATES_COUNT)) { - if (arrange_polygon.bed_idx == -1) - { - // outarea for large object - arrange_polygon.bed_idx = m_plate_list.size(); - BoundingBox apbox = get_extents(arrange_polygon.transformed_poly()); // the item may have been rotated - auto apbox_size = apbox.size(); - - arrange_polygon.translation(X) = 0.5 * apbox_size[0]; - arrange_polygon.translation(Y) = scaled(static_cast(m_plate_depth)) - 0.5 * apbox_size[1]; - } - arrange_polygon.row = arrange_polygon.bed_idx / m_plate_cols; arrange_polygon.col = arrange_polygon.bed_idx % m_plate_cols; arrange_polygon.translation(X) += scaled(plate_stride_x() * arrange_polygon.col); diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index 043fc3ee82..d90e6f2767 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -19,11 +19,14 @@ #include #include #include +#include #include +#include #include #include #include #include +#include #include #include "libslic3r/ObjectID.hpp" @@ -159,6 +162,14 @@ private: PickingModel m_triangles; GLModel m_exclude_triangles; GLModel m_wrapping_detection_triangles; + GLModel m_exclusion_volume_floor_triangles; + GLModel m_exclusion_volume_border_triangles; + std::vector, ColorRGBA>> m_extruder_exclusion_volume_borders; + GLModel m_active_exclusion_volume_prisms; + GLModel m_exclusion_volume_intersection_triangles; + std::string m_exclusion_volume_preview_cache_key; + bool m_exclusion_volume_preview_dirty { true }; + bool m_exclusion_volume_intersections_cleared { false }; GLModel m_logo_triangles; GLModel m_gridlines; GLModel m_gridlines_bolder; @@ -241,6 +252,11 @@ private: void render_logo(bool bottom, bool render_cali = true); void render_logo_texture(GLTexture &logo_texture, GLModel &logo_buffer, bool bottom); void render_exclude_area(bool force_default_color); + void render_exclusion_volume_previews(bool force_default_color); + void render_exclusion_volume_intersections(); + void update_exclusion_volume_preview_models(); + std::string exclusion_volume_preview_cache_key(const std::vector ®ions) const; + double max_broad_phase_intersecting_object_height(const Polygons& regions) const; //void render_background_for_picking(const ColorRGBA render_color) const; void render_grid(bool bottom); void render_wrapping_detection_area(bool force_default_color); @@ -485,6 +501,16 @@ public: const std::vector& get_slice_filaments_info() const { return slice_filaments_info; } int get_physical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const; int get_logical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const; + // Resolve the mapping policy used specifically by exclusion regions. + // Values are 1-based nozzle ids; 0 means automatic Bambu mapping has not + // produced a concrete plate-local assignment yet. + std::vector get_effective_exclusion_filament_maps(const DynamicConfig &g_config, size_t filament_count, + size_t extruder_count) const; + // 1-based filament id -> 0-based nozzle/exclusion-region id for the + // object's current plate mapping. Includes every filament referenced by + // any model volume (including painted facets). + std::map get_object_filament_extruders(const ModelObject &object, const DynamicConfig &g_config, + size_t extruder_count) const; bool check_filament_printable(const DynamicPrintConfig & config, wxString& error_message); bool check_tpu_printable_status(const DynamicPrintConfig & config, const std::vector &tpu_filaments); bool check_mixture_of_pla_and_petg(const DynamicPrintConfig & config); @@ -508,6 +534,8 @@ public: //check whether instance is outside the plate or not bool check_outside(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); + void clear_exclusion_volume_intersections(); + void invalidate_exclusion_volume_preview(); //judge whether instance is intesected with plate or not bool intersect_instance(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); @@ -713,6 +741,8 @@ public: for (std::vector>::iterator it = instances_outside.begin(); it != instances_outside.end(); ++it) instance_outside_set.insert(std::pair(it->first, it->second)); + + invalidate_exclusion_volume_preview(); } template void save(Archive& ar) const { std::vector> objects_and_instances; @@ -893,6 +923,8 @@ public: // Pantheon: update plates after moving plate to the front void update_plates(); + void invalidate_exclusion_volume_previews(); + void render_exclusion_volume_intersections(const Transform3d &view_matrix, const Transform3d &projection_matrix); /*basic plate operations*/ //create an empty plate and return its index @@ -1009,7 +1041,8 @@ public: //preprocess an arrangement::ArrangePolygon, return true if it is in a locked plate bool preprocess_arrange_polygon(int obj_index, int instance_index, arrangement::ArrangePolygon& arrange_polygon, bool selected); bool preprocess_arrange_polygon_other_locked(int obj_index, int instance_index, arrangement::ArrangePolygon& arrange_polygon, bool selected); - bool preprocess_exclude_areas(arrangement::ArrangePolygons& unselected, bool enable_wrapping_detect, int num_plates = 16, float inflation = 0); + bool preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, const DynamicPrintConfig &config, + bool enable_wrapping_detect, int num_plates = 16, float inflation = 0); bool preprocess_nonprefered_areas(arrangement::ArrangePolygons& regions, int num_plates = 1, float inflation=0); void postprocess_bed_index_for_selected(arrangement::ArrangePolygon& arrange_polygon); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index dd20492ce3..a7e3a9ca6d 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7830,7 +7830,8 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) , main_frame(main_frame) //BBS: add bed_exclude_area , config(Slic3r::DynamicPrintConfig::new_from_defaults_keys({ - "printable_area", "bed_exclude_area", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", + "printable_area", "bed_exclude_area", "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", "extruder_offset", + "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", "nozzle_height", "skirt_type", "skirt_loops", "skirt_speed","min_skirt_length", "skirt_distance", "skirt_start_angle", @@ -11037,10 +11038,68 @@ void Plater::priv::split_volume() wxGetApp().obj_list()->split(); } +// Boxes within bed that clear every rectangular exclusion zone: the rectangles spanned by bed and +// exclusion edges that overlap no exclusion. Slivers no wider than the bed padding are dropped. +static std::vector free_print_volumes(const BoundingBoxf3& bed, const std::vector& excludes) +{ + std::vector xs{ bed.min.x(), bed.max.x() }; + std::vector ys{ bed.min.y(), bed.max.y() }; + for (const BoundingBoxf3& ex : excludes) { + for (const double x : { ex.min.x(), ex.max.x() }) + if (x > bed.min.x() && x < bed.max.x()) + xs.push_back(x); + for (const double y : { ex.min.y(), ex.max.y() }) + if (y > bed.min.y() && y < bed.max.y()) + ys.push_back(y); + } + std::sort(xs.begin(), xs.end()); + std::sort(ys.begin(), ys.end()); + xs.erase(std::unique(xs.begin(), xs.end()), xs.end()); + ys.erase(std::unique(ys.begin(), ys.end()), ys.end()); + + const double min_size = 2. * Slic3r::BuildVolume::SceneEpsilon; + std::vector free_volumes; + for (size_t i = 0; i < xs.size(); ++i) + for (size_t j = i + 1; j < xs.size(); ++j) + for (size_t k = 0; k < ys.size(); ++k) + for (size_t l = k + 1; l < ys.size(); ++l) { + const double min_x = xs[i], max_x = xs[j], min_y = ys[k], max_y = ys[l]; + if (max_x - min_x <= min_size || max_y - min_y <= min_size) + continue; + + const bool blocked = std::any_of(excludes.begin(), excludes.end(), [&](const BoundingBoxf3& ex) { + return min_x < ex.max.x() && max_x > ex.min.x() && min_y < ex.max.y() && max_y > ex.min.y(); + }); + if (blocked) + continue; + + BoundingBoxf3 box = bed; + box.min.x() = min_x; + box.min.y() = min_y; + box.max.x() = max_x; + box.max.y() = max_y; + free_volumes.push_back(box); + } + return free_volumes; +} + void Plater::priv::scale_selection_to_fit_print_volume() { #if ENABLE_ENHANCED_PRINT_VOLUME_FIT - this->view3D->get_canvas3d()->get_selection().scale_to_fit_print_volume(this->bed.build_volume()); + const BuildVolume volume = this->bed.build_volume(); + // Every plate shares the bed size, but each sits at its own origin: fit onto the + // plate the selection is on instead of always onto the first one. + PartPlate* plate = this->partplate_list.get_curr_plate(); + const Vec3d bed_center = plate != nullptr ? plate->get_center_origin() : + Vec3d(volume.bed_center().x(), volume.bed_center().y(), 0.); + // On a multi-nozzle printer each nozzle reaches only part of the bed, so a model fitted + // to the bed can still exceed a nozzle's printable range. Fit into the volume every + // nozzle shares, which is also the area Arrange places items in, minus any exclusion zone. + const BoundingBoxf3 bed_box = plate != nullptr ? plate->get_build_volume(true) : volume.bounding_volume(); + std::vector print_volumes{ bed_box }; + if (plate != nullptr && !plate->get_exclude_areas().empty()) + print_volumes = free_print_volumes(bed_box, plate->get_exclude_areas()); + this->view3D->get_canvas3d()->get_selection().scale_to_fit_print_volume(volume, Vec2d(bed_center.x(), bed_center.y()), print_volumes); #else this->view3D->get_canvas3d()->get_selection().scale_to_fit_print_volume(*config); #endif // ENABLE_ENHANCED_PRINT_VOLUME_FIT @@ -19066,6 +19125,19 @@ bool Plater::is_view3D_shown() const { return p->is_view3D_shown(); } bool Plater::are_view3D_labels_shown() const { return p->are_view3D_labels_shown(); } void Plater::show_view3D_labels(bool show) { p->show_view3D_labels(show); } +bool Plater::are_collision_volumes_shown() const +{ + return wxGetApp().app_config->get_bool("show_collision_volumes"); +} + +void Plater::show_collision_volumes(bool show) +{ + wxGetApp().app_config->set_bool("show_collision_volumes", show); + p->partplate_list.invalidate_exclusion_volume_previews(); + p->view3D->get_canvas3d()->set_as_dirty(); + p->view3D->get_canvas3d()->request_extra_frame(); +} + bool Plater::is_view3D_overhang_shown() const { return p->is_view3D_overhang_shown(); } void Plater::show_view3D_overhang(bool show) { p->show_view3D_overhang(show); } @@ -21437,6 +21509,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) { bool update_scheduled = false; bool bed_shape_changed = false; + bool exclusion_preview_changed = false; bool imex_changed = false; //bool print_sequence_changed = false; t_config_option_keys diff_keys = p->config->diff(config); @@ -21455,6 +21528,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) if (update_filament_colors_in_full_config()) { p->sidebar->update_mixed_filament_list(); + p->partplate_list.invalidate_exclusion_volume_previews(); p->sidebar->obj_list()->update_filament_colors(); p->sidebar->update_dynamic_filament_list(); continue; @@ -21478,6 +21552,12 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } p->config->set_key_value(opt_key, config.option(opt_key)->clone()); + if (opt_key == "bed_exclude_volume_mode" || opt_key == "bed_exclude_area" || + opt_key == "bed_exclude_volumes" || opt_key == "extruder_bed_exclude_volumes" || opt_key == "extruder_offset" || + opt_key == "master_extruder_id" || opt_key == "nozzle_diameter" || + opt_key == "printable_height" || opt_key == "extruder_colour") + exclusion_preview_changed = true; + if (opt_key == "printer_technology") { this->set_printer_technology(config.opt_enum(opt_key)); // print technology is changed, so we should to update a search list @@ -21489,7 +21569,8 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->partplate_list.invalid_all_slice_result(); } //BBS: add bed_exclude_area - else if (opt_key == "printable_area" || opt_key == "bed_exclude_area" + else if (opt_key == "printable_area" || opt_key == "bed_exclude_volume_mode" || opt_key == "bed_exclude_area" + || opt_key == "bed_exclude_volumes" || opt_key == "extruder_bed_exclude_volumes" || opt_key == "extruder_offset" || opt_key == "bed_custom_texture" || opt_key == "bed_custom_model" || opt_key == "extruder_clearance_height_to_lid" || opt_key == "extruder_clearance_height_to_rod") { @@ -21511,6 +21592,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } else if(opt_key == "extruder_colour") { update_scheduled = true; + p->partplate_list.invalidate_exclusion_volume_previews(); //p->sidebar->obj_list()->update_extruder_colors(); } else if (opt_key == "printable_height") { @@ -21535,8 +21617,12 @@ void Plater::on_config_change(const DynamicPrintConfig &config) else if (opt_key == "support_interface_filament" || opt_key == "support_filament" || opt_key == "outer_wall_filament_id" || opt_key == "inner_wall_filament_id" || opt_key == "sparse_infill_filament_id" || opt_key == "internal_solid_filament_id" || - opt_key == "top_surface_filament_id" || opt_key == "bottom_surface_filament_id") { + opt_key == "top_surface_filament_id" || opt_key == "bottom_surface_filament_id" || + opt_key == "enable_support" || opt_key == "raft_layers" || opt_key == "wall_loops" || + opt_key == "sparse_infill_density" || opt_key == "top_shell_layers" || + opt_key == "bottom_shell_layers" || opt_key == "brim_type" || opt_key == "brim_width") { update_scheduled = true; + p->partplate_list.invalidate_exclusion_volume_previews(); } // IDEX/IQEX: when is_imex toggles the mode icon needs to be repositioned on every plate. // set_shape() short-circuits when the bed geometry is unchanged, so we refresh explicitly. @@ -21550,8 +21636,16 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->view3D->get_canvas3d()->set_as_dirty(); } - if (bed_shape_changed) + if (bed_shape_changed) { set_bed_shape(); + get_current_canvas3D()->requires_check_outside_state(); + } + + if (exclusion_preview_changed) + p->partplate_list.invalidate_exclusion_volume_previews(); + + if (bed_shape_changed || exclusion_preview_changed) + get_current_canvas3D()->request_extra_frame(); // After any bed-shape or is_imex change, ensure the IMEX mode icon geometry and // raycaster are correct. set_shape() short-circuits when the bed is unchanged, @@ -21632,9 +21726,10 @@ void Plater::set_bed_shape() const } } } + const ConfigOptionPoints *bed_exclude_area = p->config->option("bed_exclude_area"); set_bed_shape(p->config->option("printable_area")->values, //BBS: add bed exclude areas - p->config->option("bed_exclude_area")->values, + bed_exclude_area->values, p->config->option("wrapping_exclude_area")->values, p->config->option("printable_height")->value, p->config->option("extruder_printable_area")->values, @@ -21875,6 +21970,7 @@ void Plater::set_global_filament_map(const std::vector& filament_map) { auto& project_config = wxGetApp().preset_bundle->project_config; project_config.option("filament_map")->values = filament_map; + p->partplate_list.invalidate_exclusion_volume_previews(); } void Plater::set_global_filament_volume_map(const std::vector& filament_volume_map) @@ -22127,6 +22223,7 @@ void Plater::changed_mesh(int obj_idx) void Plater::changed_object(ModelObject &object){ assert(object.get_model() == &p->model); // is object from same model? object.invalidate_bounding_box(); + p->partplate_list.invalidate_exclusion_volume_previews(); // recenter and re - align to Z = 0 object.ensure_on_bed(p->printer_technology != ptSLA); @@ -22168,6 +22265,8 @@ void Plater::changed_objects(const std::vector& object_idxs) if (object_idxs.empty()) return; + p->partplate_list.invalidate_exclusion_volume_previews(); + for (size_t obj_idx : object_idxs) { if (obj_idx < p->model.objects.size()) { if (p->model.objects[obj_idx]->min_z() >= SINKING_Z_THRESHOLD) @@ -22356,7 +22455,9 @@ void Plater::clone_selection() dlg.ShowModal(); } -std::vector Plater::get_empty_cells(const Vec2f step) +std::vector Plater::get_empty_cells(const Vec2f step, + const std::vector &local_exclude_boxes, + bool include_plate_exclude_areas) { PartPlate* plate = wxGetApp().plater()->get_partplate_list().get_curr_plate(); BoundingBoxf3 build_volume = plate->get_build_volume(true); @@ -22365,11 +22466,18 @@ std::vector Plater::get_empty_cells(const Vec2f step) std::vector cells; auto min_x = step(0)/2;// start_point.x() - step(0) * int((start_point.x() - bbox.min.x()) / step(0)); auto min_y = step(1)/2;// start_point.y() - step(1) * int((start_point.y() - bbox.min.y()) / step(1)); - auto& exclude_box3s = plate->get_exclude_areas(); std::vector exclude_boxs; - for (auto& box : exclude_box3s) { - Vec2d vmin(box.min.x(), box.min.y()), vmax(box.max.x(), box.max.y()); - exclude_boxs.emplace_back(vmin, vmax); + if (include_plate_exclude_areas) { + const auto &exclude_box3s = plate->get_exclude_areas(); + for (const auto &box : exclude_box3s) { + Vec2d vmin(box.min.x(), box.min.y()), vmax(box.max.x(), box.max.y()); + exclude_boxs.emplace_back(vmin, vmax); + } + } + const Vec3d plate_origin = plate->get_origin(); + for (BoundingBoxf box : local_exclude_boxes) { + box.translate(Vec2d(plate_origin.x(), plate_origin.y())); + exclude_boxs.emplace_back(std::move(box)); } for (float x = min_x + bbox.min.x(); x < bbox.max.x() - step(0) / 2; x += step(0)) for (float y = min_y + bbox.min.y(); y < bbox.max.y() - step(1) / 2; y += step(1)) { diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index a879226b42..f00cdbacc8 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -505,6 +505,9 @@ public: bool are_view3D_labels_shown() const; void show_view3D_labels(bool show); + bool are_collision_volumes_shown() const; + void show_collision_volumes(bool show); + bool is_view3D_overhang_shown() const; void show_view3D_overhang(bool show); @@ -770,7 +773,9 @@ public: void split_volume(); void optimize_rotation(); // find all empty cells on the plate and won't overlap with exclusion areas - static std::vector get_empty_cells(const Vec2f step); + static std::vector get_empty_cells(const Vec2f step, + const std::vector &local_exclude_boxes = {}, + bool include_plate_exclude_areas = true); //BBS: void fill_color(int extruder_id); diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index 86ca31ba0f..0a7338e6b3 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -1158,10 +1158,7 @@ void PluginsDialog::run_script_plugin_capability(const std::string& plugin_key, { PluginManager& manager = PluginManager::instance(); - std::string error; - ExecutionResult result; - - auto complete_with_error = [this, &manager, &plugin_key](const std::string& plugin_error, const wxString& status_message) { + auto complete_with_error = [this, &manager, plugin_key](const std::string& plugin_error, const wxString& status_message) { const std::string normalized_error = plugin_error.empty() ? _u8L("Script plugin failed.") : plugin_error; if (!manager.set_plugin_error(plugin_key, normalized_error)) BOOST_LOG_TRIVIAL(warning) << "Failed to record plugin error. plugin_key=" << plugin_key; @@ -1177,32 +1174,53 @@ void PluginsDialog::run_script_plugin_capability(const std::string& plugin_key, show_status(message, "error"); }; + // Always runs on the GUI thread. For a started invocation (sync `def execute` or `async def`) + // the runtime delivers it later; it is called inline here only when the launch itself failed. + auto finish = [this, alive = m_alive, plugin_key, &manager, complete_with_error](const ScriptCompletion& completion) { + if (!alive->load()) + return; + + // Cancelled by PluginManager (unload/shutdown): expected termination. Report neither an + // error nor a normal success, and do not touch the plugin's error/state. + if (completion.cancelled) + return; + + if (!completion.error.empty()) { + complete_with_error(completion.error, wxString()); + return; + } + + const ExecutionResult& result = completion.result; + + BOOST_LOG_TRIVIAL(info) << "Script plugin execution completed. plugin_key=" << plugin_key + << " status=" << static_cast(result.status) << " message=" << result.message + << " data=" << result.data; + + const bool failed = result.status == PluginResult::RecoverableError || result.status == PluginResult::FatalError; + if (failed) { + complete_with_error(result.message, wxString()); + return; + } + + manager.clear_plugin_error(plugin_key); + send_plugins(); + + const bool skipped = result.status == PluginResult::Skipped; + const wxString fallback = skipped ? _L("Script plugin skipped.") : _L("Script plugin finished."); + const wxString message = result.message.empty() ? fallback : from_u8(result.message); + show_status(message, skipped ? "info" : "success"); + }; + + PluginManager::ScriptLaunchResult launch; { wxBusyCursor busy; - result = manager.run_script_capability(plugin_key, capability_name, error); + launch = manager.launch_script_capability(plugin_key, capability_name, finish); } - if (!error.empty()) { - complete_with_error(error, wxString()); - return; - } - - BOOST_LOG_TRIVIAL(info) << "Script plugin execution completed. plugin_key=" << plugin_key - << " status=" << static_cast(result.status) << " message=" << result.message << " data=" << result.data; - - const bool failed = result.status == PluginResult::RecoverableError || result.status == PluginResult::FatalError || !error.empty(); - if (failed) { - complete_with_error(result.message, wxString()); - return; - } - - manager.clear_plugin_error(plugin_key); - send_plugins(); - - const bool skipped = result.status == PluginResult::Skipped; - const wxString fallback = skipped ? _L("Script plugin skipped.") : _L("Script plugin finished."); - const wxString message = result.message.empty() ? fallback : from_u8(result.message); - show_status(message, skipped ? "info" : "success"); + // Every started invocation — a synchronous `def execute` included — completes later through + // `finish`; only a launch failure is reported inline. Return without blocking. + if (!launch.launched_async) + finish(launch.outcome); } void PluginsDialog::update_plugin(const std::string& plugin_key) diff --git a/src/slic3r/GUI/PrinterWebView.cpp b/src/slic3r/GUI/PrinterWebView.cpp index e3c1202b5a..c27ddc62d4 100644 --- a/src/slic3r/GUI/PrinterWebView.cpp +++ b/src/slic3r/GUI/PrinterWebView.cpp @@ -1,31 +1,38 @@ #include "PrinterWebView.hpp" #include "PrinterWebViewHandler.hpp" +#include "I18N.hpp" + #include "slic3r/GUI/PrinterWebView.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/MainFrame.hpp" -#include "libslic3r_version.h" +#include +#include +#include "libslic3r_version.h" +#include +#include "libslic3r/Utils.hpp" +#include "libslic3r/Config.hpp" +#include "libslic3r/PresetBundle.hpp" + +#include #include -#include + +#include + +#include #include #include -#include #include -#include "libslic3r/Utils.hpp" -#include -#include #include #include #include - -#include -#include -#include "I18N.hpp" -#include #include #include +#include +#include + class wxWindow; #ifdef __linux__ @@ -203,16 +210,32 @@ void PrinterWebView::reset_browser() // OnLoaded may have cleared m_url_deferred already, so requeue the last url for Show(). m_apikey_sent = false; + m_url_loaded = false; m_url_deferred = m_url; } +// Same lookup as create_printer_webview_handler(). +static PrintHostType active_host_type() +{ + if (wxGetApp().preset_bundle == nullptr) + return htOctoPrint; + return wxGetApp().preset_bundle->printers.get_edited_preset().config.option>("host_type")->value; +} + void PrinterWebView::load_url(wxString& url, wxString apikey) { // this->Show(); // this->Raise(); + const PrintHostType host_type = active_host_type(); + // Selecting the tab requests the same page again; navigating would reload it and drop its state. + if (m_url_loaded && url == m_url && apikey == m_apikey && host_type == m_host_type) + return; + m_url = url; m_apikey = apikey; + m_host_type = host_type; m_apikey_sent = false; + m_url_loaded = false; m_handler = create_printer_webview_handler(*this); if (this->IsShown()) { @@ -337,6 +360,7 @@ void PrinterWebView::OnLoaded(wxWebViewEvent& evt) return; //ORCA: url loaded successfully, safe to clear m_url_deferred.clear(); + m_url_loaded = true; SendAPIKey(); if (m_handler != nullptr) { diff --git a/src/slic3r/GUI/PrinterWebView.hpp b/src/slic3r/GUI/PrinterWebView.hpp index 53c4f30557..01ee229baa 100644 --- a/src/slic3r/GUI/PrinterWebView.hpp +++ b/src/slic3r/GUI/PrinterWebView.hpp @@ -29,6 +29,7 @@ #include #include #include "Lazy.hpp" +#include "libslic3r/PrintConfig.hpp" namespace Slic3r { @@ -68,6 +69,10 @@ private: // Last url passed to load_url(), reloaded after reset_browser(). wxString m_url; wxString m_url_deferred; + // Host type the page was loaded for; it selects the handler, so a change needs a reload. + PrintHostType m_host_type{htOctoPrint}; + // True once the page for m_url has finished loading in m_browser. + bool m_url_loaded{false}; std::unique_ptr m_handler; bool m_reset_on_show{false}; diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index e9c91bc337..a6e6d96dc3 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -17,6 +17,7 @@ #include "libslic3r/Color.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/Geometry.hpp" +#include "libslic3r/LayOnFace.hpp" #include "slic3r/GUI/GLModel.hpp" #include #include @@ -1455,11 +1456,9 @@ void Selection::flattening_rotate(const Vec3d& normal) for (unsigned int i : m_list) { GLVolume& v = *(*m_volumes)[i]; - // Normal transformed from the object coordinate space to the world coordinate space. + // Additional rotation to align the face normal with the down vector in the world coordinate space. const Geometry::Transformation& old_inst_trafo = v.get_instance_transformation(); - const Vec3d tnormal = old_inst_trafo.get_matrix().matrix().block(0, 0, 3, 3).inverse().transpose() * normal; - // Additional rotation to align tnormal with the down vector in the world coordinate space. - const Transform3d rotation_matrix = Transform3d(Eigen::Quaterniond().setFromTwoVectors(tnormal, -Vec3d::UnitZ())); + const Transform3d rotation_matrix = lay_on_face_rotation(normal, old_inst_trafo.get_matrix_no_offset()); v.set_instance_transformation(old_inst_trafo.get_offset_matrix() * rotation_matrix * old_inst_trafo.get_matrix_no_offset()); } @@ -1479,7 +1478,7 @@ void Selection::scale(const Vec3d& scale, TransformationType transformation_type } #if ENABLE_ENHANCED_PRINT_VOLUME_FIT -void Selection::scale_to_fit_print_volume(const BuildVolume& volume) +void Selection::scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d& bed_center, const std::vector& print_volumes) { auto fit = [this](double s, Vec3d offset) { if (s <= 0.0 || s == 1.0) @@ -1509,22 +1508,30 @@ void Selection::scale_to_fit_print_volume(const BuildVolume& volume) //wxGetApp().obj_manipul()->set_dirty(); }; - auto fit_rectangle = [this, fit](const BuildVolume& volume) { - const BoundingBoxf3 print_volume = volume.bounding_volume(); - const Vec3d print_volume_size = print_volume.size(); - + auto fit_rectangle = [this, fit, &print_volumes]() { // adds 1/100th of a mm on all sides to avoid false out of print volume detections due to floating-point roundings const Vec3d box_size = get_bounding_box().size() + 0.02 * Vec3d::Ones(); - const double sx = (box_size.x() != 0.0) ? print_volume_size.x() / box_size.x() : 0.0; - const double sy = (box_size.y() != 0.0) ? print_volume_size.y() / box_size.y() : 0.0; - const double sz = (box_size.z() != 0.0) ? print_volume_size.z() / box_size.z() : 0.0; + double best_s = 0.0; + const BoundingBoxf3* best = nullptr; + for (const BoundingBoxf3& print_volume : print_volumes) { + const Vec3d print_volume_size = print_volume.size(); - if (sx != 0.0 && sy != 0.0 && sz != 0.0) - fit(std::min(sx, std::min(sy, sz)), print_volume.center() - get_bounding_box().center()); + const double sx = (box_size.x() != 0.0) ? print_volume_size.x() / box_size.x() : 0.0; + const double sy = (box_size.y() != 0.0) ? print_volume_size.y() / box_size.y() : 0.0; + const double sz = (box_size.z() != 0.0) ? print_volume_size.z() / box_size.z() : 0.0; + + if (sx != 0.0 && sy != 0.0 && sz != 0.0 && std::min(sx, std::min(sy, sz)) > best_s) { + best_s = std::min(sx, std::min(sy, sz)); + best = &print_volume; + } + } + + if (best != nullptr) + fit(best_s, best->center() - get_bounding_box().center()); }; - auto fit_circle = [this, fit](const BuildVolume& volume) { + auto fit_circle = [this, fit, &bed_center](const BuildVolume& volume) { const Geometry::Circled& print_circle = volume.circle(); double print_circle_radius = unscale(print_circle.radius); @@ -1555,7 +1562,9 @@ void Selection::scale_to_fit_print_volume(const BuildVolume& volume) const double s = std::min(print_circle_radius / circle_radius, volume.printable_height() / max_z); const Vec3d sel_center = get_bounding_box().center(); const Vec3d offset = s * (Vec3d(unscale(circle.center.x()), unscale(circle.center.y()), 0.5 * max_z) - sel_center); - const Vec3d print_center = { unscale(print_circle.center.x()), unscale(print_circle.center.y()), 0.5 * volume.printable_height() }; + // The active plate's bed is the same circle, moved by its centre. + const Vec3d plate_shift = Vec3d(bed_center.x() - volume.bed_center().x(), bed_center.y() - volume.bed_center().y(), 0.); + const Vec3d print_center = Vec3d(unscale(print_circle.center.x()), unscale(print_circle.center.y()), 0.5 * volume.printable_height()) + plate_shift; fit(s, print_center - (sel_center + offset)); }; @@ -1564,7 +1573,7 @@ void Selection::scale_to_fit_print_volume(const BuildVolume& volume) switch (volume.type()) { - case BuildVolume_Type::Rectangle: { fit_rectangle(volume); break; } + case BuildVolume_Type::Rectangle: { fit_rectangle(); break; } case BuildVolume_Type::Circle: { fit_circle(volume); break; } default: { break; } } diff --git a/src/slic3r/GUI/Selection.hpp b/src/slic3r/GUI/Selection.hpp index a02f01da00..e35b71677f 100644 --- a/src/slic3r/GUI/Selection.hpp +++ b/src/slic3r/GUI/Selection.hpp @@ -354,7 +354,11 @@ public: void flattening_rotate(const Vec3d& normal); void scale(const Vec3d& scale, TransformationType transformation_type); #if ENABLE_ENHANCED_PRINT_VOLUME_FIT - void scale_to_fit_print_volume(const BuildVolume& volume); + // bed_center is the centre of the plate the selection is on: every plate shares the + // bed size, but each sits at its own origin. print_volumes are the candidate boxes the + // selection may be fitted into (e.g. the bed minus rectangular exclusion zones); the one + // allowing the largest scale is used. + void scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d& bed_center, const std::vector& print_volumes); #else void scale_to_fit_print_volume(const DynamicPrintConfig& config); #endif // ENABLE_ENHANCED_PRINT_VOLUME_FIT @@ -392,6 +396,11 @@ public: render_bounding_box(box, Transform3d::Identity(), get_auto_drop(), color); } + void render_bounding_box(const BoundingBoxf3& box, const Transform3d& trafo, const ColorRGB& color, float scale) { + m_scale_factor = scale; + render_bounding_box(box, trafo, get_auto_drop(), color); + } + //BBS void cut_to_clipboard(); void copy_to_clipboard(); diff --git a/src/slic3r/GUI/Shortcuts.cpp b/src/slic3r/GUI/Shortcuts.cpp index b3809ade38..03fc6937b8 100644 --- a/src/slic3r/GUI/Shortcuts.cpp +++ b/src/slic3r/GUI/Shortcuts.cpp @@ -147,6 +147,7 @@ constexpr std::array shortcut_table = {{ // Display SHORTCUT(ShowLabels, "show_labels", L("Show object labels in 3D scene."), GLOBAL, { 'E', CTRL }), + SHORTCUT(ShowCollisionVolumes, "show_collision_volumes", L("Show all collision volumes"), GLOBAL, { 'K', CTRL_SHIFT }), SHORTCUT(ShowWireframe, "show_wireframe", L("Show/Hide wireframe"), CANVAS, { WXK_RETURN, CTRL_SHIFT }), SHORTCUT(ToggleGcodeWindow, "toggle_gcode_window", L("On/Off G-code window"), PREVIEW, { 'C' }), SHORTCUT(ToggleOneLayerMode, "toggle_one_layer_mode", L("On/Off one layer mode of the vertical slider"), PREVIEW, { 'L' }), diff --git a/src/slic3r/GUI/Shortcuts.hpp b/src/slic3r/GUI/Shortcuts.hpp index 50652af000..ddc9a7ed8d 100644 --- a/src/slic3r/GUI/Shortcuts.hpp +++ b/src/slic3r/GUI/Shortcuts.hpp @@ -46,7 +46,7 @@ enum class Shortcut : uint8_t { // Camera ViewDefault, ViewTop, ViewBottom, ViewFront, ViewRear, ViewLeft, ViewRight, ViewPlate, ZoomIn, ZoomOut, Mouse3DSettings, // Display - ShowLabels, ShowWireframe, ToggleGcodeWindow, ToggleOneLayerMode, ToggleBeltRawGcode, + ShowLabels, ShowCollisionVolumes, ShowWireframe, ToggleGcodeWindow, ToggleOneLayerMode, ToggleBeltRawGcode, // Application Preferences, Search, SwitchView, CollapseSidebar, ReloadDevicePage, KeyboardShortcuts, Quit, // Speed Dial diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 00fd72e57f..31aa897f2e 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -46,6 +46,7 @@ #include "slic3r/GUI/DeviceCore/DevConfigUtil.h" #include #include +#include #include "libslic3r/LifecycleEvents.hpp" #include "libslic3r/Point.hpp" #include "slic3r/GUI/SettingsIndex.hpp" @@ -81,6 +82,7 @@ #include "wxExtensions.hpp" #include "PresetComboBoxes.hpp" #include +#include #include "GUI_App.hpp" #include "GUI_ObjectList.hpp" @@ -1645,6 +1647,138 @@ void Tab::load_config(const DynamicPrintConfig& config) } } +// The option keys a preset of `type` may hold. The tab's config shares the global +// print_config_def with every other preset type, so membership has to be checked against the +// preset type's own key list instead of the config definition, or a printer setting could be +// written into the process preset. +static const std::vector& preset_type_options(Preset::Type type) +{ + static const std::vector none; + switch (type) { + case Preset::TYPE_PRINT: return Preset::print_options(); + case Preset::TYPE_FILAMENT: return Preset::filament_options(); + case Preset::TYPE_PRINTER: return Preset::printer_options(); + default: return none; + } +} + +static const char* preset_type_name(Preset::Type type) +{ + switch (type) { + case Preset::TYPE_PRINT: return "process"; + case Preset::TYPE_FILAMENT: return "filament"; + case Preset::TYPE_PRINTER: return "printer"; + default: return "preset"; + } +} + +// Commit one option whose new value already sits in m_config through the same path a hand edit +// runs. The key-specific behaviour (ConfigOptionsGroup::on_change_OG, including the printer_agent +// canonicalization, the group's pre-checks and Tab::on_value_change()) runs exactly as for a hand +// edit. A built field supplies the field's typed/clamped value; otherwise the owning +// ConfigOptionsGroup builds the value from the config it edits and dispatches the same +// on_change_OG(). The option's page is reloaded from the config just committed first, so a built +// field reports the committed value rather than a stale one. No tab-wide refresh happens here: the +// caller does it once for the whole batch. +bool Tab::commit_preset_config_value(const std::string& opt_key) +{ + if (Page* field_page = nullptr; Field* field = get_field(opt_key, &field_page)) { + field_page->reload_config(); + field->field_changed(); + return true; + } + for (const PageShp& page : m_pages) + for (const ConfigOptionsGroupShp& group : page->m_optgroups) + if (group->commit_config_value(opt_key)) + return true; + return false; +} + +// Set one option of the currently edited preset from its serialized string form, then run the +// same update path a hand edit runs. The edited preset is not saved: it only becomes dirty, +// exactly as if the field had been edited by hand. +void Tab::apply_preset_config_value(const std::string& opt_key, const std::string& value) +{ + apply_preset_config_values({{opt_key, value}}); +} + +// Apply a batch of settings as one transaction: parse and validate the whole batch first, then +// commit it through the same per-setting path apply_preset_config_value() uses, restoring the edited +// preset and the state derived from it if a setting fails. See the header for the contract and its +// limits. +void Tab::apply_preset_config_values(const std::vector>& values) +{ + if (m_config == nullptr) + throw std::runtime_error("The preset configuration is not available"); + if (wxGetApp().plater() == nullptr) + throw std::runtime_error("OrcaSlicer main window is not available"); + + if (values.empty()) + return; + + const std::vector& options = preset_type_options(m_type); + + // Preparation: reject every batch that cannot be applied before touching the edited preset, so a + // bad key or value fails without a partial write. The key must belong to this preset type, it must + // not repeat, and each value is strict-parsed into a scratch copy (the strict deserializer can + // already have mutated an option when it rejects a bad value, so the check has to run somewhere + // the edited preset is not affected). Callback failures cannot be prepared this way: a setting's + // on_change callback is a GUI method, not a pure function of the config, so whether it throws is + // only known by running it. That residual case is handled by the rollback below. + std::set seen; + DynamicPrintConfig scratch(*m_config); + for (const auto& kv : values) { + const std::string& opt_key = kv.first; + if (std::find(options.begin(), options.end(), opt_key) == options.end()) + throw std::invalid_argument(format("Unknown %1% preset setting \"%2%\"", preset_type_name(m_type), opt_key)); + if (!seen.insert(opt_key).second) + throw std::invalid_argument(format("%1% preset setting \"%2%\" is set more than once in the same update", + preset_type_name(m_type), opt_key)); + try { + scratch.set_deserialize_strict(opt_key, kv.second); + } catch (const ConfigurationError& err) { + throw std::invalid_argument(err.what()); + } + } + + // Rollback boundary: snapshot the whole edited config, not just the keys the batch names, because a + // key-specific callback can adjust related settings of the edited preset (mutually exclusive + // options, compatibility, and so on). A failure restores this config and then recomputes the state + // derived from it. + DynamicPrintConfig before(*m_config); + try { + for (const auto& kv : values) { + m_config->set_deserialize_strict(kv.first, kv.second); + if (!commit_preset_config_value(kv.first)) + // The GUI edits this setting through a custom widget rather than a group (e.g. + // compatible_printers), so take the same shared no-field commit path the widget uses. + // The value was written above, so saved mode skips the write and keeps the path's + // compatibility recompute, dirty flag, preset-combo and plater updates. + load_key_value(kv.first, boost::any(), /*saved_value=*/true); + } + } catch (...) { + *m_config = before; + // A callback can rewrite state derived from the config (compatibility marks, the preset + // selector, dependent tabs, the Plater and, on the printer tab, the printer agent) before it + // throws. Recompute that derived state from the restored config so none of it is left + // reflecting the failed batch. Effects that are not a function of the config (a dialog the + // user already accepted, an undo snapshot, a command already sent to a device, the target + // selection) cannot be reversed here; see the header. + m_preset_bundle->update_compatible(PresetSelectCompatibleType::Never); + reload_config(); + update_dirty(); + update(); + throw; + } + + // Apply the batch's final state once. The commit paths above already maintained the dirty flag, + // preset combo and, on the printer tab, the printer-agent switch; this reloads the visible page + // and pushes the config to the Plater. + reload_config(); + update_dirty(); + update(); +} + // Reload current $self->{config} (aka $self->{presets}->edited_preset->config) into the UI fields. void Tab::reload_config() { @@ -1944,6 +2078,36 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) return; } + // The bed-area point option cannot store collision-volume syntax. Offer to + // copy it to the volume setting while retaining the area's previous value. + if (opt_key == "bed_exclude_area" && m_type == Preset::TYPE_PRINTER) { + const std::string *definition = boost::any_cast(&value); + if (definition != nullptr && is_bed_exclusion_volume_syntax(*definition)) { + const double printable_height = m_config->opt_float("printable_height"); + if (!is_valid_bed_exclude_volumes_string(*definition, printable_height)) { + show_error(wxGetApp().plater(), _L("Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + reload_config(); + return; + } + + MessageDialog dialog( + wxGetApp().plater(), + _L("This definition contains collision-volume syntax. Add it to the toolhead collision volumes for G-code checking and travel avoidance? The existing excluded bed area will be preserved."), + _L("Add collision volumes"), wxICON_QUESTION | wxYES | wxNO); + if (dialog.ShowModal() == wxID_YES) { + DynamicPrintConfig converted = *m_config; + append_bed_exclude_volumes(converted, *definition); + load_config(converted); + reload_config(); + on_presets_changed(); + wxGetApp().plater()->update(); + } else { + reload_config(); + } + return; + } + } + // Keep this preset's "plugins" manifest in sync when a plugin picker changes, so full_config() and // save_to_json() always find resolved "name;uuid;capability" references and rebuild it nowhere else. // Also drop any plugin config override entries for a capability the change just stopped @@ -1966,6 +2130,25 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) printer_tab->on_gcode_flavor_changed(); } + if (opt_key == "bed_exclude_volume_mode" && m_type == Preset::TYPE_PRINTER && + m_config->opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder) { + auto *per_extruder = m_config->option("extruder_bed_exclude_volumes"); + const auto *shared = m_config->option("bed_exclude_volumes"); + const size_t extruder_count = m_config->option("nozzle_diameter")->size(); + const bool definitions_empty = per_extruder == nullptr || + std::all_of(per_extruder->values.begin(), per_extruder->values.end(), [](const std::string &entry) { return entry.empty(); }); + + if (definitions_empty && shared != nullptr && extruder_count > 0) { + const std::string serialized = shared->value; + const bool valid_shared_definition = + is_valid_bed_exclude_volumes_string(serialized, std::numeric_limits::max()); + DynamicPrintConfig new_conf = *m_config; + new_conf.set_key_value("extruder_bed_exclude_volumes", + new ConfigOptionStrings(std::vector(extruder_count, valid_shared_definition ? serialized : std::string{}))); + m_config_manipulation.apply(m_config, &new_conf); + } + } + if (opt_key == "compatible_prints") this->compatible_widget_reload(m_compatible_prints); if (opt_key == "compatible_printers") @@ -5250,11 +5433,15 @@ void TabPrinter::build_fff() Option option = optgroup->get_option("bed_exclude_area"); option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_basic_information_printable_space#excluded-bed-area"); - // optgroup->append_single_option_line("printable_area"); + + option = optgroup->get_option("bed_exclude_volumes"); + option.opt.full_width = true; + optgroup->append_single_option_line(option, "printer_basic_information_printable_space#toolhead-collision-volumes"); + optgroup->append_single_option_line("bed_exclude_volume_mode", "printer_basic_information_printable_space#toolhead-collision-volumes"); + optgroup->append_single_option_line("printable_height", "printer_basic_information_printable_space#printable-height"); - optgroup->append_single_option_line("support_multi_bed_types","printer_basic_information_printable_space#support-multi-bed-types"); + optgroup->append_single_option_line("support_multi_bed_types", "printer_basic_information_printable_space#support-multi-bed-types"); optgroup->append_single_option_line("best_object_pos", "printer_basic_information_printable_space#best-object-position"); - // todo: for multi_extruder test optgroup->append_single_option_line("z_offset", "printer_basic_information_printable_space#z-offset"); optgroup->append_single_option_line("preferred_orientation", "printer_basic_information_printable_space#preferred-orientation"); @@ -6068,6 +6255,10 @@ if (is_marlin_flavor) option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_extruder_basic_information#extruder-printable-area"); + Option exclusion_option = optgroup->get_option("extruder_bed_exclude_volumes", extruder_idx); + exclusion_option.opt.full_width = true; + optgroup->append_single_option_line(exclusion_option, "printer_basic_information_printable_space#toolhead-collision-volumes"); + optgroup->m_on_change = [this](const t_config_option_key& opt_key, boost::any value) { // The page edits the extruder selected on the variant switch. @@ -6549,6 +6740,16 @@ void TabPrinter::toggle_options() const bool support_parallel_printheads = printer_cfg.opt_bool("support_parallel_printheads"); toggle_line("parallel_printheads_count", support_parallel_printheads); + const size_t exclusion_extruder_count = m_preset_bundle->get_printer_extruder_count(); + // UI visibility follows the selected mode even before any volumes are + // entered. The runtime resolver still ignores empty configurations. + const BedExcludeVolumeMode exclusion_mode = m_config->opt_enum("bed_exclude_volume_mode"); + // Legacy areas and collision volumes are additive. Keep the established + // material keep-out editable while the opt-in motion constraints exist. + toggle_option("bed_exclude_area", true); + toggle_line("bed_exclude_volume_mode", exclusion_extruder_count > 1); + toggle_line("bed_exclude_volumes", exclusion_extruder_count <= 1 || exclusion_mode != BedExcludeVolumeMode::PerExtruder); + toggle_line("fan_direction", m_config->opt_bool("auxiliary_fan")); // The cooling filter and air filtration are alternative accessories: show only the one the printer supports. @@ -6665,6 +6866,9 @@ void TabPrinter::toggle_options() toggle_option("extruder_printable_area", false, i); // disable toggle_line("extruder_printable_area", m_preset_bundle->get_printer_extruder_count() == 2, i); //hide + const bool per_extruder_exclusions = + m_config->opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder; + toggle_line("extruder_bed_exclude_volumes", m_preset_bundle->get_printer_extruder_count() > 1 && per_extruder_exclusions, i); toggle_option("extruder_printable_height", false, i); toggle_line("extruder_printable_height", m_preset_bundle->get_printer_extruder_count() == 2, i); diff --git a/src/slic3r/GUI/Tab.hpp b/src/slic3r/GUI/Tab.hpp index 44ef0704a3..89e3ce0960 100644 --- a/src/slic3r/GUI/Tab.hpp +++ b/src/slic3r/GUI/Tab.hpp @@ -424,6 +424,40 @@ public: //BBS update plater presets if update_plater_presets = true void update_tab_ui(bool update_plater_presets = false); void load_config(const DynamicPrintConfig& config); + // Host/plugin API: set one option of this tab's currently edited preset from its serialized + // string value, then run the same committed-change path a field edit runs. `opt_key` must be a + // setting of this tab's preset type, so a key of another preset type (e.g. a printer setting + // passed to the process tab) is rejected instead of written silently. `value` is parsed by the + // strict config deserializer, which raises std::invalid_argument for an unknown key or a value + // the option cannot parse, and leaves the preset unchanged. The key-specific behaviour runs + // through its ConfigOptionsGroup::on_change_OG(): with the option's built field it uses the + // field's typed value, otherwise the owning group builds the value and dispatches the same call, + // so a not-yet-built field still gets it. A key the GUI edits through a custom widget instead + // takes the shared no-field commit path, Tab::load_key_value() in saved mode. + void apply_preset_config_value(const std::string& opt_key, const std::string& value); + + // Host/plugin API: apply a batch of settings to this tab's currently edited preset as one + // transaction. Each pair is a setting of this tab's preset type and its serialized string value. + // The whole batch is parsed and validated before the edited preset is touched; each setting then + // runs the same committed-change path apply_preset_config_value() uses, so setting-specific + // validation, correction and on_change callbacks stay authoritative. Duplicate keys are rejected, + // because the transaction must not resolve an incidental write order, and the batch order is + // preserved. If applying the batch fails, the edited preset's config is restored to its pre-batch + // state and the state derived from it (compatibility marks, the preset selector, dependent tabs, + // the Plater and the printer agent) is recomputed, so the edited preset never keeps a subset of + // the staged settings. + // + // Only the edited preset is restored. A setting's on_change callback is a GUI method, not a pure + // function of the config, so effects outside the edited preset cannot be prepared or undone: the + // transaction does not reverse preset/slot selection made while resolving the target, a dialog + // decision the user already accepted, an undo snapshot, a dependent preset's rewritten config, or + // anything already sent to a device. Exact all-or-nothing across those is not achievable while the + // authoritative GUI callbacks run; this method guarantees the edited preset's own settings, not + // those external effects. + // + // Throws std::invalid_argument for an unknown key, a value the option cannot parse, or a duplicate + // key; std::runtime_error when the preset or main window is unavailable. + void apply_preset_config_values(const std::vector>& values); virtual void reload_config(); void update_mode(); void update_visibility(); @@ -507,6 +541,12 @@ protected: wxSizer* compatible_widget_create(wxWindow* parent, PresetDependencies &deps); void compatible_widget_reload(PresetDependencies &deps); void load_key_value(const std::string& opt_key, const boost::any& value, bool saved_value = false); + // Commit one option whose new value already sits in m_config through the same path a field edit + // runs (throwing field, otherwise the owning group's on_change_OG()). Reloads the option's page + // so a built field reports the committed value, but performs no tab-wide refresh. Returns true + // when a built field or a group owns the option, false when the GUI edits it through a custom + // widget with no group entry. + bool commit_preset_config_value(const std::string& opt_key); //BBS: GUI refactor // return true if cancelled diff --git a/src/slic3r/GUI/TextureImportDialog.cpp b/src/slic3r/GUI/TextureImportDialog.cpp index 8e83f0302a..cee0b5fe5b 100644 --- a/src/slic3r/GUI/TextureImportDialog.cpp +++ b/src/slic3r/GUI/TextureImportDialog.cpp @@ -32,6 +32,8 @@ #include "slic3r/GUI/GUI_Utils.hpp" #include "libslic3r/TexturePainting.hpp" #include "slic3r/GUI/Widgets/SpinInput.hpp" +#include +#include #include "libslic3r/TriangleMesh.hpp" #include #include @@ -101,34 +103,6 @@ static wxColour texture_import_separator_colour() return StateColor::darkModeColorFor(wxColour(SEPARATOR_COLOUR_KEY)); } -// Orca's confirm palette, applied here rather than through Button::SetStyle because these buttons -// keep custom pill geometry that SetStyle resets. The Disabled entries are load-bearing: without -// one, StateColor::colorForStates falls through to the Normal entry and a disabled button paints -// as a live accent button. -static void apply_accent_button_colours(Button* btn) -{ - btn->SetBackgroundColor(StateColor( - std::pair(wxColour("#CECECE"), StateColor::Disabled), - std::pair(wxColour(0, 137, 123), StateColor::Pressed), - std::pair(wxColour(38, 166, 154), StateColor::Hovered), - std::pair(wxColour(0, 150, 136), StateColor::Normal))); - btn->SetBorderColor(StateColor( - std::pair(wxColour("#CECECE"), StateColor::Disabled), - std::pair(wxColour(0, 150, 136), StateColor::Normal))); - btn->SetTextColor(StateColor( - std::pair(wxColour("#6B6B6A"), StateColor::Disabled), - std::pair(wxColour("#FFFFFE"), StateColor::Normal))); -} - -// The same button while the parameters behind it are dirty: still clickable, but reading as -// "what you see is not what this button would apply". -static void apply_muted_button_colours(Button* btn) -{ - btn->SetBackgroundColor(wxColour("#CECECE")); - btn->SetBorderColor(wxColour("#CECECE")); - btn->SetTextColor(wxColour("#6B6B6A")); -} - static wxFont texture_import_section_title_font(wxWindow* win) { wxFont font = win ? win->GetFont() : wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); @@ -327,7 +301,7 @@ void AccentSlider::OnPaint(wxPaintEvent&) int ts = FromDIP(8); int pen_w = FromDIP(2); - wxColour accent_clr = StateColor::darkModeColorFor(IsEnabled() ? wxColour("#009688") : wxColour("#ACACAC")); + wxColour accent_clr = IsEnabled() ? wxColour("#009688") : StateColor::darkModeColorFor(wxColour("#ACACAC")); // use original accent color here to make it more readable wxColour track_clr = StateColor::darkModeColorFor(IsEnabled() ? wxColour("#CECECE") : wxColour("#DFDFDF")); int tx = xFromValue(); @@ -547,6 +521,14 @@ public: wxColour pop_bg = StateColor::darkModeColorFor(*wxWHITE); SetBackgroundColour(pop_bg); + // ORCA add border for popups. it required to add this controls because it covers all background + Bind(wxEVT_PAINT, [this](wxPaintEvent& evt) { + wxPaintDC dc(this); + dc.SetPen(wxPen(StateColor::darkModeColorFor(wxColour("#DBDBDB")), FromDIP(1))); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + dc.DrawRoundedRectangle(0, 0, GetSize().x, GetSize().y, 0); + }); + m_content = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL); m_content->SetBackgroundColour(pop_bg); m_content->SetScrollRate(0, FromDIP(20)); @@ -556,7 +538,7 @@ public: const int row_h = FromDIP(32); const int pad = FromDIP(8); const int max_visible_rows = 10; - const wxColour header_clr = StateColor::darkModeColorFor(wxColour("#ACACAC")); + const wxColour header_clr = StateColor::darkModeColorFor(wxColour("#363636")); auto add_section_header = [&](const wxString& label) { auto* hdr = new wxStaticText(m_content, wxID_ANY, label); @@ -567,7 +549,7 @@ public: outer->Add(hdr, 0, wxLEFT | wxRIGHT | wxTOP, pad); auto* line = new StaticLine(m_content); line->SetLineColour(wxColour(SEPARATOR_COLOUR_KEY)); - outer->Add(line, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP | wxBOTTOM, pad); + outer->Add(line, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, pad); }; auto add_section = [&](const wxString& label, TextureFilamentKind kind) { @@ -605,7 +587,7 @@ public: add_label->SetFont(af); decompose_label->SetFont(af); const bool add_enabled = !m_can_add_filament || m_can_add_filament(); - const wxColour action_clr = StateColor::darkModeColorFor(wxColour("#009688")); + const wxColour action_clr = wxColour("#009688"); add_label->SetForegroundColour(add_enabled ? action_clr : header_clr); decompose_label->SetForegroundColour(add_enabled ? action_clr : header_clr); add_label->SetCursor(wxCursor(add_enabled ? wxCURSOR_HAND : wxCURSOR_ARROW)); @@ -659,7 +641,7 @@ public: list_h -= ((int)m_colors_rgba.size() - max_visible_rows) * row_h; m_content->SetMinSize(wxSize(pop_w, list_h)); m_content->SetMaxSize(wxSize(pop_w, list_h)); - top_sizer->Add(m_content, 0, wxEXPAND); + top_sizer->Add(m_content, 0, wxEXPAND | wxALL, FromDIP(1)); top_sizer->AddSpacer(FromDIP(4)); auto* sep_line = new StaticLine(this); @@ -714,8 +696,8 @@ private: row->SetBackgroundStyle(wxBG_STYLE_PAINT); row->SetCursor(wxCursor(wxCURSOR_HAND)); - const int sq = row->FromDIP(24); - const int sq_r = row->FromDIP(2); + const int sq = row->FromDIP(20); // ORCA match color swatch sizes + const int sq_r = row->FromDIP(0); const int sq_x = row->FromDIP(4); const int gap1 = row->FromDIP(8); @@ -754,7 +736,7 @@ private: wxFont nf = p->GetFont(); nf.SetPointSize(9); dc.SetFont(nf); - dc.SetTextForeground(paint_clr.GetLuminance() < 0.6 ? *wxWHITE : texture_import_gray9000()); + dc.SetTextForeground(paint_clr.GetLuminance() < 0.51 ? *wxWHITE : *wxBLACK); // ORCA match used foreground color with other swatches wxString ns = wxString::Format("%d", display_number((int)idx)); wxSize tsz = dc.GetTextExtent(ns); dc.DrawText(ns, sq_x + (sq - tsz.x) / 2, sq_y + (sq - tsz.y) / 2); @@ -823,9 +805,9 @@ private: wxFont font = p->GetFont(); font.SetPointSize(9); dc.SetFont(font); - int x = p->FromDIP(2); - const int sw = p->FromDIP(22); - const int sw_r = p->FromDIP(2); + int x = p->FromDIP(6); // ORCA Match left margins + const int sw = p->FromDIP(20); // ORCA Match color swatch sizes + const int sw_r = 0; //p->FromDIP(2); const int y = (sz.y - sw) / 2; for (size_t ci = 0; ci < entry.mixed_components.size() && ci < entry.mixed_ratios.size(); ++ci) { @@ -936,12 +918,20 @@ public: wxColour pop_bg = StateColor::darkModeColorFor(*wxWHITE); SetBackgroundColour(pop_bg); + // ORCA add border for popups. it required to add this controls because it covers all background + Bind(wxEVT_PAINT, [this](wxPaintEvent& evt) { + wxPaintDC dc(this); + dc.SetPen(wxPen(StateColor::darkModeColorFor(wxColour("#DBDBDB")), FromDIP(1))); + dc.SetBrush(*wxTRANSPARENT_BRUSH); + dc.DrawRoundedRectangle(0, 0, GetSize().x, GetSize().y, 0); + }); + auto* content = new wxPanel(this, wxID_ANY); content->SetBackgroundColour(pop_bg); content->SetBackgroundStyle(wxBG_STYLE_PAINT); auto* sizer = new wxBoxSizer(wxVERTICAL); - const int row_h = FromDIP(36); + const int row_h = FromDIP(32); const int pop_w = std::max(FromDIP(216), popup_width); sizer->Add(create_item_row(content, TextureAutoMixMode::CMYW, row_h), 0, wxEXPAND); sizer->Add(create_item_row(content, TextureAutoMixMode::RYBW, row_h), 0, wxEXPAND); @@ -966,7 +956,7 @@ private: wxPanel* create_item_row(wxWindow* parent, TextureAutoMixMode mode, int row_h) { wxColour row_bg = StateColor::darkModeColorFor(*wxWHITE); - wxColour hover_bg = StateColor::darkModeColorFor(wxColour("#F4F4F4")); + wxColour checked_bg = StateColor::darkModeColorFor(wxColour("#BFE1DE")); wxColour text_fg = texture_import_text_colour(); wxColour accent = StateColor::darkModeColorFor(wxColour("#009688")); @@ -977,15 +967,16 @@ private: row->SetCursor(wxCursor(wxCURSOR_HAND)); const int row_idx = mode == TextureAutoMixMode::CMYW ? 0 : 1; - row->Bind(wxEVT_PAINT, [this, row_bg, hover_bg, text_fg, accent, mode, row_idx](wxPaintEvent& e) { + row->Bind(wxEVT_PAINT, [this, row_bg, checked_bg, text_fg, accent, mode, row_idx](wxPaintEvent& e) { auto* p = static_cast(e.GetEventObject()); wxAutoBufferedPaintDC dc(p); wxSize sz = p->GetClientSize(); const bool hovered = (m_hover_idx == row_idx); const bool selected = (m_current_mode == mode); - dc.SetBrush(wxBrush(hovered ? hover_bg : row_bg)); - dc.SetPen(*wxTRANSPARENT_PEN); + // ORCA Match look with combo box dropdown + dc.SetBrush(wxBrush(selected ? checked_bg : row_bg)); + dc.SetPen(hovered ? wxPen(accent) : *wxTRANSPARENT_PEN); dc.DrawRectangle(0, 0, sz.x, sz.y); wxFont font = p->GetFont(); @@ -996,6 +987,7 @@ private: wxSize tsz = dc.GetTextExtent(label); dc.DrawText(label, p->FromDIP(12), (sz.y - tsz.y) / 2); + /* if (selected) { wxFont check_font = p->GetFont(); check_font.SetPointSize(12); @@ -1006,6 +998,7 @@ private: wxSize csz = dc.GetTextExtent(check); dc.DrawText(check, sz.x - p->FromDIP(16) - csz.x, (sz.y - csz.y) / 2); } + */ }); row->Bind(wxEVT_MOTION, [this, row, row_idx](wxMouseEvent& evt) { @@ -1913,7 +1906,7 @@ void TextureImportDialog::build_ui() { const wxColour dialog_bg = StateColor::darkModeColorFor(*wxWHITE); SetBackgroundColour(dialog_bg); - SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D"))); + SetForegroundColour(StateColor::darkModeColorFor(wxColour("#363636"))); wxBoxSizer* root_sizer = new wxBoxSizer(wxVERTICAL); @@ -1993,18 +1986,14 @@ void TextureImportDialog::build_preview_panel(wxWindow* parent, wxSizer* sizer) m_tab_panel->SetBackgroundColour(preview_bg); m_btn_view_original = new Button(m_tab_panel, _L("Original")); + m_btn_view_original->SetStyle(ButtonStyle::Regular, ButtonType::Parameter); m_btn_view_original->SetId(ID_VIEW_ORIGINAL); m_btn_view_multicolor = new Button(m_tab_panel, _L("Multi-Color")); + m_btn_view_multicolor->SetStyle(ButtonStyle::Regular, ButtonType::Parameter); m_btn_view_multicolor->SetId(ID_VIEW_MULTICOLOR); const int view_button_height = FromDIP(27); - m_btn_view_original->SetCornerRadius(view_button_height / 2); - m_btn_view_original->SetMinSize(wxSize(FromDIP(57), view_button_height)); - m_btn_view_original->SetFont(m_btn_view_original->GetFont().Bold()); m_btn_view_original->SetToolTip(_L("Your input texture model")); - m_btn_view_multicolor->SetCornerRadius(view_button_height / 2); - m_btn_view_multicolor->SetMinSize(wxSize(FromDIP(57), view_button_height)); - m_btn_view_multicolor->SetFont(m_btn_view_multicolor->GetFont().Bold()); m_btn_view_multicolor->SetToolTip(_L("Processed multi-color model")); wxBoxSizer* tab_sizer = new wxBoxSizer(wxHORIZONTAL); @@ -2014,7 +2003,6 @@ void TextureImportDialog::build_preview_panel(wxWindow* parent, wxSizer* sizer) m_tab_panel->Fit(); m_btn_view_multicolor->Hide(); - auto preview_original = [this](wxMouseEvent& e) { if (m_preview_canvas) { m_preview_canvas->set_render_mode(TexturePreviewCanvas::RenderMode::Original); @@ -2069,12 +2057,12 @@ void TextureImportDialog::build_preview_panel(wxWindow* parent, wxSizer* sizer) void TextureImportDialog::build_params_panel(wxWindow* parent, wxSizer* sizer) { - wxColour label_fg = StateColor::darkModeColorFor(wxColour("#323A3D")); + wxColour label_fg = StateColor::darkModeColorFor(wxColour("#363636")); wxBoxSizer* color_header_sizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText* lbl_colors = new wxStaticText(parent, wxID_ANY, _L("Color Count")); lbl_colors->SetForegroundColour(label_fg); - lbl_colors->SetFont(lbl_colors->GetFont().Bold()); + lbl_colors->SetFont(Label::Head_14); color_header_sizer->Add(lbl_colors, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(8)); m_btn_color_4 = new Button(parent, "4"); @@ -2085,33 +2073,11 @@ void TextureImportDialog::build_params_panel(wxWindow* parent, wxSizer* sizer) m_btn_color_16->SetId(ID_COLOR_16); m_btn_color_auto = new Button(parent, _L("Auto")); m_btn_color_auto->SetId(ID_COLOR_AUTO); - - { - StateColor preset_bg( - std::pair(wxColour(0, 137, 123), StateColor::Pressed | StateColor::Checked), - std::pair(wxColour(38, 166, 154), StateColor::Hovered | StateColor::Checked), - std::pair(wxColour(0, 150, 136), StateColor::Checked), - std::pair(wxColour("#CECECE"), StateColor::Pressed), - std::pair(wxColour("#EEEEEE"), StateColor::Hovered), - std::pair(*wxWHITE, StateColor::Normal)); - StateColor preset_bd( - std::pair(wxColour(0, 150, 136), StateColor::Checked), - std::pair(wxColour("#CECECE"), StateColor::Normal)); - StateColor preset_text( - std::pair(wxColour("#FFFFFE"), StateColor::Checked), - std::pair(wxColour("#323A3D"), StateColor::Normal)); - - for (auto* btn : {m_btn_color_4, m_btn_color_8, m_btn_color_16}) { - btn->SetCornerRadius(FromDIP(12)); - btn->SetMinSize(wxSize(FromDIP(28), FromDIP(28))); - btn->SetBackgroundColor(preset_bg); - btn->SetBorderColor(preset_bd); - btn->SetTextColor(preset_text); - } - } + m_btn_color_auto->SetStyle(ButtonStyle::Regular, ButtonType::Window); update_color_count_preset_buttons(); + color_header_sizer->AddStretchSpacer(); color_header_sizer->Add(m_btn_color_4, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(2)); color_header_sizer->Add(m_btn_color_8, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(2)); color_header_sizer->Add(m_btn_color_16, 0, wxALIGN_CENTER_VERTICAL); @@ -2134,7 +2100,7 @@ void TextureImportDialog::build_params_panel(wxWindow* parent, wxSizer* sizer) wxStaticText* lbl_smooth = new wxStaticText(parent, wxID_ANY, _L("Smooth Level")); lbl_smooth->SetForegroundColour(label_fg); - lbl_smooth->SetFont(lbl_smooth->GetFont().Bold()); + lbl_smooth->SetFont(Label::Head_14); sizer->Add(lbl_smooth, 0, wxBOTTOM, FromDIP(4)); wxBoxSizer* smooth_sizer = new wxBoxSizer(wxHORIZONTAL); @@ -2154,27 +2120,7 @@ void TextureImportDialog::build_params_panel(wxWindow* parent, wxSizer* sizer) m_btn_apply = new Button(parent, _L("Apply")); m_btn_apply->SetId(ID_BTN_APPLY); - - { - StateColor btn_bg_white( - std::pair(wxColour("#CECECE"), StateColor::Pressed), - std::pair(wxColour("#EEEEEE"), StateColor::Hovered), - std::pair(*wxWHITE, StateColor::Normal)); - const wxColour btn_bd_accent = wxColour(0, 150, 136); - const wxColour btn_text_accent = wxColour(0, 150, 136); - - m_btn_color_auto->SetCornerRadius(FromDIP(12)); - m_btn_color_auto->SetMinSize(wxSize(FromDIP(60), FromDIP(28))); - m_btn_color_auto->SetBackgroundColor(btn_bg_white); - m_btn_color_auto->SetBorderColor(btn_bd_accent); - m_btn_color_auto->SetTextColor(btn_text_accent); - - m_btn_apply->SetCornerRadius(FromDIP(12)); - m_btn_apply->SetMinSize(wxSize(FromDIP(60), FromDIP(28))); - m_btn_apply->SetBackgroundColor(btn_bg_white); - m_btn_apply->SetBorderColor(btn_bd_accent); - m_btn_apply->SetTextColor(btn_text_accent); - } + m_btn_apply->SetStyle(ButtonStyle::Regular, ButtonType::Window); // Defer attaching the Auto/Apply tooltips until the dialog has actually // been shown. On macOS, AppKit creates NSTrackingArea and dispatches a @@ -2198,7 +2144,7 @@ void TextureImportDialog::build_params_panel(wxWindow* parent, wxSizer* sizer) wxBoxSizer* apply_sizer = new wxBoxSizer(wxHORIZONTAL); apply_sizer->Add(m_btn_color_auto, 0, wxRIGHT, FromDIP(4)); apply_sizer->Add(m_btn_apply, 0); - sizer->Add(apply_sizer, 0, wxALIGN_RIGHT | wxBOTTOM, FromDIP(8)); + sizer->Add(apply_sizer, 0, wxALIGN_RIGHT | wxBOTTOM | wxTOP, FromDIP(8)); m_hint_label = new wxStaticText(parent, wxID_ANY, _L("Reminder: parameters changed, click Apply to take effect")); @@ -2214,27 +2160,19 @@ void TextureImportDialog::build_params_panel(wxWindow* parent, wxSizer* sizer) void TextureImportDialog::build_mapping_panel(wxWindow* parent, wxSizer* sizer) { - wxColour secondary_fg = StateColor::darkModeColorFor(wxColour("#6B6B6B")); + wxColour secondary_fg = StateColor::darkModeColorFor(wxColour("#363636")); wxBoxSizer* header_sizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText* lbl_mapping = new wxStaticText(parent, wxID_ANY, _L("Filament Mapping")); lbl_mapping->SetForegroundColour(secondary_fg); - lbl_mapping->SetFont(texture_import_section_title_font(parent)); + lbl_mapping->SetFont(Label::Head_14); m_auto_mix_font_point_size = lbl_mapping->GetFont().GetPointSize(); header_sizer->Add(lbl_mapping, 0, wxALIGN_CENTER_VERTICAL); m_btn_mix_reset = new Button(parent, "", "revert_btn", wxBORDER_NONE, 16); m_btn_mix_reset->SetCanFocus(false); - m_btn_mix_reset->SetPaddingSize(wxSize(FromDIP(2), FromDIP(2))); - { - StateColor reset_bg( - std::pair(wxColour("#F4F4F4"), StateColor::Pressed), - std::pair(wxColour("#F8F8F8"), StateColor::Hovered), - std::pair(*wxWHITE, StateColor::Normal)); - m_btn_mix_reset->SetBackgroundColor(reset_bg); - m_btn_mix_reset->SetBorderColor(StateColor()); - } + m_btn_mix_reset->SetStyle(ButtonStyle::Regular, ButtonType::Icon); m_btn_mix_reset->SetToolTip(_L("Reset filament mapping to the state before one-click mixing")); m_btn_mix_reset->Bind(wxEVT_BUTTON, [this](wxCommandEvent& evt) { reset_auto_mix(); @@ -2245,31 +2183,10 @@ void TextureImportDialog::build_mapping_panel(wxWindow* parent, wxSizer* sizer) header_sizer->AddStretchSpacer(); - m_btn_auto_mix = new Button(parent, auto_mix_mode_label(m_auto_mix_mode)); - { - wxFont btn_font = m_btn_auto_mix->GetFont(); - btn_font.SetPointSize(m_auto_mix_font_point_size); - m_btn_auto_mix->SetFont(btn_font); - } - m_btn_auto_mix->SetCornerRadius(FromDIP(14)); - m_btn_auto_mix->SetMinSize(wxSize(FromDIP(178), FromDIP(28))); - { - StateColor btn_bg( - std::pair(wxColour("#F4F4F4"), StateColor::Pressed), - std::pair(wxColour("#F8F8F8"), StateColor::Hovered), - std::pair(*wxWHITE, StateColor::Normal)); - const wxColour btn_bd = wxColour("#CECECE"); - const wxColour btn_text = texture_import_gray9000(); - m_btn_auto_mix->SetBackgroundColor(btn_bg); - m_btn_auto_mix->SetBorderColor(btn_bd); - m_btn_auto_mix->SetTextColor(btn_text); - } + m_btn_auto_mix = new Button(parent, auto_mix_mode_label(m_auto_mix_mode), "drop_down", 0, 16); + m_btn_auto_mix->SetStyle(ButtonStyle::Regular, ButtonType::Parameter); m_btn_auto_mix->SetToolTip(_L("Choose the one-click auto-mix mode for texture color import")); - m_btn_auto_mix->Bind(wxEVT_ENTER_WINDOW, [this](wxMouseEvent& evt) { - show_auto_mix_popup(); - evt.Skip(); - }); - m_btn_auto_mix->Bind(wxEVT_LEFT_DOWN, [this](wxMouseEvent& evt) { + m_btn_auto_mix->Bind(wxEVT_BUTTON, [this](wxCommandEvent& evt) { // ORCA show popup on click instead show_auto_mix_popup(); evt.Skip(); }); @@ -2279,11 +2196,12 @@ void TextureImportDialog::build_mapping_panel(wxWindow* parent, wxSizer* sizer) wxBoxSizer* merge_sizer = new wxBoxSizer(wxHORIZONTAL); m_auto_merge_cb = new wxCheckBox(parent, wxID_ANY, _L("Auto-merge same filament")); + m_auto_merge_cb->SetFont(Label::Body_14); m_auto_merge_cb->SetToolTip(_L("Automatically merge identical filaments into existing filaments in the project")); m_auto_merge_cb->SetForegroundColour(secondary_fg); m_auto_merge_cb->SetValue(true); m_auto_merge_cb->Bind(wxEVT_CHECKBOX, &TextureImportDialog::on_auto_merge_toggled, this); - merge_sizer->Add(m_auto_merge_cb, 0, wxALIGN_CENTER_VERTICAL); + merge_sizer->Add(m_auto_merge_cb, 0, wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, FromDIP(5)); sizer->Add(merge_sizer, 0, wxEXPAND | wxBOTTOM, FromDIP(8)); @@ -2316,29 +2234,16 @@ void TextureImportDialog::build_bottom_buttons(wxSizer* sizer) m_btn_skip = new Button(this, _L("Skip Matching")); m_btn_skip->SetId(ID_BTN_SKIP); m_btn_skip->SetToolTip(_L("Skip filament mapping and import as a single-color model")); - m_btn_skip->SetCornerRadius(FromDIP(20)); - m_btn_skip->SetMinSize(wxSize(FromDIP(136), FromDIP(40))); - { - StateColor skip_bg( - std::pair(wxColour("#CECECE"), StateColor::Pressed), - std::pair(wxColour("#EEEEEE"), StateColor::Hovered), - std::pair(*wxWHITE, StateColor::Normal)); - const wxColour skip_bd = wxColour("#CECECE"); - const wxColour skip_text = wxColour("#6B6B6A"); - m_btn_skip->SetBackgroundColor(skip_bg); - m_btn_skip->SetBorderColor(skip_bd); - m_btn_skip->SetTextColor(skip_text); - } + m_btn_skip->SetStyle(ButtonStyle::Regular, ButtonType::Choice); m_btn_ok = new Button(this, _L("Confirm")); m_btn_ok->SetId(wxID_OK); - m_btn_ok->SetCornerRadius(FromDIP(20)); - m_btn_ok->SetMinSize(wxSize(FromDIP(156), FromDIP(40))); - apply_accent_button_colours(m_btn_ok); - + m_btn_ok->SetStyle(ButtonStyle::Confirm, ButtonType::Choice); + m_btn_ok->EnableTooltipEvenDisabled(); + btn_sizer->AddStretchSpacer(); - btn_sizer->Add(m_btn_skip, 0, wxRIGHT, FromDIP(16)); - btn_sizer->Add(m_btn_ok, 0); + btn_sizer->Add(m_btn_ok, 0, wxRIGHT, FromDIP(16)); // Match ordering of choice buttons on whole UI + btn_sizer->Add(m_btn_skip, 0); sizer->Add(btn_sizer, 0, wxEXPAND | wxTOP, FromDIP(8)); } @@ -2675,11 +2580,11 @@ void TextureImportDialog::on_mesh_repair_decision_required(wxCommandEvent&) // with the same type swaps only the palette and leaves the geometry alone. if (auto* yes_btn = dynamic_cast(dlg.FindWindow(wxID_YES))) { yes_btn->SetStyle(ButtonStyle::Regular, ButtonType::Choice); - yes_btn->SetMinSize(wxSize(FromDIP(180), FromDIP(24))); + //yes_btn->SetMinSize(wxSize(FromDIP(180), FromDIP(32))); // Height not matches and will cause issues on longer translations. let dialog manages it } if (auto* no_btn = dynamic_cast(dlg.FindWindow(wxID_NO))) { no_btn->SetStyle(ButtonStyle::Confirm, ButtonType::Choice); - no_btn->SetMinSize(wxSize(FromDIP(160), FromDIP(24))); + //no_btn->SetMinSize(wxSize(FromDIP(160), FromDIP(32))); // Height not matches and will cause issues on longer translations. let dialog manages it } dlg.Layout(); dlg.Fit(); @@ -3739,7 +3644,7 @@ void TextureImportDialog::rebuild_mapping_rows() const wxColour dash_clr = StateColor::darkModeColorFor(wxColour("#ACACAC")); const wxColour hex_fg = texture_import_text_colour(); - const wxColour card_bg = StateColor::darkModeColorFor(wxColour("#E8E8E8")); + const wxColour card_bg = StateColor::darkModeColorFor(wxColour("#FFFFFF")); const wxColour card_bd = StateColor::darkModeColorFor(wxColour("#DBDBDB")); const wxColour name_fg = texture_import_text_colour(); const wxColour chev_clr = StateColor::darkModeColorFor(wxColour("#6B6B6A")); @@ -3766,7 +3671,7 @@ void TextureImportDialog::rebuild_mapping_rows() // --- Source card (dashed border, circle + hex) --- const int src_w = FromDIP(138); const int target_min_w = FromDIP(239); - const int row_h = FromDIP(44); + const int row_h = FromDIP(32); // ORCA compact row height row.source_panel = new wxPanel(row_panel, wxID_ANY, wxDefaultPosition, wxSize(src_w, row_h), wxTAB_TRAVERSAL | wxFULL_REPAINT_ON_RESIZE); row.source_panel->SetMinSize(wxSize(src_w, row_h)); @@ -3785,12 +3690,12 @@ void TextureImportDialog::rebuild_mapping_rows() wxPen dash_pen(dash_clr, 1, wxPENSTYLE_SHORT_DASH); dc.SetPen(dash_pen); dc.SetBrush(wxBrush(p->GetParent()->GetBackgroundColour())); - int r = p->FromDIP(8); + int r = 0; //p->FromDIP(8); dc.DrawRoundedRectangle(0, 0, sz.x, sz.y, r); - // Color circle 24px - int cd = p->FromDIP(24); - int cx = p->FromDIP(10); + // Color circle 20px + int cd = p->FromDIP(20); // ORCA match size of swatches + int cx = p->FromDIP(6); // ORCA match margins int cy = (sz.y - cd) / 2; dc.SetPen(*wxTRANSPARENT_PEN); dc.SetBrush(wxBrush(src_wx_color)); @@ -3874,7 +3779,7 @@ void TextureImportDialog::rebuild_mapping_rows() if (ci >= m_mapping_rows.size()) return; int fil_idx = m_mapping_rows[ci].target_filament_idx; - int r = p->FromDIP(8); + int r = 0; //p->FromDIP(8); dc.SetBrush(wxBrush(card_bg)); dc.SetPen(wxPen(card_bd, 1)); dc.DrawRoundedRectangle(0, 0, sz.x, sz.y, r); @@ -3886,9 +3791,9 @@ void TextureImportDialog::rebuild_mapping_rows() mixed_font.SetPointSize(10); dc.SetFont(mixed_font); - int x = p->FromDIP(10); - const int sw = p->FromDIP(28); - const int sw_r = p->FromDIP(6); + int x = p->FromDIP(6);// ORCA Match left margins + const int sw = p->FromDIP(20); // ORCA match size of swatches + const int sw_r = 0; //p->FromDIP(6); const int sw_y = (sz.y - sw) / 2; for (size_t mi = 0; mi < entry.mixed_components.size() && mi < entry.mixed_ratios.size(); ++mi) { if (mi > 0) { @@ -3916,7 +3821,7 @@ void TextureImportDialog::rebuild_mapping_rows() wxString num_str = wxString::Format("%d", display_number(comp_idx)); wxSize nsz = dc.GetTextExtent(num_str); - dc.SetTextForeground(comp_clr.GetLuminance() < 0.6 ? *wxWHITE : texture_import_gray9000()); + dc.SetTextForeground(comp_clr.GetLuminance() < 0.51 ? *wxWHITE : *wxBLACK); // ORCA match used foreground color with other swatches dc.DrawText(num_str, x + (sw - nsz.x) / 2, sw_y + (sw - nsz.y) / 2); x += sw + p->FromDIP(5); @@ -3940,10 +3845,10 @@ void TextureImportDialog::rebuild_mapping_rows() } // Numbered color square 32x32, rounded 6px - int sq = p->FromDIP(32); - int sq_x = p->FromDIP(6); + int sq = p->FromDIP(20); // ORCA match size of swatches + int sq_x = p->FromDIP(6);// ORCA Match left margins int sq_y = (sz.y - sq) / 2; - int sq_r = p->FromDIP(6); + int sq_r = 0; //p->FromDIP(6); wxColour fil_clr = get_target_wxcolor(fil_idx); dc.SetPen(*wxTRANSPARENT_PEN); dc.SetBrush(wxBrush(fil_clr)); @@ -3954,7 +3859,7 @@ void TextureImportDialog::rebuild_mapping_rows() wxFont num_font = p->GetFont(); num_font.SetPointSize(10); dc.SetFont(num_font); - dc.SetTextForeground(fil_clr.GetLuminance() < 0.6 ? *wxWHITE : texture_import_gray9000()); + dc.SetTextForeground(fil_clr.GetLuminance() < 0.51 ? *wxWHITE : *wxBLACK); // ORCA match used foreground color with other swatches wxString num_str = wxString::Format("%d", display_number(fil_idx)); wxSize nsz = dc.GetTextExtent(num_str); dc.DrawText(num_str, sq_x + (sq - nsz.x) / 2, sq_y + (sq - nsz.y) / 2); @@ -4030,9 +3935,12 @@ std::vector TextureImportDialog::build_matches_from_rows( void TextureImportDialog::update_color_count_preset_buttons() { - if (m_btn_color_4) m_btn_color_4->SetValue(m_param_color_count == 4); - if (m_btn_color_8) m_btn_color_8->SetValue(m_param_color_count == 8); - if (m_btn_color_16) m_btn_color_16->SetValue(m_param_color_count == 16); + auto update = [this](auto* btn, int count) { + if (btn) btn->SetStyle(m_param_color_count == count ? ButtonStyle::Confirm : ButtonStyle::Regular, ButtonType::Window); + }; + update(m_btn_color_4 , 4); + update(m_btn_color_8 , 8); + update(m_btn_color_16, 16); } void TextureImportDialog::set_color_count_value(int value, bool update_spin) @@ -4161,27 +4069,9 @@ void TextureImportDialog::highlight_view_button(int view_index) { Button* btns[] = { m_btn_view_original, m_btn_view_multicolor }; - // The inactive pill lies on m_tab_panel, which is preview_bg (#EEEEEE -> #4C4C55), and has to - // read as raised above that strip in both themes — so its fill steps away from the strip in - // opposite directions. gDarkColors pairs one light tone with one dark tone and cannot express - // an inversion, so the two are picked here the way filament_swatch_border_colour() does. - const bool dark_pill = is_dark(); - StateColor inactive_bg( - std::pair(dark_pill ? wxColour(0x5C, 0x5C, 0x64) : wxColour("#F4F4F4"), StateColor::Pressed), - std::pair(dark_pill ? wxColour(0x66, 0x66, 0x6E) : wxColour("#F8F8F8"), StateColor::Hovered), - std::pair(dark_pill ? wxColour(0x54, 0x54, 0x5B) : *wxWHITE, StateColor::Normal)); - const wxColour inactive_bd = dark_pill ? wxColour(0x54, 0x54, 0x5B) : *wxWHITE; - const wxColour inactive_text = wxColour("#6B6B6A"); - for (int i = 0; i < 2; ++i) { if (!btns[i]) continue; - if (i == view_index) { - apply_accent_button_colours(btns[i]); - } else { - btns[i]->SetBackgroundColor(inactive_bg); - btns[i]->SetBorderColor(inactive_bd); - btns[i]->SetTextColor(inactive_text); - } + btns[i]->SetStyle(i == view_index ? ButtonStyle::Confirm : ButtonStyle::Regular, ButtonType::Parameter); btns[i]->Refresh(); } } @@ -4259,10 +4149,8 @@ void TextureImportDialog::update_confirm_button_state() void TextureImportDialog::style_confirm_button(bool dirty) { if (dirty) { - apply_muted_button_colours(m_btn_ok); m_btn_ok->SetToolTip(_L("Reminder: parameters changed, click Apply to take effect")); } else { - apply_accent_button_colours(m_btn_ok); m_btn_ok->UnsetToolTip(); } if (m_hint_label) @@ -4308,33 +4196,10 @@ void TextureImportDialog::on_dpi_changed(const wxRect&) const int view_button_height = FromDIP(27); for (Button* btn : {m_btn_view_original, m_btn_view_multicolor}) { - if (btn) { - btn->SetCornerRadius(view_button_height / 2); - btn->SetMinSize(wxSize(FromDIP(57), view_button_height)); - } + if (btn) btn->Rescale(); // ORCA Rescale applies all style automatically when combined with SetStyle } - for (Button* btn : {m_btn_color_4, m_btn_color_8, m_btn_color_16}) { - if (btn) { - btn->SetCornerRadius(FromDIP(12)); - btn->SetMinSize(wxSize(FromDIP(28), FromDIP(28))); - } - } - - if (m_btn_color_auto) { - m_btn_color_auto->SetCornerRadius(FromDIP(12)); - m_btn_color_auto->SetMinSize(wxSize(FromDIP(60), FromDIP(28))); - } - if (m_btn_apply) { - m_btn_apply->SetCornerRadius(FromDIP(12)); - m_btn_apply->SetMinSize(wxSize(FromDIP(60), FromDIP(28))); - } - if (m_btn_auto_mix) { - m_btn_auto_mix->SetCornerRadius(FromDIP(14)); - m_btn_auto_mix->SetMinSize(wxSize(FromDIP(178), FromDIP(28))); - } - if (m_btn_mix_reset) - m_btn_mix_reset->SetPaddingSize(wxSize(FromDIP(2), FromDIP(2))); + update_color_count_preset_buttons(); // ORCA Rescale applies all style automatically when combined with SetStyle if (m_color_spin) m_color_spin->SetMinSize(wxSize(FromDIP(60), FromDIP(28))); @@ -4346,14 +4211,13 @@ void TextureImportDialog::on_dpi_changed(const wxRect&) m_mapping_scroll->SetScrollRate(0, FromDIP(20)); } - if (m_btn_skip) { - m_btn_skip->SetCornerRadius(FromDIP(20)); - m_btn_skip->SetMinSize(wxSize(FromDIP(136), FromDIP(40))); - } - if (m_btn_ok) { - m_btn_ok->SetCornerRadius(FromDIP(20)); - m_btn_ok->SetMinSize(wxSize(FromDIP(156), FromDIP(40))); - } + // ORCA Rescale applies all style automatically when combined with SetStyle + if (m_btn_skip) m_btn_skip->Rescale(); + if (m_btn_ok) m_btn_ok->Rescale(); + if (m_btn_color_auto) m_btn_color_auto->Rescale(); + if (m_btn_apply) m_btn_apply->Rescale(); + if (m_btn_auto_mix) m_btn_auto_mix->Rescale(); + if (m_btn_mix_reset) m_btn_mix_reset->Rescale(); // Mapping rows store their panel sizes (source/target/arrow/row height) // as fixed FromDIP min/max sizes, so rebuild them to pick up the new DPI. diff --git a/src/slic3r/plugin/PluginHooks.cpp b/src/slic3r/plugin/PluginHooks.cpp index dec7d261c6..0088bc1477 100644 --- a/src/slic3r/plugin/PluginHooks.cpp +++ b/src/slic3r/plugin/PluginHooks.cpp @@ -102,6 +102,12 @@ void install_slicing_pipeline_hook() ctx.step = step; ctx.print = &print; ctx.object = object; + // Slicing hooks are synchronous by design and never await: the context + // borrows Print/PrintObject that are only valid during this call, and the + // UI thread may itself be blocked waiting on this slicing worker. An async + // override is rejected here rather than scheduled -- cap->execute() casts + // its Python result to ExecutionResult and a coroutine object cannot be + // cast, so it surfaces as the SlicingError below. r = cap->execute(ctx); } catch (const CanceledException&) { throw; // cancellation must reach process(), never become a slicing error diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index 2150103668..27ebcdda3a 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -12,11 +12,16 @@ #include "PluginFsUtils.hpp" #include "PluginHooks.hpp" +#include "PluginAuditManager.hpp" +#include "PyPluginTrampoline.hpp" #include "PythonInterpreter.hpp" #include "PythonPluginBridge.hpp" #include "OrcaCloudServiceAgent.hpp" #include "libslic3r/Semver.hpp" +#include "pybind11/pytypes.h" +#include "pybind11/gil.h" +#include "pybind11/pybind11.h" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/NotificationManager.hpp" @@ -41,6 +46,7 @@ #include #include #include +#include #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/Plater.hpp" @@ -68,8 +74,10 @@ void Plugin::release_module() PluginManager& PluginManager::instance() { // Touch the interpreter first so its static outlives this one: ~Plugin needs it alive to - // release module, sys.modules, and sys.path ownership safely. + // release module, sys.modules, and sys.path ownership safely. Touch the async Script runtime + // next, so ~PluginManager can still drain it during its own shutdown(). PythonInterpreter::instance(); + ScriptAsyncRuntime::instance(); static PluginManager inst; return inst; } @@ -101,6 +109,9 @@ bool PluginManager::initialize() m_initialized = true; } + // Re-arm the async Script runtime in case shutdown() ran earlier in this process. + ScriptAsyncRuntime::instance().reset(); + // Bring every capability's stored config into memory. Deliberately unconditional and // independent of which plugins are installed: an entry outlives uninstall/unsubscribe, so a // plugin that comes back later finds its settings intact. A missing or malformed file just @@ -167,6 +178,10 @@ void PluginManager::shutdown() unload_all_plugins(); PythonPluginBridge::instance().clear_pending_captures(); + // Every async Script run has been drained by unload_all_plugins above; wait for every + // invocation worker before the interpreter is allowed to finalize. + ScriptAsyncRuntime::instance().shutdown(); + // Every config write already goes to disk as it happens (store_capability_config), so this // only catches an in-memory-only mutation. Note we flush rather than clear: unloading the // plugins above must never discard their stored config. @@ -754,6 +769,10 @@ void PluginManager::release_load_slot(const std::string& plugin_key) void PluginManager::cancel_and_wait_for_capabilities( const std::vector>& capabilities) { + // Ask the plugin to cancel first, then schedule the async cancellation: on_cancelled() can + // observe/record state while the run is still intact, and only afterwards is its asyncio task + // cancelled. Draining of capability references still follows, so the module is not unloaded + // until the run has settled. for (const auto& capability : capabilities) { if (!capability || !capability->is_enabled()) continue; @@ -769,15 +788,37 @@ void PluginManager::cancel_and_wait_for_capabilities( } } - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); - while (std::chrono::steady_clock::now() < deadline) { + for (const auto& capability : capabilities) { + if (capability) + ScriptAsyncRuntime::instance().cancel_plugin(capability->audit_plugin_key()); + } + + // Script rows are bounded only by their own worker: a cancelled or stalled invocation of another + // plugin can no longer couple to this one (each invocation owns a thread). A Script worker is + // drained without a deadline — forcing module unload while one is outstanding would leave Python + // executing against a freed module, or let a blocking preset selection mutate presets after the + // plugin is gone. Non-Script synchronous calls keep the historical bounded grace. On the GUI + // thread the event loop is pumped so a modal selection can settle instead of being starved by a + // blocking wait. + const auto grace_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + for (;;) { const bool all_released = std::all_of(capabilities.begin(), capabilities.end(), [](const auto& capability) { return !capability || capability->ref_count() == 0; }); - if (all_released) + // A cancellation that arrived before the invocation ran skips the ref counter, so an active + // worker must also be gone: never unload the module while any Script thread is still live. + const bool invocation_active = std::any_of(capabilities.begin(), capabilities.end(), [](const auto& capability) { + return capability != nullptr && ScriptAsyncRuntime::instance().has_active_run(capability.get()); + }); + if (all_released && !invocation_active) return; - std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (!invocation_active && std::chrono::steady_clock::now() >= grace_deadline) + break; + + if (wxTheApp != nullptr && wxIsMainThread()) + wxYield(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); } for (const auto& capability : capabilities) { @@ -2066,41 +2107,385 @@ bool PluginManager::delete_and_unsubscribe_cloud_plugin(const std::string& plugi return finalize_cloud_plugin_removal(descriptor, false, error); } +// ── Async Script runtime ──────────────────────────────────────────────────────────────────── + +namespace { + +// The asyncio loop of the Script invocation running on the calling thread. Owned +1 while set; +// always cleared under the GIL before the worker thread exits. +thread_local PyObject* tl_script_loop = nullptr; + +} // namespace + +struct ScriptAsyncRuntime::Impl +{ + struct Run + { + std::string plugin_key; + std::string capability_name; + std::shared_ptr capability; + std::function on_done; + std::atomic cancel_requested{false}; + // True while an asyncio loop/task is live for this run. Read without the GIL by + // cancel_plugin() to avoid taking the GIL for a purely synchronous invocation. + std::atomic has_loop{false}; + + // Live asyncio loop/task for cancellation. Guarded by handle_mutex and only touched + // with the GIL held. + std::mutex handle_mutex; + pybind11::object loop; + pybind11::object task; + }; + + std::mutex mutex; + std::condition_variable cv; + std::vector> active; + bool stopping = false; + + // Runs one invocation to completion on the calling (worker) thread. + void run_invocation(const std::shared_ptr& run); +}; + +void ScriptAsyncRuntime::Impl::run_invocation(const std::shared_ptr& run) +{ + ScriptCompletion completion; + + { + PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); + if (!lease) { + completion.error = _u8L("Python interpreter is shutting down"); + } else { + pybind11::gil_scoped_acquire gil; + + if (run->cancel_requested.load(std::memory_order_acquire)) { + // Cancelled before it ran: expected termination, never an error. + completion.cancelled = true; + } else { + // Hold the capability reference, the audit scope and the GIL for the whole + // invocation, so unload/shutdown cannot tear the module out from under it. + PluginCapabilityInterface::RefCounter ref_counter(*run->capability); + + std::optional audit_scope; + if (!run->capability->audit_plugin_key().empty()) + audit_scope.emplace(run->capability->audit_plugin_key(), run->capability->name()); + + // Detection and execution both happen here, on the worker: a synchronous + // `def execute` runs to completion off the UI thread, exactly like an `async def`. + ScriptExecuteInvocation invocation = invoke_script_execute(run->capability); + if (!invocation.error.empty()) { + completion.error = invocation.error; + } else if (!invocation.is_async) { + completion.result = invocation.result; + } else if (run->cancel_requested.load(std::memory_order_acquire)) { + completion.cancelled = true; + } else { + try { + pybind11::module_ asyncio = pybind11::module_::import("asyncio"); + pybind11::object loop = asyncio.attr("new_event_loop")(); + asyncio.attr("set_event_loop")(loop); + + tl_script_loop = loop.ptr(); + Py_INCREF(tl_script_loop); + + pybind11::object task = loop.attr("create_task")(std::move(invocation.awaitable)); + { + std::lock_guard lock(run->handle_mutex); + run->loop = loop; + run->task = task; + } + run->has_loop.store(true, std::memory_order_release); + // A cancellation that arrived before the loop came up must still land. + if (run->cancel_requested.load(std::memory_order_acquire)) + loop.attr("call_soon_threadsafe")(task.attr("cancel")); + + try { + pybind11::object returned = loop.attr("run_until_complete")(task); + completion.result = returned.cast(); + } catch (pybind11::error_already_set& err) { + // Only our own cancel_plugin() cancellation is expected termination; a + // CancelledError the plugin raised on its own stays a real error. + if (err.matches(asyncio.attr("CancelledError")) && + run->cancel_requested.load(std::memory_order_acquire)) { + completion.cancelled = true; + } else { + log_python_exception_keep(err); + completion.error = err.what(); + } + } + + run->has_loop.store(false, std::memory_order_release); + { + std::lock_guard lock(run->handle_mutex); + run->task = pybind11::object(); + run->loop = pybind11::object(); + } + Py_CLEAR(tl_script_loop); + loop.attr("close")(); + asyncio.attr("set_event_loop")(pybind11::none()); + } catch (pybind11::error_already_set& err) { + log_python_exception_keep(err); + completion.error = err.what(); + } catch (const std::exception& ex) { + completion.error = ex.what(); + } + + // Covers an exception thrown after the loop came up but before the clear above. + if (run->has_loop.load(std::memory_order_acquire)) { + run->has_loop.store(false, std::memory_order_release); + std::lock_guard lock(run->handle_mutex); + run->task = pybind11::object(); + run->loop = pybind11::object(); + } + + if (tl_script_loop != nullptr) + Py_CLEAR(tl_script_loop); + } + } + + // Drop the capability reference while the GIL is held: releasing a pybind holder from + // a non-Python thread would DECREF the capability without the GIL. Runs on every + // lease-valid path, including an invocation cancelled before it ran. + run->capability.reset(); + } + } + + // A cancellation requested by cancel_plugin() (unload/shutdown) is expected termination and is + // authoritative: whatever the body did — finished, swallowed CancelledError, or failed — nothing + // is surfaced as an error or as a normal success. + if (run->cancel_requested.load(std::memory_order_acquire)) { + completion.cancelled = true; + completion.error.clear(); + } + + auto on_done = std::move(run->on_done); + auto deliver = [on_done, completion]() { + if (on_done) + on_done(completion); + }; + + if (wxTheApp == nullptr || wxIsMainThread()) + deliver(); + else + GUI::wxGetApp().CallAfter(deliver); + + // Leave `active` last, so a drain cannot observe the run as finished before its completion was + // queued/delivered and its capability reference released. + { + std::lock_guard lock(mutex); + active.erase(std::remove(active.begin(), active.end(), run), active.end()); + } + cv.notify_all(); +} + +ScriptAsyncRuntime& ScriptAsyncRuntime::instance() +{ + static ScriptAsyncRuntime inst; + return inst; +} + +ScriptAsyncRuntime::ScriptAsyncRuntime() : m_impl(std::make_unique()) {} + +ScriptAsyncRuntime::~ScriptAsyncRuntime() { shutdown(); } + +bool ScriptAsyncRuntime::start(const std::string& plugin_key, + const std::string& capability_name, + std::shared_ptr capability, + std::function on_done) +{ + if (!PythonInterpreter::instance().is_initialized()) + return false; + + auto run = std::make_shared(); + run->plugin_key = plugin_key; + run->capability_name = capability_name; + run->capability = std::move(capability); + run->on_done = std::move(on_done); + + { + std::lock_guard lock(m_impl->mutex); + if (m_impl->stopping) + return false; + m_impl->active.push_back(run); + } + + // One worker thread per invocation. A stalled invocation of one plugin can never delay another + // plugin's unload or another invocation, and no invocation body ever runs on the caller (UI) + // thread. The thread holds `run` (and so the capability) until it finishes; the runtime tracks + // it in `active` and waits for it on shutdown. + Impl* impl = m_impl.get(); + try { + std::thread([impl, run] { impl->run_invocation(run); }).detach(); + } catch (...) { + std::lock_guard lock(m_impl->mutex); + m_impl->active.erase(std::remove(m_impl->active.begin(), m_impl->active.end(), run), m_impl->active.end()); + return false; + } + return true; +} + +void ScriptAsyncRuntime::cancel_plugin(const std::string& plugin_key) +{ + std::vector> runs; + { + std::lock_guard lock(m_impl->mutex); + for (const auto& run : m_impl->active) + if (run->plugin_key == plugin_key) + runs.push_back(run); + } + + for (const auto& run : runs) + run->cancel_requested.store(true, std::memory_order_release); + + for (const auto& run : runs) { + // A synchronous invocation has no loop to cancel; skip it so the caller never blocks on + // the GIL while that invocation is (uninterruptibly) running. + if (!run->has_loop.load(std::memory_order_acquire)) + continue; + + PythonGILState gil; + if (!gil) + continue; + + pybind11::object loop; + pybind11::object task; + { + std::lock_guard lock(run->handle_mutex); + loop = run->loop; + task = run->task; + } + if (!loop || !task) + continue; + + try { + loop.attr("call_soon_threadsafe")(task.attr("cancel")); + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(warning) << "Script async cancel failed for plugin '" << plugin_key << "': " << ex.what(); + } + } +} + +bool ScriptAsyncRuntime::has_active_run(const PluginCapabilityInterface* capability) const +{ + std::lock_guard lock(m_impl->mutex); + for (const auto& run : m_impl->active) + if (run->capability.get() == capability) + return true; + return false; +} + +void ScriptAsyncRuntime::shutdown() +{ + { + std::lock_guard lock(m_impl->mutex); + m_impl->stopping = true; + } + + std::unique_lock lock(m_impl->mutex); + m_impl->cv.wait(lock, [this] { return m_impl->active.empty(); }); +} + +void ScriptAsyncRuntime::reset() +{ + shutdown(); + + std::lock_guard lock(m_impl->mutex); + m_impl->stopping = false; +} + +pybind11::object ScriptAsyncRuntime::current_loop() +{ + if (tl_script_loop == nullptr) + return pybind11::object(); + return pybind11::reinterpret_borrow(pybind11::handle(tl_script_loop)); +} + ExecutionResult PluginManager::run_script_capability(const std::string& plugin_key, const std::string& capability_name, std::string& error) { - if (plugin_key.empty() || capability_name.empty()) { - return {}; + ExecutionResult result; + std::mutex mutex; + std::condition_variable cv; + bool done = false; + + ScriptLaunchResult launch = launch_script_capability( + plugin_key, capability_name, [&](const ScriptCompletion& completion) { + std::lock_guard lock(mutex); + result = completion.result; + // A cancel_plugin() cancellation is expected termination, not an error to report. + error = completion.cancelled ? std::string() : completion.error; + done = true; + cv.notify_all(); + }); + + if (launch.launched_async) { + // Async run: the completion is delivered on the GUI thread. When this call is itself on + // the GUI thread it must pump the event loop, or the completion can never be delivered. + std::unique_lock lock(mutex); + if (wxTheApp != nullptr && wxIsMainThread()) { + while (!done) { + cv.wait_for(lock, std::chrono::milliseconds(10)); + lock.unlock(); + wxYield(); + lock.lock(); + } + } else { + cv.wait(lock, [&] { return done; }); + } + } else { + result = launch.outcome.result; + error = launch.outcome.error; + } + + return result; +} + +PluginManager::ScriptLaunchResult PluginManager::launch_script_capability(const std::string& plugin_key, + const std::string& capability_name, + ScriptCompletionFn on_done) +{ + ScriptLaunchResult launch; + + // Mirror the historical synchronous behavior for a dangling reference: nothing to run and + // no error (the caller's guarded UI normally prevents this). + if (plugin_key.empty() || capability_name.empty()) + return launch; + + if (m_shutting_down.load(std::memory_order_acquire)) { + launch.outcome.error = _u8L("Plugin system is shutting down."); + return launch; } auto cap = get_plugin_capability({PluginCapabilityType::Script, capability_name, plugin_key}); if (!cap) - return {}; + return launch; - auto cap_interface = std::dynamic_pointer_cast(cap); - if (!cap_interface) - return {}; + if (!std::dynamic_pointer_cast(cap)) + return launch; - ExecutionResult result; - try { - PythonGILState gil; - if (!gil) { - error = "Python interpreter is shutting down"; - return {}; - } - result = cap_interface->execute(); - } catch (const std::exception& ex) { - error = ex.what(); - BOOST_LOG_TRIVIAL(error) << "Script plugin execution threw exception. plugin_key=" << plugin_key << " error=" << error; - } catch (...) { - error = _u8L("Unknown error"); - BOOST_LOG_TRIVIAL(error) << "Script plugin execution threw unknown exception. plugin_key=" << plugin_key; + // Every Script body runs off the caller's thread now: the invocation — including detection and + // a synchronous `def execute` — is handed to the runtime, which runs it on its own worker and + // reports the outcome through the completion callback. Nothing executes before returning here, + // so the UI thread is never blocked by a Script invocation. + const bool started = ScriptAsyncRuntime::instance().start( + plugin_key, capability_name, cap, + [this, plugin_key, on_done](const ScriptCompletion& completion) { + // A cancellation requested by cancel_plugin() (unload/shutdown) is expected termination: + // record no plugin error and surface nothing. Genuine user/plugin errors still record. + if (!completion.cancelled && !completion.error.empty()) + set_plugin_error(plugin_key, completion.error); + if (on_done) + on_done(completion); + }); + + if (!started) { + launch.outcome.error = _u8L("Plugin system is shutting down."); + set_plugin_error(plugin_key, launch.outcome.error); + BOOST_LOG_TRIVIAL(error) << "Script plugin execution failed. plugin_key=" << plugin_key + << " error=" << launch.outcome.error; + return launch; } - if (!error.empty()) { - set_plugin_error(plugin_key, error); - } - - return result; + launch.launched_async = true; + return launch; } void PluginManager::dispatch_lifecycle_event(LifecycleEvent evt, const LifecycleEventContext& ctx) { diff --git a/src/slic3r/plugin/PluginManager.hpp b/src/slic3r/plugin/PluginManager.hpp index bd7a495a67..21d2bc1e5b 100644 --- a/src/slic3r/plugin/PluginManager.hpp +++ b/src/slic3r/plugin/PluginManager.hpp @@ -15,6 +15,7 @@ #include #include #include +#include "pybind11/pytypes.h" #include "slic3r/plugin/PluginFsUtils.hpp" #include #include @@ -98,6 +99,19 @@ struct Plugin void release_module(); }; +// Outcome of one Script invocation, delivered to a script completion callback. +// +// `cancelled` marks a run terminated by PluginManager's own cancellation (plugin unload / shutdown): +// expected termination, not a failure. Callers must not surface it as an error nor as a normal +// success. `error` carries only genuine user/plugin exceptions; `result` is meaningful when neither +// `cancelled` nor a non-empty `error` is set. +struct ScriptCompletion +{ + ExecutionResult result; + std::string error; + bool cancelled = false; +}; + class PluginManager { public: @@ -214,6 +228,25 @@ public: ExecutionResult run_script_capability(const std::string& plugin_key, const std::string& capability_name, std::string& error); + // Outcome of launching a Script capability. + struct ScriptLaunchResult + { + bool launched_async = false; // true => a run started off-thread; wait for on_done + ScriptCompletion outcome; // meaningful when !launched_async (start failure only) + }; + // Invoked on the GUI thread when a Script invocation finishes (or inline, on the calling thread, + // when the run could not be started at all). + using ScriptCompletionFn = std::function; + + // Starts a Script capability off the caller's thread. Both a synchronous `def execute` and an + // `async def execute` run on a ScriptAsyncRuntime worker, so this never blocks the UI thread and + // no invocation runs before returning. `launched_async` is true exactly when a run started; the + // caller then waits for on_done instead of a returned result. When it is false, `outcome.error` + // explains why (the caller's guarded UI normally prevents this). + ScriptLaunchResult launch_script_capability(const std::string& plugin_key, + const std::string& capability_name, + ScriptCompletionFn on_done = {}); + void dispatch_lifecycle_event(LifecycleEvent evt, const LifecycleEventContext& ctx); private: @@ -309,6 +342,74 @@ private: std::atomic m_shutting_down{false}; }; +// ── Async Script execution ────────────────────────────────────────────────────────────────── +// +// A Script capability whose Python `execute` is an `async def` (or otherwise returns a +// coroutine) must not run on the UI thread, and cannot use the synchronous trampoline path, +// which casts the return value to ExecutionResult and would reject a coroutine. +// +// ScriptAsyncRuntime drives such executions off the calling (UI) thread. Each invocation gets its +// own worker thread and, for an `async def`, its own asyncio event loop. Every invocation body — +// detection, a synchronous `def execute`, or an `async def` coroutine — runs on that worker, so no +// Script invocation ever blocks the UI thread and no invocation is queued behind another plugin's. +// For the whole invocation the worker holds: +// * a shared_ptr to the capability, so the capability and its module stay alive across awaits; +// * a PythonRuntimeLease plus the GIL, so the interpreter cannot finalize underneath it; +// * the capability's audit scope (ScopedPluginAuditContext), +// which keeps plugin unload and interpreter shutdown from tearing the module out from under a +// suspended run. Unload cancels the run and drains it (it never force-unloads after a timeout). +// +// Interface for host awaitables (see plugin/host/): a host awaitable is constructed inside the +// Script coroutine, i.e. on the worker thread with that invocation's loop running, so it can +// read that loop with asyncio.get_running_loop() or ScriptAsyncRuntime::current_loop(). To +// resume from another thread (typically the UI thread) it must resolve its future with +// loop.call_soon_threadsafe(...) and must never touch plugin Python objects, or the loop, +// directly from that other thread. The loop only runs while the coroutine is suspended inside +// run_until_complete; once Script execute returns the loop is closed and the module may unload. +class ScriptAsyncRuntime +{ +public: + static ScriptAsyncRuntime& instance(); + + ~ScriptAsyncRuntime(); + ScriptAsyncRuntime(const ScriptAsyncRuntime&) = delete; + ScriptAsyncRuntime& operator=(const ScriptAsyncRuntime&) = delete; + + // Starts one Script invocation on its own worker thread. The invocation body (Python `execute`, + // whether `def` or `async def`) and its detection both run on that worker, never on the calling + // thread. `on_done` is invoked on the GUI thread (or inline when there is no wx app) when the + // invocation finishes; a `cancelled` completion is expected termination from cancel_plugin(). + // Returns false when the runtime is shutting down. + bool start(const std::string& plugin_key, + const std::string& capability_name, + std::shared_ptr capability, + std::function on_done); + + // Requests cancellation of every active run owned by plugin_key: marks the run and cancels + // its asyncio task via loop.call_soon_threadsafe (a synchronous invocation has no loop). + void cancel_plugin(const std::string& plugin_key); + + // True while a run for `capability` is active. + bool has_active_run(const PluginCapabilityInterface* capability) const; + + // Stops accepting runs and waits for every in-flight invocation worker. Nothing is torn down + // by force. + void shutdown(); + + // Re-arms the runtime after a shutdown() so a later initialize() in the same process can + // start runs again. + void reset(); + + // The asyncio loop of the Script invocation running on the calling thread, or an empty + // object when the calling thread is not running one. Must be called with the GIL held. + static pybind11::object current_loop(); + +private: + ScriptAsyncRuntime(); + struct Impl; + std::unique_ptr m_impl; +}; + // Resolve each configured capability reference to a loaded capability of type T and run `execute`. template void execute_capabilities_from_refs(const ConfigOptionStrings& capabilities, diff --git a/src/slic3r/plugin/PyPluginTrampoline.hpp b/src/slic3r/plugin/PyPluginTrampoline.hpp index 6d7ca9135c..074a140735 100644 --- a/src/slic3r/plugin/PyPluginTrampoline.hpp +++ b/src/slic3r/plugin/PyPluginTrampoline.hpp @@ -2,10 +2,12 @@ #define slic3r_PyPluginTrampoline_hpp_ #include "libslic3r/LifecycleEvents.hpp" +#include #include #include +#include #include #include #include @@ -14,9 +16,11 @@ #include "PythonInterpreter.hpp" #include "PluginFsUtils.hpp" #include "PluginAuditManager.hpp" +#include "pybind11/cast.h" #include #include #include +#include // Trampoline variants of pybind11's override macros. Every C++->Python plugin call crosses a // trampoline method, so this single boundary is where we (1) log the full Python traceback and @@ -61,6 +65,78 @@ } while (0) namespace Slic3r { + +// True when `object` is a coroutine object (the value produced by calling an `async def`). +// Match inspect.iscoroutine() without importing Python modules inside the plugin audit scope. +// Must be called with the GIL held. +inline bool py_is_coroutine(const pybind11::handle& object) +{ + return object && PyCoro_CheckExact(object.ptr()); +} + +// Result of invoking a Script capability's Python `execute` exactly once. +// +// A synchronous override (`def execute`) runs to completion here and yields `result`. +// An asynchronous override (`async def execute`, or any override that returns a coroutine) +// yields the coroutine object in `awaitable` WITHOUT running it: the cast to ExecutionResult +// that the trampoline would otherwise perform is impossible for a coroutine, so the caller +// chooses how to drive it. Whoever drives it must keep the capability referenced and re-open +// this call's GIL + runtime lease + audit scope for the coroutine's whole lifetime (see +// ScriptAsyncRuntime in PluginManager.hpp). +struct ScriptExecuteInvocation +{ + bool is_async = false; + pybind11::object awaitable; // valid iff is_async; a coroutine object created under the GIL + ExecutionResult result; // valid iff !is_async + std::string error; // non-empty when the call or coroutine creation raised +}; + +// Invokes ScriptPluginCapability::execute() under the GIL, replicating the audited trampoline +// call (capability ref counter, audit scope, traceback-preserving rethrow) but returning a +// coroutine object instead of forcing a cast when the plugin's `execute` is `async def`. +// +// `capability` must be the concrete, Python-bound capability instance (obtainable from +// get_plugin_capability()); it is resolved back to its Python object through pybind's instance +// map. Never throws: a Python exception is logged (full traceback) and reported in `error`. +inline ScriptExecuteInvocation invoke_script_execute(const std::shared_ptr& capability) +{ + ScriptExecuteInvocation invocation; + if (!capability) + return invocation; + + try { + pybind11::gil_scoped_acquire gil; + PluginCapabilityInterface::RefCounter ref_counter(*capability); + + std::optional audit_scope; + if (const std::string& audit_key = capability->audit_plugin_key(); !audit_key.empty()) + audit_scope.emplace(audit_key, capability->name()); + + pybind11::object py_capability = pybind11::cast(capability); + pybind11::object returned = py_capability.attr("execute")(); + + if (py_is_coroutine(returned)) { + invocation.is_async = true; + invocation.awaitable = std::move(returned); + return invocation; + } + + invocation.result = returned.cast(); + } catch (pybind11::error_already_set& err) { + const bool audit_denial = PluginAuditManager::instance().audit_denial_pending(); + if (audit_denial) + PluginAuditManager::instance().clear_current_plugin(); + invocation.error = err.what(); + log_python_exception_keep(err); + if (audit_denial) + PluginAuditManager::instance().clear_audit_denial(); + } catch (const std::exception& ex) { + invocation.error = ex.what(); + } + + return invocation; +} + template class PyPluginCommonTrampoline : public Base { public: diff --git a/src/slic3r/plugin/host/PluginHostPresets.cpp b/src/slic3r/plugin/host/PluginHostPresets.cpp index 4f032e0808..6997e4e6bc 100644 --- a/src/slic3r/plugin/host/PluginHostPresets.cpp +++ b/src/slic3r/plugin/host/PluginHostPresets.cpp @@ -2,6 +2,7 @@ #include "PluginHostUi.hpp" #include "slic3r/plugin/PluginBindingUtils.hpp" +#include #include #include #include @@ -11,18 +12,21 @@ #include #include -#include - #include #include #include #include +#include // TabPresetComboBox::set_filament_idx #include #include +#include + +#include #include #include +#include #include namespace py = pybind11; @@ -48,6 +52,543 @@ PresetCollection& printer_presets(PresetBundle& bundle) return static_cast(bundle.printers); } +// Handle to one category of currently edited preset. It is a category, not a snapshot: it always +// resolves the preset the matching tab edits now, so it stays valid across preset switches. +struct PresetEditor +{ + Preset::Type type = Preset::TYPE_INVALID; +}; + +const char* preset_tab_name(Preset::Type type) +{ + switch (type) { + case Preset::TYPE_PRINT: return "process"; + case Preset::TYPE_FILAMENT: return "filament"; + case Preset::TYPE_PRINTER: return "printer"; + default: return "preset"; + } +} + +PresetCollection& collection_for(PresetBundle& bundle, Preset::Type type) +{ + switch (type) { + case Preset::TYPE_PRINT: return bundle.prints; + case Preset::TYPE_FILAMENT: return bundle.filaments; + case Preset::TYPE_PRINTER: return printer_presets(bundle); + default: throw std::invalid_argument("Unsupported preset category"); + } +} + +// Marker for a user-declined selection: Tab::select_preset() returned false. It derives from +// std::runtime_error (pybind11 maps the base to RuntimeError), so callers see it as an ordinary +// failed transaction and no staged setting or slot assignment is created. +struct SelectionCancelled : std::runtime_error +{ + using std::runtime_error::runtime_error; +}; + +// -------------------------------------------------------------------------- +// The staged preset update lifecycle described in docs/HLSD/preset-plugin-api.md. +// +// begin_update() resolves and binds one target (selecting it through the normal UI flow when +// the caller asked for a preset that is not already active), returns a PresetTransaction that +// stages changes with set(), and applies them only on commit(). The transaction holds names, +// never preset pointers, so it stays valid across reloads; a target or filament slot that changed +// between begin_update() and commit() is rejected instead of silently editing the new mapping. +// +// begin_update() is synchronous: it runs on the background Script worker, marshals the target +// selection to the UI thread with PluginHostUi::run_on_ui_thread(), and blocks that worker until +// the selection and any unsaved-edit dialog settle. The UI thread stays responsive because the +// Script capability owns its worker thread. No GUI or preset pointer outlives the call; the +// returned transaction holds copied category/name/slot values. The update() shorthand shares the +// same target resolution and is safe only from that worker, never from the UI thread or a slicing +// pipeline hook. +// +// Known limits of this implementation, kept explicit rather than hidden: +// * A requested preset_name is resolved by the exact name its dropdown entry shows: the item's +// display label or its stored item alias (the internal preset name). A name two entries carry +// is rejected as ambiguous instead of being resolved by position. Process and printer resolve +// against the tab dropdown; a filament preset_name resolves against the requested slot's own +// sidebar selector, not the tab's, so its compatibility filter is the one that applies. A +// target the selector does not offer fails before the flow's unsaved-edit prompt. The flow +// itself is unchanged and the target is still confirmed as the edited preset afterwards. +// * A filament preset_name that names a different preset for a slot selects it through +// Tab::select_preset() (the normal flow, honouring unsaved-edit prompts) and then updates the +// slot mapping with PresetBundle::set_filament_preset() plus every dependent side effect the +// sidebar selection path performs: the project-dirty/selection refresh, the dynamic filament +// list, the slot's own combo (re-run so it lists and selects the assigned target), the +// conditional support-filament flushing recalc and the slot's AMS sync badge (read from the +// slot combo's own flag). The private Plater::priv::on_select_preset() path cannot be reused +// from here, so this mirrors its filament branch rather than calling it. +// * A user-declined selection does not undo decisions the user already accepted in an earlier +// dialog. It aborts before any slot assignment or transaction is created, so no staged +// setting is applied. +// -------------------------------------------------------------------------- + +// Outcome of one committed transaction. Identifies the target, whether selecting it switched +// anything, and for filament (whose preset may be shared) which slots share the edited preset. +struct PresetUpdateResult +{ + Preset::Type type = Preset::TYPE_INVALID; + std::string target_name; + bool selection_changed = false; + int slot_number = -1; // 1-based for filament, -1 otherwise + bool slot_assignment_changed = false; + std::vector shared_slots; + std::vector keys; + bool dirty = false; +}; + +struct PresetTransaction +{ + Preset::Type type = Preset::TYPE_INVALID; + std::string target_name; + bool filament = false; + int slot_number = 0; // 1-based, filament only + std::string slot_assignment_snapshot; // slot's assigned preset as of begin_update() + bool selection_changed = false; + bool slot_assignment_changed = false; + + std::vector> staged; + std::set staged_keys; + bool committed = false; + + void set(const std::string& key, const std::string& value); + PresetUpdateResult commit(); +}; + +GUI::GUI_App& require_gui_app() +{ + GUI::GUI_App& app = GUI::wxGetApp(); + if (app.is_closing()) + throw std::runtime_error("OrcaSlicer is closing"); + if (app.preset_bundle == nullptr) + throw std::runtime_error("Preset bundle is not available"); + if (app.plater() == nullptr) + throw std::runtime_error("OrcaSlicer main window is not available"); + return app; +} + +GUI::Tab* require_tab(GUI::GUI_App& app, Preset::Type type) +{ + GUI::Tab* tab = app.get_tab(type); + if (tab == nullptr) + throw std::runtime_error(std::string("The ") + preset_tab_name(type) + " preset tab is not available"); + // The tab for this preset type exists, but the selected printer's technology may not use it + // (the print tab no-ops under SLA); refuse instead of writing a value the UI cannot apply. + if (!tab->supports_printer_technology(app.preset_bundle->printers.get_selected_preset().printer_technology())) + throw std::runtime_error(std::string("The ") + preset_tab_name(type) + + " preset is not available for the selected printer technology"); + return tab; +} + +// True for a combo row that is a group header, a marker or a disabled row: it carries a marker in +// its client data and is not a selectable preset. +bool combo_item_is_marker(GUI::PresetComboBox& combo, int item) +{ + const auto marker = reinterpret_cast(combo.GetClientData(item)); + return marker >= GUI::PresetComboBox::LABEL_ITEM_DISABLED && marker < GUI::PresetComboBox::LABEL_ITEM_MAX; +} + +// How a caller-supplied name resolved against a combo's actual items. +struct ComboPresetMatch +{ + int item = -1; // first matching item, or -1 + bool ambiguous = false; // two distinct items carry this name + std::string internal_name; // internal preset name of the match (empty when none) +}; + +// Resolve `requested` by the name each combo item shows: its display label, or its stored item +// alias (the internal preset name, or the printer model for a system printer preset). Names are +// compared with the modified-dirty suffix removed, i.e. exactly what the dropdown shows. Reading +// the combo's own items means this respects the combo's real selectable model (visibility, its +// show-incompatible state and, for a slot combo, that slot's compatibility). A name that two +// distinct items carry is reported ambiguous instead of being resolved by position. +ComboPresetMatch resolve_combo_preset(GUI::PresetComboBox& combo, const std::string& requested) +{ + ComboPresetMatch match; + const std::string want = Preset::remove_suffix_modified(requested); + const int item_count = combo.GetCount(); + for (int item = 0; item < item_count; ++item) { + if (combo_item_is_marker(combo, item)) + continue; + const wxString alias = combo.GetItemAlias(item); + const std::string alias_name = alias.empty() ? std::string() + : Preset::remove_suffix_modified(alias.ToUTF8().data()); + const std::string label_name = Preset::remove_suffix_modified(combo.GetString(item).ToUTF8().data()); + if ((alias_name.empty() || alias_name != want) && label_name != want) + continue; + if (match.item >= 0 && match.item != item) { + match.ambiguous = true; + return match; + } + match.item = item; + match.internal_name = alias_name.empty() ? label_name : alias_name; + } + return match; +} + +// Index of the item whose internal name is `preset_name`, or -1. Used for per-item flags (the AMS +// sync badge); the internal name is unique, so no ambiguity handling is needed here. +int combo_item_for_preset(GUI::PresetComboBox& combo, const std::string& preset_name) +{ + const std::string want = Preset::remove_suffix_modified(preset_name); + const int item_count = combo.GetCount(); + for (int item = 0; item < item_count; ++item) { + if (combo_item_is_marker(combo, item)) + continue; + const wxString alias = combo.GetItemAlias(item); + const std::string alias_name = alias.empty() ? std::string() + : Preset::remove_suffix_modified(alias.ToUTF8().data()); + if (!alias_name.empty() && alias_name == want) + return item; + } + return -1; +} + +// Resolve `requested` to the internal preset name its dropdown entry names, or throw. `category` +// and `selector` are used only for the error text. A name the selector does not offer, or that two +// entries share, raises std::invalid_argument. +std::string resolve_preset_in_combo(GUI::PresetComboBox& combo, const std::string& requested, + const std::string& category, const std::string& selector) +{ + const ComboPresetMatch match = resolve_combo_preset(combo, requested); + if (match.ambiguous) + throw std::invalid_argument("The " + category + " name \"" + requested + "\" is ambiguous in the " + selector + + "; more than one entry shows it, so name the preset by its own entry"); + if (match.item < 0) + throw std::invalid_argument("The " + category + " preset \"" + requested + "\" is not offered by the " + selector); + return match.internal_name; +} + +// The preset a filament slot currently resolves to, by its internal name. A slot whose stored +// name is empty or does not resolve yields an error identifying the slot. +std::string resolved_slot_preset(PresetBundle& bundle, int slot_number) +{ + if (slot_number < 1 || static_cast(slot_number) > bundle.filament_presets.size()) + throw std::out_of_range("Filament slot " + std::to_string(slot_number) + + " is out of range; slot numbers are 1-based and this printer has " + + std::to_string(bundle.filament_presets.size()) + " filament slot(s)"); + const std::string& assigned_name = bundle.filament_presets[static_cast(slot_number) - 1]; + if (assigned_name.empty()) + throw std::runtime_error("Filament slot " + std::to_string(slot_number) + " has no assigned filament preset"); + Preset* preset = bundle.filaments.find_preset(assigned_name); + if (preset == nullptr) + throw std::runtime_error("Filament slot " + std::to_string(slot_number) + " is assigned \"" + assigned_name + + "\", which does not resolve to a filament preset"); + return preset->name; +} + +void PresetTransaction::set(const std::string& key, const std::string& value) +{ + if (committed) + throw std::runtime_error("This preset transaction has already been committed; start a new begin_update()"); + if (key.empty()) + throw std::invalid_argument("A setting key is required"); + // Conflicting duplicate writes to one setting are rejected rather than resolved by order. + if (!staged_keys.insert(key).second) + throw std::invalid_argument("Setting \"" + key + "\" is already staged in this transaction; " + "conflicting duplicate writes to one setting are rejected"); + staged.emplace_back(key, value); +} + +PresetUpdateResult PresetTransaction::commit() +{ + if (committed) + throw std::runtime_error("This preset transaction has already been committed; start a new begin_update()"); + if (type == Preset::TYPE_INVALID) + throw std::runtime_error("This preset transaction has no target"); + + PresetUpdateResult result; + PluginHostUi::run_on_ui_thread([&] { + GUI::GUI_App& app = require_gui_app(); + GUI::Tab* tab = require_tab(app, type); + PresetBundle& bundle = *app.preset_bundle; + PresetCollection& collection = collection_for(bundle, type); + + // The target must still be the edited preset: the user may have switched away while the + // transaction was staged, and editing a different preset would break "explicit target". + const std::string edited = collection.get_edited_preset().name; + if (edited != target_name) + throw std::runtime_error("The edited " + std::string(preset_tab_name(type)) + " preset is \"" + edited + + "\", not this transaction's target \"" + target_name + + "\"; nothing was applied"); + + if (filament) { + // Reject a stale slot mapping instead of editing whatever the slot now points at. + const std::string now_assigned = resolved_slot_preset(bundle, slot_number); + if (now_assigned != slot_assignment_snapshot) + throw std::runtime_error("Filament slot " + std::to_string(slot_number) + " now holds \"" + now_assigned + + "\", not \"" + slot_assignment_snapshot + + "\" as when this transaction was created; the slot mapping changed, so nothing was applied"); + } + + // Apply the whole batch through the tab's batch path: it validates every key and value before + // touching the preset, rejects duplicate keys, runs the same per-setting commit path a hand + // edit uses (validation, on_change, dirty state) and refreshes once for the batch. A failure + // restores the edited preset, so no staged setting survives a failed commit. + tab->apply_preset_config_values(staged); + + result.type = type; + result.target_name = target_name; + result.selection_changed = selection_changed; + result.slot_number = filament ? slot_number : -1; + result.slot_assignment_changed = slot_assignment_changed; + result.keys.reserve(staged.size()); + for (const auto& entry : staged) + result.keys.push_back(entry.first); + result.dirty = collection.get_edited_preset().is_dirty; + + if (filament) { + // Every slot whose assigned preset resolves to the edited one is affected: the preset + // is shared, not a per-slot override. + for (std::size_t index = 0; index < bundle.filament_presets.size(); ++index) { + Preset* preset = bundle.filaments.find_preset(bundle.filament_presets[index]); + if (preset != nullptr && preset->name == target_name) + result.shared_slots.push_back(static_cast(index) + 1); + } + } + }); + + committed = true; + return result; +} + +// Process/printer target resolution: the active preset when no name is given, otherwise the named +// preset selected through the normal tab-selection flow (which enforces the dropdown/compatibility +// rules and the unsaved-edit prompt). Binds only after confirming the requested preset is edited. +// Runs on the UI thread with the GIL released, called from begin_preset_update(). +void bind_preset_target(Preset::Type type, const std::string& preset_name, PresetTransaction& transaction) +{ + GUI::GUI_App& app = require_gui_app(); + GUI::Tab* tab = require_tab(app, type); + PresetCollection& collection = collection_for(*app.preset_bundle, type); + + const std::string current = collection.get_edited_preset().name; + std::string target = current; + bool selection_changed = false; + + if (!preset_name.empty()) { + // Resolve by the name the tab's dropdown actually shows (display label or item alias), so a + // plugin can pass exactly what the user sees. With no populated dropdown there is nothing + // to resolve against, so fall back to collection internal names. + GUI::TabPresetComboBox* combo = tab->get_combo_box(); + std::string resolved; + if (combo != nullptr && combo->GetCount() > 0) + resolved = resolve_preset_in_combo(*combo, preset_name, preset_tab_name(type), + "preset selector for the selected printer"); + else + resolved = preset_name; + + Preset* requested = collection.find_preset(resolved); + if (requested == nullptr) + throw std::invalid_argument("No " + std::string(preset_tab_name(type)) + " preset named \"" + resolved + + "\" is available to select"); + target = requested->name; + if (target != current) { + // Normal UI selection: honours the unsaved-edit prompt; a declined prompt returns false + // and is a user cancellation, distinct from any other resolution failure. + if (!tab->select_preset(target)) + throw SelectionCancelled("Switching the edited " + std::string(preset_tab_name(type)) + " preset to \"" + + target + "\" was canceled; nothing was staged"); + selection_changed = true; + } + } + + // select_preset() can still leave a different preset edited (e.g. the target is not an + // allowed dropdown choice), so confirm before binding. + if (collection.get_edited_preset().name != target) + throw std::runtime_error("The edited " + std::string(preset_tab_name(type)) + " preset is \"" + + collection.get_edited_preset().name + "\", not \"" + target + + "\"; the transaction was not created"); + + transaction.type = type; + transaction.target_name = target; + transaction.selection_changed = selection_changed; +} + +// Blocking form used by begin_update() and update(). +PresetTransaction begin_preset_update(Preset::Type type, const std::string& preset_name) +{ + PresetTransaction transaction; + PluginHostUi::run_on_ui_thread([&] { bind_preset_target(type, preset_name, transaction); }); + return transaction; +} + +// Filament target resolution: slot_number identifies the slot; an omitted preset_name keeps the +// preset assigned to it. A supplied preset_name selects that preset for the slot through the normal +// tab-selection flow, then records the slot assignment and its dependent Plater side effects (the +// ones the sidebar selection path performs) only after that flow succeeds, so a canceled prompt +// changes neither. A mixed-color virtual slot is rejected before any of this, with or without a +// preset_name. A requested preset the requested slot's own dropdown does not offer is rejected +// before the selection flow, so no dialog is raised for it; the one exception is the slot's own +// current assignment, which stays targetable when the dropdown hides it. A different preset the +// tab happens to edit is a globally edited target, not an offered choice for this slot, and is +// rejected. +// Runs on the UI thread with the GIL released, called from begin_filament_update(). +void bind_filament_target(int slot_number, const std::string& preset_name, PresetTransaction& transaction) +{ + GUI::GUI_App& app = require_gui_app(); + PresetBundle& bundle = *app.preset_bundle; + GUI::Plater* plater = app.plater(); + + // A mixed-color virtual slot has no single filament preset behind it, so every form of this + // call is rejected: with or without a preset_name there is no one preset to edit or assign. + // Range-guarded so an out-of-range slot still gets resolved_slot_preset()'s clear error. + if (slot_number >= 1 && static_cast(slot_number) <= bundle.filament_presets.size() + && bundle.is_mixed_filament(static_cast(slot_number) - 1)) + throw std::invalid_argument("Filament slot " + std::to_string(slot_number) + + " is a mixed-color virtual slot; it has no single filament preset to edit or assign"); + + // Resolve and validate before any selection, so a bad slot fails without a prompt. + const std::string assigned_internal = resolved_slot_preset(bundle, slot_number); + + GUI::Tab* tab = require_tab(app, Preset::TYPE_FILAMENT); + + const size_t slot_index = static_cast(slot_number) - 1; + + std::string target = assigned_internal; + if (!preset_name.empty()) { + // Resolve against the requested sidebar slot's own selector, not the tab's: that is the + // model the user picks this slot's filament from, including its compatibility filter. The + // selector matches the exact name shown (display label or item alias). + std::vector& slot_combos = plater->sidebar().combos_filament(); + GUI::PlaterPresetComboBox* slot_combo = slot_index < slot_combos.size() ? slot_combos[slot_index] : nullptr; + std::string resolved; + if (slot_combo != nullptr && slot_combo->GetCount() > 0) { + const ComboPresetMatch match = resolve_combo_preset(*slot_combo, preset_name); + if (match.ambiguous) + throw std::invalid_argument("The filament name \"" + preset_name + + "\" is ambiguous in the filament preset selector for filament slot " + + std::to_string(slot_number) + + "; more than one entry shows it, so name the preset by its own entry"); + if (match.item >= 0) { + resolved = match.internal_name; + } else { + // Not shown by this slot's selector. Only the slot's current assignment stays + // targetable (a hidden or incompatible-but-selected preset the dropdown omits); + // resolve it by internal name or by display alias and accept only that preset. A + // different preset the tab happens to edit is a globally edited target, not an + // offered choice for this slot, and is rejected. + Preset* by_name = bundle.filaments.find_preset(preset_name); + if (by_name == nullptr) { + const std::string& alias_name = bundle.filaments.get_preset_name_by_alias(preset_name); + by_name = bundle.filaments.find_preset(alias_name); + } + if (by_name == nullptr || by_name->name != assigned_internal) + throw std::invalid_argument("Filament preset \"" + preset_name + + "\" is not offered by the filament preset selector for filament slot " + + std::to_string(slot_number)); + resolved = by_name->name; + } + } else { + // The slot selector is not populated; fall back to the tab selector, then to collection + // internal names, so the call still works when the sidebar has not been laid out. + GUI::TabPresetComboBox* tab_combo = tab->get_combo_box(); + if (tab_combo != nullptr && tab_combo->GetCount() > 0) + resolved = resolve_preset_in_combo(*tab_combo, preset_name, "filament", + "filament preset selector for the selected printer"); + else + resolved = preset_name; + } + + Preset* requested = bundle.filaments.find_preset(resolved); + if (requested == nullptr) + throw std::invalid_argument("No filament preset named \"" + resolved + "\" is available to select"); + target = requested->name; + } + + bool selection_changed = false; + if (bundle.filaments.get_edited_preset().name != target) { + // A declined prompt is a user cancellation: it is thrown before any slot-assignment change, + // so neither the mapping nor a setting is touched. + if (!tab->select_preset(target)) + throw SelectionCancelled("Switching the edited filament preset to \"" + target + "\" for filament slot " + + std::to_string(slot_number) + + " was canceled; neither the slot assignment nor any setting was changed"); + if (bundle.filaments.get_edited_preset().name != target) + throw std::runtime_error("The edited filament preset is \"" + bundle.filaments.get_edited_preset().name + + "\", not \"" + target + "\"; the transaction was not created"); + selection_changed = true; + } + + bool assignment_changed = false; + if (!preset_name.empty() && target != assigned_internal) { + if (app.app_config == nullptr) + throw std::runtime_error("Application configuration is not available"); + // Mirror the filament branch of Plater::priv::on_select_preset() (the sidebar's normal + // preset selection): update the mapping, then every dependent project/UI side effect, + // rather than the vector entry alone. + const bool was_support = GUI::is_support_filament(static_cast(slot_index)); + bundle.set_filament_preset(slot_index, target); + plater->update_project_dirty_from_presets(); + bundle.export_selections(*app.app_config); + plater->sidebar().update_dynamic_filament_list(); + // Assigning a support filament (or moving away from one) changes which filaments the + // flush rules apply to, so the normal flow recalculates the flushing volumes when + // auto-calc covers every filament. + if (GUI::is_support_filament(static_cast(slot_index)) != was_support + && app.app_config->get("auto_calculate_flush") == "all") + plater->sidebar().auto_calc_flushing_volumes(static_cast(slot_index)); + // Refresh the requested slot's own sidebar combo so its list and current selection show the + // newly assigned target (the list may not have contained it), matching the sidebar + // selection path. Fetch the pointer after update_dynamic_filament_list(), which may + // rebuild the combo vector. + std::vector& slot_combos = plater->sidebar().combos_filament(); + if (slot_index < slot_combos.size() && slot_combos[slot_index] != nullptr) { + GUI::PlaterPresetComboBox* slot_combo = slot_combos[slot_index]; + slot_combo->update(); + // Keep the slot's AMS sync badge truthful, reading the item's own flag, the same source + // on_select_preset() reads, so no UI state is invented here. + const int item = combo_item_for_preset(*slot_combo, target); + if (item >= 0) + slot_combo->set_sync_badge(slot_combo->GetFlag(item) + == static_cast(GUI::PresetComboBox::FilamentAMSType::FROM_AMS)); + } + plater->on_filament_change(slot_index); + assignment_changed = true; + } + + // Match PlaterPresetComboBox::switch_to_tab(): record which 0-based filament slot this tab + // combobox now edits, so the GUI shows the slot the value was written for. + if (GUI::TabPresetComboBox* combo = tab->get_combo_box()) + combo->set_filament_idx(slot_number - 1); + + transaction.type = Preset::TYPE_FILAMENT; + transaction.filament = true; + transaction.slot_number = slot_number; + transaction.target_name = target; + transaction.selection_changed = selection_changed; + transaction.slot_assignment_changed = assignment_changed; + // Snapshot the mapping after the explicit assignment, as the slot's resolved internal name, + // so commit() compares like with like (a stored alias resolves to the same internal preset). + transaction.slot_assignment_snapshot = resolved_slot_preset(bundle, slot_number); +} + +// Blocking form used by begin_update() and update(). +PresetTransaction begin_filament_update(int slot_number, const std::string& preset_name) +{ + PresetTransaction transaction; + PluginHostUi::run_on_ui_thread([&] { bind_filament_target(slot_number, preset_name, transaction); }); + return transaction; +} + +// Compatibility shorthand: one staged setting, committed immediately through the same +// begin_update()/set()/commit() path, so targeting, selection, validation and commit are shared. +void update_edited_preset(Preset::Type type, const std::string& key, const std::string& value) +{ + PresetTransaction transaction = begin_preset_update(type, std::string()); + transaction.set(key, value); + transaction.commit(); +} + +void update_filament_slot(int slot_number, const std::string& key, const std::string& value) +{ + PresetTransaction transaction = begin_filament_update(slot_number, std::string()); + transaction.set(key, value); + transaction.commit(); +} + void reload_local_bundle(const std::string& bundle_id) { bool reloaded = false; @@ -100,7 +641,7 @@ 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 operations"); 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."); @@ -119,6 +660,145 @@ void host_bindings::register_presets(py::module_& host) .value("Plate", Preset::TYPE_PLATE) .value("Model", Preset::TYPE_MODEL); + 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); }) + .def("__repr__", [](const PresetUpdateResult& result) { + return std::string(""; + }); + + py::class_(preset, "PresetTransaction", + "A staged, single-target preset edit returned by begin_update(). set() stages a " + "serialized value without mutating the preset; commit() validates and applies the " + "whole batch through the normal setting-change path. begin_update() blocks the " + "background Script worker until any selection or unsaved-edit dialog is answered, " + "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("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 " + "fails. Staging the same key twice in one transaction raises ValueError (conflicting duplicate " + "writes are rejected). After commit() the transaction is closed.") + .def("commit", &PresetTransaction::commit, + "Validate and apply every staged setting through the same path as editing it in the GUI, then return " + "a PresetUpdateResult. An invalid key or value raises ValueError; a changed target or filament slot " + "mapping raises RuntimeError; a failure leaves none of the staged settings applied. The edited preset " + "becomes dirty until the user saves it."); + + py::class_(preset, "PresetEditor", + "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( + "begin_update", + [](const PresetEditor& editor, const std::string& preset_name) { + if (editor.type == Preset::TYPE_FILAMENT) + throw std::invalid_argument("begin_update on the filament editor takes " + "(slot_number, preset_name=\"\"); use orca.host.preset.filament.begin_update(slot_number, ...)"); + return begin_preset_update(editor.type, preset_name); + }, + py::arg("preset_name") = "", + "Resolve and bind this category's target preset and return a PresetTransaction. With no preset_name the " + "currently active preset is targeted; a preset_name must be a preset this category can select, and is " + "selected through the normal preset-selection flow (which prompts about unsaved edits). The call blocks " + "the background Script worker until any such dialog is answered, leaving the UI thread responsive. A " + "selection the user cancels raises RuntimeError; an unavailable or invalid target raises ValueError. " + "Either failure creates no transaction and stages no setting. Call it from the background Script worker, " + "never from the UI thread. This form is for process and printer; filament takes " + "begin_update(slot_number, preset_name=\"\").") + .def( + "begin_update", + [](const PresetEditor& editor, int slot_number, const std::string& preset_name) { + if (editor.type != Preset::TYPE_FILAMENT) + throw std::invalid_argument("The slot_number form of begin_update() is only available on " + "orca.host.preset.filament; call begin_update(preset_name=\"\") on this editor"); + return begin_filament_update(slot_number, preset_name); + }, + py::arg("slot_number"), py::arg("preset_name") = "", + "Resolve and bind a filament preset by 1-based slot and return a PresetTransaction. Omitting preset_name " + "targets the preset assigned to the slot; supplying a different name selects it for the slot through the " + "normal flow (prompting about unsaved edits) and, once that succeeds, records the new slot assignment with " + "the same Plater side effects the sidebar selection performs (project/selection refresh, dynamic filament " + "list, conditional support-filament flushing recalc and the slot's AMS sync badge). A requested preset " + "this slot's dropdown does not offer is rejected before that flow, so it raises no prompt; the slot's own " + "current assignment stays targetable even when the dropdown hides it. A selection the user cancels raises " + "RuntimeError and changes neither the slot assignment nor any setting. An out-of-range, empty or " + "unresolved slot is rejected, and a mixed-color virtual slot is rejected whether or not preset_name is " + "given. The transaction edits the shared preset, so every slot assigned to it is affected. The call " + "blocks the background Script worker until the selection settles, leaving the UI thread responsive; call " + "it from that worker, never from the UI thread.") + .def( + "update", + [](const PresetEditor& editor, const std::string& key, const std::string& value) { + update_edited_preset(editor.type, key, value); + }, + py::arg("key"), py::arg("value"), + "Set one setting of the currently edited preset and run the same committed-change path as " + "editing the setting in the GUI; the edited preset becomes dirty until saved/exported. " + "key must be a setting of this preset category and value its serialized string form, " + "otherwise ValueError is raised and nothing is written. A setting edited through a field " + "runs that field's validation even before its page has been opened; one the GUI edits " + "outside a field (such as compatible printers) also recomputes preset compatibility. " + "Equivalent to begin_update() with the active preset as target, then set(key, value) " + "and commit(); like begin_update() this call blocks the background Script worker.") + .def( + "update", + [](const PresetEditor& editor, int slot_number, const std::string& key, const std::string& value) { + if (editor.type != Preset::TYPE_FILAMENT) + throw std::invalid_argument("The slot_number form of update() is only available on " + "orca.host.preset.filament; call update(key, value) on this editor"); + update_filament_slot(slot_number, key, value); + }, + py::arg("slot_number"), py::arg("key"), py::arg("value"), + "Set one setting of the filament preset assigned to a 1-based filament slot. When that preset " + "is not the one currently edited the call switches to it through the normal preset-selection " + "flow, so an unsaved edited preset still prompts the user and a declined prompt cancels the " + "call with an error and no change. An out-of-range, empty or unresolved slot is rejected with " + "a clear error, as is a mixed-color virtual slot, which has no single preset to edit. Other " + "preset editors accept only update(key, value); this form raises " + "ValueError on them. Equivalent to begin_update(slot_number) with an omitted preset_name " + "(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) diff --git a/tests/fff_print/CMakeLists.txt b/tests/fff_print/CMakeLists.txt index a8e0f1575d..4cf0826a2c 100644 --- a/tests/fff_print/CMakeLists.txt +++ b/tests/fff_print/CMakeLists.txt @@ -6,6 +6,7 @@ add_executable(${_TEST_NAME}_tests test_cooling.cpp test_extrusion_entity.cpp test_extrusion_processor.cpp + test_exclusion_volumes.cpp test_fill.cpp test_flow.cpp test_gcode_processor.cpp diff --git a/tests/fff_print/test_cooling.cpp b/tests/fff_print/test_cooling.cpp index 1645d99a75..a1a840c745 100644 --- a/tests/fff_print/test_cooling.cpp +++ b/tests/fff_print/test_cooling.cpp @@ -40,7 +40,7 @@ TEST_CASE("Arc fitting remains active with overhang fan control", "[Cooling][Reg { DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_deserialize_strict({ - { "enable_arc_fitting", true }, + { "enable_arc_fitting", "enabled" }, { "enable_overhang_bridge_fan", true }, { "enable_overhang_speed", true }, { "initial_layer_print_height", 0.2 }, @@ -99,7 +99,7 @@ TEST_CASE("Overhang fan transitions do not depend on overhang speed", "[Cooling] DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_deserialize_strict({ { "bridge_speed", 2.0 }, - { "enable_arc_fitting", false }, + { "enable_arc_fitting", "disabled" }, { "enable_overhang_bridge_fan", true }, { "enable_overhang_speed", false }, { "initial_layer_print_height", 0.3 }, diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp new file mode 100644 index 0000000000..6b20d07973 --- /dev/null +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -0,0 +1,812 @@ +#include +#include +#include +#include +#include +#include "libslic3r/Config.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/Polyline.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" +#include +#include +#include +#include +#include + +#include "libslic3r/GCode/ExclusionVolumePathCheck.hpp" +#include "libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Support/SupportCommon.hpp" +#include "libslic3r/Support/SupportLayer.hpp" + +#include "test_helpers.hpp" +#include "test_utils.hpp" + +#include +#include +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { + +DynamicPrintConfig exclusion_config( + BedExcludeVolumeMode mode = BedExcludeVolumeMode::Shared, + const std::string &shared = "0..10;40x40,60x40,60x60,40x60", + const std::vector &per_extruder = {}) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const size_t extruder_count = std::max(1, per_extruder.size()); + config.set_num_extruders(extruder_count); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats(extruder_count, 0.4)); + config.set_key_value("extruder_offset", new ConfigOptionPoints(extruder_count, Vec2d::Zero())); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable(extruder_count, 100.0)); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_key_value("printable_area", new ConfigOptionPoints{ + Vec2d(0.0, 0.0), Vec2d(100.0, 0.0), Vec2d(100.0, 100.0), Vec2d(0.0, 100.0), + }); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString(shared)); + if (!per_extruder.empty()) + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(per_extruder)); + return config; +} + +DynamicPrintConfig legacy_exclusion_config() +{ + DynamicPrintConfig config = exclusion_config(); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString()); + config.set_deserialize_strict("bed_exclude_area", "40x40,60x40,60x60,40x60"); + return config; +} + +FullPrintConfig static_config(const DynamicPrintConfig &dynamic) +{ + FullPrintConfig config; + // full_print_config() also contains GUI/profile-only keys which are not + // members of the static slicing config used by these lower-level classes. + config.apply(dynamic, true); + return config; +} + +Polyline travel(std::initializer_list points) +{ + Points scaled_points; + scaled_points.reserve(points.size()); + for (const Vec2d &point : points) + scaled_points.emplace_back(Point::new_scale(point)); + return Polyline(std::move(scaled_points)); +} + +Vec2d to_mm(const Point &point) +{ + return point.cast() * SCALING_FACTOR; +} + +struct Rect +{ + double min_x; + double min_y; + double max_x; + double max_y; +}; + +bool point_inside_open_rect(const Vec2d &point, const Rect &rect) +{ + return point.x() > rect.min_x && point.x() < rect.max_x && + point.y() > rect.min_y && point.y() < rect.max_y; +} + +// Independent Liang-Barsky-style test oracle for the simple rectangular +// obstacles used here. This deliberately does not call the production path +// checker, so matching bugs in the checker and router cannot hide each other. +bool segment_enters_open_rect(const Vec2d &from, const Vec2d &to, const Rect &rect) +{ + if (point_inside_open_rect(from, rect) || point_inside_open_rect(to, rect)) + return true; + + double t_min = 0.0; + double t_max = 1.0; + const Vec2d delta = to - from; + const auto clip_axis = [&](double origin, double direction, double min_value, double max_value, + double &lower, double &upper) { + if (std::abs(direction) < 1e-12) + return origin > min_value && origin < max_value; + double first = (min_value - origin) / direction; + double second = (max_value - origin) / direction; + if (first > second) + std::swap(first, second); + lower = std::max(lower, first); + upper = std::min(upper, second); + return lower < upper; + }; + + if (!clip_axis(from.x(), delta.x(), rect.min_x, rect.max_x, t_min, t_max)) + return false; + if (!clip_axis(from.y(), delta.y(), rect.min_y, rect.max_y, t_min, t_max)) + return false; + if (t_min >= t_max) + return false; + + const double midpoint_t = 0.5 * (std::max(0.0, t_min) + std::min(1.0, t_max)); + return midpoint_t >= 0.0 && midpoint_t <= 1.0 && + point_inside_open_rect(from + midpoint_t * delta, rect); +} + +void check_path_avoids_rect(const Polyline &path, const Rect &rect) +{ + REQUIRE(path.points.size() >= 2); + for (size_t idx = 1; idx < path.points.size(); ++idx) + CHECK_FALSE(segment_enters_open_rect(to_mm(path.points[idx - 1]), to_mm(path.points[idx]), rect)); +} + +ExclusionVolumePathChecker configured_checker(const FullPrintConfig &config) +{ + ExclusionVolumePathChecker checker; + checker.configure(config); + return checker; +} + +void check_motion( + ExclusionVolumePathChecker &checker, + const Vec3d &from, + const Vec3d &to, + int extruder_id = 0, + ExclusionVolumeMotionType type = ExclusionVolumeMotionType::Travel, + bool start_xy_known = true, + bool end_xy_known = true, + bool start_z_known = true, + bool end_z_known = true, + unsigned int gcode_id = 17, + size_t move_id = 23) +{ + checker.check_motion( + from, to, start_xy_known, end_xy_known, start_z_known, end_z_known, + extruder_id, type, 7, gcode_id, move_id); +} + +struct ProcessorExclusionResult +{ + bool checked {false}; + bool conflict {false}; + bool travel_conflict {false}; + bool extrusion_conflict {false}; + int conflict_extruder_id {-1}; +}; + +class ScopedBblPrinterMode +{ +public: + explicit ScopedBblPrinterMode(bool enabled) + : m_previous(GCodeProcessor::s_IsBBLPrinter) + { + GCodeProcessor::s_IsBBLPrinter = enabled; + } + + ~ScopedBblPrinterMode() { GCodeProcessor::s_IsBBLPrinter = m_previous; } + +private: + bool m_previous; +}; + +ProcessorExclusionResult run_processor(const FullPrintConfig &config, const std::string &gcode) +{ + ScopedTemporaryFile file(".gcode"); + { + std::ofstream output(file.string()); + output << gcode; + } + + // The processor exposes this mode as shared state. Restore it after each + // invocation so these tests remain independent of Catch2 execution order. + ScopedBblPrinterMode printer_mode(false); + GCodeProcessor processor; + processor.apply_config(config); + processor.configure_exclusion_volume_path_check(config); + processor.process_file(file.string()); + const GCodeProcessorResult &result = processor.get_result(); + return { + result.exclusion_volume_path_checked, + result.exclusion_volume_path_conflict, + result.exclusion_volume_travel_conflict, + result.exclusion_volume_extrusion_conflict, + result.exclusion_volume_conflict_extruder_id, + }; +} + +Polygon rectangle(double min_x, double min_y, double max_x, double max_y) +{ + Polygon polygon({ + Point::new_scale(min_x, min_y), + Point::new_scale(max_x, min_y), + Point::new_scale(max_x, max_y), + Point::new_scale(min_x, max_y), + }); + polygon.make_counter_clockwise(); + return polygon; +} + +bool polygons_cover(const Polygons &polygons, double x, double y) +{ + const Point point = Point::new_scale(x, y); + const ExPolygons expolygons = union_ex(polygons); + return std::any_of(expolygons.begin(), expolygons.end(), + [&point](const ExPolygon &polygon) { return polygon.contains(point); }); +} + +struct BrimRun +{ + double total_length {0.0}; + bool intersects_test_region {false}; + bool leaves_bed {false}; +}; + +BrimRun generate_brim(const std::string &exclusion_definition, const Vec2d &object_position = Vec2d(40.0, 40.0)) +{ + DynamicPrintConfig config = exclusion_config(BedExcludeVolumeMode::Shared, exclusion_definition); + // Brim clipping normally receives the cached bed polygon initialized by + // the application. Give this headless fixture an explicit nozzle-reachable + // area so it exercises the same boundary path without mutating global state. + config.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups{{ + Vec2d(0.0, 0.0), Vec2d(100.0, 0.0), Vec2d(100.0, 100.0), Vec2d(0.0, 100.0), + }}); + config.set_deserialize_strict({ + {"skirt_loops", "0"}, + {"brim_type", "outer_only"}, + {"brim_width", "10"}, + {"initial_layer_line_width", "0.5"}, + }); + + TriangleMesh mesh = make_cube(20.0, 20.0, 20.0); + mesh.translate(float(object_position.x()), float(object_position.y()), 0.0f); + Print print; + Model model; + Test::init_print(std::vector{std::move(mesh)}, print, model, config, nullptr, false); + print.process(); + + Polylines paths; + for (const Print::SkirtBrimGroup &group : print.skirt_brim_groups()) + for (const Print::SkirtBrimGroup::Brim &brim : group.brims) { + Polylines current = brim.brim.as_polylines(); + paths.insert(paths.end(), std::make_move_iterator(current.begin()), std::make_move_iterator(current.end())); + } + + BrimRun result; + for (const Polyline &path : paths) + result.total_length += path.length(); + result.intersects_test_region = + !intersection_pl(paths, Polygons{rectangle(32.0, 35.0, 38.0, 65.0)}).empty(); + result.leaves_bed = std::any_of(paths.begin(), paths.end(), [](const Polyline &path) { + return std::any_of(path.points.begin(), path.points.end(), [](const Point &point) { + const Vec2d position = to_mm(point); + return position.x() < -EPSILON || position.x() > 100.0 + EPSILON || + position.y() < -EPSILON || position.y() > 100.0 + EPSILON; + }); + }); + return result; +} + +DynamicPrintConfig support_config(int support_filament, int interface_filament) +{ + DynamicPrintConfig config = exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", + {"0..10;4x4,12x4,12x12,4x12", "0..10;22x4,30x4,30x12,22x12"}); + // PrintObject clamps support role ids against the number of logical + // filaments, represented by filament_diameter in the static config. + config.set_key_value("filament_diameter", new ConfigOptionFloats{1.75, 1.75}); + config.set_key_value("filament_map_mode", new ConfigOptionEnum(fmmManual)); + config.set_key_value("filament_map", new ConfigOptionInts{1, 2}); + config.set_key_value("support_filament", new ConfigOptionInt(support_filament)); + config.set_key_value("support_interface_filament", new ConfigOptionInt(interface_filament)); + return config; +} + +struct SupportPrintFixture +{ + Model model; + Print print; + + explicit SupportPrintFixture(const DynamicPrintConfig &config) + { + ModelObject *object = model.add_object(); + ModelVolume *first = object->add_volume(make_cube(20.0, 20.0, 20.0)); + ModelVolume *second = object->add_volume(make_cube(20.0, 20.0, 20.0)); + first->config.set("extruder", 1); + second->config.set("extruder", 2); + // Pin the role assignments on the object as well as the process + // config. This fixture intentionally exercises support exclusion + // selection, not the separate preset-remapping subsystem. + object->config.set("support_filament", config.opt_int("support_filament")); + object->config.set("support_interface_filament", config.opt_int("support_interface_filament")); + object->add_instance(); + object->ensure_on_bed(); + print.apply(model, config); + } + + PrintObject &object() { return *print.objects_mutable().front(); } +}; + +} // namespace + +TEST_CASE("Path checker ignores clear motions and motions outside the active Z slab", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("clear XY") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(10.0, 10.0, 5.0), Vec3d(20.0, 20.0, 5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("above volume") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 20.0), Vec3d(80.0, 50.0, 20.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("below volume") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, -5.0), Vec3d(80.0, 50.0, -5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } +} + +TEST_CASE("Legacy excluded areas do not constrain machine motion", "[ExclusionVolume][GCode][Compatibility]") +{ + const FullPrintConfig config = static_config(legacy_exclusion_config()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + + ExclusionVolumeTravelAvoidance router; + router.init(config, Vec3d::Zero()); + const auto route = router.route(direct, 5.0, 5.0, 0); + CHECK(route.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(route.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); + CHECK(route.path.points == direct.points); +} + +TEST_CASE("G-code preview retains the bed area alongside collision volumes", "[ExclusionVolume][GCode][Compatibility][Regression]") +{ + const auto mode = GENERATE(BedExcludeVolumeMode::Shared, BedExcludeVolumeMode::ToolheadOffset, + BedExcludeVolumeMode::PerExtruder); + DynamicPrintConfig config = exclusion_config(mode, "0..10;70x70,80x70,80x80,70x80", + {"0..10;70x70,80x70,80x80,70x80"}); + config.set_deserialize_strict("bed_exclude_area", "0x0,18x0,18x28,0x28"); + ScopedTemporaryFile file(".gcode"); + { + std::ofstream output(file.string()); + REQUIRE(output.is_open()); + output << "; generated by OrcaSlicer\nG90\nM83\nG1 X30 Y30 Z0.2 F3000\n" + << "; CONFIG_BLOCK_START\n"; + for (const std::string &key : config.keys()) + output << "; " << key << " = " << config.opt_serialize(key) << '\n'; + output << "; CONFIG_BLOCK_END\n"; + REQUIRE(output.good()); + } + ScopedBblPrinterMode printer_mode(false); + GCodeProcessor processor; + // Standalone preview loading uses the embedded DynamicPrintConfig, not + // the streaming writer's PrintConfig overload. + processor.process_file(file.string()); + CHECK(processor.get_result().bed_exclude_area == config.option("bed_exclude_area")->values); +} + +TEST_CASE("Collision volumes preserve the configured cutter travel points", "[ExclusionVolume][GCode][Compatibility][Regression]") +{ + DynamicPrintConfig config = Test::multifilament_config(2, { + {"enable_prime_tower", "0"}, {"gcode_flavor", "klipper"}, + {"start_end_points", "20x-3,60x90"}, {"bed_exclude_area", "0x0,18x0,18x28,0x28"}, + {"change_filament_gcode", ";CUTTER_PATH [travel_point_1_x],[travel_point_1_y];[travel_point_2_x],[travel_point_2_y];[travel_point_3_x],[travel_point_3_y]"}, + }); + const auto cutter_path = [](const DynamicPrintConfig &settings) { + Model model; + Print print; + const std::vector> overrides{ + {{"extruder", "1"}}, {{"extruder", "2"}}}; + std::vector meshes; + for (const double x : {30.0, 45.0}) { + TriangleMesh mesh = make_cube(5.0, 5.0, 0.6); + mesh.translate(Vec3f(float(x), 40.0f, 0.0f)); + meshes.push_back(std::move(mesh)); + } + Test::init_print(std::move(meshes), print, model, settings, &overrides, false); + const std::string gcode = Test::gcode(print); + const size_t marker = gcode.find(";CUTTER_PATH "); + REQUIRE(marker != std::string::npos); + return gcode.substr(marker, gcode.find('\n', marker) - marker); + }; + const std::string expected = cutter_path(config); + // The configured endpoint differs from the fallback (54, 245), so this + // comparison cannot pass by silently disabling the cutter-area calculation. + CHECK_THAT(expected, Catch::Matchers::ContainsSubstring("60")); + CHECK_THAT(expected, Catch::Matchers::ContainsSubstring("90")); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..10;80x80,90x80,90x90,80x90")); + CHECK(cutter_path(config) == expected); +} + +TEST_CASE("Path checker detects crossing inside and boundary motions", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + const auto [from, to] = GENERATE(table({ + {Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0)}, + {Vec3d(45.0, 45.0, 5.0), Vec3d(55.0, 55.0, 5.0)}, + {Vec3d(20.0, 40.0, 5.0), Vec3d(80.0, 40.0, 5.0)}, + {Vec3d(50.0, 20.0, -5.0), Vec3d(50.0, 80.0, 15.0)}, + })); + + auto checker = configured_checker(config); + check_motion(checker, from, to); + CHECK(checker.result().has_any_conflict); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 0); +} + +TEST_CASE("Path checker records motion classification and stable first-hit metadata", "[ExclusionVolume][GCode]") +{ + const auto [type, travel_hit, extrusion_hit, other_hit] = GENERATE(table({ + {ExclusionVolumeMotionType::Travel, true, false, false}, + {ExclusionVolumeMotionType::Extrude, false, true, false}, + {ExclusionVolumeMotionType::Other, false, false, true }, + })); + + auto checker = configured_checker(static_config(exclusion_config())); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, type, + true, true, true, true, 101, 202); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, type, + true, true, true, true, 303, 404); + + const ExclusionVolumePathCheckResult &result = checker.result(); + CHECK(result.has_travel_conflict == travel_hit); + CHECK(result.has_extrusion_conflict == extrusion_hit); + CHECK(result.has_other_motion_conflict == other_hit); + REQUIRE(result.first_hit.has_value()); + CHECK(result.first_hit->gcode_id == 101); + CHECK(result.first_hit->move_id == 202); + CHECK(result.first_hit->source_move_type == 7); +} + +TEST_CASE("Path checker handles unknown coordinates conservatively without inventing XY", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("unknown XY start is ignored") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 0.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, + ExclusionVolumeMotionType::Travel, false, true); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("unknown Z checks every height and marks the result") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 100.0), Vec3d(80.0, 50.0, 100.0), 0, + ExclusionVolumeMotionType::Travel, true, true, false, false); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->used_unknown_z); + } +} + +TEST_CASE("Path checker selects the active nozzle and applies its XY offset", "[ExclusionVolume][GCode][MultiNozzle]") +{ + DynamicPrintConfig dynamic = exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"}); + dynamic.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); + const FullPrintConfig config = static_config(dynamic); + + SECTION("unrelated nozzle remains clear") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("active nozzle offset converts emitted coordinates into model space") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 50.0, 5.0), Vec3d(50.0, 50.0, 5.0), 1); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 1); + CHECK_THAT(checker.result().first_hit->from.x(), WithinAbs(20.0, 1e-9)); + } + + SECTION("unknown active nozzle checks all physical nozzles") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 50.0, 5.0), Vec3d(50.0, 50.0, 5.0), -1); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 1); + } +} + +TEST_CASE("Travel router leaves clear and vertically separated paths unchanged", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + + const Polyline clear = travel({Vec2d(10.0, 10.0), Vec2d(90.0, 10.0)}); + auto result = router.route(clear, 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::NoIntersection); + CHECK(result.path.points == clear.points); + + const Polyline crossing = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + result = router.route(crossing, 20.0, 20.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); +} + +TEST_CASE("Travel router produces a safe in-bed detour around an active volume", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + const auto result = router.route(direct, 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + REQUIRE(result.path.points.size() > 2); + CHECK(result.path.points.front() == direct.points.front()); + CHECK(result.path.points.back() == direct.points.back()); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + for (const Point &point : result.path.points) { + const Vec2d position = to_mm(point); + CHECK(position.x() >= 0.0); + CHECK(position.x() <= 100.0); + CHECK(position.y() >= 0.0); + CHECK(position.y() <= 100.0); + } +} + +TEST_CASE("Travel router activates volumes touched by a sloped Z move", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + const auto result = router.route(direct, -5.0, 15.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); +} + +TEST_CASE("Travel router reports unsafe endpoints unknown tools and blocked beds", "[ExclusionVolume][TravelRouting]") +{ + SECTION("endpoint inside") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(50.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::EndpointInside); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::EndpointInside); + } + + SECTION("unknown tool") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, -1); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Failed); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::UnknownExtruder); + } + + SECTION("obstacle separates the bed") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config( + BedExcludeVolumeMode::Shared, "0..10;45x0,55x0,55x100,45x100")), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Failed); + } +} + +TEST_CASE("Travel router uses only the active nozzle exclusion set", "[ExclusionVolume][TravelRouting][MultiNozzle]") +{ + const FullPrintConfig config = static_config(exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", {"0..10;40x40,60x40,60x60,40x60", ""})); + ExclusionVolumeTravelAvoidance router; + router.init(config, Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + CHECK(router.route(direct, 5.0, 5.0, 0).status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + const auto clear = router.route(direct, 5.0, 5.0, 1); + CHECK(clear.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(clear.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); +} + +TEST_CASE("Travel router accepts firmware positions outside the printable boundary", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + + SECTION("start outside") { + const auto result = router.route( + travel({Vec2d(-5.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + } + + SECTION("end outside") { + const auto result = router.route( + travel({Vec2d(20.0, 50.0), Vec2d(105.0, 50.0)}), 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + } +} + +TEST_CASE("G-code processor ignores the artificial first XY origin and checks subsequent travel", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("first explicit position has no invented start") { + const ProcessorExclusionResult result = run_processor(config, "G90\nG1 X80 Y50 Z5 F6000\n"); + CHECK(result.checked); + CHECK_FALSE(result.conflict); + } + + SECTION("next motion starts at the established position") { + const ProcessorExclusionResult result = run_processor(config, "G90\nG1 X80 Y50 Z5 F6000\nG1 X20 Y50\n"); + CHECK(result.conflict); + CHECK(result.travel_conflict); + } +} + +TEST_CASE("G-code processor tracks absolute relative and reset coordinate state", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("relative move crosses the volume") { + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\nG91\nG1 X60 Y0\n"); + CHECK(result.conflict); + } + + SECTION("G92 preserves a known transformed coordinate frame") { + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\nG92 X0 Y0\nG1 X60 Y0\n"); + CHECK(result.conflict); + } + + SECTION("homing does not create a synthetic checked move") { + const ProcessorExclusionResult result = run_processor(config, "G28\nG1 X80 Y50 Z5\n"); + CHECK_FALSE(result.conflict); + } + + SECTION("full or XY homing makes the XY start position unknown") { + const std::string homing = GENERATE( + std::string("G28"), std::string("G28 X"), std::string("G28 X Y"), + std::string("G28 XY"), std::string("G28 X0 Y0"), std::string("G28 XYZ"), + std::string("G28 W")); + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\n" + homing + "\nG1 X80 Y50 Z5\n"); + CHECK_FALSE(result.conflict); + } + + SECTION("Z-only homing preserves the known XY position") { + const std::string homing = GENERATE( + std::string("G28 Z P0"), std::string("G28 Z Z_OFFSET -0.07")); + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\n" + homing + "\nG1 X80 Y50 Z5\n"); + CHECK(result.conflict); + } +} + +TEST_CASE("G-code processor classifies extrusion conflicts", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + const ProcessorExclusionResult result = run_processor( + config, "G90\nM83\nG1 X20 Y50 Z5\nG1 X80 Y50 E1\n"); + + CHECK(result.conflict); + CHECK(result.extrusion_conflict); + CHECK_FALSE(result.travel_conflict); +} + +TEST_CASE("G-code processor changes the active physical nozzle at tool selection", "[ExclusionVolume][GCodeProcessor][MultiNozzle]") +{ + const FullPrintConfig config = static_config(exclusion_config( + BedExcludeVolumeMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"})); + + const ProcessorExclusionResult first_tool = run_processor(config, "G90\nT0\nG1 X20 Y50 Z5\nG1 X80 Y50\n"); + CHECK_FALSE(first_tool.conflict); + + const ProcessorExclusionResult second_tool = run_processor(config, "G90\nT1\nG1 X20 Y50 Z5\nG1 X80 Y50\n"); + CHECK(second_tool.conflict); + CHECK(second_tool.conflict_extruder_id == 1); +} + +TEST_CASE("Brim paths are clipped only by exclusions active on the first layer", "[ExclusionVolume][Brim]") +{ + const BrimRun active = generate_brim("0..1;32x35,38x35,38x65,32x65"); + const BrimRun raised = generate_brim("10..20;32x35,38x35,38x65,32x65"); + + REQUIRE(active.total_length > 0.0); + REQUIRE(raised.total_length > 0.0); + CHECK_FALSE(active.intersects_test_region); + CHECK(raised.intersects_test_region); + CHECK(active.total_length < raised.total_length); +} + +TEST_CASE("Brim paths remain clipped to the bed without collision volumes", "[ExclusionVolume][Brim][Regression]") +{ + const BrimRun brim = generate_brim("", Vec2d(21.0, 5.0)); + REQUIRE(brim.total_length > 0.0); + CHECK_FALSE(brim.leaves_bed); +} + +TEST_CASE("Support exclusion masks follow explicit and current-filament roles", "[ExclusionVolume][Support][MultiNozzle]") +{ + SECTION("explicit support roles select one physical nozzle each") { + SupportPrintFixture fixture(support_config(1, 2)); + CHECK(support_exclusion_filaments(fixture.object(), false) == std::vector{0}); + CHECK(support_exclusion_filaments(fixture.object(), true) == std::vector{1}); + + const auto base_masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}}, false); + const auto interface_masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}}, true); + REQUIRE(base_masks.size() == 1); + REQUIRE(interface_masks.size() == 1); + // PrintObject support geometry is centred around the object's local + // origin; the plate-space regions above are shifted by (10, 10). + CHECK(polygons_cover(base_masks.front(), -4.0, -4.0)); + CHECK_FALSE(polygons_cover(base_masks.front(), 14.0, -4.0)); + CHECK_FALSE(polygons_cover(interface_masks.front(), -4.0, -4.0)); + CHECK(polygons_cover(interface_masks.front(), 14.0, -4.0)); + } + + SECTION("current filament remains conservative across every used nozzle") { + SupportPrintFixture fixture(support_config(0, 2)); + std::vector filaments = support_exclusion_filaments(fixture.object(), false); + std::sort(filaments.begin(), filaments.end()); + CHECK(filaments == std::vector{0, 1}); + + const auto masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}, {11.0, 12.0}}, false); + REQUIRE(masks.size() == 2); + CHECK(polygons_cover(masks[0], -4.0, -4.0)); + CHECK(polygons_cover(masks[0], 14.0, -4.0)); + CHECK(masks[1].empty()); + } +} + +TEST_CASE("Support trimming applies the correct nozzle mask to every polygon category", "[ExclusionVolume][Support][MultiNozzle]") +{ + SupportPrintFixture fixture(support_config(1, 2)); + const Polygon source = rectangle(-20.0, -20.0, 40.0, 20.0); + + SupportGeneratorLayer base; + base.layer_type = SupporLayerType::Base; + base.print_z = 1.0; + base.height = 0.2; + base.polygons = {source}; + base.contact_polygons = std::make_unique(Polygons{source}); + base.overhang_polygons = std::make_unique(Polygons{source}); + base.enforcer_polygons = std::make_unique(Polygons{source}); + + SupportGeneratorLayer interface; + interface.layer_type = SupporLayerType::TopInterface; + interface.print_z = 1.0; + interface.height = 0.2; + interface.polygons = {source}; + + const SupportGeneratorLayersPtr none; + const SupportGeneratorLayersPtr base_layers{&base}; + const SupportGeneratorLayersPtr interface_layers{&interface}; + trim_support_layers_by_exclusion_volumes( + fixture.object(), none, none, none, base_layers, interface_layers, none); + + // Base support uses filament 1 and interface support uses filament 2. + CHECK_FALSE(polygons_cover(base.polygons, -4.0, -4.0)); + CHECK(polygons_cover(base.polygons, 14.0, -4.0)); + CHECK(polygons_cover(interface.polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(interface.polygons, 14.0, -4.0)); + + // The same sanitization is mandatory for the auxiliary support categories. + REQUIRE(base.contact_polygons != nullptr); + REQUIRE(base.overhang_polygons != nullptr); + REQUIRE(base.enforcer_polygons != nullptr); + CHECK_FALSE(polygons_cover(*base.contact_polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(*base.overhang_polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(*base.enforcer_polygons, -4.0, -4.0)); +} diff --git a/tests/fff_print/test_gcode.cpp b/tests/fff_print/test_gcode.cpp index cb707ae3d4..a82adbb6ea 100644 --- a/tests/fff_print/test_gcode.cpp +++ b/tests/fff_print/test_gcode.cpp @@ -2,6 +2,7 @@ #include #include +#include #include "libslic3r/BoundingBox.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/Model.hpp" @@ -16,9 +17,13 @@ #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/Point.hpp" +#include "libslic3r/libslic3r.h" +#include #include #include #include +#include +#include #include #include #include @@ -176,6 +181,54 @@ TEST_CASE("The G-code header names the first object's filament when printing by CHECK(header_value("first_layer_temperature") == 250); } +// A filament that starts above the first layer, such as a support interface, never touches the bed. Heating the +// bed to its temperature would soften the filament the part stands on, so only first layer filaments count. +TEST_CASE("The highest temperature bed formula ignores filaments that start above the first layer", "[GCode]") +{ + // Filament 1: bed 65 on the first layer, 60 after it. Filament 2: bed 100. A 30 mm cap on a 10 mm tall stem prints + // with filament 1 and is supported from the bed, the support with filament 1 and its interface under the cap + // with filament 2. + TriangleMesh mesh = make_cube(10, 10, 10); + mesh.translate(10, 10, 0); + TriangleMesh cap = make_cube(30, 30, 2); + cap.translate(0, 0, 10); + mesh.merge(cap); + DynamicPrintConfig config = Test::multifilament_config(2, { + {"bed_temperature_formula", "by_highest_temp"}, + {"enable_prime_tower", 0}, + {"enable_support", 1}, + {"support_filament", 1}, + {"support_interface_filament", 2}, + {"supertack_plate_temp_initial_layer", "65,100"}, + {"cool_plate_temp_initial_layer", "65,100"}, + {"textured_cool_plate_temp_initial_layer", "65,100"}, + {"eng_plate_temp_initial_layer", "65,100"}, + {"hot_plate_temp_initial_layer", "65,100"}, + {"textured_plate_temp_initial_layer", "65,100"}, + {"supertack_plate_temp", "60,100"}, + {"cool_plate_temp", "60,100"}, + {"textured_cool_plate_temp", "60,100"}, + {"eng_plate_temp", "60,100"}, + {"hot_plate_temp", "60,100"}, + {"textured_plate_temp", "60,100"}, + {"skirt_loops", 0}, + {"brim_type", "no_brim"}, + }); + const std::string gcode = Test::slice({mesh}, config); + REQUIRE(gcode.find("\nT1") != std::string::npos); + + std::vector bed_temps; + std::istringstream lines(gcode); + for (std::string line; std::getline(lines, line);) + if (line.rfind("M140 S", 0) == 0 || line.rfind("M190 S", 0) == 0) + bed_temps.push_back(std::stoi(line.substr(6))); + INFO("bed temperatures: " << Catch::Detail::stringify(bed_temps)); + REQUIRE_FALSE(bed_temps.empty()); + CHECK(bed_temps.front() == 65); + CHECK(std::find(bed_temps.begin(), bed_temps.end(), 60) != bed_temps.end()); + CHECK(std::find(bed_temps.begin(), bed_temps.end(), 100) == bed_temps.end()); +} + TEST_CASE("Object label comments number each object and copy with or without exclude object", "[GCode]") { // repetier has no exclude-object commands, so set_object_info() writes nothing for it. @@ -213,6 +266,40 @@ TEST_CASE("Object label comments number each object and copy with or without exc } } +TEST_CASE("Sparse infill only arc fitting emits arcs in the sparse infill alone", "[GCode]") +{ + const auto arcs_per_type = [](const char *arc_fitting) { + // 360 facets keep the walls and the concentric infill within the resolution of a circle, so both fit arcs. + const std::string gcode = Test::slice({ make_cylinder(25.0, 10.0, 2.0 * PI / 360.0) }, { + { "enable_arc_fitting", arc_fitting }, + { "sparse_infill_pattern", "concentric" }, + { "sparse_infill_density", "20%" }, + { "z_hop", "0" }, + }); + std::map arcs; + std::istringstream input(gcode); + std::string line, type; + while (std::getline(input, line)) { + if (line.rfind(";TYPE:", 0) == 0) + type = line.substr(6); + else if (line.rfind("G2 ", 0) == 0 || line.rfind("G3 ", 0) == 0) + ++arcs[type]; + } + return arcs; + }; + + CHECK(arcs_per_type("enabled").count("Outer wall") == 1); + + const std::map sparse_only = arcs_per_type("sparse_infill"); + CHECK(sparse_only.count("Sparse infill") == 1); + for (const auto &[type, count] : sparse_only) { + INFO(type << ": " << count << " arcs"); + CHECK(type == "Sparse infill"); + } + + CHECK(arcs_per_type("disabled").empty()); +} + TEST_CASE("An exported G-code's settings load back as the settings it was sliced with", "[GCode]") { // Two filaments, so the config block carries the flush matrix already multiplied by flush_multiplier. diff --git a/tests/fff_print/test_gcodeprocessor.cpp b/tests/fff_print/test_gcodeprocessor.cpp index 48cf3e8ae9..f57bd0895a 100644 --- a/tests/fff_print/test_gcodeprocessor.cpp +++ b/tests/fff_print/test_gcodeprocessor.cpp @@ -282,6 +282,48 @@ TEST_CASE("A seam takes the actual speed of the move it follows", "[GCodeProcess REQUIRE(seams > 0); } +TEST_CASE("A pause keeps the moves around it in order and on their own layers", "[GCodeProcessor][Regression]") +{ + // libvgcode numbers layers from the order of the moves, so the moves around a pause must stay in layer and + // line order. The pause vertex itself moves to the first extrusion after it and keeps its own line. + std::ostringstream gcode; + gcode << "M83\nG90\n"; + for (int layer = 1; layer <= 3; ++layer) { + gcode << "; CHANGE_LAYER\n; LAYER_HEIGHT: 0.2\n"; + if (layer == 2) + gcode << "G1 E-0.8 F3000\n; PAUSE_PRINTING\nM601\n"; + gcode << "G1 X10 Y10 F12000\nG1 Z" << 0.2 * layer << "\n"; + if (layer == 2) + gcode << "G1 E0.8 F3000\n"; + gcode << "; FEATURE: Outer wall\n" + << "G1 X50 Y10 E2 F3000\nG1 X50 Y50 E2\nG1 X10 Y50 E2\nG1 X10 Y10 E2\n"; + } + GCodeProcessorResult result; + process_gcode(gcode.str(), result); + const auto &moves = result.moves; + + REQUIRE(result.custom_gcode_per_print_z.size() == 1); + CHECK_THAT(result.custom_gcode_per_print_z.front().print_z, Catch::Matchers::WithinAbs(0.4, 1e-4)); + REQUIRE(std::count_if(moves.begin(), moves.end(), [](const auto &move) { return move.internal_only; }) > 0); + + const auto pause = std::find_if(moves.begin(), moves.end(), [](const auto &move) { return move.type == EMoveType::Pause_Print; }); + REQUIRE(pause != moves.end()); + CHECK(pause->layer_id == 1); + CHECK_THAT(pause->position.z(), Catch::Matchers::WithinAbs(0.4f, 1e-4f)); + + const GCodeProcessorResult::MoveVertex *previous = nullptr; + for (const auto &move : moves) { + if (move.type == EMoveType::Pause_Print) + continue; + if (previous != nullptr) { + CAPTURE(previous->gcode_id, move.gcode_id, static_cast(move.type)); + CHECK(move.layer_id >= previous->layer_id); + CHECK(move.gcode_id >= previous->gcode_id); + } + previous = &move; + } +} + TEST_CASE("Line ends of the exported G-code mark every newline in the file", "[GCodeProcessor]") { struct Case diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 29decadcdd..bd51352b60 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -286,6 +286,39 @@ size_t count_opt_key(const std::vector& warnings, const s [&](const StringObjectException& w) { return w.opt_key == key; }); } +DynamicPrintConfig dual_extruder_exclusion_config( + BedExcludeVolumeMode mode, + const std::vector &per_extruder, + const std::vector &filament_map = {1}) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.4}); + config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{256.0, 256.0}); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(per_extruder)); + config.set_key_value("filament_map_mode", new ConfigOptionEnum(fmmManual)); + config.set_key_value("filament_map", new ConfigOptionInts(filament_map)); + return config; +} + +StringObjectException validate_multimaterial_cube(const DynamicPrintConfig &config) +{ + Model model; + ModelObject *object = model.add_object(); + ModelVolume *first = object->add_volume(cube(20)); + ModelVolume *second = object->add_volume(cube(20)); + first->config.set("extruder", 1); + second->config.set("extruder", 2); + object->add_instance(); + object->ensure_on_bed(); + + Print print; + print.apply(model, config); + return print.validate(); +} + // Make `default_acceleration` exceed the machine's extruding-acceleration limit. void trigger_acceleration_warning(DynamicPrintConfig& c) { @@ -312,6 +345,73 @@ void trigger_precise_wall_warning(DynamicPrintConfig& c) } // namespace +TEST_CASE("Print validation applies individual exclusion volumes to the mapped physical extruder", "[Print][ExclusionVolume][MultiNozzle]") +{ + const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300"; + std::vector warnings; + + SECTION("mapped colliding extruder is rejected") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {1}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.find("extruder 1") != std::string::npos); + } + + SECTION("mapped clear extruder is accepted") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {2}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } + + SECTION("an unrelated nozzle exclusion does not reject the object") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } +} + +TEST_CASE("Print validation applies shared exclusions and ignores volumes above the object", "[Print][ExclusionVolume]") +{ + std::vector warnings; + + SECTION("shared volume intersects") { + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {2}); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..30;-100x-100,300x-100,300x300,-100x300")); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.find("extruder 2") != std::string::npos); + } + + SECTION("elevated shared volume clears a 20mm cube") { + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {1}); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("30..50;-100x-100,300x-100,300x300,-100x300")); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } +} + +TEST_CASE("Legacy excluded areas retain object placement validation", "[Print][ExclusionVolume][Compatibility]") +{ + DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::Shared, {"", ""}, {1}); + config.set_deserialize_strict("bed_exclude_area", "-100x-100,300x-100,300x300,-100x300"); + + std::vector warnings; + const StringObjectException error = validate_cubes(config, warnings); + CHECK_FALSE(error.string.empty()); +} + +TEST_CASE("Print validation checks every nozzle used by a multimaterial object", "[Print][ExclusionVolume][MultiNozzle]") +{ + const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300"; + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1, 2}); + + const StringObjectException error = validate_multimaterial_cube(config); + CHECK(error.string.find("extruder 2") != std::string::npos); +} + // --------------------------------------------------------------------------- // {first_object_name} filename placeholder // --------------------------------------------------------------------------- diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 44afdece7c..a42ead92e4 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -37,6 +37,7 @@ add_executable(${_TEST_NAME}_tests test_preset_options.cpp test_edge_grid.cpp test_elephant_foot_compensation.cpp + test_exclusion_volumes.cpp test_fill_corner_smoothing.cpp test_filament_mixer.cpp test_fill_plane_path.cpp diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index 7287b9d5d3..00721b952f 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -51,6 +52,7 @@ #include #include #include +#include #include #include #include // for std::enable_if_t @@ -180,6 +182,78 @@ SCENARIO("Export+Import geometry to/from 3mf file cycle", "[3mf]") { } } +TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ExclusionVolume][MultiNozzle]") +{ + // The importer creates a backup tree for the reloaded model. Give that + // process-global temp root a writable, isolated location on every OS. + ScopedSlic3rTemporaryDir temporary_dir("orca_exclusion"); + + Model model; + ModelObject *object = model.add_object(); + object->add_volume(make_cube(10.0, 10.0, 10.0)); + object->add_instance(); + + // Keep the project config intentionally sparse: this test owns only the + // exclusion settings and should not depend on unrelated printer-profile + // defaults surviving the project archive round-trip. + DynamicPrintConfig source; + source.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + source.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + source.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..10;1x1,2x1,2x2,1x2")); + source.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "0..25;5x5,15x5,15x15,5x15", + "30..80;40x40,55x40,55x55,40x55|0..5;70x10,80x10,80x20,70x20", + }); + + const boost::filesystem::path backup_dir = temporary_dir.path() / "source_backup"; + model.set_backup_path(backup_dir.string()); + + const boost::filesystem::path path = temporary_dir.path() / "round_trip.3mf"; + const std::string path_string = path.string(); + auto plate = std::make_unique(); + plate->plate_index = 0; + StoreParams store_params; + store_params.path = path_string.c_str(); + store_params.model = &model; + store_params.config = &source; + store_params.plate_data_list.push_back(plate.get()); + store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence; + REQUIRE(store_bbs_3mf(store_params)); + + Model reloaded_model; + DynamicPrintConfig reloaded; + ConfigSubstitutionContext substitutions{ForwardCompatibilitySubstitutionRule::Disable}; + PlateDataPtrs reloaded_plates; + std::vector project_presets; + bool is_bbl_3mf = false; + bool is_orca_3mf = false; + Semver file_version; + const bool loaded = load_bbs_3mf( + path_string.c_str(), &reloaded, &substitutions, &reloaded_model, &reloaded_plates, + &project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr, + LoadStrategy::LoadModel | LoadStrategy::LoadConfig); + release_PlateData_list(reloaded_plates); + + REQUIRE(loaded); + REQUIRE(reloaded.option>("bed_exclude_volume_mode") != nullptr); + CHECK(reloaded.option>("bed_exclude_volume_mode")->value == + BedExcludeVolumeMode::PerExtruder); + + const auto *areas = reloaded.option("extruder_bed_exclude_volumes"); + REQUIRE(areas != nullptr); + REQUIRE(areas->values.size() == 2); + CHECK(areas->values == source.option("extruder_bed_exclude_volumes")->values); + + const auto *shared_volumes = reloaded.option("bed_exclude_volumes"); + REQUIRE(shared_volumes != nullptr); + CHECK(shared_volumes->value == source.opt_string("bed_exclude_volumes")); + + const auto *legacy = reloaded.option("bed_exclude_area"); + REQUIRE(legacy != nullptr); + CHECK(legacy->serialize() == "0x0,10x0,10x10,0x10"); +} + SCENARIO("Mirrored instance transforms survive 3mf round trips", "[3mf][Regression]") { const bool bbs_format = GENERATE(false, true); diff --git a/tests/libslic3r/test_appconfig.cpp b/tests/libslic3r/test_appconfig.cpp index 01ceebc538..d4149c4fce 100644 --- a/tests/libslic3r/test_appconfig.cpp +++ b/tests/libslic3r/test_appconfig.cpp @@ -8,6 +8,17 @@ using namespace Slic3r; +TEST_CASE("Full collision-volume previews are opt-in and retain the user's preference", "[AppConfig][ExclusionVolume]") +{ + AppConfig config; + config.set_defaults(); + CHECK_FALSE(config.get_bool("show_collision_volumes")); + + config.set_bool("show_collision_volumes", true); + config.set_defaults(); + CHECK(config.get_bool("show_collision_volumes")); +} + TEST_CASE("AppConfig network version helpers", "[AppConfig]") { AppConfig config; diff --git a/tests/libslic3r/test_arrange.cpp b/tests/libslic3r/test_arrange.cpp index 030dd9e4b6..68669949a6 100644 --- a/tests/libslic3r/test_arrange.cpp +++ b/tests/libslic3r/test_arrange.cpp @@ -220,11 +220,39 @@ TEST_CASE("An item larger than the bed cannot be placed", "[Arrange]") ArrangePolygons items; items.emplace_back(make_square(scaled(20.))); items.emplace_back(make_square(scaled(400.))); // far bigger than the bed + // An item that cannot be placed keeps the position it came in with, so the + // caller can leave it where the user had it. + items[1].translation = {scaled(10.), scaled(20.)}; arrange(items, bed(200, 200), quiet_params(scaled(1.))); REQUIRE(items[0].bed_idx == 0); REQUIRE(items[1].bed_idx == UNARRANGED); + REQUIRE(items[1].translation.x() == scaled(10.)); + REQUIRE(items[1].translation.y() == scaled(20.)); +} + +TEST_CASE("An item filling the printable area is arranged", "[Arrange]") +{ + // The arrange bed keeps a margin from the printable area and the item is widened by + // its brim. Neither may keep an item that fits the printable area from being placed. + DynamicPrintConfig cfg = bed_config(); // 200 x 200 + ArrangeParams p = quiet_params(); + + ArrangePolygons items = squares(1, 197.); + items.front().brim_width = 1.; + update_arrange_params(p, &cfg, items); + update_selected_items_inflation(items, &cfg, p); + arrange(items, get_shrink_bedpts(&cfg, p), p); + REQUIRE(items.front().bed_idx == 0); + + // Larger than the printable area is still refused. + ArrangeParams p_large = quiet_params(); + ArrangePolygons large = squares(1, 201.); + update_arrange_params(p_large, &cfg, large); + update_selected_items_inflation(large, &cfg, p_large); + arrange(large, get_shrink_bedpts(&cfg, p_large), p_large); + REQUIRE(large.front().bed_idx == UNARRANGED); } TEST_CASE("Items overflowing one bed spill onto virtual beds", "[Arrange]") @@ -477,3 +505,71 @@ TEST_CASE("Layered printing does not floor the object distance", "[Arrange]") update_selected_items_inflation(items, &cfg, p); CHECK(p.min_obj_distance == 0); } + +TEST_CASE("Bed exclusions apply by physical nozzle and overlapping Z range", "[Arrange][ExclusionVolume][MultiNozzle]") +{ + ArrangePolygon object = make_square(scaled(20.)); + object.has_z_range = true; + object.z_min = 0.0; + object.z_max = 20.0; + object.bed_exclusion_extruder_ids = {1}; + + ArrangePolygon exclusion = make_square(scaled(20.)); + exclusion.is_bed_exclusion = true; + exclusion.has_z_range = true; + exclusion.z_min = 10.0; + exclusion.z_max = 30.0; + exclusion.bed_exclusion_extruder_id = 1; + + CHECK(bed_exclusion_applies(object, exclusion)); + + exclusion.bed_exclusion_extruder_id = 0; + CHECK_FALSE(bed_exclusion_applies(object, exclusion)); + + // Empty physical-nozzle assignments mean unresolved, so arrangement stays conservative. + object.bed_exclusion_extruder_ids.clear(); + CHECK(bed_exclusion_applies(object, exclusion)); + + object.bed_exclusion_extruder_ids = {0}; + object.z_max = 9.0; + CHECK_FALSE(bed_exclusion_applies(object, exclusion)); + + // Touching at one Z plane is intentionally treated as a collision. + object.z_max = 10.0; + CHECK(bed_exclusion_applies(object, exclusion)); +} + +TEST_CASE("Shared bed exclusions apply to every arranged object", "[Arrange][ExclusionVolume]") +{ + ArrangePolygon object = make_square(scaled(20.)); + object.bed_exclusion_extruder_ids = {1}; + + ArrangePolygon shared = make_square(scaled(20.)); + shared.is_bed_exclusion = true; + shared.bed_exclusion_extruder_id = -1; + + CHECK(has_bed_exclusion_regions({shared})); + CHECK_FALSE(has_bed_exclusion_regions({object})); + CHECK(bed_exclusion_applies(object, shared)); +} + +TEST_CASE("Arrange keeps relevant objects outside conditional exclusion obstacles", "[Arrange][ExclusionVolume]") +{ + ArrangePolygon exclusion = make_square(scaled(30.)); + exclusion.translation = Vec2crd(scaled(35.0), scaled(35.0)); + exclusion.is_bed_exclusion = true; + exclusion.bed_exclusion_extruder_id = 0; + + ArrangePolygons items = squares(4, 20.0); + for (ArrangePolygon &item : items) + item.bed_exclusion_extruder_ids = {0}; + + arrange(items, {exclusion}, bed(100.0, 100.0), quiet_params(scaled(1.0))); + + const ExPolygon excluded_shape = exclusion.transformed_poly(); + for (const ArrangePolygon &item : items) { + REQUIRE(item.bed_idx == 0); + CHECK(intersection(ExPolygons{item.transformed_poly()}, ExPolygons{excluded_shape}).empty()); + } + require_no_overlap(items); +} diff --git a/tests/libslic3r/test_clipper_utils.cpp b/tests/libslic3r/test_clipper_utils.cpp index 4f8d872ae5..00c2fd56e3 100644 --- a/tests/libslic3r/test_clipper_utils.cpp +++ b/tests/libslic3r/test_clipper_utils.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include "libslic3r/Polygon.hpp" @@ -21,6 +23,7 @@ #include #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/ExPolygon.hpp" +#include "libslic3r/MultiPoint.hpp" #include "libslic3r/Point.hpp" using namespace Slic3r; @@ -394,6 +397,172 @@ TEST_CASE("Tiled diff and intersection return the same polygons as the plain cal CHECK(same_rings(intersection_tiled, intersection_plain, tolerance)); } +TEST_CASE("Subtracting a far expansion gives the same polygons as diff with expand", "[ClipperUtils]") { + // As bridge_over_infill uses it: the lower layer's solids, each shrunk by the solid infill spacing on its own, expanded by + // two or four spacings. + const float spacing = scaled(0.45); + const float delta = GENERATE(2.f, 4.f) * spacing; + const auto expanded_diff = [delta](const Polygons &subject, const Polygons &clip) { return diff(subject, expand(clip, delta)); }; + // Whether the smaller round expansion that diff_expanded tries first covers the subject on its own. + const auto coarse_covers = [delta](const Polygons &subject, const Polygons &coarse) { + return diff(subject, expand(coarse, 0.7f * delta, jtRound, 0.01 * delta)).empty(); + }; + const auto rectangle = [](double x0, double y0, double x1, double y1) { + return Polygon::new_scale({ { x0, y0 }, { x1, y0 }, { x1, y1 }, { x0, y1 } }); + }; + // A rectangle whose sides are sawteeth 12 µm deep, as the slices of a relief are. + const auto sawtooth = [](double x0, double y0, double x1, double y1) { + const Vec2d corners[] = { { x0, y0 }, { x1, y0 }, { x1, y1 }, { x0, y1 } }; + Polygon out; + for (size_t i = 0; i < 4; ++ i) { + const Vec2d a = corners[i], b = corners[(i + 1) % 4], outward = Vec2d((b - a).y(), (a - b).x()).normalized(); + const int teeth = int(std::round((b - a).norm() / 0.024)); + for (int t = 0; t < teeth; ++ t) { + out.points.emplace_back(Point::new_scale(a + (b - a) * (t / double(teeth)))); + out.points.emplace_back(Point::new_scale(a + (b - a) * ((t + 0.5) / teeth) + 0.012 * outward)); + } + } + return out; + }; + + SECTION("A crack between solids shrunk apart is covered") { + const Polygons solids = shrink(Polygons{ rectangle(0., 0., 10., 10.), rectangle(10., 0., 20., 10.) }, spacing); + const Polygons subject{ rectangle(2., 2., 18., 8.) }; + REQUIRE_FALSE(diff(subject, solids).empty()); + CHECK(coarse_covers(subject, polygons_simplify(solids, delta / 8.))); + CHECK(expanded_diff(subject, solids).empty()); + CHECK(diff_expanded(subject, solids, delta).empty()); + } + SECTION("A crack between detailed solids shrunk apart is covered") { + const Polygons solids = shrink(Polygons{ sawtooth(0., 0., 10., 10.), sawtooth(10., 0., 20., 10.) }, spacing); + const Polygons subject{ rectangle(2., 2., 18., 8.) }; + REQUIRE_FALSE(diff(subject, solids).empty()); + // The shrink's miters cut steep teeth about 1.4 spacings deep, which widens the crack to about what the coarse + // expansion reaches at two spacings. So only the default reach, four spacings, is sure to take the early-out. + if (delta > 3.f * spacing) + CHECK(coarse_covers(subject, polygons_simplify(solids, delta / 8.))); + CHECK(expanded_diff(subject, solids).empty()); + CHECK(diff_expanded(subject, solids, delta).empty()); + } + SECTION("Strips too thin to survive the shrink leave the subject unsupported") { + const Polygons solids = shrink(Polygons{ rectangle(0., 0., 10., 10.), rectangle(10., 0., 10.6, 10.), rectangle(11.2, 0., 11.8, 10.), + rectangle(12.4, 0., 13., 10.) }, + spacing); + const Polygons subject{ rectangle(1., 1., 14., 9.) }; + const Polygons expected = expanded_diff(subject, solids); + REQUIRE_FALSE(expected.empty()); + CHECK(diff_expanded(subject, solids, delta) == expected); + } + SECTION("A hole wider than the expansion leaves the subject over it") { + Polygon hole = rectangle(5., 5., 15., 15.); + hole.reverse(); + const Polygons solids{ rectangle(0., 0., 20., 20.), hole }; + const Polygons subject{ rectangle(2., 2., 18., 18.) }; + const Polygons expected = expanded_diff(subject, solids); + REQUIRE_FALSE(expected.empty()); + CHECK(diff_expanded(subject, solids, delta) == expected); + } + SECTION("A hole that simplification removes is covered") { + Polygon hole = rectangle(5., 9.975, 10., 10.025); + hole.reverse(); + const Polygons solids{ rectangle(0., 0., 20., 20.), hole }; + const Polygons subject{ rectangle(2., 2., 18., 18.) }; + REQUIRE(polygons_simplify({ hole }, delta / 8.).empty()); + CHECK(expanded_diff(subject, solids).empty()); + CHECK(diff_expanded(subject, solids, delta).empty()); + } + SECTION("A thin C that simplification would turn into a hole is kept as it is") { + // A C 100 µm wide over a 10 mm radius at a tolerance of 0.5 mm, scaled with the tolerance. Arcs of 3,200 and 2,500 + // points leave 0.05 radians open at each end, and the path starts 4,500 points in. + const double scale = delta / 8. / scaled(0.5); + const auto arc = [](double radius, int n, Points &out) { + for (int i = 0; i < n; ++ i) { + const double a = 0.05 + (2. * PI - 0.1) * i / (n - 1); + out.emplace_back(coord_t(std::round(radius * std::cos(a))), coord_t(std::round(radius * std::sin(a)))); + } + }; + Points outer, inner; + arc(std::round(scale * scaled(10.)) + std::round(scale * scaled(0.1)), 3200, outer); + arc(std::round(scale * scaled(10.)), 2500, inner); + Polygon c(std::move(outer)); + c.points.insert(c.points.end(), inner.rbegin(), inner.rend()); + std::rotate(c.points.begin(), c.points.begin() + 4500, c.points.end()); + REQUIRE(c.is_counter_clockwise()); + REQUIRE(area(polygons_simplify({ c }, delta / 8.)) < 0.); + // A square beside the C, halfway round, which its own round expansion covers. + const coord_t x = coord_t(-scale * scaled(10.05)), half = coord_t(scale * scaled(0.2)); + const Polygons subject{ Polygon({ { x - half, -half }, { x + half, -half }, { x + half, half }, { x - half, half } }) }; + CHECK(coarse_covers(subject, { c })); + CHECK(expanded_diff(subject, { c }).empty()); + CHECK(diff_expanded(subject, { c }, delta).empty()); + } + SECTION("A path that simplifies into several contours and holes keeps its sign") { + // A band 1 mm wide winding once and a radian more, its end 20 µm outside its start, then on as a strand 40 µm wide for + // two radians. Simplified, the end crosses the start, closing a ring around holes, and the strand's sides cross each other. + const double radius = scaled(5.), width = scaled(1.), pitch = width + scaled(0.02), band_end = 2. * PI + 1., + end = band_end + 2.; + const int n = 6000; + Points outer, inner; + for (int i = 0; i < n; ++ i) { + const double t = end * i / (n - 1), centre = radius + pitch * t / (2. * PI), half = t <= band_end ? width / 2. : scaled(0.02); + outer.emplace_back(coord_t(std::round((centre + half) * std::cos(t))), coord_t(std::round((centre + half) * std::sin(t)))); + inner.emplace_back(coord_t(std::round((centre - half) * std::cos(t))), coord_t(std::round((centre - half) * std::sin(t)))); + } + Polygon band(std::move(outer)); + band.points.insert(band.points.end(), inner.rbegin(), inner.rend()); + REQUIRE(band.is_counter_clockwise()); + Points path = MultiPoint::_douglas_peucker(to_polyline(band).points, delta / 8.); + path.pop_back(); + const Polygons simplified = polygons_simplify({ band }, delta / 8.); + const size_t contours = size_t(std::count_if(simplified.begin(), simplified.end(), [](const Polygon &p) { return p.is_counter_clockwise(); })); + CHECK(contours >= 2); + CHECK(simplified.size() - contours >= 1); + CHECK((area(simplified) > 0.) == (Polygon(path).area() > 0.)); + const Polygons subject{ rectangle(-8., -8., 8., 8.) }; + CHECK(diff_expanded(subject, { band }, delta) == expanded_diff(subject, { band })); + } + SECTION("Random solids give the same polygons") { + // Overlapping rectangles, some too thin to survive the shrink, and jittered rings, under the region they cover and on + // every other seed a rectangle more. + size_t empty = 0, unsupported = 0; + for (unsigned seed = 1; seed <= 24; ++ seed) { + std::mt19937 rng(seed); + const auto uniform = [&rng](double from, double to) { return from + (to - from) * double(rng()) / double(std::mt19937::max()); }; + Polygons solids; + for (int i = 0; i < 6; ++ i) { + const double x = uniform(0., 40.), y = uniform(0., 40.); + solids.emplace_back(rectangle(x, y, x + uniform(0.3, 12.), y + uniform(0.3, 12.))); + } + for (int i = 0; i < 2; ++ i) { + const Vec2d centre(uniform(5., 45.), uniform(5., 45.)); + const double r = uniform(2., 8.), r_hole = r * uniform(0.3, 0.7); + Polygon ring, hole; + for (int k = 0; k < 96; ++ k) { + const Vec2d direction(std::cos(2. * PI * k / 96), std::sin(2. * PI * k / 96)); + ring.points.emplace_back(Point::new_scale(centre + r * uniform(0.97, 1.03) * direction)); + hole.points.emplace_back(Point::new_scale(centre + r_hole * uniform(0.97, 1.03) * direction)); + } + hole.reverse(); + solids.emplace_back(std::move(ring)); + solids.emplace_back(std::move(hole)); + } + Polygons covered = solids; + if (seed % 2 == 0) { + const double x = uniform(0., 40.), y = uniform(0., 40.); + covered.emplace_back(rectangle(x, y, x + uniform(2., 10.), y + uniform(2., 10.))); + } + const Polygons subject = shrink(union_(covered), spacing); + const Polygons shrunk = shrink(solids, spacing); + const Polygons expected = expanded_diff(subject, shrunk); + CHECK(diff_expanded(subject, shrunk, delta) == expected); + ++ (expected.empty() ? empty : unsupported); + } + // The seeds give both outcomes: subjects the solids support entirely, and subjects with unsupported parts left. + CHECK(empty > 0); + CHECK(unsupported > 0); + } +} + // An outline with a small clockwise hole well inside it, cut along its edge by three clip polygons that never reach the // hole. Clipper2 puts the hole at the top level of its PolyTree, beside the outline rather than under it. The coordinates // come from a sliced layer reduced to the few paths that still do this; most changes to them don't. diff --git a/tests/libslic3r/test_config.cpp b/tests/libslic3r/test_config.cpp index b1add2b3c5..705da9d36a 100644 --- a/tests/libslic3r/test_config.cpp +++ b/tests/libslic3r/test_config.cpp @@ -1507,6 +1507,21 @@ TEST_CASE("min_object_distance yields no floor when an FFF config lacks the opti } } +TEST_CASE("handle_legacy maps the boolean arc fitting values to modes", "[Config]") { + const auto [value, mode] = GENERATE(table({ + { "0", ArcFittingMode::Disabled }, + { "false", ArcFittingMode::Disabled }, + { "1", ArcFittingMode::Enabled }, + { "true", ArcFittingMode::Enabled }, + { "sparse_infill", ArcFittingMode::SparseInfill }, + })); + INFO(value); + ConfigSubstitutionContext ctxt(ForwardCompatibilitySubstitutionRule::Disable); + DynamicPrintConfig config; + config.set_deserialize("enable_arc_fitting", value, ctxt); + CHECK(config.opt_enum("enable_arc_fitting") == mode); +} + TEST_CASE("handle_legacy migrates the adaptive TPMS keys", "[Config]") { ConfigSubstitutionContext ctxt(ForwardCompatibilitySubstitutionRule::Enable); DynamicPrintConfig config; diff --git a/tests/libslic3r/test_connected_bodies.cpp b/tests/libslic3r/test_connected_bodies.cpp index b4e897ffe3..56e604e46d 100644 --- a/tests/libslic3r/test_connected_bodies.cpp +++ b/tests/libslic3r/test_connected_bodies.cpp @@ -23,6 +23,21 @@ namespace { ExPolygon rectangle(double x, double width) { return ExPolygon(Polygon::new_scale({ { x, 0. }, { x + width, 0. }, { x + width, 10. }, { x, 10. } })); } +// A ring from 0 to 30 mm with a hole from 5 to 25 mm, an island from 10 to 20 mm in that hole, and one from 40 to 50 mm alone. +ExPolygons ring_inner_alone() +{ + const auto square = [](double from, double to) { + return Polygon::new_scale({ { from, from }, { to, from }, { to, to }, { from, to } }); + }; + Polygon hole = square(5., 25.); + hole.make_clockwise(); + ExPolygon ring(square(0., 30.)); + ring.holes.emplace_back(hole); + return { ring, ExPolygon(square(10., 20.)), ExPolygon(square(40., 50.)) }; +} + +Point at(double x, double y) { return Point::new_scale(x, y); } + } // namespace TEST_CASE("Islands overlapping their neighbors' make one body", "[ConnectedBodies]") @@ -48,17 +63,8 @@ TEST_CASE("Islands overlapping their neighbors' make one body", "[ConnectedBodie TEST_CASE("The island locator tests the outlines only where boxes overlap", "[ConnectedBodies]") { - const auto square = [](double from, double to) { - return Polygon::new_scale({ { from, from }, { to, from }, { to, to }, { from, to } }); - }; - Polygon hole = square(5., 25.); - hole.make_clockwise(); - ExPolygon ring(square(0., 30.)); - ring.holes.emplace_back(hole); - ExPolygon alone(square(40., 50.)); - const ExPolygons islands = { ring, ExPolygon(square(10., 20.)), alone }; + const ExPolygons islands = ring_inner_alone(); const IslandLocator locator(islands, scaled(1.)); - const auto at = [](double x, double y) { return Point::new_scale(x, y); }; CHECK(locator.find(at(2., 2.)).first == 0); CHECK(locator.find(at(15., 15.)).first == 1); @@ -77,6 +83,23 @@ TEST_CASE("The island locator tests the outlines only where boxes overlap", "[Co CHECK(locator.find(at(35., 45.)).first == -1); } +TEST_CASE("Islands not told apart are found by their boxes", "[ConnectedBodies]") +{ + const ExPolygons islands = ring_inner_alone(); + const IslandLocator locator(islands, scaled(1.), false); + + // In the ring's hole, outside the island within it, the ring's box holds the point. + CHECK(locator.holds(0, at(7., 15.))); + const auto [island, distance] = locator.find(at(7., 15.)); + CHECK(island == 0); + CHECK_THAT(distance, WithinAbs(0., 0.)); + // A strict call still tests the outline: the ring is only the nearest, 2 mm away. + CHECK_FALSE(locator.holds(0, at(7., 15.), true)); + const auto [nearest, strict_distance] = locator.find(at(7., 15.), true); + CHECK(nearest == 0); + CHECK_THAT(strict_distance, WithinRel(sqr(scaled(2.)), 1e-6)); +} + TEST_CASE("Separate solids are separate bodies", "[ConnectedBodies]") { const indexed_triangle_set cube = its_make_cube(10., 10., 10.); diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp new file mode 100644 index 0000000000..d006e88b54 --- /dev/null +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -0,0 +1,601 @@ +#include +#include +#include +#include +#include +#include "libslic3r/Config.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" + +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" + +#include +#include +#include +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { + +Polygon rectangle(double min_x, double min_y, double max_x, double max_y) +{ + Polygon polygon({ + Point::new_scale(min_x, min_y), + Point::new_scale(max_x, min_y), + Point::new_scale(max_x, max_y), + Point::new_scale(min_x, max_y), + }); + polygon.make_counter_clockwise(); + return polygon; +} + +BedExcludeRegion region(double min_x, double min_y, double max_x, double max_y, + double z_min, double z_max, bool has_z_range = true) +{ + return {rectangle(min_x, min_y, max_x, max_y), z_min, z_max, + BedExcludeRegion::Purpose::CollisionVolume, has_z_range}; +} + +DynamicPrintConfig two_extruder_config() +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.6}); + config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d(0.0, 0.0), Vec2d(20.0, 5.0)}); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{200.0, 200.0}); + config.set_key_value("master_extruder_id", new ConfigOptionInt(1)); + config.set_key_value("printable_height", new ConfigOptionFloat(200.0)); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("10..30;0x0,10x0,10x10,0x10")); + return config; +} + +BoundingBox bounds(const BedExcludeRegion ®ion) +{ + return get_extents(region.polygon); +} + +double unscaled_x(coord_t value) +{ + return unscale(value); +} + +bool contains(const ExPolygons &polygons, double x, double y) +{ + const Point point = Point::new_scale(x, y); + return std::any_of(polygons.begin(), polygons.end(), [&](const ExPolygon &polygon) { + return polygon.contains(point); + }); +} + +struct CubeModel +{ + Model model; + ModelInstance *instance {nullptr}; + + explicit CubeModel(const Vec3d &offset = Vec3d::Zero(), const Vec3d &size = Vec3d(20.0, 20.0, 20.0)) + { + ModelObject *object = model.add_object(); + object->add_volume(make_cube(size.x(), size.y(), size.z())); + instance = object->add_instance(); + instance->set_offset(offset); + } +}; + +} // namespace + +TEST_CASE("Legacy exclusion polygons keep their point representation", "[ExclusionVolume][PrintConfig]") +{ + ConfigOptionPoints option; + REQUIRE(option.deserialize("0x0,10x0,10x10,0x10")); + REQUIRE(option.values.size() == 4); + CHECK(option.serialize() == "0x0,10x0,10x10,0x10"); + CHECK_FALSE(is_bed_exclusion_volume_syntax(option.serialize())); +} + +TEST_CASE("Belt material keep-outs are projected once without projecting collision volumes", "[ExclusionVolume][PrintConfig][Belt][Regression]") +{ + const auto [belt, axis, angle, scale_x, scale_y] = GENERATE(table({ + {true, BeltRotationAxis::X, 60.0, 1.0, 0.5}, + {true, BeltRotationAxis::X, -60.0, 1.0, 0.5}, + {true, BeltRotationAxis::Y, 60.0, 0.5, 1.0}, + {true, BeltRotationAxis::Z, 60.0, 1.0, 1.0}, + {true, BeltRotationAxis::None, 60.0, 1.0, 1.0}, + {false, BeltRotationAxis::X, 60.0, 1.0, 1.0}, + })); + const auto mode = GENERATE(BedExcludeVolumeMode::Shared, BedExcludeVolumeMode::ToolheadOffset, + BedExcludeVolumeMode::PerExtruder); + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("belt_printer", new ConfigOptionBool(belt)); + config.set_key_value("belt_slice_rotation", new ConfigOptionEnum(axis)); + config.set_key_value("belt_slice_rotation_angle", new ConfigOptionFloat(angle)); + config.set_deserialize_strict("bed_exclude_area", "100x100,150x100,150x150,100x150"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "10..30;0x0,10x0,10x10,0x10", "10..30;20x5,30x5,30x15,20x15"}); + + PrintConfig fixed; + fixed.apply(config, true); + const auto dynamic_regions = get_bed_excluded_regions_by_extruder(config); + const auto fixed_regions = get_bed_excluded_regions_by_extruder(fixed); + REQUIRE(dynamic_regions.size() == 2); + REQUIRE(fixed_regions.size() == 2); + for (size_t nozzle = 0; nozzle < dynamic_regions.size(); ++nozzle) { + REQUIRE(dynamic_regions[nozzle].size() == 2); + REQUIRE(fixed_regions[nozzle].size() == 2); + const BoundingBox area = bounds(dynamic_regions[nozzle][0]); + CHECK_THAT(unscale(area.min.x()), WithinAbs(100.0 * scale_x, 1e-5)); + CHECK_THAT(unscale(area.min.y()), WithinAbs(100.0 * scale_y, 1e-5)); + CHECK_THAT(unscale(area.max.x()), WithinAbs(150.0 * scale_x, 1e-5)); + CHECK_THAT(unscale(area.max.y()), WithinAbs(150.0 * scale_y, 1e-5)); + CHECK(dynamic_regions[nozzle][0].polygon.points == fixed_regions[nozzle][0].polygon.points); + const double offset_x = mode == BedExcludeVolumeMode::Shared ? 0.0 : 20.0 * nozzle; + const double offset_y = mode == BedExcludeVolumeMode::Shared ? 0.0 : 5.0 * nozzle; + CHECK(dynamic_regions[nozzle][1].polygon.points == rectangle(offset_x, offset_y, offset_x + 10.0, offset_y + 10.0).points); + CHECK(dynamic_regions[nozzle][1].polygon.points == fixed_regions[nozzle][1].polygon.points); + } + // The older polygon API must not apply the projection a second time. + const Polygons projected = get_bed_excluded_area(fixed); + REQUIRE(projected.size() == 1); + CHECK(projected.front().points == fixed_regions.front().front().polygon.points); + CHECK(config.option("bed_exclude_area")->serialize() == "100x100,150x100,150x150,100x150"); +} + +TEST_CASE("Belt object intersections use the projected bed area", "[ExclusionVolume][PrintConfig][Belt][Regression]") +{ + const auto [y, collides] = GENERATE(table({ + {80.0, true}, {95.0, true}, {110.0, false}, {125.0, false}, {140.0, false}, + })); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("belt_printer", new ConfigOptionBool(true)); + config.set_key_value("belt_slice_rotation", new ConfigOptionEnum(BeltRotationAxis::X)); + config.set_key_value("belt_slice_rotation_angle", new ConfigOptionFloat(45.0)); + config.set_deserialize_strict("bed_exclude_area", "100x100,150x100,150x150,100x150"); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CubeModel cube(Vec3d(120.0, y, 0.0), Vec3d(10.0, 10.0, 10.0)); + CHECK(cube.instance->intersects_bed_exclude_region(regions.front()) == collides); +} + +TEST_CASE("Legacy point options reject collision-volume syntax", "[ExclusionVolume][PrintConfig]") +{ + const std::string definition = "0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"; + ConfigOptionPoints option; + CHECK_FALSE(option.deserialize(definition)); + CHECK(option.values.empty()); + CHECK(is_bed_exclusion_volume_syntax(definition)); +} + +TEST_CASE("A bed-area polygon can also define a full-height collision volume", "[ExclusionVolume][PrintConfig]") +{ + const std::string definition = "0x0,20x0,20x10,10x10,10x20,0x20"; + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict("bed_exclude_area", definition); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString(definition)); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 2); + CHECK(regions[0].polygon.points == regions[1].polygon.points); +} + +TEST_CASE("Copied volumes preserve the bed area, existing definitions and nozzle mode", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + const std::string converted = "40x40,50x40,50x50,40x50"; + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", converted); + + SECTION("toolhead-relative definitions remain shared") { + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + append_bed_exclude_volumes(config, converted); + + CHECK(config.opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::ToolheadOffset); + CHECK(config.opt_string("bed_exclude_volumes") == + "10..30;0x0,10x0,10x10,0x10|40x40,50x40,50x50,40x50"); + } + + SECTION("individual definitions receive the former shared keep-out") { + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{"", "60x60,70x60,70x70,60x70"}); + append_bed_exclude_volumes(config, converted); + + CHECK(config.opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder); + const ConfigOptionStrings *per_extruder = config.option("extruder_bed_exclude_volumes"); + REQUIRE(per_extruder != nullptr); + REQUIRE(per_extruder->values.size() == 2); + CHECK(per_extruder->values[0] == converted); + CHECK(per_extruder->values[1] == "60x60,70x60,70x70,60x70|40x40,50x40,50x50,40x50"); + } + + CHECK(config.option("bed_exclude_area")->serialize() == converted); + + // Resetting just the opt-in settings must leave the original keep-out intact. + config.set_key_value("bed_exclude_volumes", new ConfigOptionString()); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{""}); + CHECK_FALSE(has_bed_exclude_volumes(config)); + CHECK(config.option("bed_exclude_area")->serialize() == converted); +} + +TEST_CASE("Exclusion syntax validation accepts supported forms and rejects malformed regions", "[ExclusionVolume][PrintConfig]") +{ + const auto [definition, valid] = GENERATE(table({ + {"", true}, + {"0x0,10x0,10x10,0x10", true}, + {"0..10;0x0,10x0,10x10,0x10", true}, + {"0.5..10.5;0x0,10x0,10x10,0x10", true}, + {"..10;0x0,10x0,10x10,0x10", true}, + {"10..;0x0,10x0,10x10,0x10", true}, + {"0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30", true}, + {"20..10;0x0,10x0,10x10,0x10", false}, + {"10..10;0x0,10x0,10x10,0x10", false}, + {"300..400;0x0,10x0,10x10,0x10", false}, + {"zero..10;0x0,10x0,10x10,0x10", false}, + {"0..10;0x0,10x0", false}, + {"0..10;", false}, + {"|", false}, + })); + + DYNAMIC_SECTION(definition) { + CHECK(is_valid_bed_exclude_volumes_string(definition, 200.0) == valid); + } +} + +TEST_CASE("Extended exclusion Z ranges are defaulted and clamped to printable height", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString( + "-20..25;0x0,10x0,10x10,0x10|75..150;20x0,30x0,30x10,20x10|..;40x0,50x0,50x10,40x10")); + + const std::vector regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 3); + CHECK_THAT(regions[0].z_min, WithinAbs(0.0, 1e-9)); + CHECK_THAT(regions[0].z_max, WithinAbs(25.0, 1e-9)); + CHECK_THAT(regions[1].z_min, WithinAbs(75.0, 1e-9)); + CHECK_THAT(regions[1].z_max, WithinAbs(100.0, 1e-9)); + CHECK_THAT(regions[2].z_min, WithinAbs(0.0, 1e-9)); + CHECK_THAT(regions[2].z_max, WithinAbs(100.0, 1e-9)); +} + +TEST_CASE("CLI keeps legacy areas and collision volumes on separate options", "[ExclusionVolume][PrintConfig][CLI]") +{ + const char *legacy_area_argv[] = { + "orca-slicer", "--bed-exclude-area", "0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig legacy_area_config; + t_config_option_keys extra; + t_config_option_keys keys; + REQUIRE(legacy_area_config.read_cli(3, legacy_area_argv, &extra, &keys)); + REQUIRE(legacy_area_config.opt("bed_exclude_area") != nullptr); + CHECK(legacy_area_config.opt("bed_exclude_area")->values.size() == 4); + + const char *volume_argv[] = { + "orca-slicer", "--bed-exclude-volumes", "0..10;0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig volume_config; + extra.clear(); + keys.clear(); + REQUIRE(volume_config.read_cli(3, volume_argv, &extra, &keys)); + CHECK(volume_config.opt_string("bed_exclude_volumes") == volume_argv[2]); + + const char *legacy_argv[] = { + "orca-slicer", "--bed-exclude-area", "0..10;0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig legacy_config; + extra.clear(); + keys.clear(); + CHECK_FALSE(legacy_config.read_cli(3, legacy_argv, &extra, &keys)); +} + +TEST_CASE("Legacy areas and collision volumes remain additive", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + + auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CHECK_FALSE(regions.front().is_collision_volume()); + CHECK_FALSE(has_bed_exclude_volumes(config)); + + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("20x20,30x20,30x30,20x30")); + regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 2); + CHECK_FALSE(regions[0].is_collision_volume()); + CHECK(regions[0].polygon.contains(Point::new_scale(5.0, 5.0))); + CHECK(regions[1].is_collision_volume()); + CHECK(regions[1].polygon.contains(Point::new_scale(25.0, 25.0))); +} + +TEST_CASE("An invalid collision-volume definition does not suppress the legacy area", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("not a polygon")); + + CHECK(has_bed_exclude_volumes(config)); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CHECK_FALSE(regions.front().is_collision_volume()); + CHECK_FALSE(is_valid_bed_exclude_volumes_string(config.opt_string("bed_exclude_volumes"), 100.0)); +} + +TEST_CASE("An empty collision-volume configuration falls back to the legacy area", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{"", ""}); + + CHECK_FALSE(has_bed_exclude_volumes(config)); + CHECK(active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared); + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + CHECK_FALSE(groups[0][0].is_collision_volume()); +} + +TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK_THAT(groups[0][0].z_min, WithinAbs(10.0, 1e-9)); + CHECK_THAT(groups[0][0].z_max, WithinAbs(30.0, 1e-9)); + + // A shared compatibility view contains one definition, not one duplicate per nozzle. + CHECK(get_bed_excluded_regions(config).size() == 1); +} + +TEST_CASE("Toolhead-relative exclusion volumes follow nozzle offset deltas", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + const BoundingBox reference = bounds(groups[0][0]); + const BoundingBox shifted = bounds(groups[1][0]); + CHECK_THAT(unscaled_x(shifted.min.x() - reference.min.x()), WithinAbs(20.0, 1e-6)); + CHECK_THAT(unscaled_x(shifted.min.y() - reference.min.y()), WithinAbs(5.0, 1e-6)); +} + +TEST_CASE("Toolhead-relative mode offsets collision volumes but not the shared legacy area", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", "70x70,80x70,80x80,70x80"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 2); + REQUIRE(groups[1].size() == 2); + CHECK_FALSE(groups[0][0].is_collision_volume()); + CHECK_FALSE(groups[1][0].is_collision_volume()); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK(groups[0][1].polygon.points != groups[1][1].polygon.points); + + const auto flattened = get_bed_excluded_regions(config); + CHECK(flattened.size() == 3); + CHECK(std::count_if(flattened.begin(), flattened.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }) == 1); +} + +TEST_CASE("Toolhead-relative exclusions honour a non-default reference extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("master_extruder_id", new ConfigOptionInt(2)); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + const BoundingBox first = bounds(groups[0][0]); + const BoundingBox reference = bounds(groups[1][0]); + CHECK_THAT(unscaled_x(first.min.x() - reference.min.x()), WithinAbs(-20.0, 1e-6)); + CHECK_THAT(unscaled_x(first.min.y() - reference.min.y()), WithinAbs(-5.0, 1e-6)); +} + +TEST_CASE("Individual exclusion volumes remain authoritative per extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "0..25;0x0,8x0,8x8,0x8|40..60;20x20,30x20,30x30,20x30", + "", + }); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + CHECK(groups[0].size() == 2); + CHECK(groups[1].empty()); + CHECK(get_bed_excluded_regions(config).size() == 2); +} + +TEST_CASE("Individual collision volumes retain the shared legacy area", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", "70x70,80x70,80x80,70x80"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "0..25;0x0,8x0,8x8,0x8", "0..25;20x0,28x0,28x8,20x8" + }); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 2); + REQUIRE(groups[1].size() == 2); + CHECK_FALSE(groups[0][0].is_collision_volume()); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK(groups[0][1].is_collision_volume()); + CHECK(groups[1][1].is_collision_volume()); +} + +TEST_CASE("Individual exclusion validation accepts omitted trailing extruders", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig dynamic = two_extruder_config(); + dynamic.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + dynamic.set_key_value("extruder_bed_exclude_volumes", + new ConfigOptionStrings{"0..25;0x0,8x0,8x8,0x8"}); + + FullPrintConfig config; + config.apply(dynamic, true); + const std::map errors = validate(config); + CHECK(errors.find("extruder_bed_exclude_volumes") == errors.end()); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + CHECK(groups[0].size() == 1); + CHECK(groups[1].empty()); +} + +TEST_CASE("Legacy bed helpers include only regions touching the first layer", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig dynamic = DynamicPrintConfig::full_print_config(); + dynamic.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + dynamic.set_key_value("bed_exclude_volumes", new ConfigOptionString( + "0..5;0x0,10x0,10x10,0x10|20..30;20x0,30x0,30x10,20x10")); + PrintConfig config; + config.apply(dynamic, true); + + const Polygons bed_regions = get_bed_excluded_area(config); + REQUIRE(bed_regions.size() == 1); + CHECK(bed_regions.front().contains(Point::new_scale(5.0, 5.0))); + CHECK_FALSE(bed_regions.front().contains(Point::new_scale(25.0, 5.0))); +} + +TEST_CASE("Filament mapping resolves physical exclusion extruders conservatively", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + CHECK(bed_exclusion_extruder_for_filament(0, {2, 1}, fmmManual, false, true, 2) == 1); + CHECK(bed_exclusion_extruder_for_filament(1, {2, 1}, fmmManual, false, true, 2) == 0); + + // Generic automatic multi-tool printers use matching logical and physical ids. + CHECK(bed_exclusion_extruder_for_filament(1, {1, 1}, fmmAutoForMatch, false, false, 2) == 1); + + // Until Bambu automatic grouping has produced a concrete mapping, every nozzle remains possible. + CHECK(bed_exclusion_extruder_for_filament(0, {1}, fmmAutoForMatch, true, false, 2) == -1); + CHECK(bed_exclusion_extruder_for_filament(0, {2}, fmmAutoForMatch, true, true, 2) == 1); + CHECK(bed_exclusion_extruder_for_filament(3, {}, fmmManual, false, true, 2) == -1); +} + +TEST_CASE("Exclusion Z overlap treats touching slabs conservatively", "[ExclusionVolume][Geometry]") +{ + CHECK(bed_exclusion_z_ranges_overlap(0.0, 10.0, 10.0, 20.0)); + CHECK(bed_exclusion_z_ranges_overlap(10.0, 0.0, 20.0, 10.0)); + CHECK_FALSE(bed_exclusion_z_ranges_overlap(0.0, 9.0, 10.0, 20.0)); +} + +TEST_CASE("Arrange keeps convex exclusions exact and bounds concave exclusions", "[ExclusionVolume][Geometry][Arrange]") +{ + const Polygon convex = rectangle(0.0, 0.0, 10.0, 10.0); + CHECK(bed_exclusion_arrange_polygon(convex).points == convex.points); + + Polygon concave({ + Point::new_scale(0.0, 0.0), Point::new_scale(10.0, 0.0), + Point::new_scale(10.0, 4.0), Point::new_scale(4.0, 4.0), + Point::new_scale(4.0, 10.0), Point::new_scale(0.0, 10.0), + }); + concave.make_counter_clockwise(); + REQUIRE_FALSE(concave.contains(Point::new_scale(8.0, 8.0))); + + const Polygon blocker = bed_exclusion_arrange_polygon(concave); + CHECK(blocker.points.size() == 4); + CHECK(blocker.contains(Point::new_scale(8.0, 8.0))); +} + +TEST_CASE("Active exclusion footprints select Z range nozzle translation and clearance", "[ExclusionVolume][Geometry][MultiNozzle]") +{ + const std::vector> regions_by_extruder{ + {region(0.0, 0.0, 10.0, 10.0, 0.0, 5.0)}, + {region(20.0, 0.0, 30.0, 10.0, 10.0, 20.0)}, + }; + + ExPolygons active = active_bed_exclusion_footprints( + regions_by_extruder, {1, 1, 99}, 12.0, 13.0, Point::new_scale(5.0, 2.0), scale_(1.0)); + REQUIRE(active.size() == 1); + CHECK(contains(active, 26.0, 3.0)); + CHECK(contains(active, 35.5, 3.0)); + CHECK_FALSE(contains(active, 5.0, 5.0)); + + CHECK(active_bed_exclusion_footprints(regions_by_extruder, {0}, 6.0, 9.0).empty()); +} + +TEST_CASE("Exact model intersection respects XY Z and preview collection", "[ExclusionVolume][Model]") +{ + CubeModel cube(Vec3d(30.0, 40.0, 0.0)); + + // Cross the cube's outer surface so this case can also verify the red + // preview, which is built from clipped surface triangles. The enclosed + // prism topology is covered separately below. + const BedExcludeRegion crossing = region(45.0, 45.0, 55.0, 55.0, 5.0, 15.0); + const BedExcludeRegion above = region(45.0, 45.0, 55.0, 55.0, 25.0, 30.0); + const BedExcludeRegion outside = region(60.0, 70.0, 70.0, 80.0, 0.0, 20.0); + + CHECK(cube.instance->intersects_bed_exclude_region(crossing)); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(above)); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(outside)); + + indexed_triangle_set preview; + CHECK(cube.instance->intersects_bed_exclude_region(crossing, &preview)); + CHECK_FALSE(preview.empty()); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(above, &preview)); + CHECK(preview.empty()); +} + +TEST_CASE("Exact model intersection follows instance and volume transforms", "[ExclusionVolume][Model]") +{ + CubeModel cube(Vec3d(50.0, 50.0, 0.0)); + cube.instance->set_rotation(Vec3d(0.0, 0.0, PI / 4.0)); + cube.instance->set_scaling_factor(Vec3d(1.5, 0.5, 1.0)); + + CHECK(cube.instance->intersects_bed_exclude_region(region(50.0, 50.0, 55.0, 55.0, 0.0, 20.0))); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(region(100.0, 100.0, 110.0, 110.0, 0.0, 20.0))); +} + +TEST_CASE("Exact model intersection detects an exclusion prism enclosed by a solid", "[ExclusionVolume][Model]") +{ + // A surface-only test misses this topology: the exclusion prism is fully + // enclosed, so none of the block's surface triangles enters the prism. + CubeModel block(Vec3d(200.0, 300.0, 0.0), Vec3d(100.0, 100.0, 60.0)); + const BedExcludeRegion enclosed = region(230.0, 330.0, 260.0, 358.0, 8.0, 22.0); + const BedExcludeRegion enclosing = region(190.0, 290.0, 310.0, 410.0, -5.0, 65.0); + const BedExcludeRegion above = region(230.0, 330.0, 260.0, 358.0, 65.0, 75.0); + + CHECK(block.instance->intersects_bed_exclude_region(enclosed)); + CHECK_FALSE(block.instance->intersects_bed_exclude_region(above)); + + indexed_triangle_set preview; + CHECK(block.instance->intersects_bed_exclude_region(enclosed, &preview)); + // There is no model surface inside a fully enclosed prism from which to + // build the usual red clipped-surface preview. + CHECK(preview.empty()); + + // Pin the opposite containment topology too. Here the model surface lies + // inside the prism, so the existing clipped preview remains available. + CHECK(block.instance->intersects_bed_exclude_region(enclosing, &preview)); + CHECK_FALSE(preview.empty()); + + // The multi-region wrapper must preserve the collision result even when + // that optional surface preview is empty. + CHECK(block.instance->intersects_bed_exclude_regions({above, enclosed}, &preview)); + CHECK(preview.empty()); +} diff --git a/tests/libslic3r/test_lay_on_face.cpp b/tests/libslic3r/test_lay_on_face.cpp index f1bb92a1e8..b72600807f 100644 --- a/tests/libslic3r/test_lay_on_face.cpp +++ b/tests/libslic3r/test_lay_on_face.cpp @@ -187,6 +187,23 @@ TEST_CASE("A part rests on its largest hull face even when parallel inner faces check_on_bed(plate); } +TEST_CASE("A box laid on its top face is turned over about X", "[LayOnFace]") +{ + // A face pointing straight up leaves the half turn's axis open to every horizontal + // direction. It must be the fixed X flip both times, keep the footprint and not follow + // rounding noise to an arbitrary angle. + Model model; + ModelObject &box = add_box_object(model, { 40, 20, 10 }); + lay_on_face(box, 0, { 0, 0, 1 }); + + check_size(box, { 40, 20, 10 }); + check_on_bed(box); + const Matrix3d rotation = box.instances.front()->get_matrix_no_offset().linear(); + CHECK_THAT(rotation(0, 0), WithinAbs(1., 1e-9)); + CHECK_THAT(rotation(1, 1), WithinAbs(-1., 1e-9)); + CHECK_THAT(rotation(2, 2), WithinAbs(-1., 1e-9)); +} + TEST_CASE("Faces are selected in object coordinates whatever the instance rotation", "[LayOnFace]") { Model model; diff --git a/tests/libslic3r/test_texture_displacement.cpp b/tests/libslic3r/test_texture_displacement.cpp index 4c3e74d705..d9b3ad3d90 100644 --- a/tests/libslic3r/test_texture_displacement.cpp +++ b/tests/libslic3r/test_texture_displacement.cpp @@ -2424,6 +2424,89 @@ TEST_CASE("TextureDisplacement: moving the model about the plate does not move t CHECK(max_diff < 1e-3f); } +TEST_CASE("Parts anchored at one point carry one continuous texture", "[TextureDisplacement]") +{ + // The same surface, once as a part whose origin is the anchor and once as a part whose own origin + // sits `offset` away from it - the way the bodies of a multibody object are each centred on their + // own origin. Anchored at the same point they must bake the same relief; anchored at their own + // origins, the second is the tiled pattern shifted by `offset`. + const indexed_triangle_set cube = subdivide_mesh_uniform(its_make_cube(10.f, 10.f, 10.f), 1.f, 6); + // Not a multiple of the 4 mm tile, and exact in binary like the grid itself: the checkerboard's steps + // fall right on grid vertices, so a vertex rounded across a step would bake the other side of it. + const Vec3d offset(1.25, 2.5, 0.75); + indexed_triangle_set shifted = cube; + for (Vec3f &v : shifted.vertices) + v -= offset.cast(); + const Transform3d shifted_to_world = Transform3d(Eigen::Translation3d(offset)); + + TextureDisplacementLayer layer; + layer.slot = 0; + layer.image_data = make_checkerboard_png(16, 16); + layer.tiling_scale = 4.f; + layer.depth_mm = 0.5f; + TextureDisplacementFacetsData facets; + facets[0] = paint_whole_mesh(cube); + + const indexed_triangle_set reference = build_texture_displacement(cube, { layer }, facets, classic_options()); + const Vec3d anchor = Vec3d::Zero(); + const indexed_triangle_set anchored = build_texture_displacement(shifted, { layer }, facets, classic_options(), {}, + nullptr, shifted_to_world, nullptr, nullptr, + nullptr, &anchor); + const indexed_triangle_set own_origin = build_texture_displacement(shifted, { layer }, facets, classic_options(), {}, + nullptr, shifted_to_world); + REQUIRE(anchored.vertices.size() == reference.vertices.size()); + REQUIRE(own_origin.vertices.size() == reference.vertices.size()); + + float anchored_diff = 0.f, own_origin_diff = 0.f; + for (size_t i = 0; i < reference.vertices.size(); ++i) { + anchored_diff = std::max(anchored_diff, (anchored.vertices[i] + offset.cast() - reference.vertices[i]).norm()); + own_origin_diff = std::max(own_origin_diff, (own_origin.vertices[i] + offset.cast() - reference.vertices[i]).norm()); + } + CHECK(anchored_diff < 1e-3f); + CHECK(own_origin_diff > 0.1f); +} + +TEST_CASE("A part held above the plate keeps the relief on its underside", "[TextureDisplacement]") +{ + // A fully painted cube displaces its bottom face straight down by the full depth. On its own, that + // relief is clamped to the cube's bottom (see "relief is never driven below the model's resting + // plane"); as a part of an object resting `drop` below it, it is clamped only at the object's plane. + const bool v2 = GENERATE(false, true); + const indexed_triangle_set cube = subdivide_mesh_uniform(its_make_cube(10.f, 10.f, 10.f), 2.f, 6); + + TextureDisplacementFacetsData facets{}; + facets[0] = paint_whole_mesh(cube); + TextureDisplacementLayer layer; + layer.slot = 0; + layer.depth_mm = 2.0f; + layer.tiling_scale = 5.0f; + layer.image_data = make_flat_gray_png(255); // full depth everywhere + + TextureDisplacementOptions options = classic_options(); + options.pipeline_v2 = v2; + options.v2_refine_mm = 2.f; + options.v2_max_triangles_k = 0; + + const auto lowest_after = [&](float drop) { + const indexed_triangle_set out = build_texture_displacement(cube, { layer }, facets, options, {}, nullptr, + Transform3d::Identity(), nullptr, nullptr, nullptr, + nullptr, drop); + REQUIRE_FALSE(out.vertices.empty()); + float lowest = std::numeric_limits::max(); + for (const Vec3f &v : out.vertices) + lowest = std::min(lowest, v.z()); + return lowest; + }; + + CAPTURE(v2); + // The cube's bottom is z = 0. With the object resting 5 mm lower, the 2 mm relief fits above it... + CHECK_THAT(lowest_after(5.f), WithinAbs(-2.0f, 1e-3f)); + // ...with the object resting 1 mm lower, it is clamped at that plane... + CHECK_THAT(lowest_after(1.f), WithinAbs(-1.0f, 1e-3f)); + // ...and as the lowest part, at its own bottom. + CHECK_THAT(lowest_after(0.f), WithinAbs(0.0f, 1e-3f)); +} + // Longest edge over the shortest altitude: 1.15 for an equilateral triangle, 2 for a right isosceles // one, unbounded for a needle. static float triangle_aspect(const Vec3f &a, const Vec3f &b, const Vec3f &c) diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 727709f5b2..f1cd69b601 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -2,6 +2,7 @@ get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME) add_executable(${_TEST_NAME}_tests ${_TEST_NAME}_tests_main.cpp test_bambu_filament_ids.cpp + test_bed_exclusion_fields.cpp test_config_value_formatter.cpp test_creality_cfs_match.cpp test_dev_mapping.cpp diff --git a/tests/slic3rutils/test_bed_exclusion_fields.cpp b/tests/slic3rutils/test_bed_exclusion_fields.cpp new file mode 100644 index 0000000000..2c02e5578a --- /dev/null +++ b/tests/slic3rutils/test_bed_exclusion_fields.cpp @@ -0,0 +1,39 @@ +#include +#include "libslic3r/Point.hpp" +#include + +#include "libslic3r/PrintConfig.hpp" +#include "slic3r/GUI/GUI.hpp" + +#include + +using namespace Slic3r; + +TEST_CASE("Pasted volume syntax leaves the saved bed area intact pending confirmation", "[ExclusionVolume][GUI][Regression]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const std::string area = "0x0,20x0,20x10,10x10,10x20,0x20"; + config.set_deserialize_strict("bed_exclude_area", area); + const std::string pasted = "5..10;40x40,50x40,50x50,40x50"; + + // OptionsGroup updates the config before Tab asks whether to copy the text. + GUI::change_opt_value(config, "bed_exclude_area", boost::any(pasted)); + CHECK(config.option("bed_exclude_area")->serialize() == area); + CHECK_FALSE(has_bed_exclude_volumes(config)); + + append_bed_exclude_volumes(config, pasted); + CHECK(config.opt_string("bed_exclude_volumes") == pasted); + CHECK(config.option("bed_exclude_area")->serialize() == area); +} + +TEST_CASE("The normal bed-area field still accepts arbitrary polygons and clearing", "[ExclusionVolume][GUI][Regression]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const Pointfs polygon{Vec2d(0, 0), Vec2d(20, 0), Vec2d(20, 10), Vec2d(10, 10), Vec2d(10, 20), Vec2d(0, 20)}; + GUI::change_opt_value(config, "bed_exclude_area", boost::any(polygon)); + CHECK(config.option("bed_exclude_area")->values == polygon); + CHECK_FALSE(has_bed_exclude_volumes(config)); + + GUI::change_opt_value(config, "bed_exclude_area", boost::any(Pointfs{})); + CHECK(config.option("bed_exclude_area")->values.empty()); +} diff --git a/tests/slic3rutils/test_imgui_wrapper.cpp b/tests/slic3rutils/test_imgui_wrapper.cpp index 544a3832f5..bdb6f24966 100644 --- a/tests/slic3rutils/test_imgui_wrapper.cpp +++ b/tests/slic3rutils/test_imgui_wrapper.cpp @@ -75,7 +75,27 @@ struct ImGuiFrames ImGui::End(); } - char text[16] = ""; + void draw_slider() + { + ImGui::Begin("window"); + ImGui::SliderFloat("##slider", &value, 0.f, 1.f); + const ImVec2 min = ImGui::GetItemRectMin(), max = ImGui::GetItemRectMax(); + slider_center = ImVec2((min.x + max.x) / 2, (min.y + max.y) / 2); + ImGui::End(); + } + + // Presses the left button at pos, or releases it, and draws the slider in two frames. + void mouse(const ImVec2& pos, bool down) + { + ImGui::GetIO().MousePos = pos; + ImGui::GetIO().MouseDown[0] = down; + frame([this] { draw_slider(); }); + frame([this] { draw_slider(); }); + } + + char text[16] = ""; + float value = 0.f; + ImVec2 slider_center; }; void draw_modal() @@ -84,6 +104,28 @@ void draw_modal() ImGui::EndPopup(); } +void draw_dropdown(bool open) +{ + ImGui::Begin("window"); + if (open) + ImGui::OpenPopup("dropdown"); + if (ImGui::BeginPopup("dropdown")) { + ImGui::Text("item"); + ImGui::EndPopup(); + } + ImGui::End(); +} + +wxKeyEvent key_event(wxEventType type, int key_code, int modifiers = wxMOD_NONE) +{ + wxKeyEvent evt(type); + evt.m_keyCode = key_code; + evt.SetControlDown(modifiers & wxMOD_CONTROL); + evt.SetShiftDown(modifiers & wxMOD_SHIFT); + evt.SetAltDown(modifiers & wxMOD_ALT); + return evt; +} + } // namespace TEST_CASE("a vertical wheel event steps ImGui's wheel in its own direction", "[ImGuiWrapper]") @@ -103,6 +145,21 @@ TEST_CASE("a wheel event with no rotation or on the horizontal axis does not ste CHECK_THAT(wheel_after(rotation, axis), WithinAbs(0.0, 0.0)); } +TEST_CASE("a mouse event replaces a modifier whose key-up went to another window", "[ImGuiWrapper][Regression]") +{ + ImGuiWrapper imgui; + imgui.set_display_size(800.f, 600.f); + ImGui::GetIO().KeyCtrl = true; + + wxMouseEvent move(wxEVT_MOTION); + imgui.update_mouse_data(move); + CHECK_FALSE(ImGui::GetIO().KeyCtrl); + + move.SetControlDown(true); + imgui.update_mouse_data(move); + CHECK(ImGui::GetIO().KeyCtrl); +} + TEST_CASE("an InputText counts as active only while it holds the keyboard", "[ImGuiWrapper]") { ImGuiFrames f; @@ -161,3 +218,137 @@ TEST_CASE("ImGui owns every key under a modal and text-editing keys in an active }); CHECK(f.imgui.owns_key(save)); } + +TEST_CASE("ImGui owns the whole keyboard under a modal or in an active InputText", "[ImGuiWrapper]") +{ + ImGuiFrames f; + CHECK_FALSE(f.imgui.owns_keyboard()); + + f.frame([&] { f.draw_input(true); }); + f.frame([&] { f.draw_input(false); }); + CHECK(f.imgui.owns_keyboard()); + + f.frame([] {}); + CHECK_FALSE(f.imgui.owns_keyboard()); + f.frame([] { + ImGui::OpenPopup("modal"); + draw_modal(); + }); + CHECK(f.imgui.owns_keyboard()); +} + +TEST_CASE("an open dropdown owns the whole keyboard until it is closed", "[ImGuiWrapper]") +{ + ImGuiFrames f; + f.frame([] { draw_dropdown(true); }); + CHECK(f.imgui.popup_open()); + CHECK(f.imgui.owns_keyboard()); + + f.imgui.close_top_popup(); + f.frame([] { draw_dropdown(false); }); + CHECK_FALSE(f.imgui.popup_open()); + CHECK_FALSE(f.imgui.owns_keyboard()); +} + +TEST_CASE("closing the top popup leaves a modal open", "[ImGuiWrapper]") +{ + ImGuiFrames f; + f.frame([] { + ImGui::OpenPopup("modal"); + draw_modal(); + }); + f.imgui.close_top_popup(); + f.frame([] { draw_modal(); }); + CHECK(f.imgui.modal_popup_open()); +} + +TEST_CASE("a held slider owns the keyboard but not the keys Global shortcuts use", "[ImGuiWrapper]") +{ + ImGuiFrames f; + f.mouse(ImVec2(0, 0), false); + CHECK_FALSE(f.imgui.item_held()); + f.mouse(f.slider_center, true); + CHECK(f.imgui.item_held()); + CHECK(f.imgui.owns_keyboard()); + CHECK_FALSE(f.imgui.owns_key(KeyChord{ 'M' })); + CHECK_FALSE(f.imgui.owns_key(KeyChord{ WXK_LEFT })); + + f.mouse(f.slider_center, false); + CHECK_FALSE(f.imgui.owns_keyboard()); +} + +TEST_CASE("a slider typed into once is not a text field when dragged", "[ImGuiWrapper][Regression]") +{ + ImGuiFrames f; + f.mouse(ImVec2(0, 0), false); + ImGui::GetIO().KeyCtrl = true; // Ctrl+click types a value + f.mouse(f.slider_center, true); + ImGui::GetIO().KeyCtrl = false; + f.mouse(f.slider_center, false); + REQUIRE(f.imgui.text_input_active()); + + f.mouse(ImVec2(0, 0), true); // a click elsewhere closes the field + f.mouse(ImVec2(0, 0), false); + f.mouse(f.slider_center, true); + REQUIRE(ImGui::GetInputTextState(ImGui::GetActiveID()) != nullptr); + CHECK_FALSE(f.imgui.text_input_active()); + CHECK_FALSE(f.imgui.owns_key(KeyChord{ 'M' })); +} + +TEST_CASE("a key's char event gets its key-down's answer", "[ImGuiWrapper]") +{ + ImGuiFrames f; + f.frame([&] { f.draw_input(true); }); + f.frame([&] { f.draw_input(false); }); + CHECK(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, 'A'))); + f.frame([] {}); // the field closes before the char arrives + REQUIRE_FALSE(f.imgui.text_input_active()); + CHECK(f.imgui.claim_key_event(key_event(wxEVT_CHAR, 'a'))); + + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, 'B'))); + f.frame([&] { f.draw_input(true); }); // the field opens before the char arrives + f.frame([&] { f.draw_input(false); }); + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_CHAR, 'b'))); + // A char with no key-down before it is decided on its own. + CHECK(f.imgui.claim_key_event(key_event(wxEVT_CHAR, 'c'))); +} + +TEST_CASE("a held key's repeats and release get its press's answer", "[ImGuiWrapper]") +{ + ImGuiFrames f; + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, WXK_RIGHT))); + f.frame([&] { f.draw_input(true); }); + f.frame([&] { f.draw_input(false); }); + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, WXK_RIGHT))); + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_KEY_UP, WXK_RIGHT))); + + CHECK(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, WXK_RIGHT))); + CHECK(f.imgui.claim_key_event(key_event(wxEVT_KEY_UP, WXK_RIGHT))); + // The release also clears the press's answer for a later char with no key-down. + f.frame([] {}); + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_CHAR, 'a'))); +} + +TEST_CASE("a key pressed again after the canvas lost the focus is decided afresh", "[ImGuiWrapper]") +{ + ImGuiFrames f; + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, 'M'))); + f.imgui.forget_key_claims(); // the key-up went to the window that took the focus + + f.frame([&] { f.draw_input(true); }); + f.frame([&] { f.draw_input(false); }); + CHECK(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, 'M'))); +} + +TEST_CASE("an active ImGui field claims every key, whether it edits text or not", "[ImGuiWrapper]") +{ + const int key = GENERATE(int('A'), int('D'), int(WXK_SHIFT)); + ImGuiFrames f; + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, key, wxMOD_CONTROL))); + CHECK_FALSE(f.imgui.claim_key_event(key_event(wxEVT_KEY_UP, key, wxMOD_CONTROL))); + + f.frame([&] { f.draw_input(true); }); + f.frame([&] { f.draw_input(false); }); + CHECK(f.imgui.claim_key_event(key_event(wxEVT_KEY_DOWN, key, wxMOD_CONTROL))); + CHECK(f.imgui.claim_key_event(key_event(wxEVT_KEY_UP, key, wxMOD_CONTROL))); +} diff --git a/tests/slic3rutils/test_plugin_host_api.cpp b/tests/slic3rutils/test_plugin_host_api.cpp index 301acbc7cc..bcb95ecceb 100644 --- a/tests/slic3rutils/test_plugin_host_api.cpp +++ b/tests/slic3rutils/test_plugin_host_api.cpp @@ -1,3 +1,20 @@ +// why: keep the Windows headers ahead of libslic3r. Model.hpp pulls in Format/STEP.hpp, and +// OCCT's Standard_Macro.hxx defines NOUSER and NOGDI on Windows so that windows.h does not +// collide with OCCT's identifiers. Defined that early they also hide the USER and GDI +// declarations, and the wx MSW headers Field.hpp reaches (wx/wxprec.h -> wx/msw/private.h) +// need WNDPROC, RGB and the ::GetWindowRect family. Including windows.h first, as +// libslic3r_gui does through pchheader.hpp or win_platform.hpp, keeps them. +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include + #include +#endif + #include #include @@ -6,8 +23,12 @@ #include #include #include +#include #include +#include +#include + #include #include #include @@ -137,6 +158,143 @@ TEST_CASE("Plugin host API exposes host-owned bundle and preset surface to Pytho CHECK(printers.attr("find_preset")(printer_preset.name).attr("name").cast() == printer_preset.name); } +TEST_CASE("Plugin host API exposes the editable preset category handles and guards them before Orca app initialization", + "[PluginHost][Python]") +{ + py::object host = import_orca_module().attr("host"); + py::object preset = host.attr("preset"); + + REQUIRE(has_attr(preset, "PresetEditor")); + REQUIRE(has_attr(preset, "process")); + REQUIRE(has_attr(preset, "printer")); + REQUIRE(has_attr(preset, "filament")); + + py::object process = preset.attr("process"); + py::object printer = preset.attr("printer"); + py::object filament = preset.attr("filament"); + + CHECK(process.attr("type").cast() == Slic3r::Preset::TYPE_PRINT); + CHECK(printer.attr("type").cast() == Slic3r::Preset::TYPE_PRINTER); + CHECK(filament.attr("type").cast() == Slic3r::Preset::TYPE_FILAMENT); + for (const py::object& editor : { process, printer, filament }) + CHECK(has_attr(editor, "update")); + + // With no wx application the call must fail cleanly, like the rest of host.preset, and must not + // be mistaken for a missing attribute or an argument error. + for (const py::object& editor : { process, printer, filament }) { + try { + editor.attr("update")("layer_height", "0.25"); + FAIL("preset editor update unexpectedly succeeded without a wx application"); + } catch (const py::error_already_set& error) { + CHECK(error.matches(PyExc_RuntimeError)); + CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos); + } + } +} + +TEST_CASE("Plugin host API exposes the filament slot form of preset update and guards it", "[PluginHost][Python]") +{ + py::object host = import_orca_module().attr("host"); + py::object preset = host.attr("preset"); + + // The filament editor accepts update(slot_number, key, value) as well as update(key, value); with + // no wx application it reaches the same clean failure as the rest of host.preset. The slot + // validation and the switch/cancel path need a running app, so they are not exercised here. + try { + preset.attr("filament").attr("update")(1, "layer_height", "0.25"); + FAIL("slot-addressed filament update unexpectedly succeeded without a wx application"); + } catch (const py::error_already_set& error) { + CHECK(error.matches(PyExc_RuntimeError)); + CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos); + } + + // The process and printer editors accept only update(key, value); the slot form is rejected + // before any application access, naming the editor that does accept it. + for (const char* name : { "process", "printer" }) { + CAPTURE(name); + try { + preset.attr(name).attr("update")(1, "layer_height", "0.25"); + FAIL("slot-addressed update on a non-filament editor unexpectedly succeeded"); + } catch (const py::error_already_set& error) { + CHECK(error.matches(PyExc_ValueError)); + CHECK(std::string(error.what()).find("only available on") != std::string::npos); + } + } +} + +TEST_CASE("Plugin host API exposes staged preset update transactions", "[PluginHost][Python]") +{ + py::object preset = import_orca_module().attr("host").attr("preset"); + py::object transaction_type = preset.attr("PresetTransaction"); + py::object result_type = preset.attr("PresetUpdateResult"); + + CHECK(has_attr(transaction_type, "set")); + CHECK(has_attr(transaction_type, "commit")); + CHECK(has_attr(result_type, "target_name")); + CHECK(has_attr(result_type, "selection_changed")); + CHECK(has_attr(result_type, "slot_assignment_changed")); + CHECK(has_attr(result_type, "shared_slots")); + + for (const char* name : { "process", "printer" }) { + CAPTURE(name); + py::object editor = preset.attr(name); + CHECK(has_attr(editor, "begin_update")); + try { + editor.attr("begin_update")(); + FAIL("begin_update unexpectedly succeeded without a wx application"); + } catch (const py::error_already_set& error) { + CHECK(error.matches(PyExc_RuntimeError)); + CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos); + } + } + + py::object filament = preset.attr("filament"); + CHECK(has_attr(filament, "begin_update")); + try { + filament.attr("begin_update")(1); + FAIL("filament begin_update unexpectedly succeeded without a wx application"); + } catch (const py::error_already_set& error) { + CHECK(error.matches(PyExc_RuntimeError)); + CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos); + } +} + +TEST_CASE("A settings group resolves an option's id from its option map", "[PluginHost]") +{ + using Slic3r::GUI::option_id_in_map; + using Slic3r::GUI::t_opt_map; + + // The map ConfigOptionsGroup::get_option leaves: a scalar option, and a per-extruder option + // whose entries carry their index. + t_opt_map options; + options.emplace("layer_height", std::make_pair(std::string("layer_height"), -1)); + options.emplace("nozzle_diameter#0", std::make_pair(std::string("nozzle_diameter"), 0)); + options.emplace("nozzle_diameter#1", std::make_pair(std::string("nozzle_diameter"), 1)); + + // A negative index resolves a scalar option and yields its own (negative) index. + int index = -1; + CHECK(option_id_in_map(options, "layer_height", index) == "layer_height"); + CHECK(index == -1); + + // A negative index on a vector option matches several entries, so it resolves to nothing. + index = -1; + CHECK(option_id_in_map(options, "nozzle_diameter", index).empty()); + + // An explicit index selects that entry. + index = 1; + CHECK(option_id_in_map(options, "nozzle_diameter", index) == "nozzle_diameter#1"); + CHECK(index == 1); + + // An index no entry carries, and a key the map does not own, resolve to nothing. + index = 7; + CHECK(option_id_in_map(options, "nozzle_diameter", index).empty()); + index = -1; + CHECK(option_id_in_map(options, "wall_loops", index).empty()); + + const t_opt_map empty; + CHECK(option_id_in_map(empty, "layer_height", index).empty()); +} + TEST_CASE("Plugin host API reports unavailable GUI objects before Orca app initialization", "[PluginHost][Python]") { py::object host = import_orca_module().attr("host"); diff --git a/tests/slic3rutils/test_shortcuts.cpp b/tests/slic3rutils/test_shortcuts.cpp index 171d3257b0..036c769dc0 100644 --- a/tests/slic3rutils/test_shortcuts.cpp +++ b/tests/slic3rutils/test_shortcuts.cpp @@ -221,6 +221,7 @@ TEST_CASE("Every shortcut is listed under the section of its table row", "[Short CHECK(shortcut_section(Shortcut::GizmoBrimEars) == ShortcutSection::Gizmos); CHECK(shortcut_section(Shortcut::MovesSliderEnd) == ShortcutSection::Sliders); CHECK(shortcut_section(Shortcut::ViewDefault) == ShortcutSection::Camera); + CHECK(shortcut_section(Shortcut::ShowCollisionVolumes) == ShortcutSection::Display); CHECK(shortcut_section(Shortcut::KeyboardShortcuts) == ShortcutSection::Application); CHECK(shortcut_section(Shortcut::Quit) == ShortcutSection::Application); CHECK(std::string(section_name(ShortcutSection::SlicingAndPrinting)) == "Slicing and printing");