mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-11-22 21:50:51 -05:00
Merge branch 'main' into hanif/seam-stagger-hairpin-bound
This commit is contained in:
117 files changed
+7423
-838
No files matched your search
@@ -10,35 +10,42 @@ permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
# Overlapping runs would overwrite each other's saved progress.
|
||||
concurrency:
|
||||
group: stale
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v11
|
||||
with:
|
||||
# Each new stale label costs about 2 operations. Runs that stop early
|
||||
# continue from the same place the next day.
|
||||
operations-per-run: 300
|
||||
# Each stale label or close costs about 2 operations and posts one
|
||||
# comment, so 800 stays under GitHub's limit of 500 comments an hour.
|
||||
# Runs that stop early continue from the same place the next day.
|
||||
operations-per-run: 800
|
||||
ascending: true
|
||||
stale-issue-label: stale
|
||||
stale-pr-label: stale
|
||||
remove-stale-when-updated: true
|
||||
|
||||
# The last step mirrors the exempt and only-labels options below.
|
||||
# Update its filters when they change.
|
||||
|
||||
# Issues
|
||||
days-before-issue-stale: 90
|
||||
days-before-issue-close: 14
|
||||
close-issue-reason: not_planned
|
||||
exempt-issue-labels: enhancement
|
||||
exempt-all-issue-assignees: true
|
||||
exempt-all-issue-milestones: true
|
||||
stale-issue-message: |
|
||||
This issue has had no activity for 90 days, so it will be closed in 14 days.
|
||||
|
||||
If it still happens on the latest OrcaSlicer release, please leave a comment with the version you tested and it will stay open.
|
||||
If it's a bug that still happens on the latest OrcaSlicer release, please leave a comment with the version you tested. If it's a feature request you still want, please leave a comment saying so. Either one keeps it open.
|
||||
close-issue-message: |
|
||||
This issue was closed because there was no activity after the reminder.
|
||||
|
||||
If it still happens on the latest release, leave a comment here and a team member can reopen it, or open a new issue with the details.
|
||||
If it still matters to you, leave a comment here and a team member can reopen it, or open a new issue with the details.
|
||||
|
||||
# PRs: only PRs where we asked the author for something
|
||||
only-pr-labels: "wait for response"
|
||||
@@ -51,8 +58,29 @@ jobs:
|
||||
stale-pr-message: |
|
||||
We asked for changes or more information on this PR, and there has been no activity for 90 days. It will be closed in 14 days.
|
||||
|
||||
To keep it open, leave a comment. If you push new commits, please also leave a short comment, because a push alone does not reset this. If you no longer have time for it, that is fine, just let us know.
|
||||
To keep it open, leave a comment. If you push new commits, please also leave a short comment so we know it's ready for another look. If you no longer have time for it, that is fine, just let us know.
|
||||
close-pr-message: |
|
||||
This PR was closed because we did not hear back after the reminder. Thank you for the work you put into it.
|
||||
|
||||
If you want to continue, push your changes and reopen it, or open a new PR.
|
||||
|
||||
# The stale bot checks exemptions before activity, so it never comes back
|
||||
# to a stale item that became exempt. Remove the label from those here.
|
||||
- name: Remove stale labels the stale bot will not revisit
|
||||
if: ${{ !cancelled() }}
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
{
|
||||
gh issue list -R "$GITHUB_REPOSITORY" --label stale --state open --limit 5000 \
|
||||
--json number,assignees,milestone \
|
||||
--jq '.[] | select((.assignees | length > 0) or .milestone != null) | .number'
|
||||
gh pr list -R "$GITHUB_REPOSITORY" --label stale --state open --limit 1000 \
|
||||
--json number,isDraft,assignees,milestone,labels \
|
||||
--jq '.[] | select(.isDraft or (.assignees | length > 0) or .milestone != null
|
||||
or ([.labels[].name] | index("wait for response") | not)) | .number'
|
||||
} | while read -r n; do
|
||||
gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$n/labels/stale" --silent < /dev/null ||
|
||||
echo "::warning::Could not remove the stale label from #$n"
|
||||
done
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Remove stale label on comment
|
||||
|
||||
# stale.yml only removes the label when its daily run gets back to an item,
|
||||
# which can take a few days. This removes it as soon as someone comments.
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
unstale:
|
||||
if: >-
|
||||
github.repository == 'OrcaSlicer/OrcaSlicer' &&
|
||||
github.event.issue.state == 'open' &&
|
||||
github.event.comment.user.type == 'User' &&
|
||||
contains(github.event.issue.labels.*.name, 'stale')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Remove the stale label
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
NUMBER: ${{ github.event.issue.number }}
|
||||
run: |
|
||||
# "Close with comment" sends the event while the issue is still open.
|
||||
state=$(gh api "repos/$GITHUB_REPOSITORY/issues/$NUMBER" --jq .state)
|
||||
if [ "$state" != open ]; then
|
||||
exit 0
|
||||
fi
|
||||
# A 404 means another comment or the stale run already removed it.
|
||||
if ! gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$NUMBER/labels/stale" --silent 2> err.txt; then
|
||||
cat err.txt >&2
|
||||
grep -q "HTTP 404" err.txt
|
||||
fi
|
||||
Vendored
+2
@@ -43,6 +43,8 @@ orcaslicer_add_cmake_project(Boost
|
||||
URL "https://github.com/boostorg/boost/releases/download/boost-1.84.0/boost-1.84.0.tar.gz"
|
||||
URL_HASH SHA256=4d27e9efed0f6f152dc28db6430b9d3dfb40c0345da7342eaa5a987dde57bd95
|
||||
LIST_SEPARATOR |
|
||||
# Lets Boost.Locale configure with CMake 4.5; see the script.
|
||||
PATCH_COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=<SOURCE_DIR> -P ${CMAKE_CURRENT_LIST_DIR}/fix_locale_source_group.cmake
|
||||
CMAKE_ARGS
|
||||
-DBOOST_EXCLUDE_LIBRARIES:STRING=contract|fiber|numpy|stacktrace|wave|test
|
||||
-DBOOST_LOCALE_ENABLE_ICU:BOOL=OFF # do not link to libicu, breaks compatibility between distros
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
# Boost.Locale lists include/boost/locale.hpp in a source_group(TREE) rooted at include/boost/locale.
|
||||
# Before 4.5, CMake compared the two as strings and accepted it. CMake 4.5 reworked source_group() and
|
||||
# compares path components, so it stops the configure with "is not a prefix of file". locale.hpp gets its own group on the
|
||||
# following line of that file, so only the headers under include/boost/locale/ go into the tree.
|
||||
#
|
||||
# Run as the PATCH_COMMAND with -DSOURCE_DIR=<Boost source>. A second run leaves the file as it is.
|
||||
set(_file "${SOURCE_DIR}/libs/locale/CMakeLists.txt")
|
||||
set(_old [[list(FILTER sources_inc EXCLUDE REGEX "^src/")]])
|
||||
set(_new [[list(FILTER sources_inc INCLUDE REGEX "^include/boost/locale/")]])
|
||||
|
||||
file(READ "${_file}" _content)
|
||||
string(FIND "${_content}" "${_new}" _patched)
|
||||
if (_patched EQUAL -1)
|
||||
string(FIND "${_content}" "${_old}" _found)
|
||||
if (_found EQUAL -1)
|
||||
message(FATAL_ERROR "${_file} no longer has the line this script replaces. Check whether this Boost "
|
||||
"version still needs deps/Boost/fix_locale_source_group.cmake.")
|
||||
endif ()
|
||||
string(REPLACE "${_old}" "${_new}" _content "${_content}")
|
||||
file(WRITE "${_file}" "${_content}")
|
||||
endif ()
|
||||
Vendored
+8
@@ -2,10 +2,18 @@
|
||||
# the parser must not come from a distro or SDK copy that may predate it.
|
||||
# XML_DTD and XML_GE are passed explicitly: 2.4.0 gated the guard behind XML_DTD
|
||||
# and 2.6.0 behind XML_GE, so neither may be left to the default.
|
||||
set(_expat_c_flags_line "")
|
||||
if (MSVC)
|
||||
# UTF-8 quotes in random_rand_s.c comments can swallow a preprocessor line
|
||||
# when MSVC reads the source using the system's legacy code page.
|
||||
set(_expat_c_flags_line "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} /utf-8")
|
||||
endif ()
|
||||
|
||||
orcaslicer_add_cmake_project(EXPAT
|
||||
URL https://github.com/libexpat/libexpat/releases/download/R_2_10_0/expat-2.10.0.tar.gz
|
||||
URL_HASH SHA256=5466a341f9c692ef7a958a6881311be597f8e1ce345984cf78414f54793dea4c
|
||||
CMAKE_ARGS
|
||||
"${_expat_c_flags_line}"
|
||||
-DBUILD_SHARED_LIBS=OFF
|
||||
-DEXPAT_SHARED_LIBS=OFF
|
||||
-DEXPAT_DTD=ON
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
diff --git a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx
|
||||
index 6f63781..9b1c08e 100644
|
||||
--- a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx
|
||||
+++ b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx
|
||||
@@ -210,10 +210,10 @@ private:
|
||||
|
||||
// Define two pcurves of the seam-edge.
|
||||
occ::handle<Geom2d_Curve> aPC1, aPC2;
|
||||
- double af, al;
|
||||
+ double af, al, af1, al1;
|
||||
|
||||
aE.Orientation(TopAbs_FORWARD);
|
||||
- aPC1 = BRep_Tool::CurveOnSurface(aE, aF, af, al);
|
||||
+ aPC1 = BRep_Tool::CurveOnSurface(aE, aF, af1, al1);
|
||||
|
||||
aE.Orientation(TopAbs_REVERSED);
|
||||
aPC2 = BRep_Tool::CurveOnSurface(aE, aF, af, al);
|
||||
@@ -224,7 +224,9 @@ private:
|
||||
}
|
||||
|
||||
// Select the correct pcurve of the seam-edge.
|
||||
- const gp_Pnt2d& aFPntOfPC1 = aPC1->Value(aPC1->FirstParameter());
|
||||
+ // Use the edge's first parameter. A Geom2d_Line's FirstParameter() is -Precision::Infinite(),
|
||||
+ // where a direction of (2e-16, -1) from rounding error gives an X far outside the U range.
|
||||
+ const gp_Pnt2d aFPntOfPC1 = aPC1->Value(af1);
|
||||
|
||||
if (std::abs(aLPntOfIPC1.X() - aFPntOfPC1.X()) > Precision::Confusion())
|
||||
{
|
||||
@@ -0,0 +1,25 @@
|
||||
diff --git a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx
|
||||
index 6f63781..97a20d3 100644
|
||||
--- a/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx
|
||||
+++ b/src/ModelingAlgorithms/TKMesh/BRepMesh/BRepMesh_ModelPreProcessor.cxx
|
||||
@@ -223,10 +223,16 @@ private:
|
||||
return false;
|
||||
}
|
||||
|
||||
- // Select the correct pcurve of the seam-edge.
|
||||
- const gp_Pnt2d& aFPntOfPC1 = aPC1->Value(aPC1->FirstParameter());
|
||||
-
|
||||
- if (std::abs(aLPntOfIPC1.X() - aFPntOfPC1.X()) > Precision::Confusion())
|
||||
+ // Select the correct pcurve of the seam-edge: the one closer to the discrete pcurve.
|
||||
+ // Both pcurves of a seam share the edge's range, so evaluate them at its start. A
|
||||
+ // Geom2d_Line's FirstParameter() is -Precision::Infinite(), where a direction of (2e-16, -1)
|
||||
+ // from rounding error gives an X far outside the U range. A Precision::Confusion() threshold
|
||||
+ // fails too, because BRepMesh_ModelHealer has already moved the ends of the discrete pcurve
|
||||
+ // onto those of the neighbouring edges, whose pcurves can end slightly past the seam.
|
||||
+ const gp_Pnt2d aFPntOfPC1 = aPC1->Value(af);
|
||||
+ const gp_Pnt2d aFPntOfPC2 = aPC2->Value(af);
|
||||
+
|
||||
+ if (std::abs(aLPntOfIPC1.X() - aFPntOfPC1.X()) > std::abs(aLPntOfIPC1.X() - aFPntOfPC2.X()))
|
||||
{
|
||||
std::swap(aPC1, aPC2);
|
||||
}
|
||||
Vendored
+5
-3
@@ -48,12 +48,14 @@ endif ()
|
||||
orcaslicer_add_cmake_project(OCCT
|
||||
URL https://github.com/Open-Cascade-SAS/OCCT/archive/refs/tags/V8_0_1.zip
|
||||
URL_HASH SHA256=7c033d917ee8f040c0512d289dcc5f02c148889d5bac17c3e25639accb44f0da
|
||||
# Makes BRepMesh triangulate cone faces whose seam pcurve is slightly tilted
|
||||
# (Open-Cascade-SAS/OCCT#572); remove the patch once an OCCT release includes the fix.
|
||||
# 0001 makes BRepMesh pair each seam pcurve of a cone with the right side of the seam, which
|
||||
# failed when the seam pcurve is slightly tilted (Open-Cascade-SAS/OCCT#572) or the adjacent
|
||||
# pcurves end slightly past the seam. Either way the face meshed to a sliver or not at all.
|
||||
# Remove the patch once an OCCT release includes the fix.
|
||||
# 0002 compiles one file without optimization under cl for ARM64, where MSVC 14.52 crashes
|
||||
# on it with an internal compiler error; remove it once the runner image ships a fixed MSVC.
|
||||
PATCH_COMMAND git apply ${OCCT_DIRECTORY_FLAG} --verbose --ignore-space-change --whitespace=fix
|
||||
${CMAKE_CURRENT_LIST_DIR}/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch
|
||||
${CMAKE_CURRENT_LIST_DIR}/0001-BRepMesh-seam-pcurve-selection.patch
|
||||
${CMAKE_CURRENT_LIST_DIR}/0002-BRepGraph-MSVC-ARM64-ICE-workaround.patch
|
||||
#DEPENDS dep_Boost
|
||||
CMAKE_ARGS
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
--- a/Modules/_winapi.c
|
||||
+++ b/Modules/_winapi.c
|
||||
@@ -1252,7 +1252,7 @@ _winapi_CreateProcess_impl(PyObject *module, const Py_UNICODE *application_name,
|
||||
wchar_t *command_line_copy = NULL;
|
||||
AttributeList attribute_list = {0};
|
||||
|
||||
- if (PySys_Audit("_winapi.CreateProcess", "uuu", application_name,
|
||||
+ if (PySys_Audit("_winapi.CreateProcess", "uOu", application_name,
|
||||
command_line, current_directory) < 0) {
|
||||
return NULL;
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# Applied as PATCH_COMMAND for CPython on Windows, from the extracted source directory.
|
||||
#
|
||||
# CPython 3.12.13 raises the _winapi.CreateProcess audit event with PySys_Audit format "uuu",
|
||||
# although command_line is a Python object: audit hooks receive garbage instead of the command
|
||||
# line. PluginAuditManager turns that argument into a process grant's target, so the prompt
|
||||
# named the wrong executable and the grant it saved could not cover a real call. The patch
|
||||
# changes the format to "uOu", as upstream does (python/cpython#159237), until the pinned
|
||||
# CPython release carries the fix.
|
||||
#
|
||||
# Applying is idempotent: ExternalProject re-runs the patch step when PATCH_COMMAND changes or
|
||||
# the patch stamp is missing, which can happen on a source tree that already carries the patch.
|
||||
# A reverse check recognises that state instead of failing the build on an already patched file.
|
||||
# When the pinned CPython release carries the fix, drop this script, its patch and PATCH_COMMAND.
|
||||
|
||||
set(_patch "${CMAKE_CURRENT_LIST_DIR}/0001-winapi-createprocess-audit-format.patch")
|
||||
|
||||
if(NOT GIT_EXECUTABLE)
|
||||
message(FATAL_ERROR "GIT_EXECUTABLE is required")
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND "${GIT_EXECUTABLE}" apply --check --reverse --ignore-space-change "${_patch}"
|
||||
RESULT_VARIABLE _already_applied
|
||||
OUTPUT_QUIET
|
||||
ERROR_QUIET
|
||||
)
|
||||
if(_already_applied EQUAL 0)
|
||||
message(STATUS "CPython: _winapi.CreateProcess audit format is already patched")
|
||||
return()
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND "${GIT_EXECUTABLE}" apply --verbose --ignore-space-change --whitespace=fix "${_patch}"
|
||||
RESULT_VARIABLE _apply_result
|
||||
)
|
||||
if(NOT _apply_result EQUAL 0)
|
||||
message(FATAL_ERROR "CPython: failed to apply ${_patch} (exit ${_apply_result})")
|
||||
endif()
|
||||
Vendored
+11
@@ -181,6 +181,16 @@ if(WIN32)
|
||||
-DPYTHON_LAYOUT_ARCH=${_python_layout_arch}
|
||||
-P ${CMAKE_CURRENT_LIST_DIR}/stage_windows.cmake
|
||||
)
|
||||
# CPython 3.12.13 raises the _winapi.CreateProcess audit event with PySys_Audit's "u" format
|
||||
# for command_line although it is a Python object, so audit hooks received garbage instead of
|
||||
# the command line and the plugin audit prompt named the wrong executable. Apply upstream's
|
||||
# "uOu" fix (python/cpython#159237) until the pinned release carries it. The step tolerates
|
||||
# an already patched tree, which a re-run after a stamp change can meet.
|
||||
set(_python_patch_cmd
|
||||
${CMAKE_COMMAND}
|
||||
"-DGIT_EXECUTABLE=${GIT_EXECUTABLE}"
|
||||
-P "${CMAKE_CURRENT_LIST_DIR}/patch_winapi_audit.cmake"
|
||||
)
|
||||
elseif(APPLE)
|
||||
# macOS configuration
|
||||
if(CMAKE_OSX_ARCHITECTURES)
|
||||
@@ -351,6 +361,7 @@ ExternalProject_Add(dep_python3
|
||||
URL_HASH SHA256=${_python_sha256}
|
||||
DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/python3
|
||||
BUILD_IN_SOURCE ON
|
||||
PATCH_COMMAND ${_python_patch_cmd}
|
||||
CONFIGURE_COMMAND ${_conf_cmd}
|
||||
BUILD_COMMAND ${_build_cmd}
|
||||
INSTALL_COMMAND ${_install_cmd}
|
||||
|
||||
Vendored
+3
-1
@@ -45,7 +45,9 @@ orcaslicer_add_cmake_project(
|
||||
wxWidgets
|
||||
GIT_REPOSITORY "https://github.com/OrcaSlicer/Orca-deps-wxWidgets"
|
||||
GIT_TAG b44c39c100975a0ac0e46f937aa3f3eae5e18631
|
||||
GIT_SHALLOW ON
|
||||
# A shallow clone fetches only the branch head, so checking out a pinned commit fails once the
|
||||
# branch moves past it.
|
||||
GIT_SHALLOW OFF
|
||||
GIT_SUBMODULES 3rdparty/catch 3rdparty/pcre 3rdparty/libwebp
|
||||
DEPENDS ${PNG_PKG} ${ZLIB_PKG} ${EXPAT_PKG} ${JPEG_PKG}
|
||||
CMAKE_ARGS
|
||||
|
||||
@@ -488,6 +488,12 @@ void stl_check_facets_nearby(stl_file *stl, float tolerance)
|
||||
// No need to check any further. All facets are connected.
|
||||
return;
|
||||
|
||||
// A mesh built in memory has no shortest edge, so the tolerance arrives as 0, and load_nearby() would divide by it.
|
||||
// Converting the infinities and NaNs to int is undefined: x86-64 makes them all INT_MIN, so no edge was ever
|
||||
// matched, while ARM64 saturates them by sign and merged unrelated edges. Keep the x86-64 result everywhere.
|
||||
if (!(tolerance > 0.f))
|
||||
return;
|
||||
|
||||
HashTableEdges hash_table(stl->stats.number_of_facets);
|
||||
for (uint32_t i = 0; i < stl->stats.number_of_facets; ++ i) {
|
||||
//FIXME is the copy necessary?
|
||||
|
||||
@@ -817,9 +817,18 @@ namespace Clipper2Lib {
|
||||
std::stable_sort(minima_list_.begin(), minima_list_.end(), LocMinSorter()); //#594
|
||||
minima_list_sorted_ = true;
|
||||
}
|
||||
LocalMinimaList::const_reverse_iterator i;
|
||||
for (i = minima_list_.rbegin(); i != minima_list_.rend(); ++i)
|
||||
InsertScanline((*i)->vertex->pt.y);
|
||||
// Orca: PopScanline() returns each pending y once, however many times it was inserted, so only the
|
||||
// distinct ys of the local minima are queued. Sorted by descending y they already form a max-heap;
|
||||
// inserting them one by one in ascending order made every insertion climb to the top of the heap.
|
||||
std::vector<int64_t> minima_ys;
|
||||
minima_ys.reserve(minima_list_.size());
|
||||
for (const LocalMinima_ptr& lm : minima_list_)
|
||||
if (minima_ys.empty() || minima_ys.back() != lm->vertex->pt.y)
|
||||
minima_ys.push_back(lm->vertex->pt.y);
|
||||
if (scanline_list_.empty())
|
||||
scanline_list_ = std::priority_queue<int64_t>(std::less<int64_t>(), std::move(minima_ys));
|
||||
else
|
||||
for (int64_t y : minima_ys) InsertScanline(y);
|
||||
|
||||
current_locmin_iter_ = minima_list_.begin();
|
||||
actives_ = nullptr;
|
||||
@@ -883,7 +892,9 @@ namespace Clipper2Lib {
|
||||
|
||||
void ClipperBase::InsertScanline(int64_t y)
|
||||
{
|
||||
scanline_list_.push(y);
|
||||
// Orca: a y already at the top is popped together with this one anyway.
|
||||
if (scanline_list_.empty() || scanline_list_.top() != y)
|
||||
scanline_list_.push(y);
|
||||
}
|
||||
|
||||
|
||||
@@ -2978,8 +2989,14 @@ namespace Clipper2Lib {
|
||||
for (size_t idx = 0; idx < splits->size(); ++idx)
|
||||
{
|
||||
OutRec* split = (*splits)[idx];
|
||||
if (!split->pts && split->splits &&
|
||||
CheckSplitOwner(outrec, split->splits)) return true; //#942
|
||||
if (!split->pts && split->splits)
|
||||
{
|
||||
if (split->recursive_split == outrec) continue;
|
||||
split->recursive_split = outrec; // emptied OutRecs can reference each other
|
||||
|
||||
if (CheckSplitOwner(outrec, split->splits)) return true; //#942
|
||||
}
|
||||
|
||||
split = GetRealOutRec(split);
|
||||
if (!split || split == outrec || split->recursive_split == outrec) continue;
|
||||
split->recursive_split = outrec; // prevent infinite loops
|
||||
|
||||
@@ -101,7 +101,7 @@ The solid stands in for the toolpaths, so it wears their colours. In the views t
|
||||
filament (Summary, Filament, Tool) each body keeps the filament colour its shell was loaded with.
|
||||
In every other view `GCodeViewer::update_solid_model_colors()` samples the toolpaths through
|
||||
`Viewer::get_vertex_color()`: the body takes the outer wall's colour over the layers the solid
|
||||
stands for, each cap the infill's in the layer it is cut under, sparse infill before solid, and
|
||||
stands for, each layer cap the infill's in the layer it is cut under, sparse infill before solid, and
|
||||
the prime tower its own role's. One vertex stands for the role, chosen by
|
||||
`Viewer::find_extrusion_vertex()`: in a view that grades the toolpaths by a value, the
|
||||
length-weighted median of that value over the role's extrusions in up to eight layers spread over
|
||||
@@ -116,7 +116,9 @@ the ends of the layer range then do not bound. And so does a belt printer's: its
|
||||
tilted at the belt angle, with heights in the G-code's frame, which no horizontal cut follows.
|
||||
|
||||
A section view cuts the solid by its plane as it cuts the toolpaths, and the section face is one
|
||||
more cap, counted on the body cut by that plane alone and drawn between the two heights.
|
||||
more cap, counted on the body cut by that plane alone and drawn between the two heights. It may
|
||||
cross any of the layers the solid stands for, so its colour is the infill's sampled over all of
|
||||
them, as the body's is, or the body's own where the body has no infill.
|
||||
|
||||
The solid is drawn opaque whatever the filaments' alpha: a translucent filament shows its toolpaths
|
||||
inside through the walls at rest, and the solid has no inside to show.
|
||||
|
||||
@@ -29,7 +29,7 @@ Permissions are stored per plugin key. A plugin can hold:
|
||||
| `fs_delete` | folder list | Filesystem delete events such as `os.remove` and `shutil.rmtree`. |
|
||||
| `network_http` | target list | Network targets, consulted together with `network_socket` for both HTTP and socket events. A canonical `scheme://host` entry is host-wide and covers both layers; a URL with a path, port, query or trailing slash is exact; a bare host or legacy address tuple covers raw sockets. |
|
||||
| `network_socket` | target list | The same network matching, kept as a separate list so a plugin can declare socket access without an HTTP URL. |
|
||||
| `process` | target list | Process creation and process replacement: `os.system`, `subprocess.Popen`, `os.spawn*`, `os.exec*`, `pty.spawn`, `_winapi.CreateProcess`, and similar. Targets match the audited value verbatim. |
|
||||
| `process` | target list | Process creation and process replacement: `subprocess.Popen`, `os.spawn*`, `os.exec*`, `pty.spawn`, `_winapi.CreateProcess`, and similar. Targets name the tool, not its arguments. The exception is a Windows command line with an unquoted executable followed by arguments: it is stored as an exact full command line, because `CreateProcess` may resolve a longer executable prefix than the first token shows. `os.system` names the shell it runs (see "Target matching"). |
|
||||
| `threading` | boolean | Permission to start a Python thread with `_thread.start_new_thread`. |
|
||||
| `events` | target list | Audited events that expose no target, keyed as `<Category>:<event>`, for example `Socket:socket.__new__`. Matched verbatim. |
|
||||
| `full_access` | boolean | Turns off the permission decision for the plugin. See "Full access". |
|
||||
@@ -89,8 +89,36 @@ that requested it and the nested deletes it performs inside that subtree.
|
||||
A canonical entry is host-wide and applies to HTTP and raw socket events for that host.
|
||||
A URL with a path, port, query, fragment or trailing slash that was stored without
|
||||
normalization remains an exact match.
|
||||
- Process entries are compared verbatim with the string the audit event reports,
|
||||
including Python representations of a command.
|
||||
- Process entries name the tool an event runs, compared verbatim. When the event exposes
|
||||
the executable or path, that argument is the target. For a command string or argv, the
|
||||
first token or element is the target. Arguments after the tool are ignored, so one grant
|
||||
covers repeated runs of the tool with different arguments. The exception is a Windows
|
||||
command line whose executable is unquoted and followed by non-whitespace text.
|
||||
`CreateProcess` resolves such a name by trying successively longer prefixes, so the first
|
||||
whitespace-delimited token need not be the executable it starts: a command line
|
||||
`C:\Program Files\app.exe --x` can start `C:\Program Files\app.exe`, not `C:\Program`.
|
||||
The audit therefore stores the exact full command line instead of the first token, in a
|
||||
reserved `CommandLine:` namespace in the `process` list. An exact entry matches only the
|
||||
same full command line, compared verbatim, and a later run with different arguments asks
|
||||
again. A quoted first argument, an explicit executable or application name, and a command
|
||||
line that has no arguments keep the executable-only, argument-insensitive grant. The
|
||||
command line is not parsed further, and the resolved executable is not checked: the same
|
||||
approved command line can start a different binary if the working directory, `PATH`, or
|
||||
the files it resolves through change. `os.system` works differently:
|
||||
Python hands its whole string to the platform shell, so the target is every shell that may
|
||||
run it. On POSIX that is `/bin/sh`. On Windows the C runtime runs the interpreter named by
|
||||
`COMSPEC`, or `cmd.exe` when `COMSPEC` is unset or empty, and also falls back to `cmd.exe`
|
||||
when it cannot open the configured file (ENOENT or EACCES). The configured interpreter and
|
||||
the fallback are both required targets: a grant for a narrow `COMSPEC` does not authorize
|
||||
the fallback shell. A `COMSPEC` that is already the bare name `cmd.exe`, in any casing,
|
||||
names the fallback itself and is listed once. The value is read from the CRT environment
|
||||
that `_wsystem` consults, not the process environment block, which can differ. The audit
|
||||
does not test whether the `COMSPEC` file exists; the runtime decides that when it runs the
|
||||
command, so a file present at prompt time can be gone by the call. The command string is
|
||||
not parsed, and approving the shells covers every command and argument the plugin passes
|
||||
to `os.system`. The targets are read when the event is raised, so a grant saved under one
|
||||
`COMSPEC` value does not cover a run under another. Direct process creation, such as
|
||||
`subprocess.Popen`, still names its executable.
|
||||
- An event with no target is granted by the `events` entry for its category and name. A
|
||||
targetless network event, such as `http.client.send`, is covered by any recorded
|
||||
network grant instead.
|
||||
@@ -191,8 +219,12 @@ whose denial aborted the load and then retry with the saved grant.
|
||||
|
||||
Runtime approvals store the target observed by the audit hook, except that create and delete
|
||||
approvals store its parent folder. A URL with a path, port or
|
||||
query is therefore an exact grant; a bare host remains usable for raw sockets. The
|
||||
declared form and the runtime form are not normalized by the same code path.
|
||||
query is therefore an exact grant; a bare host remains usable for raw sockets. A Windows
|
||||
command line that needs the exact fallback is saved in the reserved `CommandLine:` namespace
|
||||
as its full text, so the approval is argument-sensitive; the prompt shows the command line
|
||||
without the storage marker and states that the full line, including any sensitive values in
|
||||
its arguments, is shown and saved. The declared form and the runtime form are not normalized
|
||||
by the same code path.
|
||||
|
||||
A recursive delete is different: a Yes grants consent for the canonical target subtree for
|
||||
that operation only. The prompt shows the subtree root and states that the consent is not
|
||||
@@ -361,6 +393,15 @@ never treated as an opt-out.
|
||||
context, so its events are not attributed or restricted.
|
||||
- **Subprocesses leave the policy.** A process created by a granted or full-access
|
||||
plugin runs with the user's rights and is not covered by the parent's audit scope.
|
||||
- **An `os.system` grant is a shell grant.** It authorizes every command string the plugin
|
||||
passes to `os.system`, not only the one that triggered the prompt, because the shell
|
||||
parses and runs the whole string. Arguments are not inspected or restricted.
|
||||
- **An exact command line grant is command-sensitive, not binary-sensitive.** It is stored
|
||||
and shown in full, so it can expose credentials or tokens passed as arguments to anyone
|
||||
who sees the prompt or the sidecar. Approval covers only the same full command line.
|
||||
`CreateProcess` still resolves the executable from the working directory, `PATH`, and the
|
||||
filesystem, so the same approved command line can start a different binary later; the
|
||||
grant does not pin the resolved image or verify it.
|
||||
- **Host APIs are not audit events.** Calls into OrcaSlicer's Python host APIs, such as
|
||||
preset updates or UI actions, execute C++ host code and follow that API's contract. The
|
||||
audit hook judges the Python-level filesystem, network, process and thread events it is
|
||||
|
||||
@@ -29,10 +29,10 @@ as for predictable geometry.
|
||||
|
||||
## Vendored Clipper2
|
||||
|
||||
`deps_src/clipper2` builds the static target `Clipper2`. It carries five
|
||||
`deps_src/clipper2` builds the static target `Clipper2`. It carries six
|
||||
changes to the upstream sources that must be carried over when Clipper2 is
|
||||
updated. The namespace switch sits at the top of every header and source, the
|
||||
other four are marked with `Orca:` comments.
|
||||
other five are marked with `Orca:` comments.
|
||||
|
||||
| Change | Files | Why |
|
||||
| --- | --- | --- |
|
||||
@@ -40,6 +40,7 @@ other four are marked with `Orca:` comments.
|
||||
| Engine nodes from tbbmalloc | `clipper.engine.h`, `clipper.engine.cpp` | Vertices, active edges, output points and records, local minima and `PolyTree` nodes are allocated one by one. `CLIPPER2_NODE_ALLOCATOR` routes them through `scalable_malloc`, because the default heap does not scale when all slicing threads clip at once. |
|
||||
| Concave joins at the edge crossing | `clipper.offset.cpp` | For closed paths, a concave corner is joined at the crossing of the two offset edges when that point lies within half of both adjacent edges. The upstream 3-point loop makes inward offsets of dense curves very slow to union. |
|
||||
| Rounded arc steps | `clipper.offset.cpp` | Round joins use the rounded number of steps, not the ceiling, which keeps the vertex count of round offsets that the rest of the code is tuned for. |
|
||||
| Distinct scan lines | `clipper.engine.cpp` | `Reset()` builds the scan line heap from the distinct y of the local minima in one pass, and `InsertScanline()` skips a y already at the top. Upstream inserts the minima one by one in ascending order, so each climbs to the top of the heap. Scan lines are popped in the same order either way. |
|
||||
| No intersection sort for edges in order | `clipper.engine.h`, `clipper.engine.cpp` | `AdjustCurrXAndCopyToSEL()` reports whether the active edges kept their order at the top of the scanbeam, and `BuildIntersectList()` returns before its merge sort when they did. Most scanbeams have no crossing, and the sort was a large part of every boolean on dense support layers. |
|
||||
|
||||
## ClipperUtils semantics
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Python plugin wheel installation
|
||||
|
||||
## Purpose and identity
|
||||
|
||||
OrcaSlicer runs Python plugins in its embedded interpreter. A plugin's entry is a `.py` file or a wheel stored in its plugin directory. Discovery and metadata reading use that entry file; the wheel remains available after installation. Local plugin keys derive from the entry filename, while cloud plugins use their UUID. Those identities connect plugins to their settings, permissions, capabilities and other references and must not change because of how a wheel is installed.
|
||||
|
||||
Writable plugin data is stored separately from the plugin package. Package removal or replacement must not inadvertently remove that data.
|
||||
|
||||
## Installing wheels
|
||||
|
||||
A wheel entry is installed with bundled `uv` and bundled Python when the plugin is loaded, unless a usable installation is already present. The target is the plugin's legacy extraction path, `<plugin root>/__whl_extracted__/<entry package>/`, which is also where the pre-uv loader extracted the entry wheel. That gives one cache location and one loading flow: the entry package is always imported from that directory, whether it was extracted before or installed by uv. The stored wheel, plugin key and `.install_state.json` sidecar remain where they are, preserving their settings, permissions and capability choices. A `.py` entry is still imported directly.
|
||||
|
||||
`__whl_extracted__/` is shared with dependency wheels. A dependency wheel `<dep>.whl` is extracted to `__whl_extracted__/<dep>/`, so only the entry package's own subdirectory is the installation target; dependency extractions alongside it are left alone. If a dependency wheel's filename stem equals the entry package, both would need the same directory and import name. Installation fails with a collision error instead of replacing the dependency extraction.
|
||||
|
||||
An existing `__whl_extracted__/<entry package>/` without an installation marker is a pre-uv entry extraction. When it already contains the entry package it is used directly: the same directory import runs, and uv is not started, so its files are not rewritten. Only the entry package's own directory counts. The shared `__whl_extracted__/` parent, which holds dependency extractions, is never treated as an entry installation. A markerless target that does not contain the entry package is replaced. A target with a marker that is stale or invalid is a uv-managed installation and is also replaced, through the normal reinstall path. Plugin-owned data belongs in the separate plugin data directory. If uv fails before promotion, the previous directory is left untouched; if promotion fails, it is restored. Either way a markerless extraction remains usable until a replacement succeeds.
|
||||
|
||||
The entry package is metadata-derived and becomes a path component and an import name. It must be a non-empty dotted name whose components are non-empty and contain no path separators, control characters, or characters Windows forbids in filenames. Non-ASCII Unicode names are allowed. This is path-component safety rather than full Python identifier validation: a name that cannot be imported fails when the module is imported.
|
||||
|
||||
uv runs without contacting a package index and without installing dependencies:
|
||||
|
||||
```
|
||||
uv --no-config pip install --python <bundled python> --no-python-downloads
|
||||
--no-deps --no-index --no-cache --link-mode copy
|
||||
--target <staging target> <wheel>
|
||||
```
|
||||
|
||||
Declared dependencies continue to use the existing shared installation policy: they are installed separately by uv into the shared packages directory and added to the interpreter's import path. Wheel files next to the entry that are not the entry itself are extracted under `__whl_extracted__/` as before, alongside the entry target.
|
||||
|
||||
The installed directory provides real filesystem paths for package resources. Wheel installation can relocate files compared with literal extraction, especially files in a wheel's `.data` directory. Plugins that derive resource paths from their package location should be checked against the installed layout.
|
||||
|
||||
## Path spelling on Windows
|
||||
|
||||
The plugin root, its `__whl_extracted__/` caches and the files below them can pass the legacy 260-character `MAX_PATH`. Filesystem probes and operations use the extended-length (`\\?\`) spelling where the plain spelling cannot reach a path; uv receives plain paths and qualifies them itself, and a `sys.path` entry keeps the plain spelling it was given whenever the import can be served through it. For an imported package or module that is decided from the entry files the finder probes: the plain spelling is kept while `<entry>/__init__.py`, a compiled `__init__` initializer, or the single-module `<entry>.py`/compiled extension also fit below the limit. A package with no `.py` entry, such as a namespace or compiled-only package, therefore keeps the plain spelling instead of being prefixed for lack of a file to probe, while any entry file past the limit selects the extended-length form. Dependency extraction roots follow the same rule, decided by whether the extraction root itself is reachable through the plain spelling.
|
||||
|
||||
One limit remains: files nested below the entry are not probed individually. They are reached through the recorded `sys.path` entry, so a submodule that itself lies past the limit is only reached when the entry above it already selected the extended-length form.
|
||||
|
||||
## Wheel filename reconstruction
|
||||
|
||||
uv requires a valid PEP 427 wheel filename. A stored cloud download or a locally renamed wheel may not have one, so installation stages a copy under a name built from the wheel's own `METADATA` name and version and its declared `WHEEL` tags. The stored entry filename is not changed. The tag is selected from the tags the wheel declares; it is never invented, and uv performs the final interpreter/platform compatibility check.
|
||||
|
||||
## Cache and reuse
|
||||
|
||||
Installation happens in a staging directory, `__wheel_staging__-*`, and is promoted to `__whl_extracted__/<entry package>/` only after uv succeeds and the entry package is present. The previous target is moved to `__wheel_prev__-*` during promotion and restored if promotion fails; it is removed after a successful promotion. All of these names start with `__`, so discovery ignores them.
|
||||
|
||||
A marker inside the installed target records the installation format, interpreter ABI, entry package, wheel size and a fingerprint of the wheel bytes. A later load reuses the target when all of them match, so unchanged wheels do not run uv again. A markerless target that contains the entry package is a pre-uv extraction and is reused directly. Any marker that does not match the current wheel, format or ABI causes reinstallation, so a stale uv installation is never reused. The marker is a cache hint, not evidence that a plugin is trustworthy. The entry package must still be identified independently of the distribution name.
|
||||
|
||||
Legacy acceptance and uv installation take the same lock, so a load never accepts a markerless target while another load is rebuilding it.
|
||||
|
||||
The local plugin cache-clear action removes `__whl_extracted__/`, including the entry installation and all dependency extractions. It does not remove the stored wheel, the sidecar or the separate plugin data directory.
|
||||
|
||||
## Failure and lifecycle
|
||||
|
||||
If uv fails or the promoted target is incomplete, the load fails with an error naming the installation problem. There is no silent fallback to extraction. The previous target is restored if promotion fails, and the stored wheel, sidecar, settings and permissions are left in place, so a later load can retry once the problem is resolved.
|
||||
|
||||
Native extensions may remain loaded after a plugin is stopped, particularly on Windows, so replacing or removing their files may require an application restart.
|
||||
|
||||
Each plugin's installation directory is private, but plugins share one interpreter, `sys.path`, `sys.modules` and the dependency directory. Separate directories do not isolate conflicting imports. Installation and execution of plugin code are not security sandboxes.
|
||||
@@ -14890,8 +14890,9 @@ msgid "Brim ear detection radius"
|
||||
msgstr ""
|
||||
|
||||
msgid ""
|
||||
"The geometry will be decimated before detecting sharp angles. This parameter indicates the minimum length of the deviation for the decimation.\n"
|
||||
"0 to deactivate."
|
||||
"The direction change at a corner is measured over a window of this length along the outline.\n"
|
||||
"The window grows while the outline keeps curving, so a rounded corner counts as one corner once its whole turn is seen.\n"
|
||||
"0 to measure the angle at every vertex without smoothing."
|
||||
msgstr ""
|
||||
|
||||
msgid "Brim ears outer only"
|
||||
|
||||
@@ -49,7 +49,7 @@ msgid "Left extruder"
|
||||
msgstr "왼쪽 압출기"
|
||||
|
||||
msgid "left extruder"
|
||||
msgstr "왼쪽 익스트루더"
|
||||
msgstr "왼쪽 압출기"
|
||||
|
||||
msgid "Right Extruder"
|
||||
msgstr "오른쪽 압출기"
|
||||
@@ -58,7 +58,7 @@ msgid "Right extruder"
|
||||
msgstr "오른쪽 압출기"
|
||||
|
||||
msgid "right extruder"
|
||||
msgstr "오른쪽 익스트루더"
|
||||
msgstr "오른쪽 압출기"
|
||||
|
||||
# AI Translated
|
||||
msgid "Main Nozzle"
|
||||
@@ -180,7 +180,7 @@ msgid "Right"
|
||||
msgstr "오른쪽"
|
||||
|
||||
msgid "extruder"
|
||||
msgstr "익스트루더"
|
||||
msgstr "압출기"
|
||||
|
||||
msgid "TPU is not supported by AMS."
|
||||
msgstr "TPU는 AMS에서 지원되지 않습니다."
|
||||
@@ -219,7 +219,7 @@ msgid "Damp PVA will become flexible and get stuck inside AMS, please take care
|
||||
msgstr "습한 PVA는 유연해져서 AMS 내부에 달라붙게 됩니다. 사용하기 전에 건조시키십시오."
|
||||
|
||||
msgid "Damp PVA is flexible and may get stuck in extruder. Dry it before use."
|
||||
msgstr "습한 PVA는 유연하여 익스트루더에 끼일 수 있습니다. 사용 전에 건조시키세요."
|
||||
msgstr "습한 PVA는 유연하여 압출기에 끼일 수 있습니다. 사용 전에 건조시키세요."
|
||||
|
||||
msgid "The rough surface of PLA Glow can accelerate wear on the AMS system, particularly on the internal components of the AMS Lite."
|
||||
msgstr "PLA Glow의 거친 표면은 AMS 시스템, 특히 AMS Lite의 내부 부품의 마모를 가속화할 수 있습니다."
|
||||
@@ -263,7 +263,7 @@ msgstr "%s은(는) Filament Track Switch로 인해 로드 또는 언로드에
|
||||
|
||||
#, c-format, boost-format
|
||||
msgid "%s is not supported by %s extruder."
|
||||
msgstr "%s은(는) %s 익스트루더에서 지원되지 않습니다."
|
||||
msgstr "%s은(는) %s 압출기에서 지원되지 않습니다."
|
||||
|
||||
# AI Translated
|
||||
#, c-format, boost-format
|
||||
@@ -6209,10 +6209,10 @@ msgid "AMS temperature is too high, which may cause the filament to soften. Plea
|
||||
msgstr "AMS 온도가 너무 높아 필라멘트가 연화될 수 있습니다. AMS 온도가 %d℃ 이하로 떨어질 때까지 기다리세요."
|
||||
|
||||
msgid "The current chamber temperature or the target chamber temperature exceeds 45℃. In order to avoid extruder clogging, low temperature filament(PLA/PETG/TPU) is not allowed to be loaded."
|
||||
msgstr "현재 챔버 온도 또는 목표 챔버 온도가 45℃를 초과합니다. 익스트루더 막힘을 방지하기 위해 저온 필라멘트(PLA/PETG/TPU) 로딩이 허용되지 않습니다."
|
||||
msgstr "현재 챔버 온도 또는 목표 챔버 온도가 45℃를 초과합니다. 압출기 막힘을 방지하기 위해 저온 필라멘트(PLA/PETG/TPU) 로딩이 허용되지 않습니다."
|
||||
|
||||
msgid "Low temperature filament(PLA/PETG/TPU) is loaded in the extruder. In order to avoid extruder clogging, it is not allowed to set the chamber temperature."
|
||||
msgstr "저온 필라멘트(PLA/PETG/TPU)가 익스트루더에 로드되어 있습니다. 익스트루더 막힘을 방지하기 위해 챔버 온도 설정이 허용되지 않습니다."
|
||||
msgstr "저온 필라멘트(PLA/PETG/TPU)가 압출기에 로드되어 있습니다. 압출기 막힘을 방지하기 위해 챔버 온도 설정이 허용되지 않습니다."
|
||||
|
||||
msgid "When you set the chamber temperature below 40℃, the chamber temperature control will not be activated, and the target chamber temperature will automatically be set to 0℃."
|
||||
msgstr "챔버 온도를 40℃ 이하로 설정하면 챔버 온도 제어가 활성화되지 않습니다. 그리고 목표 챔버 온도는 자동으로 0℃ 로 설정됩니다."
|
||||
@@ -8466,7 +8466,7 @@ msgid "When printing is paused, filament loading and unloading are only supporte
|
||||
msgstr "인쇄가 일시 중지되면 필라멘트 로딩 및 언로딩은 외부 슬롯에서만 지원됩니다."
|
||||
|
||||
msgid "Current extruder is busy changing filament."
|
||||
msgstr "현재 익스트루더가 필라멘트 교체 중입니다."
|
||||
msgstr "현재 압출기가 필라멘트 교체 중입니다."
|
||||
|
||||
# AI Translated
|
||||
msgid "\"Load\" or \"Unload\" is not supported for external spool while using Filament Track Switch."
|
||||
@@ -13850,7 +13850,7 @@ msgid "Single extruder multi-material setup"
|
||||
msgstr "단일 압출기 다중 재료 설정"
|
||||
|
||||
msgid "Number of extruders of the printer."
|
||||
msgstr "프린터 익스트루더 수."
|
||||
msgstr "프린터 압출기 수."
|
||||
|
||||
msgid ""
|
||||
"Single Extruder Multi Material is selected, and all extruders must have the same diameter.\n"
|
||||
@@ -14420,7 +14420,7 @@ msgstr ""
|
||||
"수정한 사전 설정 값을 삭제하거나 수정된 값을 새 프로젝트로 전송하도록 선택할 수 있습니다"
|
||||
|
||||
msgid "Extruder count"
|
||||
msgstr "익스트루더 수"
|
||||
msgstr "압출기 수"
|
||||
|
||||
# AI Translated
|
||||
msgid "Capabilities"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Creality",
|
||||
"version": "02.03.02.89",
|
||||
"version": "02.03.02.90",
|
||||
"force_update": "0",
|
||||
"description": "Creality configurations",
|
||||
"machine_model_list": [
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"bed_mesh_probe_distance": "50,50",
|
||||
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n",
|
||||
"best_object_pos": "0.5,0.5",
|
||||
"change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X0 Y245 F30000\nG1 Z{z_after_toolchange} F600",
|
||||
"change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X42 Y180 F30000\nG1 Z{z_after_toolchange} F600",
|
||||
"cooling_tube_length": "0",
|
||||
"cooling_tube_retraction": "0",
|
||||
"creality_flush_time": "119",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"bed_mesh_probe_distance": "50,50",
|
||||
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n",
|
||||
"best_object_pos": "0.5,0.5",
|
||||
"change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X0 Y245 F30000\nG1 Z{z_after_toolchange} F600",
|
||||
"change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X42 Y180 F30000\nG1 Z{z_after_toolchange} F600",
|
||||
"cooling_tube_length": "0",
|
||||
"cooling_tube_retraction": "0",
|
||||
"creality_flush_time": "119",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"bed_mesh_probe_distance": "50,50",
|
||||
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n",
|
||||
"best_object_pos": "0.5,0.5",
|
||||
"change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X0 Y245 F30000\nG1 Z{z_after_toolchange} F600",
|
||||
"change_filament_gcode": "G2 Z{z_after_toolchange + 0.4} I0.86 J0.86 P1 F10000 ; spiral lift a little from second lift\nG1 X42 Y180 F30000\nG1 Z{z_after_toolchange} F600",
|
||||
"cooling_tube_length": "0",
|
||||
"cooling_tube_retraction": "0",
|
||||
"creality_flush_time": "119",
|
||||
|
||||
@@ -1115,7 +1115,7 @@ function RenderPermissions(plugin) {
|
||||
fs_readwrite: [null, ""],
|
||||
network_http: [null, "https://example.com"],
|
||||
network_socket: [null, "https://example.com"],
|
||||
process: [T("permissions_process_help", "Enter the exact value recorded by the audit. It may be a Python representation of the command."), T("permissions_process_placeholder", "Exact audited value")],
|
||||
process: [T("permissions_process_help", "Executable grants cover all arguments. CommandLine: entries cover only the exact command line."), T("permissions_process_placeholder", "Executable or command name")],
|
||||
threading: [T("permissions_threading_help_short", "Allow this plugin to create threads."), ""],
|
||||
events: [T("permissions_events_help", "Enter a category and event separated by a colon, such as Socket:socket.__new__."), T("permissions_events_placeholder", "Socket:socket.__new__")]
|
||||
};
|
||||
|
||||
@@ -119,8 +119,10 @@ modules:
|
||||
# submodules (PCRE2, etc.) that are not included in GitHub tarballs.
|
||||
- type: git
|
||||
url: https://github.com/OrcaSlicer/Orca-deps-wxWidgets.git
|
||||
branch: v3.3.2
|
||||
# flatpak-builder requires a named branch's tip to be the pinned commit, so this names no
|
||||
# branch and clones in full, which git needs to check out a commit that is not a tip.
|
||||
commit: b44c39c100975a0ac0e46f937aa3f3eae5e18631
|
||||
disable-shallow-clone: true
|
||||
|
||||
# OrcaSlicer C++ dependencies (built offline with pre-downloaded archives)
|
||||
- name: orca_deps
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cassert>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
@@ -397,51 +398,87 @@ namespace detail {
|
||||
return eps;
|
||||
}
|
||||
|
||||
template<typename RayIntersectorType, typename Scalar>
|
||||
static inline bool intersect_ray_recursive_first_hit(
|
||||
RayIntersectorType &ray_intersector,
|
||||
size_t node_idx,
|
||||
Scalar min_t,
|
||||
igl::Hit<float> &hit)
|
||||
// ray_box_intersect_invdir() for a ray whose direction signs are known at compile time: NegX etc. tell
|
||||
// which slabs are entered through the max face. The comparisons select the same entry and exit parameters
|
||||
// as the early returns of ray_box_intersect_invdir() and give the same answer for any input, NaN included,
|
||||
// but without the unpredictable branches.
|
||||
template<bool NegX, bool NegY, bool NegZ, typename Scalar, typename VectorType, typename BoxScalar>
|
||||
inline bool ray_box_intersect_invdir_signs(
|
||||
const VectorType &origin,
|
||||
const VectorType &inv_dir,
|
||||
const Eigen::AlignedBox<BoxScalar,3> &box,
|
||||
const Scalar t0,
|
||||
const Scalar t1)
|
||||
{
|
||||
const auto &node = ray_intersector.tree.node(node_idx);
|
||||
assert(node.is_valid());
|
||||
|
||||
if (! ray_box_intersect_invdir(ray_intersector.origin, ray_intersector.invdir, node.bbox.template cast<Scalar>(), Scalar(0), min_t))
|
||||
return false;
|
||||
const Scalar tx0 = (Scalar(NegX ? box.max().x() : box.min().x()) - origin.x()) * inv_dir.x();
|
||||
const Scalar tx1 = (Scalar(NegX ? box.min().x() : box.max().x()) - origin.x()) * inv_dir.x();
|
||||
const Scalar ty0 = (Scalar(NegY ? box.max().y() : box.min().y()) - origin.y()) * inv_dir.y();
|
||||
const Scalar ty1 = (Scalar(NegY ? box.min().y() : box.max().y()) - origin.y()) * inv_dir.y();
|
||||
const Scalar tz0 = (Scalar(NegZ ? box.max().z() : box.min().z()) - origin.z()) * inv_dir.z();
|
||||
const Scalar tz1 = (Scalar(NegZ ? box.min().z() : box.max().z()) - origin.z()) * inv_dir.z();
|
||||
const Scalar txy_min = ty0 > tx0 ? ty0 : tx0;
|
||||
const Scalar txy_max = ty1 < tx1 ? ty1 : tx1;
|
||||
const Scalar tmin = tz0 > txy_min ? tz0 : txy_min;
|
||||
const Scalar tmax = tz1 < txy_max ? tz1 : txy_max;
|
||||
return tmin <= tmax && tmin < t1 && tmax > t0;
|
||||
}
|
||||
|
||||
if (node.is_leaf()) {
|
||||
// shoot ray, record hit
|
||||
auto face = ray_intersector.faces[node.idx];
|
||||
double t, u, v;
|
||||
if (intersect_triangle(
|
||||
ray_intersector.origin, ray_intersector.dir,
|
||||
ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)], ray_intersector.vertices[face(2)],
|
||||
t, u, v, ray_intersector.eps)
|
||||
&& t > 0.) {
|
||||
hit = igl::Hit<float> { int(node.idx), -1, float(u), float(v), float(t) };
|
||||
return true;
|
||||
} else
|
||||
return false;
|
||||
} else {
|
||||
// Left / right child node index.
|
||||
size_t left = node_idx * 2 + 1;
|
||||
size_t right = left + 1;
|
||||
igl::Hit<float> left_hit;
|
||||
igl::Hit<float> right_hit;
|
||||
bool left_ret = intersect_ray_recursive_first_hit(ray_intersector, left, min_t, left_hit);
|
||||
if (left_ret && left_hit.t < min_t) {
|
||||
min_t = left_hit.t;
|
||||
hit = left_hit;
|
||||
} else
|
||||
left_ret = false;
|
||||
bool right_ret = intersect_ray_recursive_first_hit(ray_intersector, right, min_t, right_hit);
|
||||
if (right_ret && right_hit.t < min_t)
|
||||
hit = right_hit;
|
||||
else
|
||||
right_ret = false;
|
||||
return left_ret || right_ret;
|
||||
}
|
||||
// The depth-first, left to right search for the first hit, the nearest hit found so far bounding the ray
|
||||
// interval tested against the boxes. Iterative, with the ray direction signs resolved at compile time.
|
||||
template<bool NegX, bool NegY, bool NegZ, typename RayIntersectorType>
|
||||
static inline bool intersect_ray_first_hit_signs(const RayIntersectorType &ray_intersector, igl::Hit<float> &hit)
|
||||
{
|
||||
using Scalar = typename RayIntersectorType::VectorType::Scalar;
|
||||
const auto &nodes = ray_intersector.tree.nodes();
|
||||
Scalar min_t = std::numeric_limits<Scalar>::infinity();
|
||||
bool found = false;
|
||||
// Nodes waiting for their left sibling's subtree: at most one per level, plus the left sibling itself.
|
||||
size_t stack[65];
|
||||
size_t stack_size = 0;
|
||||
stack[stack_size ++] = 0;
|
||||
while (stack_size > 0) {
|
||||
const size_t node_idx = stack[-- stack_size];
|
||||
const auto &node = nodes[node_idx];
|
||||
assert(node.is_valid());
|
||||
if (! ray_box_intersect_invdir_signs<NegX, NegY, NegZ>(ray_intersector.origin, ray_intersector.invdir, node.bbox, Scalar(0), min_t))
|
||||
continue;
|
||||
if (node.is_leaf()) {
|
||||
auto face = ray_intersector.faces[node.idx];
|
||||
double t, u, v;
|
||||
// A leaf at the root has no parent to reject a hit beyond min_t.
|
||||
if (intersect_triangle(
|
||||
ray_intersector.origin, ray_intersector.dir,
|
||||
ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)], ray_intersector.vertices[face(2)],
|
||||
t, u, v, ray_intersector.eps)
|
||||
&& t > 0. && (float(t) < min_t || node_idx == 0)) {
|
||||
hit = igl::Hit<float> { int(node.idx), -1, float(u), float(v), float(t) };
|
||||
min_t = hit.t;
|
||||
found = true;
|
||||
}
|
||||
} else {
|
||||
assert(stack_size + 2 <= std::size(stack));
|
||||
// Push the right child first, so that the left subtree is searched first.
|
||||
stack[stack_size ++] = node_idx * 2 + 2;
|
||||
stack[stack_size ++] = node_idx * 2 + 1;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
template<typename RayIntersectorType>
|
||||
static inline bool intersect_ray_first_hit_dispatch(const RayIntersectorType &ray_intersector, igl::Hit<float> &hit)
|
||||
{
|
||||
const auto &inv_dir = ray_intersector.invdir;
|
||||
switch (int(inv_dir.x() < 0) | (int(inv_dir.y() < 0) << 1) | (int(inv_dir.z() < 0) << 2)) {
|
||||
case 0: return intersect_ray_first_hit_signs<false, false, false>(ray_intersector, hit);
|
||||
case 1: return intersect_ray_first_hit_signs<true, false, false>(ray_intersector, hit);
|
||||
case 2: return intersect_ray_first_hit_signs<false, true, false>(ray_intersector, hit);
|
||||
case 3: return intersect_ray_first_hit_signs<true, true, false>(ray_intersector, hit);
|
||||
case 4: return intersect_ray_first_hit_signs<false, false, true >(ray_intersector, hit);
|
||||
case 5: return intersect_ray_first_hit_signs<true, false, true >(ray_intersector, hit);
|
||||
case 6: return intersect_ray_first_hit_signs<false, true, true >(ray_intersector, hit);
|
||||
default: return intersect_ray_first_hit_signs<true, true, true >(ray_intersector, hit);
|
||||
}
|
||||
}
|
||||
|
||||
template<typename RayIntersectorType>
|
||||
@@ -741,14 +778,12 @@ inline bool intersect_ray_first_hit(
|
||||
// Epsilon for the ray-triangle intersection, it should be proportional to an average triangle edge length.
|
||||
const double eps = 0.000001)
|
||||
{
|
||||
using Scalar = typename VectorType::Scalar;
|
||||
auto ray_intersector = detail::RayIntersector<VertexType, IndexedFaceType, TreeType, VectorType> {
|
||||
vertices, faces, tree,
|
||||
origin, dir, VectorType(dir.cwiseInverse()),
|
||||
eps
|
||||
};
|
||||
return ! tree.empty() && detail::intersect_ray_recursive_first_hit(
|
||||
ray_intersector, size_t(0), std::numeric_limits<Scalar>::infinity(), hit);
|
||||
return ! tree.empty() && detail::intersect_ray_first_hit_dispatch(ray_intersector, hit);
|
||||
}
|
||||
|
||||
// Find all intersections of a ray with indexed triangle set.
|
||||
|
||||
+169
-17
@@ -26,6 +26,7 @@
|
||||
#include <cstddef>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <numeric>
|
||||
#include <optional>
|
||||
@@ -346,6 +347,172 @@ double configBrimWidthByVolumeGroups(double adhesion, double maxSpeed, const std
|
||||
return brim_width;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// ORCA: position at arc length a along the closed contour, interpolated inside one segment.
|
||||
Vec2d point_at_arc(const Points &pts, const std::vector<double> &cum, double perimeter, double a)
|
||||
{
|
||||
const size_t n = pts.size();
|
||||
a = std::fmod(a, perimeter);
|
||||
if (a < 0.)
|
||||
a += perimeter;
|
||||
// cum[k] <= a < cum[k + 1]. Segment lengths are positive, duplicates were dropped.
|
||||
size_t k = size_t(std::upper_bound(cum.begin(), cum.end(), a) - cum.begin()) - 1;
|
||||
if (k >= n)
|
||||
k = n - 1;
|
||||
const double t = (a - cum[k]) / (cum[k + 1] - cum[k]);
|
||||
return pts[k].cast<double>() * (1. - t) + pts[(k + 1) % n].cast<double>() * t;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ORCA: Detect mouse ear positions on one closed contour. Coordinates and ear_detection_length are scaled.
|
||||
// The turn at a vertex is measured over a window of ear_detection_length of arc length per side, doubled
|
||||
// while the outline keeps curving, so a corner is accepted once its turn saturates. Outer contours take
|
||||
// convex corners, inner contours concave ones; candidates on the same corner collapse to the sharpest.
|
||||
Points make_brim_ear_points(const Polygon &contour, coord_t ear_detection_length,
|
||||
coordf_t brim_ears_max_angle, bool is_outer_brim)
|
||||
{
|
||||
Points ears;
|
||||
if (contour.points.size() < 3 || contour.length() <= 0 || brim_ears_max_angle <= 0)
|
||||
return ears;
|
||||
|
||||
const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0;
|
||||
const double cos_threshold = cos(std::nextafter(angle_threshold, +INFINITY));
|
||||
const double L = double(ear_detection_length);
|
||||
|
||||
// ORCA: drop points closer than 1 um to the previous kept one, so no segment has zero length.
|
||||
const double min_dist2 = 1000. * 1000.;
|
||||
Points pts;
|
||||
std::vector<size_t> index_map;
|
||||
pts.reserve(contour.points.size());
|
||||
index_map.reserve(contour.points.size());
|
||||
for (size_t i = 0; i < contour.points.size(); ++i) {
|
||||
if (!pts.empty() && (contour.points[i] - pts.back()).cast<double>().squaredNorm() < min_dist2)
|
||||
continue;
|
||||
pts.push_back(contour.points[i]);
|
||||
index_map.push_back(i);
|
||||
}
|
||||
const size_t n = pts.size();
|
||||
if (n < 3)
|
||||
return ears;
|
||||
|
||||
// Cumulative arc length of every vertex, used as the position of a candidate along the closed contour.
|
||||
std::vector<double> cum(n + 1, 0.0);
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
cum[i + 1] = cum[i] + (pts[(i + 1) % n] - pts[i]).cast<double>().norm();
|
||||
const double perimeter = cum[n];
|
||||
if (perimeter <= 0.)
|
||||
return ears;
|
||||
|
||||
struct Candidate {
|
||||
size_t idx;
|
||||
double dot;
|
||||
double arc;
|
||||
double scale;
|
||||
};
|
||||
std::vector<Candidate> candidates;
|
||||
|
||||
// ORCA: window ladder L, 2L, 4L..., capped at 16L and at perimeter/8 so a window cannot reach the far side.
|
||||
std::vector<double> scales;
|
||||
if (L > 0.) {
|
||||
const double s_max = std::min(16.0 * L, perimeter / 8.0);
|
||||
for (double s = L;; s *= 2.) {
|
||||
scales.push_back(std::min(s, s_max));
|
||||
if (s >= s_max)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const Vec2d pi = pts[i].cast<double>();
|
||||
if (L == 0.) {
|
||||
// ORCA: zero window, measure the turn at the vertex itself.
|
||||
const Vec2d a = pi - pts[(i + n - 1) % n].cast<double>();
|
||||
const Vec2d b = pts[(i + 1) % n].cast<double>() - pi;
|
||||
if (a.squaredNorm() == 0. || b.squaredNorm() == 0.)
|
||||
continue;
|
||||
if (is_outer_brim ? cross2(a, b) <= 0. : cross2(a, b) >= 0.)
|
||||
continue;
|
||||
const double dot = a.normalized().dot(b.normalized());
|
||||
if (dot < cos_threshold)
|
||||
candidates.push_back({i, dot, cum[i], 0.});
|
||||
continue;
|
||||
}
|
||||
for (size_t m = 0; m < scales.size(); ++m) {
|
||||
const double s = scales[m];
|
||||
const double s_next = std::min(2.0 * s, perimeter / 4.0); // lookahead window, kept off the far side
|
||||
const Vec2d a = pi - point_at_arc(pts, cum, perimeter, cum[i] - s);
|
||||
const Vec2d b = point_at_arc(pts, cum, perimeter, cum[i] + s) - pi;
|
||||
if (a.squaredNorm() == 0. || b.squaredNorm() == 0.)
|
||||
continue;
|
||||
const Vec2d ua = a.normalized();
|
||||
const Vec2d ub = b.normalized();
|
||||
const double cross = cross2(ua, ub);
|
||||
if (is_outer_brim ? cross <= 0. : cross >= 0.)
|
||||
continue;
|
||||
const double dot = ua.dot(ub);
|
||||
if (dot >= cos_threshold)
|
||||
continue;
|
||||
const double turn = std::abs(std::atan2(cross, dot));
|
||||
if (turn == 0.)
|
||||
continue;
|
||||
// ORCA: a corner is saturated once twice the window sees no more turning; a straight leg or an
|
||||
// arc keeps turning, so the 1.5 ratio rejects it. The last rung of the ladder cannot grow any
|
||||
// further, so its turn is final: the lookahead from there reaches the neighbouring corner on a
|
||||
// small part and would otherwise reject every corner on it.
|
||||
if (m + 1 < scales.size()) {
|
||||
double next_turn = turn;
|
||||
const Vec2d a_next = pi - point_at_arc(pts, cum, perimeter, cum[i] - s_next);
|
||||
const Vec2d b_next = point_at_arc(pts, cum, perimeter, cum[i] + s_next) - pi;
|
||||
if (a_next.squaredNorm() > 0. && b_next.squaredNorm() > 0.) {
|
||||
const Vec2d ua_next = a_next.normalized();
|
||||
const Vec2d ub_next = b_next.normalized();
|
||||
next_turn = std::abs(std::atan2(cross2(ua_next, ub_next), ua_next.dot(ub_next)));
|
||||
}
|
||||
if (next_turn > 1.5 * turn)
|
||||
continue;
|
||||
}
|
||||
candidates.push_back({i, dot, cum[i], s});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ORCA: take the most local candidate first (smallest window, i.e. the corner centre), then the sharpest,
|
||||
// drop everything on the same corner, repeat. Chaining neighbours would swallow a curved contour.
|
||||
const double fallback_suppress = double(std::max<coord_t>(1, scale_(0.01))); // 0.01 mm when there is no window
|
||||
while (!candidates.empty()) {
|
||||
size_t best = 0;
|
||||
for (size_t c = 1; c < candidates.size(); ++c) {
|
||||
const Candidate &cc = candidates[c];
|
||||
const Candidate &cb = candidates[best];
|
||||
if (cc.scale < cb.scale ||
|
||||
(cc.scale == cb.scale && (cc.dot < cb.dot ||
|
||||
(cc.dot == cb.dot && cc.idx < cb.idx))))
|
||||
best = c;
|
||||
}
|
||||
const Candidate picked = candidates[best];
|
||||
ears.emplace_back(contour.points[index_map[picked.idx]]);
|
||||
// ORCA: suppress within twice the window that detected the ear, taking the wider of the two windows: a
|
||||
// candidate whose window already reaches the picked ear measured the same corner, which otherwise leaves
|
||||
// a duplicate beside a corner that meets a curve. Capped at perimeter/8 so a small part keeps every ear.
|
||||
std::vector<Candidate> remaining;
|
||||
remaining.reserve(candidates.size() - 1);
|
||||
for (size_t c = 0; c < candidates.size(); ++c) {
|
||||
if (c == best)
|
||||
continue;
|
||||
const double ds = std::abs(candidates[c].arc - picked.arc);
|
||||
const double suppress_distance =
|
||||
L > 0. ? std::min(2.0 * std::max(picked.scale, candidates[c].scale), perimeter / 8.0)
|
||||
: fallback_suppress;
|
||||
if (std::min(ds, perimeter - ds) > suppress_distance)
|
||||
remaining.push_back(candidates[c]);
|
||||
}
|
||||
candidates = std::move(remaining);
|
||||
}
|
||||
return ears;
|
||||
}
|
||||
|
||||
// Generate ears
|
||||
// Ported from SuperSlicer: https://github.com/supermerill/SuperSlicer/blob/45d0532845b63cd5cefe7de7dc4ef0e0ed7e030a/src/libslic3r/Brim.cpp#L1116
|
||||
static ExPolygons make_brim_ears_auto(const ExPolygons& obj_expoly, coord_t size_ear, coord_t ear_detection_length,
|
||||
@@ -355,24 +522,9 @@ static ExPolygons make_brim_ears_auto(const ExPolygons& obj_expoly, coord_t size
|
||||
return mouse_ears_ex;
|
||||
}
|
||||
// Detect places to put ears
|
||||
const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0;
|
||||
Points pt_ears;
|
||||
for (const ExPolygon &poly : obj_expoly) {
|
||||
Polygon decimated_polygon = poly.contour;
|
||||
if (ear_detection_length > 0) {
|
||||
// decimate polygon
|
||||
Points points = poly.contour.points;
|
||||
points.push_back(points.front());
|
||||
points = MultiPoint::_douglas_peucker(points, ear_detection_length);
|
||||
if (points.size() > 4) { // don't decimate if it's going to be below 4 points, as it's surely enough to fill everything anyway
|
||||
points.erase(points.end() - 1);
|
||||
decimated_polygon.points = points;
|
||||
}
|
||||
}
|
||||
|
||||
append(pt_ears, is_outer_brim ? decimated_polygon.convex_points(angle_threshold)
|
||||
: decimated_polygon.concave_points(angle_threshold));
|
||||
}
|
||||
for (const ExPolygon &poly : obj_expoly)
|
||||
append(pt_ears, make_brim_ear_points(poly.contour, ear_detection_length, brim_ears_max_angle, is_outer_brim));
|
||||
|
||||
// Then add ears
|
||||
// create ear pattern
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "ObjectID.hpp"
|
||||
#include "Point.hpp"
|
||||
#include "Polygon.hpp"
|
||||
#include "libslic3r.h"
|
||||
|
||||
#include<map>
|
||||
#include <utility>
|
||||
@@ -31,6 +32,13 @@ ExtrusionEntityCollection makeBrimInfillFromPlateCoordinates(const ExPolygons& s
|
||||
// BBS: automatically make brim
|
||||
ExtrusionEntityCollection make_brim_auto(const Print &print, PrintTryCancel try_cancel, Polygons &islands_area);
|
||||
|
||||
// ORCA: Detect mouse ear positions on one closed contour. Coordinates and ear_detection_length are scaled.
|
||||
// The window starts at ear_detection_length and doubles while the outline keeps curving; a corner is accepted
|
||||
// once its turn saturates. Outer contours take convex corners, inner contours concave ones; candidates on the
|
||||
// same corner collapse to the sharpest.
|
||||
Points make_brim_ear_points(const Polygon &contour, coord_t ear_detection_length,
|
||||
coordf_t brim_ears_max_angle, bool is_outer_brim);
|
||||
|
||||
} // Slic3r
|
||||
|
||||
#endif // slic3r_Brim_hpp_
|
||||
@@ -396,6 +396,7 @@ set(lisbslic3r_sources
|
||||
Optimize/Optimizer.hpp
|
||||
Orient.cpp
|
||||
Orient.hpp
|
||||
ParallelForFirstError.hpp
|
||||
ParallelResolve.hpp
|
||||
ParameterUtils.cpp
|
||||
ParameterUtils.hpp
|
||||
|
||||
@@ -92,6 +92,22 @@ bool ExPolygon::contains(const Polyline &polyline) const
|
||||
if (!bbox1.overlap(bbox2))
|
||||
return false;
|
||||
|
||||
// A polyline reaching further than SCALED_EPSILON out of the bounding box of all the outlines runs
|
||||
// outside of them all there, which the difference keeps: no need to compute it. This does not hold for
|
||||
// a polyline of a single point, which the difference drops.
|
||||
if (bbox2.min != bbox2.max) {
|
||||
auto reaches_out = [&bbox2](BoundingBox outlines) {
|
||||
outlines.offset(SCALED_EPSILON);
|
||||
return !outlines.contains(bbox2.min) || !outlines.contains(bbox2.max);
|
||||
};
|
||||
if (reaches_out(bbox1)) {
|
||||
for (const Polygon &hole : this->holes)
|
||||
bbox1.merge(get_extents(hole));
|
||||
if (reaches_out(bbox1))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return diff_pl(polyline, *this).empty();
|
||||
}
|
||||
|
||||
|
||||
@@ -384,6 +384,7 @@ static constexpr const char* FIRST_LAYER_PRINT_SEQUENCE_ATTR = "first_layer_prin
|
||||
static constexpr const char* OTHER_LAYERS_PRINT_SEQUENCE_ATTR = "other_layers_print_sequence";
|
||||
static constexpr const char* OTHER_LAYERS_PRINT_SEQUENCE_NUMS_ATTR = "other_layers_print_sequence_nums";
|
||||
static constexpr const char* SPIRAL_VASE_MODE = "spiral_mode";
|
||||
static constexpr const char* SKIRT_START_ANGLE_ATTR = "skirt_start_angle";
|
||||
static constexpr const char* IMEX_PARALLEL_MODE_ATTR = "imex_parallel_mode";
|
||||
// The same attribute before the feature was renamed IMEX. Plate metadata is matched by exact
|
||||
// string and written with set_key_value, so it never passes through handle_legacy: without this
|
||||
@@ -4683,6 +4684,13 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result)
|
||||
std::istringstream(value) >> std::boolalpha >> spiral_mode;
|
||||
m_curr_plater->config.set_key_value("spiral_mode", new ConfigOptionBool(spiral_mode));
|
||||
}
|
||||
else if (key == SKIRT_START_ANGLE_ATTR) {
|
||||
// plate override of the skirt start point, ignored when it is not a valid angle
|
||||
size_t parsed = 0;
|
||||
const double skirt_start_angle = string_to_double_decimal_point(value, &parsed);
|
||||
if (parsed > 0 && skirt_start_angle >= -180. && skirt_start_angle <= 180.)
|
||||
m_curr_plater->config.set_key_value("skirt_start_angle", new ConfigOptionFloat(skirt_start_angle));
|
||||
}
|
||||
else if (key == IMEX_PARALLEL_MODE_ATTR || key == IXEX_PARALLEL_MODE_ATTR_LEGACY) {
|
||||
m_curr_plater->config.set_key_value("imex_parallel_mode", new ConfigOptionString(value));
|
||||
}
|
||||
@@ -8558,6 +8566,11 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv
|
||||
if (spiral_mode_opt)
|
||||
stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << SPIRAL_VASE_MODE << "\" " << VALUE_ATTR << "=\"" << spiral_mode_opt->getBool() << "\"/>\n";
|
||||
|
||||
// plate override of the skirt start point, written with a decimal point in every locale
|
||||
auto* skirt_start_angle_opt = plate_data->config.option<ConfigOptionFloat>("skirt_start_angle");
|
||||
if (skirt_start_angle_opt)
|
||||
stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << SKIRT_START_ANGLE_ATTR << "\" " << VALUE_ATTR << "=\"" << float_to_string_decimal_point(skirt_start_angle_opt->value) << "\"/>\n";
|
||||
|
||||
{
|
||||
// Mode names are user supplied free text, so the value has to be escaped for an
|
||||
// attribute. xml_escape_double_quotes_attribute_value() is used rather than
|
||||
|
||||
+17
-11
@@ -2854,6 +2854,7 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu
|
||||
|
||||
// BBS
|
||||
m_curr_print = print;
|
||||
m_overhang_layers_cache.valid = false;
|
||||
m_skirt_group_done.clear();
|
||||
m_pending_start_gcode_position.reset();
|
||||
m_exclusion_volume_travel_avoidance.init(print->config(), print->get_plate_origin());
|
||||
@@ -10854,12 +10855,22 @@ bool GCode::needs_retraction(const Polyline &travel, ExtrusionRole role, LiftTyp
|
||||
std::pair<float, float> z_range;
|
||||
z_range.second = m_layer ? m_layer->print_z : 0.f;
|
||||
z_range.first = std::max(0.f, z_range.second - protect_z);
|
||||
std::vector<LayerPtrs> layers_of_objects;
|
||||
std::vector<BoundingBox> boundingBox_for_objects;
|
||||
VecOfPoints objects_instances_shift;
|
||||
std::vector<size_t> idx_of_object_sorted = m_curr_print->layers_sorted_for_object(z_range.first, z_range.second, layers_of_objects, boundingBox_for_objects, objects_instances_shift);
|
||||
|
||||
std::vector<bool> is_layers_of_objects_sorted(layers_of_objects.size(), false);
|
||||
OverhangLayersCache &cache = m_overhang_layers_cache;
|
||||
if (!cache.valid || cache.z_min != z_range.first || cache.z_max != z_range.second) {
|
||||
cache.layers_of_objects.clear();
|
||||
cache.boundingBox_for_objects.clear();
|
||||
cache.idx_of_object_sorted = m_curr_print->layers_sorted_for_object(z_range.first, z_range.second, cache.layers_of_objects,
|
||||
cache.boundingBox_for_objects, cache.objects_instances_shift);
|
||||
for (LayerPtrs &layers : cache.layers_of_objects)
|
||||
std::sort(layers.begin(), layers.end(), [](auto left, auto right) { return left->loverhangs_bbox.area() > right->loverhangs_bbox.area();});
|
||||
cache.z_min = z_range.first;
|
||||
cache.z_max = z_range.second;
|
||||
cache.valid = true;
|
||||
}
|
||||
const std::vector<LayerPtrs> &layers_of_objects = cache.layers_of_objects;
|
||||
const std::vector<BoundingBox> &boundingBox_for_objects = cache.boundingBox_for_objects;
|
||||
const VecOfPoints &objects_instances_shift = cache.objects_instances_shift;
|
||||
const std::vector<size_t> &idx_of_object_sorted = cache.idx_of_object_sorted;
|
||||
|
||||
for (size_t idx : idx_of_object_sorted) {
|
||||
for (const Point & instance_shift : objects_instances_shift[idx]) {
|
||||
@@ -10877,11 +10888,6 @@ bool GCode::needs_retraction(const Polyline &travel, ExtrusionRole role, LiftTyp
|
||||
if (intersection_pl(travel, temp).empty())
|
||||
continue;
|
||||
|
||||
if (!is_layers_of_objects_sorted[idx]) {
|
||||
std::sort(layers_of_objects[idx].begin(), layers_of_objects[idx].end(), [](auto left, auto right) { return left->loverhangs_bbox.area() > right->loverhangs_bbox.area();});
|
||||
is_layers_of_objects_sorted[idx] = true;
|
||||
}
|
||||
|
||||
for (const auto& layer : layers_of_objects[idx]) {
|
||||
for (ExPolygon overhang : layer->loverhangs) {
|
||||
overhang.translate(instance_shift);
|
||||
|
||||
@@ -932,6 +932,19 @@ protected:
|
||||
|
||||
// BBS
|
||||
Print* m_curr_print = nullptr;
|
||||
// The layers of every object below the layer being exported, which needs_retraction() searches for
|
||||
// overhangs a travel crosses: collected once per z range rather than once per travel.
|
||||
struct OverhangLayersCache
|
||||
{
|
||||
bool valid = false;
|
||||
float z_min = 0.f;
|
||||
float z_max = 0.f;
|
||||
std::vector<size_t> idx_of_object_sorted;
|
||||
// Of each object, sorted by the area of their overhangs' bounding box, largest first.
|
||||
std::vector<LayerPtrs> layers_of_objects;
|
||||
std::vector<BoundingBox> boundingBox_for_objects;
|
||||
VecOfPoints objects_instances_shift;
|
||||
} m_overhang_layers_cache;
|
||||
unsigned int m_toolchange_count;
|
||||
coordf_t m_nominal_z;
|
||||
// Mixed-color sublayer state. Non-zero only while emitting a mixed slot's sub-layer:
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
#include <tbb/parallel_for.h>
|
||||
#include <tbb/concurrent_vector.h>
|
||||
|
||||
#include <map>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <unordered_map>
|
||||
#include <atomic>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -40,9 +41,10 @@ inline IndexPair point_map_grid_index(const Point &pt, int64_t xdist, int64_t yd
|
||||
|
||||
inline bool nearly_equal(const Point &p1, const Point &p2) { return std::abs(p1.x() - p2.x()) < SCALED_EPSILON && std::abs(p1.y() - p2.y()) < SCALED_EPSILON; }
|
||||
|
||||
inline Grids line_rasterization(const Line &line, int64_t xdist = scale_(1), int64_t ydist = scale_(1))
|
||||
// The grid cells the line passes through, in order, into res.
|
||||
inline void line_rasterization(const Line &line, Grids &res, int64_t xdist = scale_(1), int64_t ydist = scale_(1))
|
||||
{
|
||||
Grids res;
|
||||
res.clear();
|
||||
Point rayStart = line.a;
|
||||
Point rayEnd = line.b;
|
||||
IndexPair currentVoxel = point_map_grid_index(rayStart, xdist, ydist);
|
||||
@@ -99,9 +101,12 @@ inline Grids line_rasterization(const Line &line, int64_t xdist = scale_(1), int
|
||||
assert(0);
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
struct IndexPairHash
|
||||
{
|
||||
size_t operator()(const IndexPair &p) const { return std::hash<int64_t>()(p.first) ^ (std::hash<int64_t>()(p.second) * 0x9e3779b97f4a7c15ull); }
|
||||
};
|
||||
} // namespace RasterizationImpl
|
||||
|
||||
void LinesBucketQueue::emplace_back_bucket(ExtrusionLayers &&els, const void *objPtr, Point offset)
|
||||
@@ -207,7 +212,7 @@ ObjectExtrusions getAllLayersExtrusionPathsFromObject(PrintObject *obj)
|
||||
|
||||
for (auto layerPtr : obj->layers()) {
|
||||
auto perimeters = getExtrusionPathsFromLayer(layerPtr->regions());
|
||||
oe.perimeters.insert(oe.perimeters.end(), perimeters.begin(), perimeters.end());
|
||||
oe.perimeters.insert(oe.perimeters.end(), std::make_move_iterator(perimeters.begin()), std::make_move_iterator(perimeters.end()));
|
||||
}
|
||||
|
||||
for (auto supportLayerPtr : obj->support_layers()) { oe.support.push_back(getExtrusionPathsFromSupportLayer(supportLayerPtr)); }
|
||||
@@ -218,18 +223,20 @@ ObjectExtrusions getAllLayersExtrusionPathsFromObject(PrintObject *obj)
|
||||
ConflictComputeOpt ConflictChecker::find_inter_of_lines(const LineWithIDs &lines)
|
||||
{
|
||||
using namespace RasterizationImpl;
|
||||
std::map<IndexPair, std::vector<int>> indexToLine;
|
||||
// Only looked up, never iterated, so the order of the cells does not matter.
|
||||
std::unordered_map<IndexPair, std::vector<int>, IndexPairHash> indexToLine;
|
||||
Grids indexes;
|
||||
|
||||
for (int i = 0; i < lines.size(); ++i) {
|
||||
const LineWithID &l1 = lines[i];
|
||||
auto indexes = line_rasterization(l1._line);
|
||||
const LineWithID &l1 = lines[i];
|
||||
line_rasterization(l1._line, indexes);
|
||||
for (auto index : indexes) {
|
||||
const auto &possibleIntersectIdxs = indexToLine[index];
|
||||
auto &possibleIntersectIdxs = indexToLine[index];
|
||||
for (auto possibleIntersectIdx : possibleIntersectIdxs) {
|
||||
const LineWithID &l2 = lines[possibleIntersectIdx];
|
||||
if (auto interRes = line_intersect(l1, l2); interRes.has_value()) { return interRes; }
|
||||
}
|
||||
indexToLine[index].push_back(i);
|
||||
possibleIntersectIdxs.push_back(i);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
|
||||
@@ -71,7 +71,7 @@ public:
|
||||
Point _offset;
|
||||
|
||||
public:
|
||||
LinesBucket(ExtrusionLayers &&paths, const void* id, Point offset) : _piles(paths), _id(id), _offset(offset) {}
|
||||
LinesBucket(ExtrusionLayers &&paths, const void* id, Point offset) : _piles(std::move(paths)), _id(id), _offset(offset) {}
|
||||
LinesBucket(LinesBucket &&) = default;
|
||||
|
||||
std::pair<int, int> curRange() const
|
||||
|
||||
@@ -3779,6 +3779,7 @@ void GCodeProcessor::reset()
|
||||
m_travel_dist = 0.0f;
|
||||
m_fan_speed = 0.0f;
|
||||
m_z_offset = 0.0f;
|
||||
m_pressure_advance = 0.0f;
|
||||
|
||||
m_extrusion_role = erNone;
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include "libslic3r/PrintBase.hpp"
|
||||
#include "PrintConfig.hpp"
|
||||
#include "libslic3r/libslic3r.h"
|
||||
#include "libslic3r/ParallelForFirstError.hpp"
|
||||
#include "libslic3r/TriangleMesh.hpp"
|
||||
#include "libslic3r/TriangleSelector.hpp"
|
||||
#include "tbb/parallel_for.h"
|
||||
@@ -390,20 +391,18 @@ struct GlobalModelInfo {
|
||||
}
|
||||
|
||||
float calculate_point_visibility(const Vec3f &position) const {
|
||||
std::vector<size_t> points = find_nearby_points(mesh_samples_tree, position, mesh_samples_radius);
|
||||
if (points.empty()) {
|
||||
return 1.0f;
|
||||
}
|
||||
|
||||
auto compute_dist_to_plane = [](const Vec3f &position, const Vec3f &plane_origin, const Vec3f &plane_normal) {
|
||||
Vec3f orig_to_point = position - plane_origin;
|
||||
return std::abs(orig_to_point.dot(plane_normal));
|
||||
};
|
||||
|
||||
// Accumulated in the order find_nearby_points() lists the samples, without collecting them first:
|
||||
// this runs for every seam candidate.
|
||||
bool any_sample = false;
|
||||
float total_weight = 0;
|
||||
float total_visibility = 0;
|
||||
for (size_t i = 0; i < points.size(); ++i) {
|
||||
size_t sample_idx = points[i];
|
||||
visit_nearby_points(mesh_samples_tree, position, mesh_samples_radius, [&](size_t sample_idx) {
|
||||
any_sample = true;
|
||||
|
||||
Vec3f sample_point = this->mesh_samples.positions[sample_idx];
|
||||
Vec3f sample_normal = this->mesh_samples.normals[sample_idx];
|
||||
@@ -412,10 +411,9 @@ struct GlobalModelInfo {
|
||||
weight += (mesh_samples_radius - (position - sample_point).norm());
|
||||
total_visibility += weight * mesh_samples_visibility[sample_idx];
|
||||
total_weight += weight;
|
||||
}
|
||||
|
||||
return total_visibility / total_weight;
|
||||
});
|
||||
|
||||
return any_sample ? total_visibility / total_weight : 1.0f;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_FILES
|
||||
@@ -1627,7 +1625,7 @@ Vec3f place_on_loop(const std::vector<SeamCandidate> &points, size_t index, cons
|
||||
void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerImpl::GlobalModelInfo &global_model_info,
|
||||
PreciseSeam::PreciseSeamWarnings* warnings) {
|
||||
using namespace SeamPlacerImpl;
|
||||
PrintObjectSeamData &seam_data = m_seam_per_object.emplace(po, PrintObjectSeamData { }).first->second;
|
||||
PrintObjectSeamData &seam_data = m_seam_per_object.at(po);
|
||||
seam_data.layers.resize(po->layer_count());
|
||||
|
||||
tbb::parallel_for(tbb::blocked_range<size_t>(0, po->layers().size()),
|
||||
@@ -1660,7 +1658,7 @@ void SeamPlacer::gather_seam_candidates(const PrintObject *po, const SeamPlacerI
|
||||
void SeamPlacer::calculate_candidates_visibility(const PrintObject *po,
|
||||
const SeamPlacerImpl::GlobalModelInfo &global_model_info) {
|
||||
|
||||
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
|
||||
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object.at(po).layers;
|
||||
tbb::parallel_for(tbb::blocked_range<size_t>(0, layers.size()),
|
||||
[&layers, &global_model_info](tbb::blocked_range<size_t> r) {
|
||||
for (size_t layer_idx = r.begin(); layer_idx < r.end(); ++layer_idx) {
|
||||
@@ -1676,7 +1674,7 @@ void SeamPlacer::calculate_overhangs_and_layer_embedding(const PrintObject *po)
|
||||
using namespace SeamPlacerImpl;
|
||||
using PerimeterDistancer = AABBTreeLines::LinesDistancer<Linef>;
|
||||
|
||||
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
|
||||
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object.at(po).layers;
|
||||
tbb::parallel_for(tbb::blocked_range<size_t>(0, layers.size()),
|
||||
[po, &layers](tbb::blocked_range<size_t> r) {
|
||||
std::unique_ptr<PerimeterDistancer> prev_layer_distancer;
|
||||
@@ -1896,7 +1894,7 @@ void SeamPlacer::align_seam_points(const PrintObject *po, const SeamPlacerImpl::
|
||||
#endif
|
||||
|
||||
//gather vector of all seams on the print_object - pair of layer_index and seam__index within that layer
|
||||
const std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
|
||||
const std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object.at(po).layers;
|
||||
// Share the largest nozzle diameter between contour bounds and corner protection.
|
||||
double max_nozzle_diameter = 0.0;
|
||||
for (double diameter : po->print()->config().nozzle_diameter.values)
|
||||
@@ -2112,7 +2110,33 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
|
||||
// Warning flags for Precise Seam processing — shared across all objects
|
||||
PreciseSeam::PreciseSeamWarnings precise_seam_warnings;
|
||||
|
||||
// The objects get their seams independently of each other, so they are processed concurrently. Their seam data
|
||||
// and the usage tracking of their Precise Seam modifiers are created first: the objects only look them up.
|
||||
struct ObjectSeams {
|
||||
const PrintObject *po;
|
||||
PrintObjectSeamData *seam_data;
|
||||
std::vector<const ModelVolume*> precise_seam_strong_volumes;
|
||||
std::vector<const ModelVolume*> precise_seam_weak_volumes;
|
||||
};
|
||||
std::vector<ObjectSeams> objects;
|
||||
objects.reserve(print.objects().size());
|
||||
for (const PrintObject *po : print.objects()) {
|
||||
ObjectSeams &object = objects.emplace_back(ObjectSeams{ po, &m_seam_per_object[po], {}, {} });
|
||||
PreciseSeam::init_precise_seam_data(
|
||||
object.precise_seam_strong_volumes,
|
||||
object.precise_seam_weak_volumes,
|
||||
object.seam_data->has_precise_seam_strong_volumes,
|
||||
po->model_object());
|
||||
// Workers only set the usage flags. Several print objects of one model object share volumes, and
|
||||
// try_emplace keeps what earlier ones recorded.
|
||||
for (const ModelVolume* vol : object.precise_seam_strong_volumes)
|
||||
precise_seam_warnings.modifier_usage.try_emplace(vol);
|
||||
for (const ModelVolume* vol : object.precise_seam_weak_volumes)
|
||||
precise_seam_warnings.modifier_usage.try_emplace(vol);
|
||||
}
|
||||
|
||||
auto place_seams = [this, &throw_if_canceled_func, &precise_seam_warnings](ObjectSeams &object) {
|
||||
const PrintObject *po = object.po;
|
||||
throw_if_canceled_func();
|
||||
SeamPosition configured_seam_preference = po->config().seam_position.value;
|
||||
SeamComparator comparator { configured_seam_preference };
|
||||
@@ -2120,23 +2144,14 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
|
||||
{
|
||||
GlobalModelInfo global_model_info { };
|
||||
gather_enforcers_blockers(global_model_info, po);
|
||||
PreciseSeam::init_precise_seam_data(
|
||||
global_model_info.precise_seam_strong_volumes,
|
||||
global_model_info.precise_seam_weak_volumes,
|
||||
m_seam_per_object[po].has_precise_seam_strong_volumes,
|
||||
po->model_object());
|
||||
global_model_info.precise_seam_strong_volumes = std::move(object.precise_seam_strong_volumes);
|
||||
global_model_info.precise_seam_weak_volumes = std::move(object.precise_seam_weak_volumes);
|
||||
|
||||
// Slice each Precise Seam modifier once per object; both consumers read the cache.
|
||||
for (const ModelVolume* vol : global_model_info.precise_seam_strong_volumes)
|
||||
global_model_info.precise_seam_slices[vol] = PreciseSeam::prepare_modifier_slices(po->slice_single_volume_regions(vol));
|
||||
for (const ModelVolume* vol : global_model_info.precise_seam_weak_volumes)
|
||||
global_model_info.precise_seam_slices[vol] = PreciseSeam::prepare_modifier_slices(po->slice_single_volume_regions(vol));
|
||||
// Register usage tracking before the parallel phase; workers only set its flags. Several print
|
||||
// objects of one model object share volumes, and try_emplace keeps what earlier ones recorded.
|
||||
for (const ModelVolume* vol : global_model_info.precise_seam_strong_volumes)
|
||||
precise_seam_warnings.modifier_usage.try_emplace(vol);
|
||||
for (const ModelVolume* vol : global_model_info.precise_seam_weak_volumes)
|
||||
precise_seam_warnings.modifier_usage.try_emplace(vol);
|
||||
|
||||
throw_if_canceled_func();
|
||||
if (configured_seam_preference == spAligned || configured_seam_preference == spNearest || configured_seam_preference == spAlignedBack) {
|
||||
@@ -2169,7 +2184,7 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
|
||||
BOOST_LOG_TRIVIAL(debug)
|
||||
<< "SeamPlacer: pick_seam_point : start";
|
||||
//pick seam point
|
||||
std::vector<PrintObjectSeamData::LayerSeams> &layers = m_seam_per_object[po].layers;
|
||||
std::vector<PrintObjectSeamData::LayerSeams> &layers = object.seam_data->layers;
|
||||
tbb::parallel_for(tbb::blocked_range<size_t>(0, layers.size()),
|
||||
[&layers, configured_seam_preference, comparator](tbb::blocked_range<size_t> r) {
|
||||
for (size_t layer_idx = r.begin(); layer_idx < r.end(); ++layer_idx) {
|
||||
@@ -2195,13 +2210,24 @@ void SeamPlacer::init(const Print &print, std::function<void(void)> throw_if_can
|
||||
}
|
||||
|
||||
// Restore precise seam positions that were potentially modified
|
||||
if (m_seam_per_object[po].has_precise_seam_strong_volumes) {
|
||||
PreciseSeam::restore_precise_seam_positions(m_seam_per_object[po].layers);
|
||||
if (object.seam_data->has_precise_seam_strong_volumes) {
|
||||
PreciseSeam::restore_precise_seam_positions(object.seam_data->layers);
|
||||
}
|
||||
|
||||
#ifdef DEBUG_FILES
|
||||
debug_export_points(m_seam_per_object[po].layers, po->bounding_box(), comparator);
|
||||
debug_export_points(object.seam_data->layers, po->bounding_box(), comparator);
|
||||
#endif
|
||||
};
|
||||
|
||||
if (objects.size() == 1)
|
||||
place_seams(objects.front());
|
||||
else if (objects.size() > 1) {
|
||||
// One object at a time, its serial steps (mesh decimation, building the search trees, aligning the seams)
|
||||
// keep most of the cores idle. A few objects at once overlap them with the others' parallel steps; no more,
|
||||
// as each holds its sampled mesh until it is done.
|
||||
constexpr size_t max_objects_at_once = 4;
|
||||
const size_t objects_per_task = (objects.size() + max_objects_at_once - 1) / max_objects_at_once;
|
||||
parallel_for_first_error(objects.size(), objects_per_task, [&objects, &place_seams](size_t i) { place_seams(objects[i]); });
|
||||
}
|
||||
|
||||
// Prepare one combined Precise Seam warning; G-code export issues it. Keep it single: separate
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <numeric>
|
||||
#include <cassert>
|
||||
#include <cctype>
|
||||
#include <optional>
|
||||
@@ -25,7 +24,6 @@
|
||||
#include "Polygon.hpp"
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/I18N.hpp"
|
||||
#include "libslic3r/PresetBundle.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
// Mark string for localization and translate.
|
||||
@@ -49,29 +47,6 @@ void strip_whitespace(std::string& token)
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count)
|
||||
{
|
||||
// One entry per logical extruder, so a profile has authored a map only when its length
|
||||
// matches. The single-element PrintConfig default does not, and is replaced rather than
|
||||
// treated as a one-extruder machine.
|
||||
if (explicit_pem && nozzle_count > 0 && (int) explicit_pem->values.size() == nozzle_count)
|
||||
return *explicit_pem;
|
||||
|
||||
ConfigOptionInts derived;
|
||||
derived.values.resize(std::max(nozzle_count, 1));
|
||||
std::iota(derived.values.begin(), derived.values.end(), 0);
|
||||
return derived;
|
||||
}
|
||||
|
||||
ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb)
|
||||
{
|
||||
const ConfigOptionInts* explicit_pem = pb.project_config.option<ConfigOptionInts>("physical_extruder_map");
|
||||
if (!explicit_pem || explicit_pem->values.size() < 2)
|
||||
explicit_pem = pb.printers.get_edited_preset().config.option<ConfigOptionInts>("physical_extruder_map");
|
||||
const auto* nozzles = pb.printers.get_edited_preset().config.option<ConfigOptionFloats>("nozzle_diameter");
|
||||
return effective_physical_extruder_map(explicit_pem, nozzles ? (int) nozzles->values.size() : 0);
|
||||
}
|
||||
|
||||
int imex_pem_tool_for(int filament_id, const std::string& parallel_mode, const ConfigOptionInts& pem)
|
||||
{
|
||||
const bool imex_parallel = !parallel_mode.empty() && parallel_mode != kImexPrimaryMode;
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
|
||||
namespace Slic3r {
|
||||
|
||||
class PresetBundle;
|
||||
|
||||
// Reserved sentinel name for the always-present, non-deletable Primary mode in
|
||||
// `imex_mode_names`. Comparison with this constant indicates "no parallel printing
|
||||
// in effect" — IMEX zone visualization, ghost rendering, secondary-tool PA / temp
|
||||
@@ -162,19 +160,8 @@ std::vector<std::string> imex_plate_mode_choices(const ConfigBase& cfg);
|
||||
// route through one of the helpers below.
|
||||
// =============================================================================
|
||||
|
||||
// physical_extruder_map has one entry per LOGICAL extruder -- the index space of
|
||||
// nozzle_diameter -- with each value a physical extruder index. It is NOT derivable from
|
||||
// printer_extruder_id, which is indexed by variant slot (one entry per extruder+variant pair):
|
||||
// an X1 Carbon has one nozzle and printer_extruder_id {1,1}, an H2D two nozzles and {1,1,2,2,2}.
|
||||
//
|
||||
// A profile has authored a map only when its length matches nozzle_count; otherwise the identity
|
||||
// is returned, which is the same default upstream applies (see Plater.cpp's extruder_map).
|
||||
ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count);
|
||||
|
||||
// GUI overload: resolves the effective pem from a live PresetBundle using the project_config
|
||||
// → printer preset fallback. Use this instead of open-coding the lookup at ghost-color,
|
||||
// tooltip, click-gate and cache-key call sites so they all agree with what the slicer sees.
|
||||
ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb);
|
||||
// effective_physical_extruder_map() lives in PrintConfig.hpp and PresetBundle.hpp: the map is a setting of
|
||||
// every multi-nozzle printer, not only IMEX ones.
|
||||
|
||||
// Returns the physical extruder index to emit as a per-tool qualifier (PA / temperature)
|
||||
// for the given filament slot, or -1 when the current IMEX state does not warrant a
|
||||
@@ -189,14 +176,15 @@ int imex_pem_tool_for(int filament_id, const std::string& parallel_mode, const C
|
||||
// so it does not depend on a parallel mode being active the way imex_pem_tool_for does.
|
||||
//
|
||||
// Gated on is_imex because physical_extruder_map carries two readings in this tree: the
|
||||
// BBL paths index it by extruder id (GCode.cpp:3295, WipeTower.cpp:1353), the IMEX paths
|
||||
// BBL paths index it by extruder id (match_physical_extruder_for_each_filament in
|
||||
// GCode::_do_export, WipeTowerWriter::format_line_M104/M109), the IMEX paths
|
||||
// by filament id. Those coincide only when the filament and nozzle counts match, so an
|
||||
// ungated mapping would impose the IMEX reading on profiles that mean the other one --
|
||||
// fdm_bbl_3dp_002_common ships a non-identity [1,0] and is spared today only because
|
||||
// single_extruder_multi_material suppresses the T qualifier entirely.
|
||||
//
|
||||
// Out-of-range ids pass through unchanged, the same rule GCodeProcessor's preheat rewrite
|
||||
// uses (GCode/GCodeProcessor.cpp:1407), so a printer whose map is the registered
|
||||
// uses (GCodeProcessor::run_post_process), so a printer whose map is the registered
|
||||
// single-entry default is unaffected.
|
||||
int imex_physical_heater_for(bool is_imex, const ConfigOptionInts& pem, int logical_id);
|
||||
|
||||
@@ -386,7 +374,7 @@ template<class T>
|
||||
T imex_cfg_enum(const ConfigBase& cfg, const std::string& key)
|
||||
{
|
||||
// Matched by type, not by the coEnum tag. Every ConfigOptionEnum<T> reports coEnum, so the
|
||||
// type() comparison that option<TYPE>() (Config.hpp:2656) and the int/float accessors rely on
|
||||
// type() comparison that ConfigBase::option<TYPE>() and the int/float accessors rely on
|
||||
// cannot tell one enum type from another: it would accept a ConfigOptionEnum<OtherEnum> and
|
||||
// static_cast it to this T. ConfigOptionEnum<A> and ConfigOptionEnum<B> are unrelated
|
||||
// siblings (both derive from ConfigOptionSingle<T>), so a dynamic_cast rejects the mismatch.
|
||||
|
||||
@@ -444,7 +444,10 @@ void Layer::make_perimeters()
|
||||
append(clipped, diff_ex(l->raw_slices, group_slices));
|
||||
clipped = union_ex(clipped);
|
||||
if (layerms.size() == 1 && clipped.empty()) { // optimization
|
||||
// The perimeter generator appends to these, so perimeters made again (other walls) start from none, as a first
|
||||
// slice does.
|
||||
(*layerm)->fill_surfaces.surfaces.clear();
|
||||
(*layerm)->fill_no_overlap_expolygons.clear();
|
||||
(*layerm)->make_perimeters((*layerm)->slices, {*layerm}, &(*layerm)->fill_surfaces, &(*layerm)->fill_no_overlap_expolygons);
|
||||
(*layerm)->fill_expolygons = to_expolygons((*layerm)->fill_surfaces.surfaces);
|
||||
} else {
|
||||
|
||||
+14
-5
@@ -72,6 +72,7 @@
|
||||
#include <map>
|
||||
#include <utility>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
@@ -2885,11 +2886,19 @@ int ModelVolume::extruder_id() const
|
||||
|
||||
bool ModelVolume::is_splittable() const
|
||||
{
|
||||
// the call mesh.is_splittable() is expensive, so cache the value to calculate it only once
|
||||
if (m_is_splittable == -1)
|
||||
m_is_splittable = its_is_splittable(this->mesh().its);
|
||||
|
||||
return m_is_splittable == 1;
|
||||
// The call its_is_splittable() is expensive, so cache the value to calculate it only once. The PrintObjects made from
|
||||
// one ModelObject ask at the same time while they prepare their infill, so the cache is read and written under a
|
||||
// lock; the call itself runs outside it, and only callers that find the cache empty at the same time make it twice.
|
||||
static std::mutex cache_mutex;
|
||||
{
|
||||
std::scoped_lock<std::mutex> lock(cache_mutex);
|
||||
if (m_is_splittable != -1)
|
||||
return m_is_splittable == 1;
|
||||
}
|
||||
const int splittable = its_is_splittable(this->mesh().its) ? 1 : 0;
|
||||
std::scoped_lock<std::mutex> lock(cache_mutex);
|
||||
m_is_splittable = splittable;
|
||||
return splittable == 1;
|
||||
}
|
||||
|
||||
// BBS
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <vector>
|
||||
|
||||
#include <tbb/blocked_range.h>
|
||||
#include <tbb/parallel_for.h>
|
||||
#include <tbb/partitioner.h>
|
||||
#include <tbb/task_arena.h>
|
||||
|
||||
namespace Slic3r {
|
||||
|
||||
// Calls process(i) for every i in [0, count) on the TBB threads, items_per_task consecutive items in each task, and
|
||||
// throws what calling them in order would: the exception of the lowest i that threw. Items after it that have not
|
||||
// started yet are skipped, as a loop stops at its first error.
|
||||
//
|
||||
// Each task runs isolated: while it waits in the parallel loops of its own items, its thread takes no other task of
|
||||
// this loop. Otherwise it could start another item meanwhile, which holds up the waiting item until that one is
|
||||
// done, keeps more items in memory at once than there are threads, and breaks code that keeps a lock or thread-local
|
||||
// scratch across a parallel loop.
|
||||
template<class Process>
|
||||
void parallel_for_first_error(size_t count, size_t items_per_task, Process &&process)
|
||||
{
|
||||
std::vector<std::exception_ptr> errors(count);
|
||||
std::atomic<size_t> first_error { count };
|
||||
tbb::parallel_for(tbb::blocked_range<size_t>(0, count, items_per_task), [&](const tbb::blocked_range<size_t> &range) {
|
||||
tbb::this_task_arena::isolate([&]() {
|
||||
for (size_t i = range.begin(); i < range.end() && i < first_error.load(std::memory_order_relaxed); ++ i)
|
||||
try {
|
||||
process(i);
|
||||
} catch (...) {
|
||||
errors[i] = std::current_exception();
|
||||
size_t lowest = first_error.load(std::memory_order_relaxed);
|
||||
while (i < lowest && ! first_error.compare_exchange_weak(lowest, i, std::memory_order_relaxed))
|
||||
;
|
||||
}
|
||||
});
|
||||
}, tbb::simple_partitioner());
|
||||
for (const std::exception_ptr &error : errors)
|
||||
if (error)
|
||||
std::rethrow_exception(error);
|
||||
}
|
||||
|
||||
} // namespace Slic3r
|
||||
@@ -9374,4 +9374,13 @@ bool PresetBundle::install_vendor_cache(const std::string& cache_path, const std
|
||||
}
|
||||
}
|
||||
|
||||
ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb)
|
||||
{
|
||||
const ConfigOptionInts* explicit_pem = pb.project_config.option<ConfigOptionInts>("physical_extruder_map");
|
||||
if (!explicit_pem || explicit_pem->values.size() < 2)
|
||||
explicit_pem = pb.printers.get_edited_preset().config.option<ConfigOptionInts>("physical_extruder_map");
|
||||
const auto* nozzles = pb.printers.get_edited_preset().config.option<ConfigOptionFloats>("nozzle_diameter");
|
||||
return effective_physical_extruder_map(explicit_pem, nozzles ? (int) nozzles->values.size() : 0);
|
||||
}
|
||||
|
||||
} // namespace Slic3r
|
||||
@@ -969,6 +969,12 @@ private:
|
||||
|
||||
ENABLE_ENUM_BITMASK_OPERATORS(PresetBundle::LoadConfigBundleAttribute)
|
||||
|
||||
// GUI overload of effective_physical_extruder_map() (PrintConfig.hpp): resolves the effective pem
|
||||
// from a live PresetBundle using the project_config → printer preset fallback. Use this instead of
|
||||
// open-coding the lookup at ghost-color, tooltip, click-gate and cache-key call sites so they all
|
||||
// agree with what the slicer sees.
|
||||
ConfigOptionInts effective_physical_extruder_map(const PresetBundle& pb);
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif /* slic3r_PresetBundle_hpp_ */
|
||||
+46
-41
@@ -68,6 +68,7 @@
|
||||
#include "Geometry/ConvexHull.hpp"
|
||||
#include "I18N.hpp"
|
||||
#include "LifecycleEvents.hpp"
|
||||
#include "ParallelForFirstError.hpp"
|
||||
#include "ShortestPath.hpp"
|
||||
#include "Thread.hpp"
|
||||
#include "Time.hpp"
|
||||
@@ -3602,16 +3603,37 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": total object counts %1% in current print, need to slice %2%")%m_objects.size()%need_slicing_objects.size();
|
||||
BOOST_LOG_TRIVIAL(info) << "Starting the slicing process." << log_memory_info();
|
||||
// Runs a step on the objects `needs` selects and `skip` on the others. A step of an object reads that object and
|
||||
// the print's configuration only, which the support step has always relied on, so the objects run the step
|
||||
// together: one after another, each object's serial parts and slowest layers kept most of the cores idle.
|
||||
// A slicing pipeline plugin runs its hook between the objects, so with one active they keep their order.
|
||||
// Nothing enforces that rule. In particular, the PrintObjects made from one ModelObject, one per distinct instance
|
||||
// transformation, share its ModelVolumes, whose lazily filled caches are not guarded: a step must not fill them
|
||||
// (ModelVolume::is_splittable() is the exception, under a lock).
|
||||
auto for_each_object_step = [this](auto &&needs, auto &&process, auto &&skip) {
|
||||
std::vector<PrintObject*> objects;
|
||||
for (PrintObject *obj : m_objects)
|
||||
if (! needs(obj))
|
||||
skip(obj);
|
||||
else if (m_pipeline_plugin_active)
|
||||
process(obj);
|
||||
else
|
||||
objects.push_back(obj);
|
||||
if (objects.size() == 1)
|
||||
process(objects.front());
|
||||
else if (objects.size() > 1)
|
||||
parallel_for_first_error(objects.size(), 1, [&process, &objects](size_t i) { process(objects[i]); });
|
||||
};
|
||||
if (!use_cache) {
|
||||
// Fire the SlicingPipeline hook for `obj` iff it just (re)computed `pstep` this pass.
|
||||
auto hook_after = [this](PrintObject* obj, bool was_done, PrintObjectStep pstep, SlicingPipelineStepPlugin sstep) {
|
||||
if (m_pipeline_plugin_active && !was_done && obj->is_step_done(pstep))
|
||||
run_pipeline_hook(sstep, obj);
|
||||
};
|
||||
auto needs_slicing = [&need_slicing_objects](PrintObject *obj) { return need_slicing_objects.count(obj) != 0; };
|
||||
|
||||
// SlicingPipeline: dedicated slice loop so the Slice boundary is hookable before perimeters.
|
||||
for (PrintObject *obj : m_objects) {
|
||||
if (need_slicing_objects.count(obj) != 0) {
|
||||
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
|
||||
const bool was_done = obj->is_step_done(posSlice);
|
||||
obj->slice();
|
||||
hook_after(obj, was_done, posSlice, SlicingPipelineStepPlugin::posSlice);
|
||||
@@ -3626,32 +3648,25 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
|
||||
if (m_pipeline_plugin_active && !was_done && obj->is_step_done(posSlice))
|
||||
for (Layer *layer : obj->layers())
|
||||
layer->backup_untyped_slices();
|
||||
} else {
|
||||
}, [](PrintObject *obj) {
|
||||
if (obj->set_started(posSlice)) obj->set_done(posSlice); // shared/duplicate — no hook
|
||||
}
|
||||
}
|
||||
for (PrintObject *obj : m_objects) {
|
||||
if (need_slicing_objects.count(obj) != 0) {
|
||||
});
|
||||
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
|
||||
const bool was_done = obj->is_step_done(posPerimeters);
|
||||
obj->make_perimeters(); // slice() inside is a no-op: posSlice already DONE
|
||||
hook_after(obj, was_done, posPerimeters, SlicingPipelineStepPlugin::posPerimeters);
|
||||
} else {
|
||||
}, [](PrintObject *obj) {
|
||||
if (obj->set_started(posPerimeters)) obj->set_done(posPerimeters);
|
||||
}
|
||||
}
|
||||
for (PrintObject *obj : m_objects) {
|
||||
if (need_slicing_objects.count(obj) != 0) {
|
||||
});
|
||||
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
|
||||
const bool was_done = obj->is_step_done(posEstimateCurledExtrusions);
|
||||
obj->estimate_curled_extrusions();
|
||||
hook_after(obj, was_done, posEstimateCurledExtrusions, SlicingPipelineStepPlugin::posEstimateCurledExtrusions);
|
||||
}
|
||||
else {
|
||||
}, [](PrintObject *obj) {
|
||||
if (obj->set_started(posEstimateCurledExtrusions))
|
||||
obj->set_done(posEstimateCurledExtrusions);
|
||||
}
|
||||
}
|
||||
for (PrintObject *obj : m_objects) {
|
||||
if (need_slicing_objects.count(obj) != 0) {
|
||||
});
|
||||
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
|
||||
// split prepare_infill (fill-surface prep) from infill (make_fills) so a
|
||||
// plugin can mutate fill surfaces at the PrepareInfill seam and have make_fills
|
||||
// consume them (unlike the Infill seam, which fires after the fills are already
|
||||
@@ -3663,25 +3678,20 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
|
||||
const bool was_done = obj->is_step_done(posInfill);
|
||||
obj->infill();
|
||||
hook_after(obj, was_done, posInfill, SlicingPipelineStepPlugin::posInfill);
|
||||
}
|
||||
else {
|
||||
}, [](PrintObject *obj) {
|
||||
if (obj->set_started(posPrepareInfill))
|
||||
obj->set_done(posPrepareInfill);
|
||||
if (obj->set_started(posInfill))
|
||||
obj->set_done(posInfill);
|
||||
}
|
||||
}
|
||||
for (PrintObject *obj : m_objects) {
|
||||
if (need_slicing_objects.count(obj) != 0) {
|
||||
});
|
||||
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
|
||||
const bool was_done = obj->is_step_done(posIroning);
|
||||
obj->ironing();
|
||||
hook_after(obj, was_done, posIroning, SlicingPipelineStepPlugin::posIroning);
|
||||
}
|
||||
else {
|
||||
}, [](PrintObject *obj) {
|
||||
if (obj->set_started(posIroning))
|
||||
obj->set_done(posIroning);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Z-Contouring
|
||||
for (PrintObject *obj : m_objects) {
|
||||
@@ -3729,17 +3739,14 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
|
||||
&& m_objects[i]->is_step_done(posSupportMaterial))
|
||||
run_pipeline_hook(SlicingPipelineStepPlugin::posSupportMaterial, m_objects[i]);
|
||||
|
||||
for (PrintObject* obj : m_objects) {
|
||||
if (need_slicing_objects.count(obj) != 0) {
|
||||
for_each_object_step(needs_slicing, [&](PrintObject *obj) {
|
||||
const bool was_done = obj->is_step_done(posDetectOverhangsForLift);
|
||||
obj->detect_overhangs_for_lift();
|
||||
hook_after(obj, was_done, posDetectOverhangsForLift, SlicingPipelineStepPlugin::posDetectOverhangsForLift);
|
||||
}
|
||||
else {
|
||||
}, [](PrintObject *obj) {
|
||||
if (obj->set_started(posDetectOverhangsForLift))
|
||||
obj->set_done(posDetectOverhangsForLift);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
for (PrintObject *obj : m_objects) {
|
||||
@@ -4104,9 +4111,9 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
|
||||
}
|
||||
}
|
||||
//BBS
|
||||
for (PrintObject *obj : m_objects) {
|
||||
if (((!use_cache)&&(need_slicing_objects.count(obj) != 0))
|
||||
|| (use_cache &&(re_slicing_objects.count(obj) != 0))){
|
||||
for_each_object_step([&](PrintObject *obj) {
|
||||
return (!use_cache && need_slicing_objects.count(obj) != 0) || (use_cache && re_slicing_objects.count(obj) != 0);
|
||||
}, [&](PrintObject *obj) {
|
||||
const bool was_done = obj->is_step_done(posSimplifyPath);
|
||||
obj->simplify_extrusion_path();
|
||||
// Unlike every other seam (all inside the `if (!use_cache)` block above), this loop is
|
||||
@@ -4114,16 +4121,14 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
|
||||
// explicitly here to keep hooks from ever firing on cache-loaded (plugin-final) objects.
|
||||
if (!use_cache && m_pipeline_plugin_active && !was_done && obj->is_step_done(posSimplifyPath))
|
||||
run_pipeline_hook(SlicingPipelineStepPlugin::posSimplifyPath, obj);
|
||||
}
|
||||
else {
|
||||
}, [](PrintObject *obj) {
|
||||
if (obj->set_started(posSimplifyPath))
|
||||
obj->set_done(posSimplifyPath);
|
||||
if (obj->set_started(posSimplifyInfill))
|
||||
obj->set_done(posSimplifyInfill);
|
||||
if (obj->set_started(posSimplifySupportPath))
|
||||
obj->set_done(posSimplifySupportPath);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// BBS
|
||||
bool has_adaptive_layer_height = false;
|
||||
|
||||
@@ -123,6 +123,7 @@ std::string PrintBase::output_filepath(const std::string &path, const std::strin
|
||||
//BBS: move set_status from hpp to cpp
|
||||
void PrintBase::set_status(int percent, const std::string &message, unsigned int flags, int warning_step) const
|
||||
{
|
||||
std::scoped_lock<std::mutex> lock(m_status_callback_mutex);
|
||||
if (m_status_callback)
|
||||
m_status_callback(SlicingStatus(percent, message, flags, warning_step));
|
||||
else
|
||||
@@ -132,6 +133,7 @@ void PrintBase::set_status(int percent, const std::string &message, unsigned in
|
||||
void PrintBase::status_update_warnings(int step, PrintStateBase::WarningLevel warning_level,
|
||||
const std::string &message, const PrintObjectBase* print_object, PrintStateBase::SlicingNotificationType message_id)
|
||||
{
|
||||
std::scoped_lock<std::mutex> lock(m_status_callback_mutex);
|
||||
if (this->m_status_callback) {
|
||||
auto status = print_object ? SlicingStatus(*print_object, step, message, message_id, warning_level) : SlicingStatus(*this, step, message, message_id, warning_level);
|
||||
m_status_callback(status);
|
||||
@@ -145,9 +147,9 @@ void PrintBase::status_update_warnings(int step, PrintStateBase::WarningLevel wa
|
||||
const std::string& message, PrintObjectBase &object, PrintStateBase::SlicingNotificationType message_id)
|
||||
{
|
||||
//BBS: add object it into slicing status
|
||||
if (this->m_status_callback) {
|
||||
std::scoped_lock<std::mutex> lock(m_status_callback_mutex);
|
||||
if (this->m_status_callback)
|
||||
m_status_callback(SlicingStatus(object, step, message, message_id, warning_level));
|
||||
}
|
||||
else if (!message.empty())
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(", PrintObject warning: %1%\n")% message.c_str();
|
||||
}
|
||||
|
||||
@@ -481,11 +481,11 @@ public:
|
||||
};
|
||||
typedef std::function<void(const SlicingStatus&)> status_callback_type;
|
||||
// Default status console print out in the form of percent => message.
|
||||
void set_status_default() { m_status_callback = nullptr; }
|
||||
void set_status_default() { set_status_callback(nullptr); }
|
||||
// No status output or callback whatsoever, useful mostly for automatic tests.
|
||||
void set_status_silent() { m_status_callback = [](const SlicingStatus&){}; }
|
||||
void set_status_silent() { set_status_callback([](const SlicingStatus&){}); }
|
||||
// Register a custom status callback.
|
||||
void set_status_callback(status_callback_type cb) { m_status_callback = cb; }
|
||||
void set_status_callback(status_callback_type cb) { std::scoped_lock<std::mutex> lock(m_status_callback_mutex); m_status_callback = std::move(cb); }
|
||||
// Calls a registered callback to update the status, or print out the default message.
|
||||
void set_status(int percent, const std::string &message, unsigned int flags = SlicingStatus::DEFAULT, int warning_step = -1) const;
|
||||
|
||||
@@ -583,6 +583,9 @@ private:
|
||||
// The mutex will be used to guard the worker thread against entering a stage
|
||||
// while the data influencing the stage is modified.
|
||||
mutable std::mutex m_state_mutex;
|
||||
// Held while the status callback runs or is replaced: the objects run their steps concurrently, a callback may keep
|
||||
// state of its own, such as the warnings the command line collects, and the GUI replaces it while a slice runs.
|
||||
mutable std::mutex m_status_callback_mutex;
|
||||
|
||||
friend PrintTryCancel;
|
||||
};
|
||||
|
||||
@@ -154,6 +154,20 @@ double nozzle_diameter_for_filament(const PrintConfig& config, int filament_id,
|
||||
return config.nozzle_diameter.get_at(extruder - 1);
|
||||
}
|
||||
|
||||
ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count)
|
||||
{
|
||||
// One entry per logical extruder, so a profile has authored a map only when its length
|
||||
// matches. The single-element PrintConfig default does not, and is replaced rather than
|
||||
// treated as a one-extruder machine.
|
||||
if (explicit_pem && nozzle_count > 0 && (int) explicit_pem->values.size() == nozzle_count)
|
||||
return *explicit_pem;
|
||||
|
||||
ConfigOptionInts derived;
|
||||
derived.values.resize(std::max(nozzle_count, 1));
|
||||
std::iota(derived.values.begin(), derived.values.end(), 0);
|
||||
return derived;
|
||||
}
|
||||
|
||||
|
||||
// Orca: input shaping values types by flavor
|
||||
std::vector<std::string> get_shaper_type_values_for_flavor(GCodeFlavor flavor)
|
||||
@@ -2211,9 +2225,10 @@ void PrintConfigDef::init_fff_params()
|
||||
def = this->add("brim_ears_detection_length", coFloat);
|
||||
def->label = L("Brim ear detection radius");
|
||||
def->category = L("Support");
|
||||
def->tooltip = L("The geometry will be decimated before detecting sharp angles. "
|
||||
"This parameter indicates the minimum length of the deviation for the decimation.\n"
|
||||
"0 to deactivate.");
|
||||
def->tooltip = L("The direction change at a corner is measured over a window of this length along the outline.\n"
|
||||
"The window grows while the outline keeps curving, so a rounded corner counts as one corner "
|
||||
"once its whole turn is seen.\n"
|
||||
"0 to measure the angle at every vertex without smoothing.");
|
||||
def->sidetext = L("mm"); // millimeters, CIS languages need translation
|
||||
def->min = 0;
|
||||
def->mode = comAdvanced;
|
||||
|
||||
@@ -2821,6 +2821,21 @@ size_t get_extruder_index(const GCodeConfig& config, unsigned int filament_id);
|
||||
|
||||
double nozzle_diameter_for_filament(const PrintConfig& config, int filament_id, bool is_bbl_printer);
|
||||
|
||||
// physical_extruder_map has one entry per LOGICAL extruder -- the index space of
|
||||
// nozzle_diameter -- with each value a physical extruder index. It is NOT derivable from
|
||||
// printer_extruder_id, which is indexed by variant slot (one entry per extruder+variant pair):
|
||||
// an X1 Carbon has one nozzle and printer_extruder_id {1,1}, an H2D two nozzles and {1,1,2,2,2}.
|
||||
//
|
||||
// The setting belongs to every printer, not only IMEX ones: the single-element default is what
|
||||
// any multi-nozzle profile that never sets it (a Snapmaker U1, say) carries, so reading it raw by
|
||||
// logical extruder runs past its end. GUI and device-side readers go through this helper (or its
|
||||
// PresetBundle overload in PresetBundle.hpp); the non-IMEX G-code paths read the raw value on
|
||||
// purpose (see the is_imex gate in PrintApply.cpp).
|
||||
//
|
||||
// A profile has authored a map only when its length matches nozzle_count; otherwise the identity
|
||||
// is returned, the default upstream's printer sync starts from before it applies an authored map.
|
||||
ConfigOptionInts effective_physical_extruder_map(const ConfigOptionInts* explicit_pem, int nozzle_count);
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
// Serialization through the Cereal library
|
||||
|
||||
@@ -2582,7 +2582,7 @@ void TreeSupport::draw_circles()
|
||||
} else
|
||||
expanded_base_areas.emplace_back(expoly);
|
||||
}
|
||||
ts_layer->base_areas = std::move(expanded_base_areas);
|
||||
ts_layer->base_areas = intersection_ex(expanded_base_areas, m_machine_border);
|
||||
}
|
||||
|
||||
// Orca: Final tree base polygons may be too close above model surfaces.
|
||||
|
||||
@@ -1238,6 +1238,8 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
|
||||
toggle_line("toolchange_cyclic_first_layer", use_cyclic_ordering, -1, cyclic_order_reason);
|
||||
|
||||
toggle_line("prime_volume",have_prime_tower && (!purge_in_primetower || !bSEMM), -1, _L("Enable the prime tower and either disable purging in the prime tower or disable single extruder multimaterial mode."));
|
||||
// Orca: the Type 1 tower takes the prime volume of each filament instead.
|
||||
toggle_field("prime_volume", supports_wipe_tower_2, -1, _L("The Type 1 prime tower takes the prime volume from each filament, on its Multimaterial page."));
|
||||
|
||||
for (auto el : {"flush_into_infill", "flush_into_support", "flush_into_objects"})
|
||||
toggle_field(el, have_prime_tower, -1, _L("Enable the prime tower to use this setting."));
|
||||
|
||||
@@ -865,6 +865,23 @@ namespace Slic3r
|
||||
m_agent->add_subscribe(subscribe_list_cache);
|
||||
}
|
||||
|
||||
void DeviceManager::reselect_cloud_machine()
|
||||
{
|
||||
if (!m_agent)
|
||||
return;
|
||||
|
||||
// The selection is a cloud subscription, and a LAN printer has none. Selecting one makes the
|
||||
// Bambu network plugin unsubscribe the device, which drops the LAN session that connected it:
|
||||
// a connect still in flight fails, and one that already succeeded stays down with no connect
|
||||
// result to say so.
|
||||
const std::string dev_id = m_agent->get_user_selected_machine();
|
||||
const MachineObject* obj = get_my_machine(dev_id);
|
||||
if (obj && obj->is_lan_mode_printer())
|
||||
return;
|
||||
|
||||
m_agent->set_user_selected_machine(dev_id);
|
||||
}
|
||||
|
||||
std::map<std::string, MachineObject*> DeviceManager::get_my_machine_list(const std::string& agent_id)
|
||||
{
|
||||
std::map<std::string, MachineObject*> result;
|
||||
|
||||
@@ -104,6 +104,9 @@ public:
|
||||
void add_user_subscribe();
|
||||
void del_user_subscribe();
|
||||
void subscribe_device_list(std::vector<std::string> dev_list);
|
||||
// Selects the agent's selected machine again, which subscribes a cloud printer once the cloud
|
||||
// server has connected. A LAN printer is left as it is.
|
||||
void reselect_cloud_machine();
|
||||
|
||||
/* my machine*/
|
||||
MachineObject* get_my_machine(std::string dev_id);
|
||||
|
||||
@@ -104,12 +104,11 @@ wxString double_to_string(double const value, const int max_precision /*= 4*/)
|
||||
|
||||
wxString s = wxNumberFormatter::ToString(value, max_precision, wxNumberFormatter::Style_None);
|
||||
|
||||
// The following code comes from wxNumberFormatter::RemoveTrailingZeroes(wxString& s)
|
||||
// with the exception that here one sets the decimal separator explicitely to dot.
|
||||
// The following code comes from wxNumberFormatter::RemoveTrailingZeroes(wxString& s).
|
||||
// If number is in scientific format, trailing zeroes belong to the exponent and cannot be removed.
|
||||
if (s.find_first_of("eE") == wxString::npos) {
|
||||
char dec_sep = is_decimal_separator_point() ? '.' : ',';
|
||||
const size_t posDecSep = s.find(dec_sep);
|
||||
// The separator ToString() wrote, from the UI locale, which can differ from the C locale's.
|
||||
const size_t posDecSep = s.find(wxNumberFormatter::GetDecimalSeparator());
|
||||
// No decimal point => removing trailing zeroes irrelevant for integer number.
|
||||
if (posDecSep != wxString::npos) {
|
||||
// Find the last character to keep.
|
||||
@@ -127,6 +126,14 @@ wxString double_to_string(double const value, const int max_precision /*= 4*/)
|
||||
return s;
|
||||
}
|
||||
|
||||
bool string_to_double_any_separator(wxString str, double* value)
|
||||
{
|
||||
// The text may carry the UI locale's separator or the C locale's, and the two can differ.
|
||||
const char dec_sep = is_decimal_separator_point() ? '.' : ',';
|
||||
str.Replace(dec_sep == '.' ? ',' : '.', dec_sep, false);
|
||||
return str.ToDouble(value);
|
||||
}
|
||||
|
||||
wxString get_thumbnail_string(const Vec2d& value)
|
||||
{
|
||||
wxString ret_str = wxString::Format("%.2fx%.2f", value[0], value[1]);
|
||||
@@ -2900,8 +2907,8 @@ void PointCtrl::set_value(const boost::any& value, bool change_event)
|
||||
boost::any& PointCtrl::get_value()
|
||||
{
|
||||
double x, y;
|
||||
if (!x_textctrl->GetValue().ToDouble(&x) ||
|
||||
!y_textctrl->GetValue().ToDouble(&y))
|
||||
if (!string_to_double_any_separator(x_textctrl->GetValue(), &x) ||
|
||||
!string_to_double_any_separator(y_textctrl->GetValue(), &y))
|
||||
{
|
||||
set_value(m_value.empty() ? Vec2d(0.0, 0.0) : m_value, true);
|
||||
show_error(m_parent, _L("Invalid numeric."));
|
||||
|
||||
@@ -59,6 +59,8 @@ using t_change = std::function<void(const t_config_option_key&, const boost::any
|
||||
using t_back_to_init = std::function<void(const std::string&)>;
|
||||
|
||||
wxString double_to_string(double const value, const int max_precision = 4);
|
||||
// Parses a number shown in a field, whichever decimal separator it uses.
|
||||
bool string_to_double_any_separator(wxString str, double* value);
|
||||
wxString get_thumbnail_string(const Vec2d& value);
|
||||
wxString get_thumbnails_string(const std::vector<Vec2d>& values);
|
||||
wxString get_formatted_tooltip_text(const ConfigOptionDef& opt, const t_config_option_key& id);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include "libslic3r/BuildVolume.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/calib.hpp"
|
||||
#include "libslic3r/Geometry.hpp"
|
||||
#include "libslic3r/TriangleMesh.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
@@ -206,6 +207,22 @@ static const std::vector<std::pair<std::string, libvgcode::EViewType>>& view_typ
|
||||
return map;
|
||||
}
|
||||
|
||||
// ORCA: the view type showing the value a calibration varies, when the preview has one.
|
||||
static std::optional<libvgcode::EViewType> calibration_view_type(CalibMode mode)
|
||||
{
|
||||
switch (mode) {
|
||||
case CalibMode::Calib_PA_Line:
|
||||
case CalibMode::Calib_PA_Pattern:
|
||||
case CalibMode::Calib_PA_Tower: return libvgcode::EViewType::PressureAdvance;
|
||||
case CalibMode::Calib_Temp_Tower: return libvgcode::EViewType::Temperature;
|
||||
case CalibMode::Calib_Flow_Rate:
|
||||
case CalibMode::Calib_Vol_speed_Tower: return libvgcode::EViewType::VolumetricFlowRate;
|
||||
case CalibMode::Calib_VFA_Tower: return libvgcode::EViewType::Speed;
|
||||
case CalibMode::Calib_Cornering: return libvgcode::EViewType::Jerk;
|
||||
default: return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
// Find an index of a value in a sorted vector, which is in <z-eps, z+eps>.
|
||||
// Returns -1 if there is no such member.
|
||||
static int find_close_layer_idx(const std::vector<double> &zs, double &z, double eps)
|
||||
@@ -1286,14 +1303,19 @@ void GCodeViewer::select_view_type(libvgcode::EViewType type)
|
||||
// ORCA: Pick the view type the preview opens with, following the "preview_default_view_type" preference:
|
||||
// a fixed view type, the one the user picked last ("last"), or the automatic choice ("auto", the default)
|
||||
// which shows Filament for multi material prints and Line Type for single material ones.
|
||||
// A calibration's view, when given, takes precedence over the preference.
|
||||
// The default is only (re)applied when it actually changes, so a view type picked by hand survives a reslice.
|
||||
void GCodeViewer::apply_default_view_type()
|
||||
void GCodeViewer::apply_default_view_type(std::optional<libvgcode::EViewType> calibration_view)
|
||||
{
|
||||
const std::string preference = wxGetApp().app_config->get("preview_default_view_type");
|
||||
|
||||
std::string key = preference;
|
||||
libvgcode::EViewType type = libvgcode::EViewType::FeatureType;
|
||||
if (preference == "last") {
|
||||
if (calibration_view) {
|
||||
type = *calibration_view;
|
||||
key = "calibration_" + view_type_to_config_name(type);
|
||||
}
|
||||
else if (preference == "last") {
|
||||
if (!view_type_from_config_name(wxGetApp().app_config->get("preview_last_view_type"), type))
|
||||
type = libvgcode::EViewType::FeatureType;
|
||||
}
|
||||
@@ -1765,7 +1787,8 @@ void GCodeViewer::load_as_gcode(const GCodeProcessorResult& gcode_result, const
|
||||
// load_toolpaths(gcode_result, build_volume, exclude_bounding_box);
|
||||
|
||||
// ORCA: Apply the default view type now that we know how many tools the G-code actually uses.
|
||||
apply_default_view_type();
|
||||
const bool flowrate_calib = print.calib_mode() == CalibMode::Calib_None && wxGetApp().plater()->is_flowrate_calib();
|
||||
apply_default_view_type(calibration_view_type(flowrate_calib ? CalibMode::Calib_Flow_Rate : print.calib_mode()));
|
||||
|
||||
// BBS: data for rendering color arrangement recommendation
|
||||
m_nozzle_nums = print.config().option<ConfigOptionFloats>("nozzle_diameter")->values.size();
|
||||
@@ -3801,6 +3824,7 @@ void GCodeViewer::init_solid_model_caps(const std::array<float, 2>& z_range, std
|
||||
init_quad(cap, on_plane, reach * u, reach * v);
|
||||
cap.count_plane = m_clipping_plane;
|
||||
cap.quad_z_range = { z_bottom, z_top };
|
||||
cap.color_index = 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3945,17 +3969,18 @@ void GCodeViewer::render_solid_model(int canvas_width, int canvas_height)
|
||||
}
|
||||
}
|
||||
|
||||
// The solid stands in for the toolpaths, so it takes their colours in the view that colours them
|
||||
// by something other than the filament: each body the outer wall's, each cap the infill's of the
|
||||
// layer it is cut under, sparse if the layer has any, else solid, and the tower its own role's,
|
||||
// each from the toolpaths within the body's own footprint, so that objects printed at different
|
||||
// grades keep their own. The views that colour by filament leave every body its own colour. The
|
||||
// bodies are sampled over the layers the solid stands for and each cap in its own layer, each
|
||||
// colour that of the vertex the viewer picks to represent the role there, so a view that grades
|
||||
// the toolpaths, by speed or fan, shows the solid in the grade most of that role was printed at.
|
||||
// The bodies are sampled once, as the drag begins, and held while a slider drag moves the span:
|
||||
// sampled again at every step, the grade would flip with the layers the sample happens to fall
|
||||
// on. Each cap follows its own layer.
|
||||
// The solid stands in for the toolpaths, so it takes their colours in the view that colours them by
|
||||
// something other than the filament: each body the outer wall's, each layer cap the infill's of the
|
||||
// layer it is cut under, sparse if the layer has any, else solid, the section view's cap the
|
||||
// infill's over all the layers, and the tower its own role's, each from the toolpaths within the
|
||||
// body's own footprint, so that objects printed at different grades keep their own. The views that
|
||||
// colour by filament leave every body its own colour. The bodies and the section view's cap are
|
||||
// sampled over the layers the solid stands for and each layer cap in its own layer, each colour
|
||||
// that of the vertex the viewer picks to represent the role there, so a view that grades the
|
||||
// toolpaths, by speed or fan, shows the solid in the grade most of that role was printed at. The
|
||||
// bodies are sampled once, as the drag begins, and held while a slider drag moves the span: sampled
|
||||
// again at every step, the grade would flip with the layers the sample happens to fall on. The
|
||||
// section view's cap is held with them; each layer cap follows its own layer.
|
||||
void GCodeViewer::update_solid_model_colors(const libvgcode::Interval& whole_layers)
|
||||
{
|
||||
SolidModelColors& colors = m_solid_model_colors;
|
||||
@@ -3996,8 +4021,13 @@ void GCodeViewer::update_solid_model_colors(const libvgcode::Interval& whole_lay
|
||||
const libvgcode::XYBox box{ { static_cast<float>(footprint.min.x()) - margin, static_cast<float>(footprint.min.y()) - margin },
|
||||
{ static_cast<float>(footprint.max.x()) + margin, static_cast<float>(footprint.max.y()) + margin } };
|
||||
SolidModelColors::Body& body = colors.bodies[n];
|
||||
if (!held)
|
||||
if (!held) {
|
||||
body.body = sample(whole_layers, tower ? tower_role : walls, box);
|
||||
// the section view's cut may cross any of the layers, so it is sampled over all of them, as the body is
|
||||
body.caps[2] = tower ? std::nullopt : sample(whole_layers, infill, box);
|
||||
if (!body.caps[2].has_value())
|
||||
body.caps[2] = body.body;
|
||||
}
|
||||
for (size_t k = 0; k < 2; ++k) {
|
||||
body.caps[k] = tower ? std::nullopt : sample({ whole_layers[k], whole_layers[k] }, infill, box);
|
||||
if (!body.caps[k].has_value())
|
||||
|
||||
@@ -354,10 +354,10 @@ private:
|
||||
// the quad, cut by the other caps
|
||||
std::array<float, 2> quad_z_range{ -FLT_MAX, FLT_MAX };
|
||||
std::array<float, 4> quad_plane{ 0.0f, 0.0f, 0.0f, 1.0f };
|
||||
// which of the sampled cap colours it takes, none for the body's own
|
||||
// which of the sampled cap colours it takes
|
||||
std::optional<size_t> color_index;
|
||||
};
|
||||
// the bottom cap, then the top one, as the colours are indexed, then the section view's; a cap
|
||||
// the bottom cap, then the top one, then the section view's, as the colours are indexed; a cap
|
||||
// the solid is not cut at is left without a quad
|
||||
void init_solid_model_caps(const std::array<float, 2>& z_range, std::array<SolidModelCap, 3>& caps) const;
|
||||
void release_caster_depth();
|
||||
@@ -392,8 +392,8 @@ private:
|
||||
{
|
||||
// unset where the view colours by filament, or no vertex of the role was found there
|
||||
std::optional<ColorRGBA> body;
|
||||
// the bottom and top caps
|
||||
std::array<std::optional<ColorRGBA>, 2> caps;
|
||||
// the bottom and top caps, then the section view's, sampled over every layer of the solid
|
||||
std::array<std::optional<ColorRGBA>, 3> caps;
|
||||
};
|
||||
std::vector<Body> bodies;
|
||||
};
|
||||
@@ -533,8 +533,8 @@ public:
|
||||
}
|
||||
// ORCA: select a view type in the preview combo box and apply it
|
||||
void select_view_type(libvgcode::EViewType type);
|
||||
// ORCA: apply the "preview_default_view_type" preference, see the definition for the supported values
|
||||
void apply_default_view_type();
|
||||
// ORCA: apply the "preview_default_view_type" preference, or the view of the calibration being previewed
|
||||
void apply_default_view_type(std::optional<libvgcode::EViewType> calibration_view = std::nullopt);
|
||||
|
||||
// ORCA: stable, locale independent name of a view type, as stored in the application config
|
||||
static std::string view_type_to_config_name(libvgcode::EViewType type);
|
||||
|
||||
@@ -2708,6 +2708,11 @@ void GLCanvas3D::toggle_model_objects_visibility(bool visible, const ModelObject
|
||||
vol->force_neutral_color = false;
|
||||
else if (gizmo_type == GLGizmosManager::MmSegmentation)
|
||||
vol->is_active = false;
|
||||
else if (gizmo_type == GLGizmosManager::TextureDisplacement) {
|
||||
vol->force_native_color = true;
|
||||
if (vol->is_modifier) // GLVolume::is_modifier == any non-model-part volume
|
||||
vol->is_active = false;
|
||||
}
|
||||
else
|
||||
vol->force_native_color = true;
|
||||
}
|
||||
|
||||
@@ -2341,12 +2341,14 @@ void GUI_App::init_networking_callbacks()
|
||||
if (provider != this->get_printer_cloud_provider()) {
|
||||
return;
|
||||
}
|
||||
m_agent->set_user_selected_machine(m_agent->get_user_selected_machine());
|
||||
if (m_device_manager)
|
||||
m_device_manager->reselect_cloud_machine();
|
||||
if (this->is_enable_multi_machine()) {
|
||||
auto evt = new wxCommandEvent(EVT_UPDATE_MACHINE_LIST);
|
||||
wxQueueEvent(this, evt);
|
||||
}
|
||||
m_agent->set_user_selected_machine(m_agent->get_user_selected_machine());
|
||||
if (m_device_manager)
|
||||
m_device_manager->reselect_cloud_machine();
|
||||
if (m_agent->is_user_login(provider)) {
|
||||
|
||||
/*disconnect lan*/
|
||||
@@ -4511,6 +4513,11 @@ void GUI_App::select_machine(const std::string& agent_id)
|
||||
}
|
||||
}
|
||||
|
||||
// Orca: the print dialog blocks a printer whose type differs from the preset's model id, so the
|
||||
// type must be that id, not the model name. A model no vendor profile lists has no id; the
|
||||
// dialog accepts any printer then, and the name stays.
|
||||
const std::string model_id = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle);
|
||||
|
||||
// If machine doesn't exist, create it first. The Orca agent never connects, so an entry saved
|
||||
// under it holds no binding; re-insert it for the active agent, whose machine list can't see
|
||||
// it otherwise. Entries bound by any other agent stay with that agent.
|
||||
@@ -4520,7 +4527,7 @@ void GUI_App::select_machine(const std::string& agent_id)
|
||||
// We use dev_id as dev_ip to store the address (host:port)
|
||||
machine.dev_ip = dev_id;
|
||||
machine.dev_name = dev_id;
|
||||
machine.printer_type = preset.config.opt_string("printer_model");
|
||||
machine.printer_type = model_id.empty() ? preset.config.opt_string("printer_model") : model_id;
|
||||
|
||||
existing = m_device_manager->insert_local_device(
|
||||
machine, "lan", "free", "", access_code);
|
||||
@@ -4534,6 +4541,11 @@ void GUI_App::select_machine(const std::string& agent_id)
|
||||
(!existing->has_access_right() || existing->get_access_code() != access_code)) {
|
||||
existing->set_access_code(access_code);
|
||||
}
|
||||
// Entries saved before held the model name; this printer's preset gives the id to repair them.
|
||||
if (!model_id.empty() && existing->printer_agent_id == agent_id && existing->printer_type != model_id) {
|
||||
existing->printer_type = model_id;
|
||||
DeviceManager::update_local_machine(*existing, app_config);
|
||||
}
|
||||
existing->local_use_ssl = boost::istarts_with(print_host, "https://");
|
||||
select_dev(dev_id);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#include "slic3r/GUI/Event.hpp"
|
||||
#include "libslic3r/Utils.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/Brim.hpp"
|
||||
#include "libslic3r/BrimEarsPoint.hpp"
|
||||
#include "libslic3r/Geometry.hpp"
|
||||
#include <limits>
|
||||
@@ -958,22 +959,9 @@ void GLGizmoBrimEars::reload_cache()
|
||||
find_single();
|
||||
}
|
||||
|
||||
Points GLGizmoBrimEars::generate_points(Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer)
|
||||
Points GLGizmoBrimEars::generate_points(const Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer)
|
||||
{
|
||||
const coordf_t angle_threshold = (180 - brim_ears_max_angle) * PI / 180.0;
|
||||
Points pt_ears;
|
||||
if (ear_detection_length > 0) {
|
||||
double detect_length = ear_detection_length / SCALING_FACTOR;
|
||||
Points points = obj_polygon.points;
|
||||
points.push_back(points.front());
|
||||
points = MultiPoint::_douglas_peucker(points, detect_length);
|
||||
if (points.size() > 4) {
|
||||
points.erase(points.end() - 1);
|
||||
}
|
||||
obj_polygon.points = points;
|
||||
}
|
||||
append(pt_ears, is_outer ? obj_polygon.convex_points(angle_threshold) : obj_polygon.concave_points(angle_threshold));
|
||||
return pt_ears;
|
||||
return make_brim_ear_points(obj_polygon, scale_(ear_detection_length), brim_ears_max_angle, is_outer);
|
||||
}
|
||||
|
||||
void GLGizmoBrimEars::first_layer_slicer()
|
||||
@@ -1053,6 +1041,7 @@ void GLGizmoBrimEars::get_detection_radius_max()
|
||||
min_points_num = MultiPoint::_douglas_peucker(out_points, 0).size();
|
||||
int repeat = 0;
|
||||
int loop_protect = 0;
|
||||
// ORCA: only a feature-size estimate for the slider's upper bound; the detector no longer decimates.
|
||||
for (;;) {
|
||||
loop_protect++;
|
||||
tolerance += 10;
|
||||
|
||||
@@ -159,7 +159,7 @@ private:
|
||||
void select_point(int i);
|
||||
void unselect_point(int i);
|
||||
void reload_cache();
|
||||
Points generate_points(Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer);
|
||||
Points generate_points(const Polygon &obj_polygon, float ear_detection_length, float brim_ears_max_angle, bool is_outer);
|
||||
void auto_generate();
|
||||
void first_layer_slicer();
|
||||
void get_detection_radius_max();
|
||||
|
||||
@@ -732,7 +732,11 @@ void GLGizmoTextureDisplacement::render_painter_gizmo()
|
||||
if (const ModelVolume *part = preview_part(*preview); part != nullptr)
|
||||
previewed.push_back(part);
|
||||
}
|
||||
m_parent.toggle_model_objects_visibility(true);
|
||||
m_parent.toggle_model_objects_visibility(
|
||||
true,
|
||||
m_c->selection_info()->model_object(),
|
||||
m_c->selection_info()->get_active_instance()
|
||||
);
|
||||
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(), volume);
|
||||
|
||||
@@ -490,17 +490,28 @@ protected:
|
||||
page->SetSize(GetPageRect());
|
||||
}
|
||||
|
||||
virtual int DoSetSelection(size_t n, int flags = 0) override
|
||||
{
|
||||
m_target_page = GetPage(n);
|
||||
const int ret = wxBookCtrlBase::DoSetSelection(n, flags);
|
||||
m_target_page = nullptr;
|
||||
return ret;
|
||||
}
|
||||
|
||||
virtual void DoShowPage(wxWindow * page, bool show) override
|
||||
{
|
||||
if (show)
|
||||
page->ShowWithEffect(m_showEffect, m_showTimeout);
|
||||
else
|
||||
// Tabs may share one page window (Prepare/Preview -> m_plater). Hiding it just to re-show it
|
||||
// unmaps and remaps its GL canvases, which triggers a mutter subsurface bug on Wayland.
|
||||
else if (page != m_target_page)
|
||||
page->HideWithEffect(m_hideEffect, m_hideTimeout);
|
||||
}
|
||||
|
||||
private:
|
||||
void Init();
|
||||
|
||||
wxWindow* m_target_page{nullptr}; // page being selected; DoShowPage must not hide it
|
||||
std::vector<wxString> m_pageNames; // index-parallel to wxBookCtrlBase::m_pages
|
||||
|
||||
wxShowEffect m_showEffect,
|
||||
|
||||
@@ -3451,19 +3451,22 @@ std::vector<int> PartPlate::get_extruders_without_support(bool conside_custom_gc
|
||||
int PartPlate::get_physical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const
|
||||
{
|
||||
const std::vector<int>& filament_map = get_real_filament_maps(g_config);
|
||||
if (filament_map.size() < idx)
|
||||
if (idx <= 0 || idx > static_cast<int>(filament_map.size()))
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
const auto the_map = g_config.option<ConfigOptionInts>("physical_extruder_map");
|
||||
if (!the_map)
|
||||
// A multi-nozzle printer whose profile never sets physical_extruder_map carries the
|
||||
// single-element default, so the raw option cannot be indexed by logical extruder.
|
||||
const auto* nozzles = g_config.option<ConfigOptionFloats>("nozzle_diameter");
|
||||
const ConfigOptionInts pem = effective_physical_extruder_map(g_config.option<ConfigOptionInts>("physical_extruder_map"),
|
||||
nozzles ? static_cast<int>(nozzles->values.size()) : 0);
|
||||
const int zero_base_logical_idx = filament_map[idx - 1] - 1;
|
||||
if (zero_base_logical_idx < 0 || zero_base_logical_idx >= static_cast<int>(pem.values.size()))
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
int zero_base_logical_idx = filament_map[idx - 1] - 1;
|
||||
return the_map->values[zero_base_logical_idx];
|
||||
return pem.values[zero_base_logical_idx];
|
||||
}
|
||||
|
||||
int PartPlate::get_logical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const
|
||||
|
||||
@@ -2396,13 +2396,9 @@ bool Sidebar::priv::sync_extruder_list(bool &only_external_material, bool is_man
|
||||
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << __LINE__ << " go on sync_extruder_list";
|
||||
const Preset &cur_preset = preset_bundle->printers.get_selected_preset();
|
||||
int extruder_nums = preset_bundle->get_printer_extruder_count();
|
||||
std::vector<int> extruder_map(extruder_nums);
|
||||
std::iota(extruder_map.begin(), extruder_map.end(), 0);
|
||||
const ConfigOptionInts *physical_extruder_map = cur_preset.config.option<ConfigOptionInts>("physical_extruder_map");
|
||||
if (physical_extruder_map != nullptr) {
|
||||
assert(physical_extruder_map->values.size() == extruder_nums);
|
||||
extruder_map = physical_extruder_map->values;
|
||||
}
|
||||
// A multi-nozzle profile that never sets physical_extruder_map carries the single-element default.
|
||||
const std::vector<int> extruder_map =
|
||||
effective_physical_extruder_map(cur_preset.config.option<ConfigOptionInts>("physical_extruder_map"), extruder_nums).values;
|
||||
assert(obj->GetExtderSystem()->GetTotalExtderCount() == extruder_nums);
|
||||
|
||||
// Multi-nozzle: resolve the nozzle option (pops MultiNozzleSyncDialog when is_manual). No-op for every
|
||||
@@ -7298,6 +7294,8 @@ struct Plater::priv
|
||||
int m_cur_slice_plate;
|
||||
//BBS: m_slice_all in .gcode.3mf file case, set true when slice all
|
||||
bool m_slice_all_only_has_gcode{ false };
|
||||
// Orca: the flow rate test sets no calibration mode on the print, as that would change its G-code
|
||||
bool m_flowrate_calib{ false };
|
||||
|
||||
bool m_need_update{false};
|
||||
//BBS: add popup object table logic
|
||||
@@ -9287,6 +9285,7 @@ std::vector<size_t> Plater::priv::load_files(const std::vector<fs::path>& input_
|
||||
q->m_3mf_path = input_files.front().string();
|
||||
// Leave the previous calibration mode intact when preparation was cancelled.
|
||||
background_process.fff_print()->calib_mode() = CalibMode::Calib_None;
|
||||
m_flowrate_calib = false;
|
||||
|
||||
for (size_t i = 0; i < input_files.size(); ++i) {
|
||||
int project_filament_count = 1;
|
||||
@@ -17780,8 +17779,11 @@ void Plater::calib_flowrate(bool is_linear, int pass, InfillPattern pattern, int
|
||||
// Refresh object after scaling
|
||||
const std::vector<size_t> object_idx(boost::counting_iterator<size_t>(0), boost::counting_iterator<size_t>(model().objects.size()));
|
||||
changed_objects(object_idx);
|
||||
p->m_flowrate_calib = true;
|
||||
}
|
||||
|
||||
bool Plater::is_flowrate_calib() const { return p->m_flowrate_calib; }
|
||||
|
||||
|
||||
// The belt provini tower (Calib_Params::test_model 1) is one embossed model per
|
||||
// temperature range.
|
||||
@@ -18145,6 +18147,7 @@ void Plater::calib_max_vol_speed(const Calib_Params& params)
|
||||
obj_cfg.set_key_value("precise_z_height", new ConfigOptionBool(false));
|
||||
print_config->set_key_value("timelapse_type", new ConfigOptionEnum<TimelapseType>(tlTraditional));
|
||||
print_config->set_key_value("spiral_mode", new ConfigOptionBool(true));
|
||||
print_config->set_key_value("spiral_starting_flow_ratio", new ConfigOptionFloat(1));
|
||||
print_config->set_key_value("max_volumetric_extrusion_rate_slope", new ConfigOptionFloat(0));
|
||||
print_config->set_key_value("enable_wrapping_detection", new ConfigOptionBool(false));
|
||||
|
||||
|
||||
@@ -414,6 +414,8 @@ public:
|
||||
void calib_pa(const Calib_Params& params);
|
||||
//ORCA: Add pattern parameter to calib_flowrate
|
||||
void calib_flowrate(bool is_linear, int pass, InfillPattern pattern = ipArchimedeanChords, int filament_id = 0, int extruder_id = 0);
|
||||
// True from calib_flowrate() until other files are loaded, like the print's calibration mode
|
||||
bool is_flowrate_calib() const;
|
||||
void calib_temp(const Calib_Params& params);
|
||||
void calib_max_vol_speed(const Calib_Params& params);
|
||||
void calib_retraction(const Calib_Params& params);
|
||||
|
||||
@@ -762,8 +762,8 @@ nlohmann::json PluginsDialog::localized_strings() const
|
||||
{"permissions_filesystem_placeholder", _u8L("/path/to/directory/*")},
|
||||
#endif
|
||||
{"permissions_network_access_guidance", _u8L("Enter a full http:// or https:// URL; only its scheme and host are saved, so the grant covers every port, path, and query on that host. A network socket grant also accepts a bare host name or IP address, with or without a port, and covers every port on that host. Other schemes are not accepted. Grants in either list are checked for HTTP and socket access.")},
|
||||
{"permissions_process_help", _u8L("Enter the exact value recorded by the audit. It may be a Python representation of the command.")},
|
||||
{"permissions_process_placeholder", _u8L("Exact audited value")},
|
||||
{"permissions_process_help", _u8L("Executable grants cover all arguments. CommandLine: entries cover only the exact command line.")},
|
||||
{"permissions_process_placeholder", _u8L("Executable or command name")},
|
||||
{"permissions_threading_help_short", _u8L("Allow this plugin to create threads.")},
|
||||
{"permissions_events_help", _u8L("Enter a category and event separated by a colon, such as Socket:socket.__new__.")},
|
||||
{"permissions_events_placeholder", _u8L("Socket:socket.__new__")},
|
||||
@@ -1735,29 +1735,28 @@ void PluginsDialog::reload_local_plugin(const std::string& plugin_key, bool clea
|
||||
[plugin_key, was_loaded, clear_cache]() -> std::pair<bool, std::string> {
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
|
||||
boost::filesystem::path cache_dir;
|
||||
boost::filesystem::path plugin_root;
|
||||
if (clear_cache) {
|
||||
PluginDescriptor descriptor;
|
||||
if (!manager.try_get_plugin_descriptor(plugin_key, descriptor))
|
||||
return {false, _u8L("Plugin not found.")};
|
||||
|
||||
boost::filesystem::path resolved_root;
|
||||
std::string resolve_error;
|
||||
std::string resolve_error;
|
||||
if (!resolve_allowed_plugin_root(descriptor, {get_orca_plugins_dir()},
|
||||
_u8L("Refusing to clear a plugin cache outside the local plugin directory."),
|
||||
resolved_root, resolve_error))
|
||||
plugin_root, resolve_error))
|
||||
return {false, resolve_error};
|
||||
cache_dir = resolved_root / "__whl_extracted__";
|
||||
}
|
||||
|
||||
if (!manager.unload_plugin(plugin_key))
|
||||
return {false, _u8L("Failed to unload plugin.")};
|
||||
|
||||
if (clear_cache) {
|
||||
boost::system::error_code ec;
|
||||
boost::filesystem::remove_all(cache_dir, ec);
|
||||
if (ec)
|
||||
return {false, GUI::format(_u8L("Failed to clear plugin cache: %1%"), ec.message())};
|
||||
// __whl_extracted__ holds both dependency extractions and the uv-installed
|
||||
// entry wheel. The stored wheel and plugin data are left untouched.
|
||||
std::string cache_error;
|
||||
if (!plugin_wheel_install::delete_install_cache(plugin_root, cache_error))
|
||||
return {false, cache_error};
|
||||
}
|
||||
|
||||
manager.load_plugin(plugin_key, false);
|
||||
|
||||
@@ -239,7 +239,10 @@ void PrinterWebView::load_url(wxString& url, wxString apikey)
|
||||
m_url_loaded = false;
|
||||
m_handler = create_printer_webview_handler(*this);
|
||||
|
||||
if (this->IsShown()) {
|
||||
// Orca: IsShownOnScreen(), not IsShown(): the idle prebuild builds this view inside the hidden
|
||||
// Device tab, and a new panel counts as shown, so the page and its camera stream would start
|
||||
// before the tab is opened. Show() loads the deferred page.
|
||||
if (this->IsShownOnScreen()) {
|
||||
//ORCA: m_url_deferred will be cleared on load success
|
||||
//m_url_deferred.clear();
|
||||
m_browser->LoadURL(url);
|
||||
|
||||
@@ -469,10 +469,14 @@ ModelObject *Selection::get_selected_single_object(int &out_object_idx) const
|
||||
|
||||
const ModelInstance *Selection::get_selected_single_intance() const
|
||||
{
|
||||
const int instance_idx = get_instance_idx();
|
||||
if (instance_idx < 0)
|
||||
return nullptr;
|
||||
|
||||
int object_idx;
|
||||
auto mo = get_selected_single_object(object_idx);
|
||||
if (mo) {
|
||||
return mo->instances[get_instance_idx()];
|
||||
return mo->instances[instance_idx];
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -5098,6 +5098,11 @@ void TabFilament::build()
|
||||
optgroup->append_single_option_line("filament_tower_interface_purge_volume", "material_multimaterial#multimaterial-wipe-tower-parameters");
|
||||
optgroup->append_single_option_line("filament_tower_interface_print_temp", "material_multimaterial#multimaterial-wipe-tower-parameters");
|
||||
|
||||
// Orca: the Type 1 prime tower takes its prime volume from each filament, not from the process.
|
||||
optgroup = page->new_optgroup(L("Prime volume"), "param_tower");
|
||||
optgroup->append_single_option_line("filament_prime_volume", "material_multimaterial#multimaterial-wipe-tower-parameters");
|
||||
optgroup->append_single_option_line("filament_prime_volume_nc", "material_multimaterial#multimaterial-wipe-tower-parameters");
|
||||
|
||||
optgroup = page->new_optgroup(L("Multi Filament"));
|
||||
// optgroup->append_single_option_line("filament_flush_temp", "", 0);
|
||||
// optgroup->append_single_option_line("filament_flush_volumetric_speed", "", 0);
|
||||
@@ -5334,6 +5339,18 @@ void TabFilament::toggle_options()
|
||||
// Orca: hide specific settings for BBL printers
|
||||
const wxString bambu_printer_reason = _L("This setting is unavailable for Bambu Lab printers.");
|
||||
toggle_option("filament_minimal_purge_on_wipe_tower", !is_BBL_printer, 256 + variant_index, bambu_printer_reason);
|
||||
|
||||
// Orca: only the Type 1 prime tower reads these. Bambu Lab printers always use the Type 1 tower. The tower
|
||||
// takes the hotend change volume only when two filaments share an extruder but not a nozzle, so only on a
|
||||
// printer whose extruder holds several nozzles, as has_multiple_nozzle tells in TabPrinter::on_preset_loaded().
|
||||
const bool type1_tower = is_BBL_printer || printer_cfg.opt_enum<WipeTowerType>("wipe_tower_type") == WipeTowerType::Type1;
|
||||
const auto *max_nozzle_counts = printer_cfg.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count");
|
||||
const bool has_multiple_nozzle = max_nozzle_counts != nullptr &&
|
||||
std::any_of(max_nozzle_counts->values.begin(), max_nozzle_counts->values.end(),
|
||||
[](int v) { return v > 1 && v != ConfigOptionIntsNullable::nil_value(); });
|
||||
toggle_line("filament_prime_volume", type1_tower, -1, _L("Select wipe tower Type 1 in the printer settings to use this setting."));
|
||||
toggle_line("filament_prime_volume_nc", type1_tower && has_multiple_nozzle, -1,
|
||||
_L("Select wipe tower Type 1 on a printer whose extruder holds more than one nozzle to use this setting."));
|
||||
for (auto el : {"filament_loading_speed_start", "filament_loading_speed",
|
||||
"filament_unloading_speed_start", "filament_unloading_speed", "filament_toolchange_delay", "filament_cooling_moves",
|
||||
"filament_cooling_initial_speed", "filament_cooling_final_speed"})
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
|
||||
#include <boost/algorithm/string/case_conv.hpp>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/filesystem/fstream.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <boost/system/error_code.hpp>
|
||||
@@ -219,7 +221,8 @@ wxImage image_from_decoded(const DecodedHeightTexture &image, std::vector<unsign
|
||||
|
||||
std::vector<unsigned char> read_file_bytes(const std::string &path)
|
||||
{
|
||||
std::ifstream ifs(path, std::ios::binary);
|
||||
// A plugin pack can extract a texture past Windows' MAX_PATH, which only extended_path() reaches.
|
||||
boost::filesystem::ifstream ifs(extended_path(boost::filesystem::path(path)), std::ios::binary);
|
||||
return std::vector<unsigned char>(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
@@ -451,8 +454,10 @@ std::shared_ptr<std::vector<unsigned char>> load_texture_image_data(const std::s
|
||||
|
||||
// Not a PNG at all (a jpg somebody copied into the folder by hand, say): convert it the same way
|
||||
// an import would - keeping its colour if it has any - but leave the file on disk alone.
|
||||
wxImage image;
|
||||
if (!image.LoadFile(from_u8(path)) || !image.IsOk()) {
|
||||
// Decoded from the bytes already read: reopening the file by name would hit MAX_PATH again.
|
||||
wxImage image;
|
||||
wxMemoryInputStream stream(bytes.data(), bytes.size());
|
||||
if (!image.LoadFile(stream) || !image.IsOk()) {
|
||||
error = _u8L("Could not load the selected image.");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include "slic3r/Utils/NetworkAgent.hpp"
|
||||
#include "libslic3r_version.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <wx/panel.h>
|
||||
#include <wx/gdicmn.h>
|
||||
@@ -31,6 +32,9 @@
|
||||
#include <wx/string.h>
|
||||
#include <wx/timer.h>
|
||||
#include <wx/toolbar.h>
|
||||
#include <wx/dialog.h>
|
||||
#include <wx/display.h>
|
||||
#include <wx/toplevel.h>
|
||||
#include <wx/textdlg.h>
|
||||
|
||||
#include <wx/webview.h>
|
||||
@@ -108,7 +112,8 @@ int ZUserLogin::ensure_loopback_port()
|
||||
}
|
||||
|
||||
ZUserLogin::ZUserLogin(std::shared_ptr<ICloudServiceAgent> cloud_agent)
|
||||
: wxDialog((wxWindow*) (wxGetApp().mainframe), wxID_ANY, "OrcaSlicer"), m_cloud_agent(cloud_agent)
|
||||
: wxDialog((wxWindow*) (wxGetApp().mainframe), wxID_ANY, "OrcaSlicer", wxDefaultPosition, wxDefaultSize,
|
||||
wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), m_cloud_agent(cloud_agent)
|
||||
{
|
||||
SetBackgroundColour(*wxWHITE);
|
||||
|
||||
@@ -183,6 +188,13 @@ ZUserLogin::ZUserLogin(std::shared_ptr<ICloudServiceAgent> cloud_agent)
|
||||
m_browser->Hide();
|
||||
m_browser->SetSize(0, 0);
|
||||
|
||||
// The webview fills the dialog, so it follows the dialog when the user resizes it.
|
||||
// Plain SetSizer: the webview is still hidden and 0x0 here, so fitting would collapse the dialog;
|
||||
// the size is set explicitly below.
|
||||
auto* browser_sizer = new wxBoxSizer(wxVERTICAL);
|
||||
browser_sizer->Add(m_browser, 1, wxEXPAND);
|
||||
SetSizer(browser_sizer);
|
||||
|
||||
// Connect the webview events
|
||||
Bind(wxEVT_WEBVIEW_NAVIGATING, &ZUserLogin::OnNavigationRequest, this, m_browser->GetId());
|
||||
Bind(wxEVT_WEBVIEW_NAVIGATED, &ZUserLogin::OnNavigationComplete, this, m_browser->GetId());
|
||||
@@ -196,10 +208,23 @@ ZUserLogin::ZUserLogin(std::shared_ptr<ICloudServiceAgent> cloud_agent)
|
||||
// UI
|
||||
SetTitle(_L("Login"));
|
||||
// Set a more sensible size for web browsing
|
||||
wxSize pSize = FromDIP(wxSize(650, 840));
|
||||
SetSize(pSize);
|
||||
// The preferred size can exceed the work area (e.g. 840 DIP at 150% on a 1080p screen),
|
||||
// which would push the title bar off screen, so clamp it to the display the dialog is on.
|
||||
const wxRect work_area = wxDisplay(GetParent()).GetClientArea();
|
||||
const int margin = FromDIP(20);
|
||||
const wxSize max_size(std::max(1, work_area.GetWidth() - margin), std::max(1, work_area.GetHeight() - margin));
|
||||
|
||||
const wxSize pSize = FromDIP(wxSize(650, 840));
|
||||
SetMinSize(wxSize(std::min(FromDIP(400), max_size.GetWidth()), std::min(FromDIP(400), max_size.GetHeight())));
|
||||
SetSize(wxSize(std::min(pSize.GetWidth(), max_size.GetWidth()), std::min(pSize.GetHeight(), max_size.GetHeight())));
|
||||
|
||||
CentreOnParent();
|
||||
|
||||
// Keep the whole dialog, title bar included, inside the work area.
|
||||
wxRect rect = GetRect();
|
||||
rect.x = std::max(work_area.GetLeft(), std::min(rect.x, work_area.GetRight() + 1 - rect.width));
|
||||
rect.y = std::max(work_area.GetTop(), std::min(rect.y, work_area.GetBottom() + 1 - rect.height));
|
||||
Move(rect.GetPosition());
|
||||
}
|
||||
wxGetApp().UpdateDlgDarkUI(this);
|
||||
}
|
||||
|
||||
@@ -367,7 +367,9 @@ static void init_multi_extruder_params_for_cali(DynamicPrintConfig& config, cons
|
||||
nozzle_volume_types.clear();
|
||||
nozzle_volume_types.resize(extruder_count, (int)calib_info.nozzle_volume_type);
|
||||
|
||||
std::vector<int> physical_extruder_maps = dynamic_cast<ConfigOptionInts*>(config.option("physical_extruder_map", true))->values;
|
||||
// One entry per nozzle even when the profile never set the map (the single-element default).
|
||||
const std::vector<int> physical_extruder_maps =
|
||||
effective_physical_extruder_map(config.option<ConfigOptionInts>("physical_extruder_map", true), extruder_count).values;
|
||||
int extruder_id = calib_info.extruder_id;
|
||||
for (size_t index = 0; index < extruder_count; ++index) {
|
||||
if (physical_extruder_maps[index] == extruder_id)
|
||||
@@ -969,7 +971,8 @@ void CalibUtils::set_for_auto_pa_model_and_config(const std::vector<CalibInfo> &
|
||||
nozzle_flush_dataset.resize(extruder_count, 0);
|
||||
|
||||
int filament_nums = calib_infos.size();
|
||||
std::vector<int> physical_extruder_maps = dynamic_cast<ConfigOptionInts *>(full_config.option("physical_extruder_map", true))->values;
|
||||
const std::vector<int> physical_extruder_maps =
|
||||
effective_physical_extruder_map(full_config.option<ConfigOptionInts>("physical_extruder_map", true), extruder_count).values;
|
||||
for (size_t filament_index = 0; filament_index < calib_infos.size(); ++filament_index) {
|
||||
CalibInfo calib_info = calib_infos[filament_index];
|
||||
int extruder_id = calib_info.extruder_id;
|
||||
@@ -1055,7 +1058,10 @@ bool CalibUtils::calib_generic_auto_pa_cali(const std::vector<CalibInfo> &calib_
|
||||
std::vector<Preset> filament_presets;
|
||||
std::vector<int> filament_map;
|
||||
filament_map.resize(calib_infos.size());
|
||||
std::vector<int> physical_extruder_maps = dynamic_cast<ConfigOptionInts *>(printer_config.option("physical_extruder_map", true))->values;
|
||||
const auto* nozzle_diameters = printer_config.option<ConfigOptionFloats>("nozzle_diameter");
|
||||
const int nozzle_count = nozzle_diameters ? static_cast<int>(nozzle_diameters->values.size()) : 0;
|
||||
const std::vector<int> physical_extruder_maps =
|
||||
effective_physical_extruder_map(printer_config.option<ConfigOptionInts>("physical_extruder_map", true), nozzle_count).values;
|
||||
for (size_t i = 0; i < calib_infos.size(); ++i) {
|
||||
CalibInfo calib_info = calib_infos[i];
|
||||
calib_info.filament_prest->config.set_key_value("curr_bed_type", new ConfigOptionEnum<BedType>(calib_info.bed_type));
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
#include <boost/nowide/convert.hpp>
|
||||
|
||||
#include <curl/curl.h>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <wx/progdlg.h>
|
||||
@@ -162,7 +164,11 @@ bool CrealityPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn,
|
||||
|
||||
auto http = Http::post(url); // std::move(url));
|
||||
set_auth(http);
|
||||
if (!supports_multi_color_print())
|
||||
// Multi-color models get no folder with the upload, so they keep it right under printer_data/gcodes.
|
||||
const bool multi_color = supports_multi_color_print();
|
||||
const auto remote_path = multi_color || upload_parent_path.empty() ? safe_upload_filename :
|
||||
(upload_parent_path / safe_upload_filename).generic_string();
|
||||
if (!multi_color)
|
||||
http.form_add("path", upload_parent_path.string());
|
||||
http.form_add_file("file", upload_data.source_path.string(), safe_upload_filename)
|
||||
|
||||
@@ -171,7 +177,7 @@ bool CrealityPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn,
|
||||
|
||||
if (upload_data.post_action == PrintHostPostUploadAction::StartPrint) {
|
||||
wxString errormsg;
|
||||
if (!start_print(errormsg, safe_upload_filename, upload_data.extended_info)) {
|
||||
if (!start_print(errormsg, remote_path, upload_data.extended_info)) {
|
||||
error_fn(std::move(errormsg));
|
||||
res = false;
|
||||
}
|
||||
@@ -278,20 +284,15 @@ static int reported_cfs_connect(const std::string& msg)
|
||||
return cfs_connect == 1 ? 1 : -1;
|
||||
}
|
||||
|
||||
// Sends the CFS slot query and returns the reply, or nothing once a status reports no CFS connected, which also sets *no_cfs.
|
||||
// The query gets slots_reply, or the later of slots_reply and cfs_reply once a status reports a CFS connected, since such a printer does answer.
|
||||
static std::string ws_query_slots(net::io_context& ioc,
|
||||
websocket::stream<beast::tcp_stream>& ws,
|
||||
std::chrono::milliseconds slots_reply,
|
||||
std::chrono::milliseconds cfs_reply,
|
||||
bool* no_cfs)
|
||||
// Reads the printer's messages until one holds key and returns it, or returns nothing once deadline passes or on_other, which gets
|
||||
// every other message, returns false. The deadline also ends the read when the printer keeps sending heartbeats or status updates.
|
||||
template<class OnOther>
|
||||
static std::string ws_await_reply(net::io_context& ioc,
|
||||
websocket::stream<beast::tcp_stream>& ws,
|
||||
const std::chrono::steady_clock::time_point& deadline,
|
||||
const char* key,
|
||||
OnOther&& on_other)
|
||||
{
|
||||
const auto sent = std::chrono::steady_clock::now();
|
||||
auto deadline = sent + slots_reply;
|
||||
beast::get_lowest_layer(ws).expires_at(deadline);
|
||||
ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"boxsInfo", 1}}}});
|
||||
|
||||
// The deadline also ends the read when the printer keeps sending heartbeats or status updates.
|
||||
while (std::chrono::steady_clock::now() < deadline) {
|
||||
beast::flat_buffer buf;
|
||||
const beast::error_code ec = ws_read(ioc, ws, buf);
|
||||
@@ -306,22 +307,131 @@ static std::string ws_query_slots(net::io_context& ioc,
|
||||
ws_write(ioc, ws, "ok");
|
||||
continue;
|
||||
}
|
||||
if (msg.find("boxsInfo") != std::string::npos)
|
||||
if (msg.find(key) != std::string::npos)
|
||||
return msg;
|
||||
if (!on_other(msg))
|
||||
break;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
// Sends the CFS slot query and returns the reply, or nothing when none arrives in time.
|
||||
// The query gets slots_reply, or the later of slots_reply and cfs_reply once a status reports a CFS connected, since such a printer does answer.
|
||||
// A status reporting no CFS connected cuts the wait to no_cfs_reply from then, and sets *no_cfs if no reply follows: a SPARKX i7
|
||||
// reports no CFS connected for its CFS Lite and still sends the slots.
|
||||
static std::string ws_query_slots(net::io_context& ioc,
|
||||
websocket::stream<beast::tcp_stream>& ws,
|
||||
std::chrono::milliseconds slots_reply,
|
||||
std::chrono::milliseconds cfs_reply,
|
||||
std::chrono::milliseconds no_cfs_reply,
|
||||
bool* no_cfs)
|
||||
{
|
||||
const auto sent = std::chrono::steady_clock::now();
|
||||
auto deadline = sent + slots_reply;
|
||||
beast::get_lowest_layer(ws).expires_at(deadline);
|
||||
ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"boxsInfo", 1}}}});
|
||||
|
||||
bool reported_no_cfs = false;
|
||||
const std::string reply = ws_await_reply(ioc, ws, deadline, "boxsInfo", [&](const std::string& msg) {
|
||||
const int cfs_connect = reported_cfs_connect(msg);
|
||||
if (cfs_connect == 0) {
|
||||
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer reports no CFS connected";
|
||||
if (no_cfs)
|
||||
*no_cfs = true;
|
||||
return {};
|
||||
}
|
||||
if (cfs_connect == 1) {
|
||||
deadline = sent + std::max(slots_reply, cfs_reply);
|
||||
if (cfs_connect == 0 && !reported_no_cfs) {
|
||||
reported_no_cfs = true;
|
||||
deadline = std::min(deadline, std::chrono::steady_clock::now() + no_cfs_reply);
|
||||
beast::get_lowest_layer(ws).expires_at(deadline);
|
||||
}
|
||||
if (cfs_connect == 1) {
|
||||
reported_no_cfs = false;
|
||||
deadline = sent + std::max(slots_reply, cfs_reply);
|
||||
beast::get_lowest_layer(ws).expires_at(deadline);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!reply.empty())
|
||||
return reply;
|
||||
if (reported_no_cfs) {
|
||||
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer reports no CFS connected";
|
||||
if (no_cfs)
|
||||
*no_cfs = true;
|
||||
} else
|
||||
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response";
|
||||
return reply;
|
||||
}
|
||||
|
||||
// The full path a reply to reqGcodeFile lists remote_path at, an empty string when it does not list it, or nothing when the reply
|
||||
// is no list this code reads. K2-family firmware answers retGcodeFileInfo2, a list of files with their path. K1-family firmware
|
||||
// answers retGcodeFileInfo, whose fileInfo holds "folder:name:size:..." entries separated by ';'.
|
||||
static std::optional<std::string> listed_gcode_path(const std::string& reply_text, const std::string& remote_path)
|
||||
{
|
||||
const json reply = json::parse(reply_text, nullptr, false);
|
||||
if (!reply.is_object())
|
||||
return std::nullopt;
|
||||
const std::string under_gcodes = "/printer_data/gcodes/" + remote_path;
|
||||
|
||||
if (const auto files = reply.find("retGcodeFileInfo2"); files != reply.end() && files->is_array()) {
|
||||
for (const json& file : *files)
|
||||
if (file.is_object() && file.contains("path") && file.at("path").is_string() &&
|
||||
boost::algorithm::ends_with(file.at("path").get<std::string>(), under_gcodes))
|
||||
return file.at("path").get<std::string>();
|
||||
return std::string();
|
||||
}
|
||||
|
||||
const auto info = reply.find("retGcodeFileInfo");
|
||||
if (info == reply.end() || !info->is_object() || !info->contains("fileInfo") || !info->at("fileInfo").is_string())
|
||||
return std::nullopt;
|
||||
// Finds the name between its folder and its size, so a name holding ';' or ':' is found too.
|
||||
const std::string file_info = info->at("fileInfo").get<std::string>();
|
||||
const std::string name = remote_path.substr(remote_path.rfind('/') + 1);
|
||||
const std::string field = ':' + name + ':';
|
||||
for (size_t at = file_info.find(field); at != std::string::npos; at = file_info.find(field, at + 1)) {
|
||||
const size_t entry = file_info.rfind(';', at);
|
||||
const size_t begin = entry == std::string::npos ? 0 : entry + 1;
|
||||
const std::string path = file_info.substr(begin, at - begin) + '/' + name;
|
||||
if (boost::algorithm::ends_with(path, under_gcodes))
|
||||
return path;
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
|
||||
namespace {
|
||||
// What the printer's G-code file list says about an upload.
|
||||
struct GcodeListing
|
||||
{
|
||||
enum class Result { NoReply, Unreadable, NotListed, Listed } result = Result::NoReply;
|
||||
std::string path; // The full path the upload is listed at
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// Asks for the G-code file list until it lists remote_path or files_reply passes. A printer can answer before it has indexed a
|
||||
// file just uploaded, so a list without the upload is asked for again after files_retry.
|
||||
static GcodeListing ws_find_listed_gcode(net::io_context& ioc,
|
||||
websocket::stream<beast::tcp_stream>& ws,
|
||||
std::chrono::milliseconds files_reply,
|
||||
std::chrono::milliseconds files_retry,
|
||||
const std::string& remote_path)
|
||||
{
|
||||
const auto deadline = std::chrono::steady_clock::now() + files_reply;
|
||||
GcodeListing listing;
|
||||
for (;;) {
|
||||
beast::get_lowest_layer(ws).expires_at(deadline);
|
||||
ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"reqGcodeFile", 1}}}});
|
||||
const std::string reply = ws_await_reply(ioc, ws, deadline, "retGcodeFileInfo", [](const std::string&) { return true; });
|
||||
if (reply.empty())
|
||||
return listing;
|
||||
const std::optional<std::string> path = listed_gcode_path(reply, remote_path);
|
||||
if (!path) {
|
||||
listing.result = GcodeListing::Result::Unreadable;
|
||||
return listing;
|
||||
}
|
||||
if (!path->empty()) {
|
||||
listing.result = GcodeListing::Result::Listed;
|
||||
listing.path = *path;
|
||||
return listing;
|
||||
}
|
||||
listing.result = GcodeListing::Result::NotListed;
|
||||
if (std::chrono::steady_clock::now() + files_retry >= deadline)
|
||||
return listing;
|
||||
std::this_thread::sleep_for(files_retry);
|
||||
}
|
||||
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response";
|
||||
return {};
|
||||
}
|
||||
|
||||
// The K1 SE closes its side after a reply and K1-family printers after a start command, so a close error is not a failure.
|
||||
@@ -331,7 +441,8 @@ static void ws_close(net::io_context& ioc, websocket::stream<beast::tcp_stream>&
|
||||
run_until_done(ioc, [&](auto&& handler) { ws.async_close(websocket::close_code::normal, handler); });
|
||||
}
|
||||
|
||||
// Add a model by its /info value once its firmware is known to keep gcodes under /usr/data; every other model uses /mnt/UDISK.
|
||||
// The folder for a printer that lists no G-code file. Add a model by its /info value once its firmware is known to keep gcodes
|
||||
// under /usr/data; every other model uses /mnt/UDISK.
|
||||
static bool stores_gcode_in_usr_data(const std::string& model)
|
||||
{
|
||||
static const std::unordered_set<std::string> usr_data_models = {
|
||||
@@ -341,6 +452,7 @@ static bool stores_gcode_in_usr_data(const std::string& model)
|
||||
"F004", // Ender-5 Max
|
||||
"F005", // Ender-3 V3 KE
|
||||
"F016", // K2 SE
|
||||
"Ender-3 V2 Neo", // Nebula Pad on an Ender-3 V2 Neo
|
||||
"K1",
|
||||
"K1 Max",
|
||||
"K1 Max_CFS-C",
|
||||
@@ -420,7 +532,7 @@ std::string CrealityPrint::query_boxes_info(bool* no_cfs) const
|
||||
websocket::stream<beast::tcp_stream> ws{ioc};
|
||||
ws_connect(ioc, ws, m_host, ws_settings.port, ws_settings.connect);
|
||||
|
||||
std::string result = ws_query_slots(ioc, ws, ws_settings.slots_reply, ws_settings.reply, no_cfs);
|
||||
std::string result = ws_query_slots(ioc, ws, ws_settings.slots_reply, ws_settings.reply, ws_settings.no_cfs_reply, no_cfs);
|
||||
|
||||
ws_close(ioc, ws, ws_settings.close);
|
||||
return result;
|
||||
@@ -430,6 +542,45 @@ std::string CrealityPrint::query_boxes_info(bool* no_cfs) const
|
||||
}
|
||||
}
|
||||
|
||||
// Uses a connection of its own, since the K1 SE closes its side after a reply. A failed connection is not caught: the start would
|
||||
// fail the same way, and trying again would double the wait.
|
||||
std::string CrealityPrint::query_listed_gcode(const std::string& remote_path) const
|
||||
{
|
||||
net::io_context ioc;
|
||||
websocket::stream<beast::tcp_stream> ws{ioc};
|
||||
ws_connect(ioc, ws, m_host, ws_settings.port, ws_settings.connect);
|
||||
|
||||
GcodeListing listing;
|
||||
try {
|
||||
listing = ws_find_listed_gcode(ioc, ws, ws_settings.files_reply, ws_settings.files_retry, remote_path);
|
||||
} catch (std::exception const& e) {
|
||||
BOOST_LOG_TRIVIAL(error) << "CrealityPrint: Failed to query the G-code file list: " << e.what();
|
||||
return {};
|
||||
}
|
||||
switch (listing.result) {
|
||||
case GcodeListing::Result::Listed:
|
||||
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer lists " << remote_path << " at " << listing.path;
|
||||
break;
|
||||
case GcodeListing::Result::NotListed:
|
||||
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: The printer's G-code file list does not include " << remote_path;
|
||||
break;
|
||||
case GcodeListing::Result::Unreadable:
|
||||
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: The printer's G-code file list has no format this host reads";
|
||||
break;
|
||||
case GcodeListing::Result::NoReply:
|
||||
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for the G-code file list";
|
||||
break;
|
||||
}
|
||||
|
||||
// A printer that sent no list may not answer a close either, so its connection is dropped without one.
|
||||
if (listing.result == GcodeListing::Result::NoReply) {
|
||||
beast::error_code ec;
|
||||
beast::get_lowest_layer(ws).socket().close(ec);
|
||||
} else
|
||||
ws_close(ioc, ws, ws_settings.close);
|
||||
return listing.path;
|
||||
}
|
||||
|
||||
CrealityPrinterInfo CrealityPrint::read_printer_info() const
|
||||
{
|
||||
CrealityPrinterInfo info;
|
||||
@@ -518,14 +669,21 @@ std::vector<std::string> CrealityPrint::start_print_commands(bool
|
||||
return commands;
|
||||
}
|
||||
|
||||
bool CrealityPrint::start_print(wxString &msg, const std::string &filename, const std::map<std::string, std::string>& extended_info) const
|
||||
bool CrealityPrint::start_print(wxString &msg, const std::string &remote_path, const std::map<std::string, std::string>& extended_info) const
|
||||
{
|
||||
try {
|
||||
// Runs before the WebSocket opens and its reply deadline starts, since it can query the
|
||||
// printer over HTTP. It also fills m_model.
|
||||
const bool multi_color = supports_multi_color_print();
|
||||
const std::string data_root = stores_gcode_in_usr_data(m_model) ? "/usr/data" : "/mnt/UDISK";
|
||||
const std::string gcode_path = data_root + "/printer_data/gcodes/" + filename;
|
||||
const bool multi_color = supports_multi_color_print();
|
||||
// Starts the file at the path the printer lists it at, as Creality Print does, since the
|
||||
// folder depends on the printer's board and not on its model. The model decides only when
|
||||
// the printer does not list the upload.
|
||||
std::string gcode_path = query_listed_gcode(remote_path);
|
||||
if (gcode_path.empty()) {
|
||||
const std::string data_root = stores_gcode_in_usr_data(m_model) ? "/usr/data" : "/mnt/UDISK";
|
||||
gcode_path = data_root + "/printer_data/gcodes/" + remote_path.substr(remote_path.rfind('/') + 1);
|
||||
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: Using " << data_root << " for model " << m_model;
|
||||
}
|
||||
|
||||
net::io_context ioc;
|
||||
websocket::stream<beast::tcp_stream> ws{ioc};
|
||||
|
||||
@@ -21,7 +21,7 @@ struct CrealityPrinterInfo
|
||||
{
|
||||
bool reachable{false};
|
||||
bool multi_color{false};
|
||||
bool no_cfs{false}; // The printer reports that no CFS is connected
|
||||
bool no_cfs{false}; // The printer reports that no CFS is connected and lists no slots
|
||||
std::string model_name;
|
||||
std::string boxes_json; // Empty unless the printer lists its CFS slots
|
||||
};
|
||||
@@ -49,7 +49,7 @@ public:
|
||||
// value: an F-code on the K2 platform, a literal name on K1-family.
|
||||
static bool model_supports_multi_color(const std::string& model);
|
||||
static std::string model_display_name(const std::string& model);
|
||||
// Sets *no_cfs to whether the printer reports that no CFS is connected.
|
||||
// Sets *no_cfs when the printer reports that no CFS is connected and then lists no slots.
|
||||
std::string query_boxes_info(bool* no_cfs = nullptr) const;
|
||||
// Reads the model and, for a CFS-capable model, the CFS slots, without translating any text, so it is safe off the UI thread.
|
||||
CrealityPrinterInfo read_printer_info() const;
|
||||
@@ -66,10 +66,13 @@ protected:
|
||||
struct WsSettings
|
||||
{
|
||||
std::string port{"9999"};
|
||||
std::chrono::milliseconds connect{std::chrono::seconds(5)}; // Per resolved address tried, then again for the opening handshake
|
||||
std::chrono::milliseconds reply{std::chrono::seconds(10)}; // Commands and the replies read after them
|
||||
std::chrono::milliseconds slots_reply{std::chrono::seconds(5)}; // The CFS slot query, extended to reply once a status reports a CFS connected
|
||||
std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake
|
||||
std::chrono::milliseconds connect{std::chrono::seconds(5)}; // Per resolved address tried, then again for the opening handshake
|
||||
std::chrono::milliseconds reply{std::chrono::seconds(10)}; // Commands and the replies read after them
|
||||
std::chrono::milliseconds slots_reply{std::chrono::seconds(5)}; // The CFS slot query, extended to reply once a status reports a CFS connected
|
||||
std::chrono::milliseconds no_cfs_reply{std::chrono::seconds(2)}; // The CFS slot query once a status reports no CFS connected
|
||||
std::chrono::milliseconds files_reply{std::chrono::seconds(3)}; // The G-code file list query before a start, asked again within it
|
||||
std::chrono::milliseconds files_retry{std::chrono::milliseconds(500)}; // The pause before asking again for a list without the upload
|
||||
std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake
|
||||
} ws_settings;
|
||||
|
||||
private:
|
||||
@@ -82,7 +85,10 @@ private:
|
||||
mutable std::string m_model;
|
||||
|
||||
std::string make_url(const std::string& path) const;
|
||||
bool start_print(wxString& msg, const std::string& filename, const std::map<std::string, std::string>& extended_info) const;
|
||||
// remote_path is where the upload went under printer_data/gcodes.
|
||||
bool start_print(wxString& msg, const std::string& remote_path, const std::map<std::string, std::string>& extended_info) const;
|
||||
// The full path the printer lists remote_path at, or nothing when it does not list it. Throws when the printer cannot be reached.
|
||||
std::string query_listed_gcode(const std::string& remote_path) const;
|
||||
std::string safe_filename(const std::string& filename) const;
|
||||
void query_model() const;
|
||||
// Reads /info and caches the model. When msg is not null, it gets a translated error, or on Windows the resolved address.
|
||||
|
||||
@@ -464,8 +464,17 @@ namespace Slic3r {
|
||||
}
|
||||
bool ElegooLink::test(wxString &curl_msg) const{
|
||||
switch (classify_printer_model(m_printerModel)) {
|
||||
case ElegooPrinterType::Other:
|
||||
return OctoPrint::test(curl_msg);
|
||||
case ElegooPrinterType::Other: {
|
||||
if (OctoPrint::test(curl_msg))
|
||||
return true;
|
||||
// A custom preset can have any printer_model, so an SDCP printer may land here too.
|
||||
// If that check fails as well, keep the OctoPrint error for the user.
|
||||
wxString sdcp_msg;
|
||||
if (!elegoo_test(sdcp_msg))
|
||||
return false;
|
||||
curl_msg = sdcp_msg;
|
||||
return true;
|
||||
}
|
||||
case ElegooPrinterType::CC2:
|
||||
return elegoo_cc2_test(curl_msg);
|
||||
case ElegooPrinterType::CC:
|
||||
@@ -556,19 +565,6 @@ namespace Slic3r {
|
||||
|
||||
return res;
|
||||
}
|
||||
bool ElegooLink::test_with_resolved_ip(wxString& msg) const
|
||||
{
|
||||
switch (classify_printer_model(m_printerModel)) {
|
||||
case ElegooPrinterType::Other:
|
||||
return OctoPrint::test_with_resolved_ip(msg);
|
||||
case ElegooPrinterType::CC2:
|
||||
return elegoo_cc2_test_with_resolved_ip(msg);
|
||||
case ElegooPrinterType::CC:
|
||||
return elegoo_test_with_resolved_ip(msg);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ElegooLink::elegoo_cc2_test_with_resolved_ip(wxString& msg) const
|
||||
{
|
||||
const char* name = get_name();
|
||||
@@ -623,11 +619,13 @@ namespace Slic3r {
|
||||
{
|
||||
const auto printer_type = classify_printer_model(m_printerModel);
|
||||
|
||||
if (printer_type == ElegooPrinterType::Other)
|
||||
return OctoPrint::upload_inner_with_resolved_ip(std::move(upload_data), prorgess_fn, error_fn, info_fn, resolved_addr);
|
||||
|
||||
info_fn(L"resolve", boost::nowide::widen(resolved_addr.to_string()));
|
||||
|
||||
// Other may be an SDCP printer: fall back to SDCP, but report the OctoPrint error if that fails too.
|
||||
wxString octoprint_msg = GUI::from_u8(resolved_addr.to_string());
|
||||
if (printer_type == ElegooPrinterType::Other && OctoPrint::test_with_resolved_ip(octoprint_msg))
|
||||
return upload_after_test_with_resolved_ip(std::move(upload_data), prorgess_fn, error_fn, info_fn, resolved_addr);
|
||||
|
||||
if (printer_type == ElegooPrinterType::CC2) {
|
||||
wxString cc2_msg = GUI::from_u8(resolved_addr.to_string());
|
||||
if (!elegoo_cc2_test_with_resolved_ip(cc2_msg)) {
|
||||
@@ -642,7 +640,7 @@ namespace Slic3r {
|
||||
|
||||
wxString legacy_msg = GUI::from_u8(resolved_addr.to_string());
|
||||
if (!elegoo_test_with_resolved_ip(legacy_msg)) {
|
||||
error_fn(std::move(legacy_msg));
|
||||
error_fn(std::move(printer_type == ElegooPrinterType::Other ? octoprint_msg : legacy_msg));
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -658,8 +656,10 @@ namespace Slic3r {
|
||||
{
|
||||
const auto printer_type = classify_printer_model(m_printerModel);
|
||||
|
||||
if (printer_type == ElegooPrinterType::Other)
|
||||
return OctoPrint::upload_inner_with_host(std::move(upload_data), prorgess_fn, error_fn, info_fn);
|
||||
// Other may be an SDCP printer: fall back to SDCP, but report the OctoPrint error if that fails too.
|
||||
wxString octoprint_msg;
|
||||
if (printer_type == ElegooPrinterType::Other && OctoPrint::test(octoprint_msg))
|
||||
return upload_after_test_with_host(std::move(upload_data), prorgess_fn, error_fn, info_fn, octoprint_msg);
|
||||
|
||||
if (printer_type == ElegooPrinterType::CC2) {
|
||||
wxString cc2_msg;
|
||||
@@ -688,7 +688,7 @@ namespace Slic3r {
|
||||
|
||||
wxString legacy_msg;
|
||||
if(!elegoo_test(legacy_msg)){
|
||||
error_fn(std::move(legacy_msg));
|
||||
error_fn(std::move(printer_type == ElegooPrinterType::Other ? octoprint_msg : legacy_msg));
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,6 @@ protected:
|
||||
virtual bool upload_inner_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn) const override;
|
||||
|
||||
#ifdef WIN32
|
||||
virtual bool test_with_resolved_ip(wxString& curl_msg) const override;
|
||||
bool elegoo_test_with_resolved_ip(wxString& curl_msg) const;
|
||||
#endif
|
||||
private:
|
||||
|
||||
@@ -348,6 +348,11 @@ bool OctoPrint::upload_inner_with_resolved_ip(PrintHostUpload upload_data, Progr
|
||||
return false;
|
||||
}
|
||||
|
||||
return upload_after_test_with_resolved_ip(std::move(upload_data), prorgess_fn, error_fn, info_fn, resolved_addr);
|
||||
}
|
||||
|
||||
bool OctoPrint::upload_after_test_with_resolved_ip(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const boost::asio::ip::address& resolved_addr) const
|
||||
{
|
||||
const char* name = get_name();
|
||||
const auto upload_filename = upload_data.upload_path.filename();
|
||||
const auto upload_parent_path = upload_data.upload_path.parent_path();
|
||||
@@ -408,11 +413,6 @@ bool OctoPrint::upload_inner_with_resolved_ip(PrintHostUpload upload_data, Progr
|
||||
|
||||
bool OctoPrint::upload_inner_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn) const
|
||||
{
|
||||
const char* name = get_name();
|
||||
|
||||
const auto upload_filename = upload_data.upload_path.filename();
|
||||
const auto upload_parent_path = upload_data.upload_path.parent_path();
|
||||
|
||||
// If test fails, test_msg_or_host_ip contains the error message.
|
||||
// Otherwise on Windows it contains the resolved IP address of the host.
|
||||
wxString test_msg_or_host_ip;
|
||||
@@ -421,6 +421,16 @@ bool OctoPrint::upload_inner_with_host(PrintHostUpload upload_data, ProgressFn p
|
||||
return false;
|
||||
}
|
||||
|
||||
return upload_after_test_with_host(std::move(upload_data), prorgess_fn, error_fn, info_fn, test_msg_or_host_ip);
|
||||
}
|
||||
|
||||
bool OctoPrint::upload_after_test_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const wxString& test_msg_or_host_ip) const
|
||||
{
|
||||
const char* name = get_name();
|
||||
|
||||
const auto upload_filename = upload_data.upload_path.filename();
|
||||
const auto upload_parent_path = upload_data.upload_path.parent_path();
|
||||
|
||||
std::string url;
|
||||
bool res = true;
|
||||
|
||||
|
||||
@@ -39,9 +39,13 @@ public:
|
||||
protected:
|
||||
#ifdef WIN32
|
||||
virtual bool upload_inner_with_resolved_ip(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const boost::asio::ip::address& resolved_addr) const;
|
||||
// Upload half of upload_inner_with_resolved_ip(), for callers that already ran the test.
|
||||
bool upload_after_test_with_resolved_ip(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const boost::asio::ip::address& resolved_addr) const;
|
||||
#endif
|
||||
virtual bool validate_version_text(const boost::optional<std::string> &version_text) const;
|
||||
virtual bool upload_inner_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn) const;
|
||||
// Upload half of upload_inner_with_host(), for callers that already ran test().
|
||||
bool upload_after_test_with_host(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn, const wxString& test_msg_or_host_ip) const;
|
||||
|
||||
std::string m_host;
|
||||
std::string m_apikey;
|
||||
|
||||
@@ -177,7 +177,7 @@ static const std::unordered_set<std::string> operation_root_events{
|
||||
};
|
||||
|
||||
// True for the categories whose targets are filesystem paths, as opposed to a network
|
||||
// address or a process command line -- the deny-path and allowed-root checks only make sense
|
||||
// address or a process executable -- the deny-path and allowed-root checks only make sense
|
||||
// against a path.
|
||||
static bool is_fs_category(AuditEventCategory category)
|
||||
{
|
||||
@@ -641,13 +641,56 @@ bool same_path_component(const boost::filesystem::path& lhs, const boost::filesy
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// Windows spells some locations two ways: the plain form ("C:\dir", "\\server\share\dir") and the
|
||||
// documented extended-length form ("\\?\C:\dir", "\\?\UNC\server\share\dir"). A plugin's __file__
|
||||
// carries whichever spelling its sys.path entry used, and a path canonicalized past MAX_PATH is
|
||||
// necessarily extended, while allowed roots and grants are registered in the plain form. The
|
||||
// prefix adds a root-name component ("\\?\C:" sees "C:", "\\?\UNC" sees "\\server"), so a
|
||||
// component-wise comparison would never match. Rewrite the two documented aliases to the plain
|
||||
// spelling here; the result is only compared, never used for I/O. Every other device-namespace
|
||||
// path ("\\?\Volume{...}", "\\?\PIPE\...", "\\.\pipe\...", "\\.\PhysicalDrive0", "\??\C:\...")
|
||||
// names something this normalization cannot reinterpret, so it is left exactly as written and
|
||||
// keeps failing closed against a plain root.
|
||||
boost::filesystem::path plain_spelling(const boost::filesystem::path& path)
|
||||
{
|
||||
const std::wstring native = path.native();
|
||||
|
||||
// "\\?\UNC\server\share\..." -> "\\server\share\..." (the Win32 UNC alias).
|
||||
constexpr std::size_t unc_prefix_length = 8; // "\\?\UNC\"
|
||||
if (native.rfind(L"\\\\?\\UNC\\", 0) == 0)
|
||||
return boost::filesystem::path(L"\\\\" + native.substr(unc_prefix_length));
|
||||
|
||||
// "\\?\C:\..." -> "C:\..." for a drive-letter root only. "\\?\UNC\..." is handled above, and
|
||||
// anything else after the prefix is a different namespace, not a longer name for a drive path.
|
||||
constexpr std::size_t prefix_length = 4; // "\\?\"
|
||||
if (native.rfind(L"\\\\?\\", 0) == 0 && native.size() > prefix_length + 1) {
|
||||
const wchar_t drive = native[prefix_length];
|
||||
const bool letter = (drive >= L'A' && drive <= L'Z') || (drive >= L'a' && drive <= L'z');
|
||||
if (letter && native[prefix_length + 1] == L':')
|
||||
return boost::filesystem::path(native.substr(prefix_length));
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
#else
|
||||
boost::filesystem::path plain_spelling(const boost::filesystem::path& path)
|
||||
{
|
||||
return path;
|
||||
}
|
||||
#endif
|
||||
|
||||
// True when two canonical paths name the same location: every component must match, using the
|
||||
// platform's case rule. Unlike suffix_inside_root() this is full equality, so a lookalike that
|
||||
// merely shares a prefix -- or a file beside the granted one -- can never match.
|
||||
bool same_canonical_path(const boost::filesystem::path& lhs, const boost::filesystem::path& rhs)
|
||||
{
|
||||
auto lhs_it = lhs.begin(), lhs_end = lhs.end();
|
||||
auto rhs_it = rhs.begin(), rhs_end = rhs.end();
|
||||
// Compare in the plain spelling; see plain_spelling().
|
||||
const boost::filesystem::path plain_lhs = plain_spelling(lhs);
|
||||
const boost::filesystem::path plain_rhs = plain_spelling(rhs);
|
||||
|
||||
auto lhs_it = plain_lhs.begin(), lhs_end = plain_lhs.end();
|
||||
auto rhs_it = plain_rhs.begin(), rhs_end = plain_rhs.end();
|
||||
for (; lhs_it != lhs_end && rhs_it != rhs_end; ++lhs_it, ++rhs_it) {
|
||||
if (!same_path_component(*lhs_it, *rhs_it))
|
||||
return false;
|
||||
@@ -658,18 +701,24 @@ bool same_canonical_path(const boost::filesystem::path& lhs, const boost::filesy
|
||||
// Component-wise containment: the whole of canonical_root must be a prefix of
|
||||
// canonical_candidate, and the remaining components must not traverse upward. Both arguments are
|
||||
// expected to come from canonicalize_for_comparison()/canonical_folder(), i.e. expanded to long
|
||||
// names where the platform has 8.3 aliases. On a match, suffix receives the candidate's
|
||||
// components below the root (empty when the two paths are equal).
|
||||
// names where the platform has 8.3 aliases and possibly carrying the extended-length prefix. On a
|
||||
// match, suffix receives the candidate's components below the root (empty when the two paths are
|
||||
// equal).
|
||||
bool suffix_inside_root(const boost::filesystem::path& canonical_candidate,
|
||||
const boost::filesystem::path& canonical_root,
|
||||
boost::filesystem::path& suffix)
|
||||
{
|
||||
suffix.clear();
|
||||
|
||||
auto cand_it = canonical_candidate.begin();
|
||||
auto cand_end = canonical_candidate.end();
|
||||
auto root_it = canonical_root.begin();
|
||||
auto root_end = canonical_root.end();
|
||||
// Compare in the plain spelling; see plain_spelling(). The components below the root never
|
||||
// carry the prefix, so the suffix is unaffected.
|
||||
const boost::filesystem::path candidate = plain_spelling(canonical_candidate);
|
||||
const boost::filesystem::path root = plain_spelling(canonical_root);
|
||||
|
||||
auto cand_it = candidate.begin();
|
||||
auto cand_end = candidate.end();
|
||||
auto root_it = root.begin();
|
||||
auto root_end = root.end();
|
||||
|
||||
// Consume matching components
|
||||
while (root_it != root_end && cand_it != cand_end && same_path_component(*root_it, *cand_it)) {
|
||||
@@ -697,9 +746,9 @@ bool suffix_inside_root(const boost::filesystem::path& canonical_candidate,
|
||||
bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root)
|
||||
{
|
||||
// Both sides are canonicalized identically, including the expansion of Windows 8.3 short
|
||||
// names, so a root registered under one spelling still contains a target reported under the
|
||||
// other. A side that cannot be normalized fails closed: comparing differently spelled paths
|
||||
// could otherwise report containment that does not hold.
|
||||
// names and the extended-length prefix, so a root registered under one spelling still contains
|
||||
// a target reported under the other. A side that cannot be normalized fails closed: comparing
|
||||
// differently spelled paths could otherwise report containment that does not hold.
|
||||
boost::filesystem::path canonical_candidate;
|
||||
if (!canonicalize_for_comparison(candidate, canonical_candidate))
|
||||
return false;
|
||||
@@ -1635,31 +1684,137 @@ static std::vector<std::string> create_permission_targets(const std::string& eve
|
||||
return targets;
|
||||
}
|
||||
|
||||
static const std::unordered_map<std::string, std::vector<Py_ssize_t>> audit_target_arg_indices{
|
||||
{"http.client.connect", {1}},
|
||||
{"urllib.Request", {0}},
|
||||
// Network events name their target directly: a host, an address tuple or a URL.
|
||||
static const std::unordered_map<std::string, Py_ssize_t> network_target_arg_indices{
|
||||
{"http.client.connect", 1},
|
||||
{"urllib.Request", 0},
|
||||
|
||||
{"socket.connect", {1}},
|
||||
{"socket.bind", {1}},
|
||||
{"socket.getaddrinfo", {0}},
|
||||
{"socket.gethostbyname", {0}},
|
||||
{"socket.gethostbyaddr", {0}},
|
||||
{"socket.getnameinfo", {0}},
|
||||
{"socket.getservbyname", {0}},
|
||||
{"socket.getservbyport", {0}},
|
||||
{"socket.sendto", {1}},
|
||||
{"socket.sendmsg", {1}},
|
||||
{"socket.connect", 1},
|
||||
{"socket.bind", 1},
|
||||
{"socket.getaddrinfo", 0},
|
||||
{"socket.gethostbyname", 0},
|
||||
{"socket.gethostbyaddr", 0},
|
||||
{"socket.getnameinfo", 0},
|
||||
{"socket.getservbyname", 0},
|
||||
{"socket.getservbyport", 0},
|
||||
{"socket.sendto", 1},
|
||||
{"socket.sendmsg", 1},
|
||||
};
|
||||
|
||||
{"os.system", {0}},
|
||||
{"subprocess.Popen", {1, 0}},
|
||||
{"os.posix_spawn", {1, 0}},
|
||||
{"os.spawn", {2, 1}},
|
||||
{"os.startfile", {0}},
|
||||
{"os.startfile/2", {0}},
|
||||
{"pty.spawn", {0}},
|
||||
{"_winapi.CreateProcess", {1, 0}},
|
||||
{"_posixsubprocess.fork_exec", {0}},
|
||||
{"os.exec", {0}},
|
||||
// Process events each expose the executable in a different argument, and some pass the whole
|
||||
// command line or argv. A grant normally names the tool only, so the arguments are dropped; the
|
||||
// exception is a Windows command line whose executable is unquoted and followed by arguments
|
||||
// (see windows_command_line_target).
|
||||
enum class ProcessTargetFormat {
|
||||
Path, // the argument is the executable path or name
|
||||
FirstToken, // a command string or argv sequence: its first token or element
|
||||
WindowsCommandLine, // a Windows command line: its first argument, possibly a quoted path
|
||||
};
|
||||
|
||||
struct ProcessTargetSource {
|
||||
Py_ssize_t index;
|
||||
ProcessTargetFormat format;
|
||||
};
|
||||
|
||||
// An exact-command entry shares the process list with executable entries. This reserved prefix
|
||||
// keeps the two namespaces apart: an exact command line can never be mistaken for an executable
|
||||
// name, and an existing executable grant (which does not carry the prefix) keeps its
|
||||
// argument-insensitive meaning. It is stored in the sidecar and listed by the Plugins dialog; the
|
||||
// permission prompt shows the command line without it.
|
||||
static const std::string kWindowsCommandLineGrantPrefix = "CommandLine:";
|
||||
|
||||
static bool is_exact_command_grant(const std::string& target)
|
||||
{
|
||||
return boost::algorithm::starts_with(target, kWindowsCommandLineGrantPrefix);
|
||||
}
|
||||
|
||||
static std::string exact_command_grant(const std::string& command_line)
|
||||
{
|
||||
return kWindowsCommandLineGrantPrefix + command_line;
|
||||
}
|
||||
|
||||
// The prompt shows the command line the user is asked about, not the storage marker.
|
||||
static std::string process_target_for_display(const std::string& target)
|
||||
{
|
||||
return is_exact_command_grant(target) ? target.substr(kWindowsCommandLineGrantPrefix.size()) : target;
|
||||
}
|
||||
|
||||
// A process prompt can list executable grants and exact command lines together (a declaration may
|
||||
// do so; a runtime event has one target). The wording must not claim argument-insensitive scope
|
||||
// for an exact command line.
|
||||
struct ProcessPromptScope {
|
||||
bool exact_command = false;
|
||||
bool executable = false;
|
||||
};
|
||||
|
||||
static ProcessPromptScope process_prompt_scope(const std::vector<std::string>& targets)
|
||||
{
|
||||
ProcessPromptScope scope;
|
||||
for (const std::string& target : targets) {
|
||||
if (is_exact_command_grant(target))
|
||||
scope.exact_command = true;
|
||||
else
|
||||
scope.executable = true;
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
|
||||
// os.system does not run a program named by its first token: it hands the whole string to the
|
||||
// platform shell. POSIX passes it to /bin/sh. The Windows C runtime runs the command interpreter
|
||||
// named by COMSPEC, or cmd.exe when COMSPEC is unset or empty, and also falls back to cmd.exe
|
||||
// when it cannot open the configured file (ENOENT or EACCES). Either interpreter may therefore
|
||||
// run the command, so every one of them is a required target: a narrow grant for a harmless
|
||||
// COMSPEC target must not admit the fallback shell. Approving the shells covers every command
|
||||
// string the plugin passes to os.system, because a shell parses and executes all of the string,
|
||||
// arguments included.
|
||||
//
|
||||
// The runtime chooses the interpreter when it runs the command, so the audit names the possible
|
||||
// interpreters instead of checking whether the COMSPEC file exists: a file that is present while
|
||||
// the prompt is answered can be removed before the call. A COMSPEC that already is the bare name
|
||||
// cmd.exe, in any casing, names the fallback itself and is listed once.
|
||||
#ifdef _WIN32
|
||||
static std::vector<std::string> system_shell_targets()
|
||||
{
|
||||
constexpr const char* kFallbackShell = "cmd.exe";
|
||||
|
||||
// _wsystem reads COMSPEC through the CRT environment, which is the copy it consults; the
|
||||
// process environment block can differ. Read the same value and copy it at once, because a
|
||||
// concurrent _wputenv may replace the buffer the pointer names.
|
||||
const wchar_t* const comspec_value = ::_wgetenv(L"COMSPEC");
|
||||
// An unset or empty COMSPEC leaves only the runtime's default interpreter.
|
||||
if (comspec_value == nullptr || *comspec_value == L'\0')
|
||||
return {kFallbackShell};
|
||||
|
||||
std::string comspec = wxString(comspec_value).utf8_string();
|
||||
// A bare cmd.exe is the fallback interpreter itself, whatever the casing, so one target stays.
|
||||
if (comspec.find_first_of("/\\") == std::string::npos &&
|
||||
wxString::FromUTF8(comspec).CmpNoCase(wxString::FromUTF8(kFallbackShell)) == 0)
|
||||
return {kFallbackShell};
|
||||
|
||||
return {std::move(comspec), kFallbackShell};
|
||||
}
|
||||
#else
|
||||
static std::vector<std::string> system_shell_targets()
|
||||
{
|
||||
return {"/bin/sh"};
|
||||
}
|
||||
#endif
|
||||
|
||||
static const std::unordered_map<std::string, std::vector<ProcessTargetSource>> process_target_sources{
|
||||
{"os.exec", {{0, ProcessTargetFormat::Path}}},
|
||||
{"os.posix_spawn", {{0, ProcessTargetFormat::Path}}},
|
||||
{"os.spawn", {{1, ProcessTargetFormat::Path}}},
|
||||
{"os.startfile", {{0, ProcessTargetFormat::Path}}},
|
||||
{"os.startfile/2", {{0, ProcessTargetFormat::Path}}},
|
||||
// executable is unresolved when the caller did not pass one, as on Windows, where args is
|
||||
// then a single command line; on POSIX args is an argv sequence and executable is always set.
|
||||
{"subprocess.Popen", {{0, ProcessTargetFormat::Path}, {1, ProcessTargetFormat::WindowsCommandLine}}},
|
||||
// application_name wins when it is given, so its source comes first; when it is omitted
|
||||
// command_line is a Windows command line whose first argument names the executable.
|
||||
{"_winapi.CreateProcess", {{0, ProcessTargetFormat::Path}, {1, ProcessTargetFormat::WindowsCommandLine}}},
|
||||
{"pty.spawn", {{0, ProcessTargetFormat::FirstToken}}},
|
||||
// The first argument is argv; its first element names the program.
|
||||
{"_posixsubprocess.fork_exec", {{0, ProcessTargetFormat::FirstToken}}},
|
||||
};
|
||||
|
||||
AuditEventCategory open_category(PyObject* args)
|
||||
@@ -1670,6 +1825,115 @@ AuditEventCategory open_category(PyObject* args)
|
||||
return AuditEventCategory::FsReadWrite;
|
||||
}
|
||||
|
||||
// The first token of a command string, or the first element of an argv sequence. A sequence
|
||||
// element is kept whole, so an executable path may contain spaces.
|
||||
std::string first_process_token(PyObject* object)
|
||||
{
|
||||
if (!object)
|
||||
return {};
|
||||
|
||||
std::string text;
|
||||
if (python_text(object, text)) {
|
||||
const size_t start = text.find_first_not_of(" \t\r\n");
|
||||
if (start == std::string::npos)
|
||||
return {};
|
||||
const size_t end = text.find_first_of(" \t\r\n", start);
|
||||
return text.substr(start, end == std::string::npos ? std::string::npos : end - start);
|
||||
}
|
||||
|
||||
if (!PySequence_Check(object))
|
||||
return python_path(object);
|
||||
|
||||
PyObject* first = PySequence_GetItem(object, 0); // new reference
|
||||
if (!first) {
|
||||
PyErr_Clear();
|
||||
return {};
|
||||
}
|
||||
std::string value = python_path(first);
|
||||
Py_DECREF(first);
|
||||
return value;
|
||||
}
|
||||
|
||||
// The grant target for a Windows command line. Windows does not split it like a POSIX shell: a
|
||||
// path that contains spaces is enclosed in double quotes, and backslashes before a quote follow
|
||||
// the CommandLineToArgvW rules (2n backslashes and a quote give n backslashes and end the
|
||||
// argument, 2n+1 give n backslashes and a literal quote).
|
||||
//
|
||||
// A quoted first argument names the executable unambiguously and is returned alone, as is a
|
||||
// command line that is only the executable: both keep the argument-insensitive executable grant.
|
||||
// An unquoted first argument followed by more text is different. CreateProcess resolves it by
|
||||
// trying successively longer prefixes of the name, so the first whitespace-delimited token need
|
||||
// not be the executable it starts (the command line "C:\Program Files\app.exe --x" can start
|
||||
// "C:\Program Files\app.exe", not "C:\Program"). Such a command line is returned as one exact
|
||||
// grant instead, because granting the first token would describe a different program and would
|
||||
// cover every later command line with that token.
|
||||
std::string windows_command_line_target(const std::string& command_line)
|
||||
{
|
||||
size_t index = command_line.find_first_not_of(" \t");
|
||||
if (index == std::string::npos)
|
||||
return {};
|
||||
|
||||
if (command_line[index] != '"') {
|
||||
const size_t end = command_line.find_first_of(" \t", index);
|
||||
const size_t token_end = end == std::string::npos ? command_line.size() : end;
|
||||
if (command_line.find_first_not_of(" \t", token_end) != std::string::npos)
|
||||
return exact_command_grant(command_line.substr(index));
|
||||
return command_line.substr(index, token_end - index);
|
||||
}
|
||||
|
||||
std::string token;
|
||||
++index; // the opening quote is not part of the argument
|
||||
while (index < command_line.size()) {
|
||||
if (command_line[index] == '\\') {
|
||||
size_t backslashes = 0;
|
||||
while (index < command_line.size() && command_line[index] == '\\') {
|
||||
++backslashes;
|
||||
++index;
|
||||
}
|
||||
if (index < command_line.size() && command_line[index] == '"') {
|
||||
token.append(backslashes / 2, '\\');
|
||||
if (backslashes % 2) {
|
||||
token.push_back('"');
|
||||
++index;
|
||||
} else {
|
||||
++index; // the closing quote
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
token.append(backslashes, '\\');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (command_line[index] == '"') {
|
||||
++index; // the closing quote
|
||||
break;
|
||||
}
|
||||
token.push_back(command_line[index]);
|
||||
++index;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
std::string process_target(const ProcessTargetSource& source, PyObject* args)
|
||||
{
|
||||
PyObject* const item = tuple_item(args, source.index);
|
||||
if (!item || item == Py_None)
|
||||
return {};
|
||||
switch (source.format) {
|
||||
case ProcessTargetFormat::Path:
|
||||
return python_path(item);
|
||||
case ProcessTargetFormat::FirstToken:
|
||||
return first_process_token(item);
|
||||
case ProcessTargetFormat::WindowsCommandLine: {
|
||||
std::string command_line;
|
||||
if (python_text(item, command_line))
|
||||
return windows_command_line_target(command_line);
|
||||
return first_process_token(item);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<std::string> audit_targets(const std::string& event_name, AuditEventCategory category, PyObject* args)
|
||||
{
|
||||
std::vector<std::string> targets;
|
||||
@@ -1687,6 +1951,24 @@ std::vector<std::string> audit_targets(const std::string& event_name, AuditEvent
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
case AuditEventCategory::ProcessCreate:
|
||||
case AuditEventCategory::ProcessReplace: {
|
||||
// The shells a command string may run in, not the command itself. Every possible
|
||||
// interpreter has to be granted before the event is allowed.
|
||||
if (event_name == "os.system")
|
||||
return system_shell_targets();
|
||||
const auto it = process_target_sources.find(event_name);
|
||||
if (it == process_target_sources.end())
|
||||
return targets;
|
||||
for (const ProcessTargetSource& source : it->second) {
|
||||
std::string value = process_target(source, args);
|
||||
if (!value.empty()) {
|
||||
targets.push_back(std::move(value));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
case AuditEventCategory::Threading:
|
||||
// Thread creation exposes no user-supplied target. Use a fixed sentinel so the grant
|
||||
// persists per plugin: the permission list matches targets by exact string, and the
|
||||
@@ -1697,18 +1979,14 @@ std::vector<std::string> audit_targets(const std::string& event_name, AuditEvent
|
||||
break;
|
||||
}
|
||||
|
||||
const auto it = audit_target_arg_indices.find(event_name);
|
||||
if (it != audit_target_arg_indices.end()) {
|
||||
for (const Py_ssize_t index : it->second) {
|
||||
// None is an argument left out (sendmsg without an address), not a target named "None".
|
||||
PyObject* const item = tuple_item(args, index);
|
||||
if (item == Py_None)
|
||||
continue;
|
||||
const auto it = network_target_arg_indices.find(event_name);
|
||||
if (it != network_target_arg_indices.end()) {
|
||||
// None is an argument left out (sendmsg without an address), not a target named "None".
|
||||
PyObject* const item = tuple_item(args, it->second);
|
||||
if (item != Py_None) {
|
||||
std::string value = python_str(item);
|
||||
if (!value.empty()) {
|
||||
if (!value.empty())
|
||||
targets.push_back(std::move(value));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2369,7 +2647,8 @@ int report_denied(PluginAuditManager& mgr,
|
||||
|
||||
wxString audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name,
|
||||
const wxString& target_list, size_t target_count, bool full_fs_scope = false,
|
||||
bool tree_scope = false, bool root_tree_scope = false)
|
||||
bool tree_scope = false, bool root_tree_scope = false, bool exact_process_command = false,
|
||||
bool executable_process_target = false)
|
||||
{
|
||||
// Create and delete grants name folders, and a declaration may ask for the whole filesystem
|
||||
// with a sole "*". Describe that scope instead of printing the marker as a folder.
|
||||
@@ -2509,13 +2788,43 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name,
|
||||
"Approval covers raw network connections to the listed hosts. It does not restrict ports."),
|
||||
plugin_name, target_list);
|
||||
case AuditEventCategory::ProcessCreate:
|
||||
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s",
|
||||
"Plugin \"%s\" is requesting to run the following commands:\n%s", target_count),
|
||||
// An exact command line is saved with its arguments rather than as a tool name, so the
|
||||
// prompt must not promise that approval covers any arguments. The full line is stored,
|
||||
// which can include credentials or tokens in its arguments.
|
||||
if (exact_process_command && !executable_process_target)
|
||||
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following exact command line:\n%s\n\n"
|
||||
"Approval is saved for this exact command line, including its arguments, and covers "
|
||||
"only it. A different command line, including different arguments, asks again. The "
|
||||
"full command line is shown and saved, so it may contain sensitive values.",
|
||||
"Plugin \"%s\" is requesting to run the following exact command lines:\n%s\n\n"
|
||||
"Approval is saved for each exact command line, including its arguments, and covers "
|
||||
"only that line. A different command line, including different arguments, asks again. "
|
||||
"The full command lines are shown and saved, so they may contain sensitive values.",
|
||||
target_count),
|
||||
plugin_name, target_list);
|
||||
if (exact_process_command)
|
||||
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following commands:\n%s\n\n"
|
||||
"Approval covers the listed executables with any arguments. A listed exact command "
|
||||
"line is saved with its arguments and covers only that command line. Exact command "
|
||||
"lines are shown and saved in full, so they may contain sensitive values. Approving a "
|
||||
"shell allows it to run any command.",
|
||||
"Plugin \"%s\" is requesting to run the following commands:\n%s\n\n"
|
||||
"Approval covers the listed executables with any arguments. Each listed exact command "
|
||||
"line is saved with its arguments and covers only that command line. Exact command "
|
||||
"lines are shown and saved in full, so they may contain sensitive values. Approving a "
|
||||
"shell allows it to run any command.",
|
||||
target_count),
|
||||
plugin_name, target_list);
|
||||
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s\n\n"
|
||||
"Approval covers any arguments. Approving a shell allows it to run any command.",
|
||||
"Plugin \"%s\" is requesting to run the following commands:\n%s\n\n"
|
||||
"Approval covers any arguments. Approving a shell allows it to run any command.", target_count),
|
||||
plugin_name, target_list);
|
||||
case AuditEventCategory::Threading:
|
||||
return wxString::Format(_L("Plugin \"%s\" is requesting permission to create a thread."), plugin_name);
|
||||
case AuditEventCategory::ProcessReplace:
|
||||
return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s"), plugin_name, target_list);
|
||||
return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s\n\n"
|
||||
"Approval covers any arguments. Approving a shell allows it to run any command."), plugin_name, target_list);
|
||||
default:
|
||||
return wxString::Format(_L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\"."), plugin_name, event_name);
|
||||
}
|
||||
@@ -2525,17 +2834,19 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name,
|
||||
PermissionMessage formatted_audit_message(AuditEventCategory category, const wxString& plugin_name,
|
||||
const wxString& event_name, const wxString& targets, size_t count,
|
||||
bool full_fs_scope = false, bool tree_scope = false,
|
||||
bool root_tree_scope = false)
|
||||
bool root_tree_scope = false, bool exact_process_command = false,
|
||||
bool executable_process_target = false)
|
||||
{
|
||||
if (targets.empty())
|
||||
return {audit_message(category, plugin_name, event_name, targets, count, full_fs_scope, tree_scope,
|
||||
root_tree_scope), {}};
|
||||
root_tree_scope, exact_process_command, executable_process_target), {}};
|
||||
|
||||
wxString marker = "__ORCA_PERMISSION_TARGETS__";
|
||||
while (plugin_name.Contains(marker) || event_name.Contains(marker) || targets.Contains(marker))
|
||||
marker += "_";
|
||||
PermissionMessage message{
|
||||
audit_message(category, plugin_name, event_name, marker, count, full_fs_scope, tree_scope, root_tree_scope), {}};
|
||||
audit_message(category, plugin_name, event_name, marker, count, full_fs_scope, tree_scope, root_tree_scope,
|
||||
exact_process_command, executable_process_target), {}};
|
||||
const size_t pos = message.text.find(marker);
|
||||
if (pos != wxString::npos) {
|
||||
message.text.replace(pos, marker.length(), targets);
|
||||
@@ -2620,9 +2931,16 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n
|
||||
return show_permission_dialog(message, _L("Plugin permission request"));
|
||||
}
|
||||
|
||||
const bool process_category =
|
||||
category == AuditEventCategory::ProcessCreate || category == AuditEventCategory::ProcessReplace;
|
||||
const ProcessPromptScope process_scope =
|
||||
process_category ? process_prompt_scope(unresolved) : ProcessPromptScope{};
|
||||
|
||||
wxString target_list;
|
||||
for (const auto& target : unresolved)
|
||||
target_list += wxString::FromUTF8(target.c_str()) + "\n";
|
||||
for (const auto& target : unresolved) {
|
||||
const std::string shown = process_category ? process_target_for_display(target) : target;
|
||||
target_list += wxString::FromUTF8(shown.c_str()) + "\n";
|
||||
}
|
||||
|
||||
const bool tree_scope = std::any_of(unresolved.begin(), unresolved.end(), [](const std::string& target) {
|
||||
boost::filesystem::path root;
|
||||
@@ -2632,7 +2950,8 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n
|
||||
PermissionMessage message = formatted_audit_message(category, wxString::FromUTF8(plugin_name.c_str()),
|
||||
wxString::FromUTF8(event_name.c_str()), target_list,
|
||||
unresolved.size(), /*full_fs_scope=*/false, tree_scope,
|
||||
/*root_tree_scope=*/false);
|
||||
/*root_tree_scope=*/false, process_scope.exact_command,
|
||||
process_scope.executable);
|
||||
return show_permission_dialog(message, _L("Plugin permission request"));
|
||||
}
|
||||
|
||||
@@ -2664,16 +2983,24 @@ PermissionMessage build_permission_message(const std::string& plugin_name, const
|
||||
return tree_grant_root(target, root) && is_filesystem_root(root);
|
||||
});
|
||||
|
||||
const bool process_category =
|
||||
bucket.category == AuditEventCategory::ProcessCreate || bucket.category == AuditEventCategory::ProcessReplace;
|
||||
const ProcessPromptScope process_scope =
|
||||
process_category ? process_prompt_scope(bucket.targets) : ProcessPromptScope{};
|
||||
|
||||
wxString targets;
|
||||
if (!full_fs_scope)
|
||||
for (const std::string& target : bucket.targets)
|
||||
targets += wxString::FromUTF8(target.c_str()) + "\n";
|
||||
for (const std::string& target : bucket.targets) {
|
||||
const std::string shown = process_category ? process_target_for_display(target) : target;
|
||||
targets += wxString::FromUTF8(shown.c_str()) + "\n";
|
||||
}
|
||||
|
||||
if (!message.text.IsEmpty())
|
||||
message.text += "\n\n";
|
||||
PermissionMessage part = formatted_audit_message(bucket.category, wxString::FromUTF8(plugin_name.c_str()),
|
||||
wxEmptyString, targets, bucket.targets.size(),
|
||||
full_fs_scope, tree_scope, root_tree_scope);
|
||||
full_fs_scope, tree_scope, root_tree_scope,
|
||||
process_scope.exact_command, process_scope.executable);
|
||||
for (const auto& range : part.targets)
|
||||
message.targets.emplace_back(message.text.length() + range.first, range.second);
|
||||
message.text += part.text;
|
||||
|
||||
+1166
-132
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,8 @@
|
||||
|
||||
#include <boost/filesystem/path.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -39,6 +41,8 @@ struct PluginPermissions
|
||||
std::vector<std::string> fs_delete;
|
||||
std::vector<std::string> network_http;
|
||||
std::vector<std::string> network_socket;
|
||||
// Executables or command names. Arguments are ignored, so one entry covers every call of
|
||||
// the tool.
|
||||
std::vector<std::string> process;
|
||||
// Thread creation is a yes/no grant. Newer sidecars store a boolean; older ones stored an
|
||||
// array (empty when denied, nonempty when granted), and nonempty strings are accepted by the
|
||||
@@ -126,6 +130,21 @@ bool read_python_plugin_metadata(const boost::filesystem::path& py_path, PluginD
|
||||
// Returns true on success.
|
||||
bool read_wheel_plugin_metadata(const boost::filesystem::path& whl_path, PluginDescriptor& descriptor, std::string& error);
|
||||
|
||||
// The subset of wheel metadata uv needs to accept a staged copy under a valid filename: the
|
||||
// distribution name and version from METADATA and the declared WHEEL Tag lines.
|
||||
struct WheelInstallMetadata
|
||||
{
|
||||
std::string name;
|
||||
std::string version;
|
||||
std::vector<std::string> tags;
|
||||
};
|
||||
bool read_wheel_install_metadata(const boost::filesystem::path& whl_path, WheelInstallMetadata& out, std::string& error);
|
||||
|
||||
// True when the path carries the wheel package extension, compared case-insensitively: a package
|
||||
// stored on a case-insensitive filesystem can end in ".WHL". Only uv requires the lower-case
|
||||
// spelling for the file it is handed, so the staged copy is normalized instead of rejecting it.
|
||||
bool has_wheel_extension(const boost::filesystem::path& path);
|
||||
|
||||
// Find the single plugin entry file (.py or .whl) in a directory.
|
||||
// Ignores __whl_extracted__ and hidden files/dirs.
|
||||
// Returns the path to the entry file, or an empty path with error set if zero or multiple candidates.
|
||||
@@ -200,3 +219,79 @@ bool read_install_state(const boost::filesystem::path& plugin_dir, PluginDescrip
|
||||
bool read_install_state(const boost::filesystem::path& plugin_dir, PluginInstallState& out);
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
// uv-based installation of a wheel plugin's entry wheel.
|
||||
namespace Slic3r::plugin_wheel_install {
|
||||
|
||||
// Shared wheel extraction root inside the plugin root. Dependency wheels are extracted into it,
|
||||
// and the entry wheel is installed into <extraction root>/<entry package>. This is the same path
|
||||
// the pre-uv loader extracted the entry wheel to, so there is one cache location. The "__" prefix
|
||||
// keeps discovery from treating it as a plugin package (see is_ignored_plugin_directory()).
|
||||
inline constexpr const char* EXTRACTED_DIR_NAME = "__whl_extracted__";
|
||||
|
||||
// Staging and retirement directories, also inside the plugin root and ignored by discovery.
|
||||
inline constexpr const char* STAGING_DIR_PREFIX = "__wheel_staging__-";
|
||||
inline constexpr const char* PREVIOUS_DIR_PREFIX = "__wheel_prev__-";
|
||||
|
||||
// Marker written into the target before it is promoted. Bump INSTALL_FORMAT when the layout or
|
||||
// the uv invocation changes, so an existing target is rebuilt instead of reused.
|
||||
inline constexpr const char* MARKER_FILE_NAME = "__wheel_install__.json";
|
||||
inline constexpr int INSTALL_FORMAT = 2;
|
||||
|
||||
inline constexpr std::chrono::seconds INSTALL_TIMEOUT{120};
|
||||
|
||||
// Runs `uv <args>` and reports success. Injectable so tests can exercise staging, promotion and
|
||||
// reuse without a real uv binary.
|
||||
using UvRunner = std::function<bool(const std::vector<std::string>& args, std::chrono::seconds timeout, std::string& error)>;
|
||||
|
||||
// True for a filename shaped like a PEP 427 wheel: name-version(-build)?-python-abi-platform.whl,
|
||||
// where the three trailing components look like real interpreter/ABI/platform tags. uv performs
|
||||
// the full metadata and compatibility validation; this only decides whether the stored name can be
|
||||
// handed to uv as-is or a metadata-derived copy has to be staged.
|
||||
bool is_valid_wheel_filename(const std::string& filename);
|
||||
|
||||
// Build a PEP 427 wheel filename from metadata. Returns an empty string when any component is
|
||||
// empty or cannot be escaped into the allowed character set.
|
||||
std::string make_wheel_filename(const std::string& name, const std::string& version, const std::string& tag);
|
||||
|
||||
// Return a python-abi-platform tag for a staged wheel filename from the tags the wheel declares.
|
||||
// A declared tag compatible with the bundled interpreter is preferred (so a wheel declaring both
|
||||
// py2 and py3 uses py3); this never invents a tag. Among the chosen tags, simple platform
|
||||
// alternatives are combined into one PEP 425 compressed tag set. uv performs the final
|
||||
// platform/architecture compatibility check. Empty when no well-formed tag exists.
|
||||
std::string wheel_filename_tag(const std::vector<std::string>& tags);
|
||||
|
||||
// True for a safe dotted package path: non-empty components separated by '.', with no ASCII path
|
||||
// separators, control characters, or characters Windows forbids in filenames. Bytes >= 0x80 are
|
||||
// allowed, so non-ASCII (Unicode) import names are not rejected. This is path-component safety,
|
||||
// not a Python identifier check; an unimportable name is reported when the module is imported.
|
||||
bool is_valid_entry_package(const std::string& entry_package);
|
||||
|
||||
// Path of the installed target: <plugin_root>/__whl_extracted__/<entry package>. Does not touch
|
||||
// the disk. Empty when entry_package is not a safe import name.
|
||||
std::string install_dir(const std::string& plugin_root, const std::string& entry_package);
|
||||
|
||||
// True when the target exists and the marker proves it was installed from the current entry wheel
|
||||
// for this interpreter and entry package.
|
||||
bool is_installed(const PluginDescriptor& descriptor);
|
||||
|
||||
// Delete the plugin's installed-wheel cache (the whole __whl_extracted__ subtree). The plugin root
|
||||
// must already have passed resolve_allowed_plugin_root(): this only removes the cache directory,
|
||||
// never the plugin root, the stored wheel or the install sidecar. Removal uses the extended-length
|
||||
// form, so a cache whose own root passes MAX_PATH is still cleared on Windows. On failure `error`
|
||||
// explains the cause.
|
||||
bool delete_install_cache(const boost::filesystem::path& plugin_root, std::string& error);
|
||||
|
||||
// Install the plugin's entry wheel with uv into the legacy extraction path
|
||||
// <plugin_root>/__whl_extracted__/<entry package> unless a matching installation already exists.
|
||||
// An existing markerless directory there is a pre-uv extraction: when it already contains the entry
|
||||
// package it is used directly, without running uv. A markerless target without the entry package,
|
||||
// and a target whose marker is stale or invalid, is replaced. Directories for dependency wheels
|
||||
// elsewhere under __whl_extracted__/ are never touched; a dependency whose filename stem equals the
|
||||
// entry package is reported as a collision instead of being replaced. The wheel is installed to a
|
||||
// fresh staging target and promoted only after a successful, complete installation; the previous
|
||||
// target is restored on failure. On failure `error` explains the cause and no partial target is
|
||||
// importable.
|
||||
bool ensure_installed(const PluginDescriptor& descriptor, std::string& error, const UvRunner& runner = {});
|
||||
|
||||
} // namespace Slic3r::plugin_wheel_install
|
||||
@@ -23,15 +23,14 @@
|
||||
#include <boost/filesystem/directory.hpp>
|
||||
#include <boost/filesystem/file_status.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <slic3r/Utils/BoostProcessCompat.hpp>
|
||||
#include "slic3r/plugin/PluginDescriptor.hpp"
|
||||
#include <optional>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include "slic3r/plugin/PythonPluginInterface.hpp"
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <system_error>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -148,6 +147,15 @@ void teardown_capabilities(std::vector<std::shared_ptr<PluginCapabilityInterface
|
||||
capabilities.clear();
|
||||
}
|
||||
|
||||
// True when the path is reachable through its plain spelling. A path past the legacy Windows
|
||||
// MAX_PATH fails the probe with an error rather than reporting nothing there, so this is the
|
||||
// non-throwing form callers need before deciding to retry with the extended-length one.
|
||||
bool plain_path_exists(const boost::filesystem::path& path)
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
return boost::filesystem::exists(path, ec) && !ec;
|
||||
}
|
||||
|
||||
// Add every .whl sitting next to the plugin entry file to sys.path, extracting it first.
|
||||
bool add_wheel_dependencies_to_sys_path(const PluginDescriptor& descriptor,
|
||||
std::vector<std::string>& plugin_paths,
|
||||
@@ -155,35 +163,57 @@ bool add_wheel_dependencies_to_sys_path(const PluginDescriptor& descriptor,
|
||||
{
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
const fs::path entry_path(descriptor.entry_path);
|
||||
const fs::path plugin_dir = entry_path.has_extension() ? entry_path.parent_path() : entry_path;
|
||||
if (!fs::exists(plugin_dir) || !fs::is_directory(plugin_dir))
|
||||
// The plugin folder, and every cache directory below it, can pass the legacy Windows
|
||||
// MAX_PATH, where the plain spelling cannot be probed at all. Each probe below therefore
|
||||
// falls back to the extended-length form (the identity off Windows), and only keeps it where
|
||||
// the plain spelling failed: those paths are what a plugin then sees as __file__ and sys.path
|
||||
// and what the host compares against the plain plugin root, so an install that resolves
|
||||
// plainly keeps the plain path it had before.
|
||||
const fs::path plain_entry_path(descriptor.entry_path);
|
||||
const fs::path plain_plugin_dir = plain_entry_path.has_extension() ? plain_entry_path.parent_path() : plain_entry_path;
|
||||
|
||||
// Walk the folder through whichever spelling reaches it; an install that fits uses the plain
|
||||
// one, as before.
|
||||
const bool plain_reachable = plain_path_exists(plain_plugin_dir);
|
||||
const fs::path entry_path = plain_reachable ? plain_entry_path : extended_path(plain_entry_path);
|
||||
const fs::path scan_dir = plain_reachable ? plain_plugin_dir : extended_path(plain_plugin_dir);
|
||||
|
||||
boost::system::error_code scan_ec;
|
||||
if (!fs::is_directory(scan_dir, scan_ec) || scan_ec)
|
||||
return true;
|
||||
|
||||
PythonInterpreter& interpreter = PythonInterpreter::instance();
|
||||
for (fs::directory_iterator it(plugin_dir); it != fs::directory_iterator(); ++it) {
|
||||
if (!fs::is_regular_file(it->status()) || it->path().extension() != ".whl")
|
||||
for (fs::directory_iterator it(scan_dir); it != fs::directory_iterator(); ++it) {
|
||||
if (!fs::is_regular_file(it->status()) || !has_wheel_extension(it->path()))
|
||||
continue;
|
||||
// Skip the entry file itself — it is loaded by its own path.
|
||||
// Skip the entry file itself — it is loaded by its own path. Both sides carry the same
|
||||
// spelling, so the comparison holds in the extended form too.
|
||||
if (it->path() == entry_path)
|
||||
continue;
|
||||
|
||||
const fs::path dep_dir = plugin_dir / "__whl_extracted__" / it->path().stem().string();
|
||||
if (!fs::exists(dep_dir)) {
|
||||
// Build from the plain folder so the recorded spelling stays plain whenever it can.
|
||||
const fs::path plain_dep_dir = plain_plugin_dir / plugin_wheel_install::EXTRACTED_DIR_NAME / it->path().stem().string();
|
||||
const fs::path io_dep_dir = extended_path(plain_dep_dir);
|
||||
if (!plain_path_exists(plain_dep_dir) && !plain_path_exists(io_dep_dir)) {
|
||||
std::string extract_error;
|
||||
if (!extract_zip_to_directory(it->path(), dep_dir, extract_error)) {
|
||||
if (!extract_zip_to_directory(it->path(), plain_dep_dir, extract_error)) {
|
||||
// TRN %1% is the dependency file, %2% the error detail.
|
||||
error = GUI::format(_u8L("Failed to extract plugin .whl dependency %1%: %2%"), it->path().string(), extract_error);
|
||||
error = GUI::format(_u8L("Failed to extract plugin .whl dependency %1%: %2%"),
|
||||
(plain_plugin_dir / it->path().filename()).string(), extract_error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string syspath_error;
|
||||
if (!interpreter.add_plugin_sys_path(dep_dir.string(), syspath_error)) {
|
||||
// The string handed to the interpreter is the one recorded for unload, so the sys.path
|
||||
// entry is removed by the same key. Re-probe after extraction: a first extraction through
|
||||
// a path that fits resolves plainly and must keep that spelling.
|
||||
const std::string dep_path = plain_path_exists(plain_dep_dir) ? plain_dep_dir.string() : io_dep_dir.string();
|
||||
std::string syspath_error;
|
||||
if (!interpreter.add_plugin_sys_path(dep_path, syspath_error)) {
|
||||
error = GUI::format(_u8L("Failed to add .whl dependency to sys.path: %1%"), syspath_error);
|
||||
return false;
|
||||
}
|
||||
plugin_paths.push_back(dep_dir.string());
|
||||
plugin_paths.push_back(dep_path);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -199,12 +229,13 @@ PyObject* import_plugin_module(const PluginDescriptor& descriptor,
|
||||
if (descriptor.entry_package.empty())
|
||||
return interpreter.load_module_from_file(descriptor.entry_path, error, &plugin_paths, &plugin_modules);
|
||||
|
||||
if (boost::filesystem::path(descriptor.entry_path).extension() == ".whl")
|
||||
return interpreter.load_module_from_whl(
|
||||
descriptor.entry_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules);
|
||||
// A wheel entry is imported from the directory its installation lives in; a .py entry in place.
|
||||
const std::string dir_path = has_wheel_extension(descriptor.entry_path) ?
|
||||
plugin_wheel_install::install_dir(descriptor.plugin_root, descriptor.entry_package) :
|
||||
descriptor.entry_path;
|
||||
|
||||
return interpreter.load_module_from_directory(
|
||||
descriptor.entry_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules);
|
||||
dir_path, descriptor.entry_package, error, &plugin_paths, &plugin_modules);
|
||||
}
|
||||
|
||||
std::string plugin_module_name(const PluginDescriptor& descriptor)
|
||||
@@ -291,6 +322,22 @@ bool load(const PluginDescriptor& descriptor,
|
||||
plugin.descriptor = descriptor;
|
||||
plugin.module_name = plugin_module_name(descriptor);
|
||||
|
||||
// Wheel entries have one installation and one loading path: uv installs the entry wheel into
|
||||
// the legacy extraction path, then the entry package is imported from there. An existing
|
||||
// markerless extraction at that path is a pre-uv cache and is used directly when it contains
|
||||
// the entry package. Dependency wheels are extracted alongside it under __whl_extracted__/
|
||||
// and are not touched.
|
||||
const bool has_entry_wheel = plugin_package_extension(descriptor.entry_path) == ".whl";
|
||||
if (has_entry_wheel) {
|
||||
std::string wheel_install_error;
|
||||
if (!plugin_wheel_install::ensure_installed(descriptor, wheel_install_error)) {
|
||||
// Report the failure instead of silently falling back to extraction.
|
||||
// TRN %1% is the uv/installation error detail.
|
||||
error = GUI::format(_u8L("Failed to install plugin wheel: %1%"), wheel_install_error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!skip_deps) {
|
||||
std::string pkg_install_error;
|
||||
if (!install_packages(descriptor.dependencies, pkg_install_error)) {
|
||||
@@ -510,12 +557,6 @@ bool install_packages(const std::vector<std::string>& pkgs, std::string& error)
|
||||
if (pkgs.empty())
|
||||
return true;
|
||||
|
||||
const std::string uv_path = PythonInterpreter::bundled_uv_path();
|
||||
if (uv_path.empty()) {
|
||||
error = "Bundled uv executable not found. Python package installation is unavailable.";
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string python_executable = PythonInterpreter::bundled_python_executable();
|
||||
if (python_executable.empty()) {
|
||||
error = "Bundled Python executable not found. Python package installation is unavailable.";
|
||||
@@ -538,81 +579,7 @@ bool install_packages(const std::vector<std::string>& pkgs, std::string& error)
|
||||
BOOST_LOG_TRIVIAL(info) << "Installing Python packages via uv for " << python_executable << ": "
|
||||
<< boost::algorithm::join(pkgs, ", ");
|
||||
|
||||
try {
|
||||
namespace process = boost::process;
|
||||
|
||||
process::ipstream std_err;
|
||||
process::child child(uv_path, process::args(args),
|
||||
#ifdef _WIN32
|
||||
// uv.exe (and the python.exe it spawns) are console-subsystem programs.
|
||||
// OrcaSlicer is a GUI app with no console of its own, so without this flag
|
||||
// Windows allocates a fresh console window for the child that flashes on
|
||||
// screen during startup plugin loading. Matches ProcessRunner/MediaPlayCtrl.
|
||||
process::windows::create_no_window,
|
||||
#endif
|
||||
process::std_err > std_err);
|
||||
|
||||
std::string err_output;
|
||||
std::thread stderr_reader([&std_err, &err_output]() {
|
||||
std::string line;
|
||||
while (std::getline(std_err, line)) {
|
||||
err_output += line + '\n';
|
||||
}
|
||||
});
|
||||
|
||||
// Wait up to 120 seconds for package install to complete.
|
||||
//
|
||||
// NOTE: we poll child.running() instead of calling child.wait_for().
|
||||
// On macOS (which lacks sigtimedwait) boost.process v1 implements the
|
||||
// timed waits with a sigwait()-based fallback that deadlocks inside a
|
||||
// multi-threaded process: SIGCHLD is delivered to an arbitrary thread
|
||||
// and consumed by an async handler, so the worker thread's sigwait()
|
||||
// never returns and the timeout never fires — the plugin load hangs
|
||||
// forever (the "Loading" status never clears). child.running() uses
|
||||
// waitpid(WNOHANG), which behaves correctly on every platform.
|
||||
// (boost.process v2, in Boost >= 1.86, implements timed waits via Asio
|
||||
// and is unaffected — revisit this when the bundled Boost is upgraded.)
|
||||
constexpr auto kInstallTimeout = std::chrono::seconds(120);
|
||||
const auto deadline = std::chrono::steady_clock::now() + kInstallTimeout;
|
||||
|
||||
std::error_code run_ec;
|
||||
while (child.running(run_ec)) {
|
||||
if (run_ec) {
|
||||
stderr_reader.join();
|
||||
error = "Failed to query uv process status: " + run_ec.message();
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
if (std::chrono::steady_clock::now() >= deadline) {
|
||||
std::error_code term_ec;
|
||||
child.terminate(term_ec);
|
||||
child.wait(term_ec);
|
||||
stderr_reader.join();
|
||||
error = "uv pip install timed out after 120s";
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
stderr_reader.join();
|
||||
|
||||
const int exit_code = child.exit_code();
|
||||
if (exit_code != 0) {
|
||||
if (!err_output.empty())
|
||||
error = "uv pip install failed (exit code " + std::to_string(exit_code) + "): " + err_output;
|
||||
else
|
||||
error = "uv pip install failed with exit code " + std::to_string(exit_code);
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << "Python packages installed successfully";
|
||||
return true;
|
||||
} catch (const std::exception& ex) {
|
||||
error = std::string("Failed to run uv: ") + ex.what();
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
return PythonInterpreter::run_uv(args, std::chrono::seconds(120), error);
|
||||
}
|
||||
|
||||
bool inspect_local_plugin_package(const boost::filesystem::path& filepath,
|
||||
@@ -634,7 +601,11 @@ bool inspect_local_plugin_package(const boost::filesystem::path& filepath,
|
||||
boost::system::error_code ec;
|
||||
const fs::path source_path = canonical_or_absolute(filepath);
|
||||
|
||||
if (!fs::exists(source_path, ec) || !fs::is_regular_file(source_path, ec))
|
||||
// Both the package file chosen by the user and the install folder derived from its name can
|
||||
// pass the legacy Windows MAX_PATH, where the plain spelling cannot be probed. The descriptor
|
||||
// keeps the plain paths; only these probes use the extended-length form.
|
||||
const fs::path io_source_path = extended_path(source_path);
|
||||
if (!fs::exists(io_source_path, ec) || !fs::is_regular_file(io_source_path, ec))
|
||||
return fail("Plugin package is not a file: " + filepath.string());
|
||||
|
||||
std::string metadata_error;
|
||||
@@ -646,7 +617,7 @@ bool inspect_local_plugin_package(const boost::filesystem::path& filepath,
|
||||
plugin_descriptor.plugin_root = final_dir.string();
|
||||
|
||||
ec.clear();
|
||||
const fs::file_status final_status = fs::status(final_dir, ec);
|
||||
const fs::file_status final_status = fs::status(extended_path(final_dir), ec);
|
||||
if (ec && final_status.type() != fs::file_not_found)
|
||||
return fail("Failed to check existing plugin " + final_dir.string() + ": " + ec.message());
|
||||
|
||||
@@ -677,6 +648,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
const bool is_cloud_install = !cloud_uuid.empty();
|
||||
|
||||
fs::path backup_dir;
|
||||
fs::path io_backup_dir;
|
||||
bool backup_created = false;
|
||||
|
||||
auto fail = [&error](const std::string& message) {
|
||||
@@ -687,7 +659,14 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
boost::system::error_code ec;
|
||||
const fs::path source_path = canonical_or_absolute(filepath);
|
||||
|
||||
if (!fs::exists(source_path, ec) || !fs::is_regular_file(source_path, ec))
|
||||
// The installed copy is <plugin_root>/<escaped plugin filename>/<plugin filename>, so a long
|
||||
// wheel filename pushes the cache past the legacy Windows MAX_PATH even when the plugin root
|
||||
// stays well below it. The descriptor and the error messages keep the plain spelling; every
|
||||
// filesystem operation below goes through the extended-length form, which the Win32 APIs
|
||||
// accept past the limit. extended_path() is the identity off Windows.
|
||||
const fs::path io_source_path = extended_path(source_path);
|
||||
|
||||
if (!fs::exists(io_source_path, ec) || !fs::is_regular_file(io_source_path, ec))
|
||||
return fail(GUI::format(_u8L("Plugin package is not a file: %1%"), filepath.string()));
|
||||
|
||||
const std::string ext = plugin_package_extension(source_path);
|
||||
@@ -701,7 +680,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
|
||||
const fs::path plugin_root = is_cloud_install && !cloud_user_id.empty() ? fs::path(get_cloud_plugin_dir(cloud_user_id)) :
|
||||
local_plugin_root();
|
||||
fs::create_directories(plugin_root, ec);
|
||||
fs::create_directories(extended_path(plugin_root), ec);
|
||||
if (ec)
|
||||
// TRN %1% is a folder path, %2% the system error message.
|
||||
return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), plugin_root.string(), ec.message()));
|
||||
@@ -735,6 +714,11 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
const fs::path final_dir = is_cloud_install ? plugin_root / cloud_uuid : local_plugin_install_dir(source_path);
|
||||
const fs::path dest_file = final_dir / source_path.filename();
|
||||
|
||||
// The spelled-out install and backup paths above are the identity used by the descriptor and
|
||||
// the error messages; these are the same locations in the form the filesystem calls need.
|
||||
const fs::path io_final_dir = extended_path(final_dir);
|
||||
const fs::path io_dest_file = extended_path(dest_file);
|
||||
|
||||
// Local key is the plugin file stem; cloud key is the cloud UUID.
|
||||
if (is_cloud_install)
|
||||
plugin_descriptor.plugin_key = cloud_uuid;
|
||||
@@ -747,12 +731,12 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
auto restore_backup = [&]() {
|
||||
// A fresh install has no backup, but its partial destination must still be removed.
|
||||
boost::system::error_code restore_ec;
|
||||
fs::remove_all(final_dir, restore_ec);
|
||||
fs::remove_all(io_final_dir, restore_ec);
|
||||
if (!backup_created)
|
||||
return;
|
||||
|
||||
restore_ec.clear();
|
||||
fs::rename(backup_dir, final_dir, restore_ec);
|
||||
fs::rename(io_backup_dir, io_final_dir, restore_ec);
|
||||
if (restore_ec) {
|
||||
BOOST_LOG_TRIVIAL(error) << "Failed to restore plugin backup " << backup_dir.string() << " to "
|
||||
<< final_dir.string() << ": " << restore_ec.message();
|
||||
@@ -765,10 +749,11 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
|
||||
// Backup existing installation if present. The "__" prefix keeps an abandoned backup out of
|
||||
// discovery if the process dies or the final cleanup below cannot remove it.
|
||||
if (fs::exists(final_dir, ec)) {
|
||||
if (fs::exists(io_final_dir, ec)) {
|
||||
backup_dir = plugin_root /
|
||||
("__" + final_dir.filename().string() + ".backup-" + fs::unique_path("%%%%-%%%%-%%%%").string());
|
||||
fs::rename(final_dir, backup_dir, ec);
|
||||
io_backup_dir = extended_path(backup_dir);
|
||||
fs::rename(io_final_dir, io_backup_dir, ec);
|
||||
if (ec)
|
||||
// TRN %1% is a folder path, %2% the system error message.
|
||||
return fail(GUI::format(_u8L("Failed to back up existing plugin %1%: %2%"), final_dir.string(), ec.message()));
|
||||
@@ -776,13 +761,13 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
}
|
||||
|
||||
// Create the plugin directory and copy the file.
|
||||
fs::create_directories(final_dir, ec);
|
||||
fs::create_directories(io_final_dir, ec);
|
||||
if (ec) {
|
||||
restore_backup();
|
||||
return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), final_dir.string(), ec.message()));
|
||||
}
|
||||
|
||||
fs::copy_file(source_path, dest_file, ec);
|
||||
fs::copy_file(io_source_path, io_dest_file, ec);
|
||||
if (ec) {
|
||||
restore_backup();
|
||||
// TRN %1% is a file path, %2% the system error message.
|
||||
@@ -824,7 +809,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
|
||||
if (backup_created) {
|
||||
boost::system::error_code remove_ec;
|
||||
fs::remove_all(backup_dir, remove_ec);
|
||||
fs::remove_all(io_backup_dir, remove_ec);
|
||||
if (remove_ec)
|
||||
BOOST_LOG_TRIVIAL(warning) << "Failed to remove plugin backup " << backup_dir.string() << ": " << remove_ec.message();
|
||||
}
|
||||
@@ -833,7 +818,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
|
||||
|
||||
if (is_cloud_install) {
|
||||
boost::system::error_code remove_ec;
|
||||
fs::remove(source_path, remove_ec);
|
||||
fs::remove(io_source_path, remove_ec);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6,13 +6,14 @@
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <boost/filesystem/directory.hpp>
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <cstddef>
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
#include <exception>
|
||||
#include <pytypedefs.h>
|
||||
#include "PluginFsUtils.hpp"
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include <pybind11/embed.h>
|
||||
@@ -22,12 +23,15 @@
|
||||
#include <boost/dll/runtime_symbol_info.hpp>
|
||||
#include <boost/nowide/convert.hpp>
|
||||
#include <boost/system/error_code.hpp>
|
||||
#include <slic3r/Utils/BoostProcessCompat.hpp>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <iomanip>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <sstream>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -190,6 +194,91 @@ std::string executable_name(const char* base)
|
||||
#endif
|
||||
}
|
||||
|
||||
// The plain Win32 APIs refuse paths at MAX_PATH (260) unless long paths are enabled;
|
||||
// extended_path() is what reaches past it. Off Windows there is no such limit.
|
||||
bool fits_plain_windows_path(const boost::filesystem::path& path)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
constexpr std::size_t kLegacyWindowsPathLimit = 260;
|
||||
return path.wstring().size() < kLegacyWindowsPathLimit;
|
||||
#else
|
||||
(void) path;
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
// True when `directory` can be listed through its plain spelling and every entry file the finder
|
||||
// would probe for `stem` also fits there: "<stem>.py" or a compiled "<stem>.<tag>.pyd"/".so".
|
||||
// A namespace package has none of them, so being able to list the directory is all its import
|
||||
// needs.
|
||||
bool plain_path_reaches_entry_files(const boost::filesystem::path& directory, const std::string& stem)
|
||||
{
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
const std::string leaf = stem + ".";
|
||||
boost::system::error_code ec;
|
||||
fs::directory_iterator it(directory, ec);
|
||||
const fs::directory_iterator end;
|
||||
for (; !ec && it != end; it.increment(ec)) {
|
||||
const fs::path& candidate = it->path();
|
||||
const std::string filename = candidate.filename().string();
|
||||
if (filename.compare(0, leaf.size(), leaf) != 0)
|
||||
continue;
|
||||
|
||||
const std::string ext = candidate.extension().string();
|
||||
if (ext != ".py" && ext != ".pyd" && ext != ".so" && ext != ".dll")
|
||||
continue;
|
||||
if (!fits_plain_windows_path(candidate))
|
||||
return false;
|
||||
}
|
||||
|
||||
// An unreadable directory cannot be probed; the extended-length form may still reach it.
|
||||
return !ec;
|
||||
}
|
||||
|
||||
// True when the plain spelling of the sys.path entry `dir` reaches everything the import of
|
||||
// `pkg_name` needs. A directory below the legacy Windows MAX_PATH can still hold package files
|
||||
// above it, and the finder then silently treats the package as a namespace package: an
|
||||
// unreachable __init__.py reads exactly like a missing one. The probes here therefore check the
|
||||
// entry files themselves, so a namespace package and a compiled-only package keep the plain
|
||||
// spelling, while any entry file past the limit gets the extended-length form, which imports it
|
||||
// just as well.
|
||||
bool module_entry_reachable(const boost::filesystem::path& dir, const std::string& pkg_name)
|
||||
{
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
fs::path relative;
|
||||
std::string component;
|
||||
for (const char ch : pkg_name) {
|
||||
if (ch == '.') {
|
||||
relative /= component;
|
||||
component.clear();
|
||||
} else {
|
||||
component += ch;
|
||||
}
|
||||
}
|
||||
if (component.empty())
|
||||
return false;
|
||||
relative /= component;
|
||||
|
||||
const fs::path entry = dir / relative;
|
||||
|
||||
boost::system::error_code ec;
|
||||
if (fs::is_directory(entry, ec))
|
||||
return plain_path_reaches_entry_files(entry, "__init__");
|
||||
|
||||
// Boost reports a missing path through ec too (ENOENT, or on Windows ERROR_FILE_NOT_FOUND /
|
||||
// ERROR_PATH_NOT_FOUND), so the code alone cannot tell the single-module layout from a path
|
||||
// past MAX_PATH. The length can: a fitting absent entry is a module that lives next to it,
|
||||
// while one that does not fit cannot be probed plainly and takes the extended-length form.
|
||||
if (!fits_plain_windows_path(entry))
|
||||
return false;
|
||||
|
||||
// A single module: <pkg>.py or a compiled <pkg>.<tag>.pyd/.so next to the package path.
|
||||
const fs::path parent = relative.parent_path().empty() ? dir : dir / relative.parent_path();
|
||||
return plain_path_reaches_entry_files(parent, relative.filename().string());
|
||||
}
|
||||
|
||||
bool add_sys_path_entry(const boost::filesystem::path& path, std::string& error, bool* inserted = nullptr)
|
||||
{
|
||||
if (inserted)
|
||||
@@ -480,6 +569,105 @@ std::string PythonInterpreter::bundled_uv_path()
|
||||
return {};
|
||||
}
|
||||
|
||||
bool PythonInterpreter::run_uv(const std::vector<std::string>& args, std::chrono::seconds timeout, std::string& error)
|
||||
{
|
||||
error.clear();
|
||||
|
||||
const std::string uv_path = bundled_uv_path();
|
||||
if (uv_path.empty()) {
|
||||
error = "Bundled uv executable not found. Python package installation is unavailable.";
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
namespace process = boost::process;
|
||||
|
||||
process::ipstream std_err;
|
||||
#ifdef _WIN32
|
||||
// boost::process' narrow overload spawns through CreateProcessA, which interprets the
|
||||
// executable and arguments in the active ANSI codepage. The uv path and every argument
|
||||
// here are UTF-8 (boost::nowide::nowide_filesystem makes path::string() UTF-8), so hand
|
||||
// Boost UTF-16 strings and let it spawn through CreateProcessW instead.
|
||||
const std::wstring uv_path_wide = boost::nowide::widen(uv_path);
|
||||
std::vector<std::wstring> args_wide;
|
||||
args_wide.reserve(args.size());
|
||||
for (const std::string& arg : args)
|
||||
args_wide.emplace_back(boost::nowide::widen(arg));
|
||||
#endif
|
||||
process::child child(
|
||||
#ifdef _WIN32
|
||||
uv_path_wide, process::args(args_wide),
|
||||
#else
|
||||
uv_path, process::args(args),
|
||||
#endif
|
||||
#ifdef _WIN32
|
||||
// uv.exe (and the python.exe it spawns) are console-subsystem programs.
|
||||
// OrcaSlicer is a GUI app with no console of its own, so without this flag
|
||||
// Windows allocates a fresh console window for the child that flashes on
|
||||
// screen during startup plugin loading. Matches ProcessRunner/MediaPlayCtrl.
|
||||
process::windows::create_no_window,
|
||||
#endif
|
||||
process::std_err > std_err);
|
||||
|
||||
std::string err_output;
|
||||
std::thread stderr_reader([&std_err, &err_output]() {
|
||||
std::string line;
|
||||
while (std::getline(std_err, line)) {
|
||||
err_output += line + '\n';
|
||||
}
|
||||
});
|
||||
|
||||
// NOTE: we poll child.running() instead of calling child.wait_for().
|
||||
// On macOS (which lacks sigtimedwait) boost.process v1 implements the
|
||||
// timed waits with a sigwait()-based fallback that deadlocks inside a
|
||||
// multi-threaded process: SIGCHLD is delivered to an arbitrary thread
|
||||
// and consumed by an async handler, so the worker thread's sigwait()
|
||||
// never returns and the timeout never fires — the plugin load hangs
|
||||
// forever (the "Loading" status never clears). child.running() uses
|
||||
// waitpid(WNOHANG), which behaves correctly on every platform.
|
||||
// (boost.process v2, in Boost >= 1.86, implements timed waits via Asio
|
||||
// and is unaffected — revisit this when the bundled Boost is upgraded.)
|
||||
const auto deadline = std::chrono::steady_clock::now() + timeout;
|
||||
|
||||
std::error_code run_ec;
|
||||
while (child.running(run_ec)) {
|
||||
if (run_ec) {
|
||||
stderr_reader.join();
|
||||
error = "Failed to query uv process status: " + run_ec.message();
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
if (std::chrono::steady_clock::now() >= deadline) {
|
||||
std::error_code term_ec;
|
||||
child.terminate(term_ec);
|
||||
child.wait(term_ec);
|
||||
stderr_reader.join();
|
||||
error = "uv pip install timed out after " + std::to_string(timeout.count()) + "s";
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
stderr_reader.join();
|
||||
|
||||
const int exit_code = child.exit_code();
|
||||
if (exit_code != 0) {
|
||||
if (!err_output.empty())
|
||||
error = "uv pip install failed (exit code " + std::to_string(exit_code) + "): " + err_output;
|
||||
else
|
||||
error = "uv pip install failed with exit code " + std::to_string(exit_code);
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (const std::exception& ex) {
|
||||
error = std::string("Failed to run uv: ") + ex.what();
|
||||
BOOST_LOG_TRIVIAL(error) << error;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool PythonInterpreter::initialize()
|
||||
{
|
||||
std::unique_lock<std::shared_timed_mutex> runtime_lock(m_runtime_mutex);
|
||||
@@ -1170,9 +1358,19 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p
|
||||
}
|
||||
|
||||
namespace fs = boost::filesystem;
|
||||
fs::path dir(dir_path);
|
||||
// A wheel cache below the data directory can pass the legacy Windows MAX_PATH, in the
|
||||
// directory itself or in the package files below it, where boost::filesystem and the
|
||||
// interpreter's finder cannot reach either. The plain spelling is what the plugin then sees as
|
||||
// __file__ and sys.path, and what the host compares against the plain plugin root, so it is
|
||||
// kept while the entry module is reachable through it; otherwise the extended-length form is
|
||||
// used for the probe and for sys.path, and the recorded entry matches what is on it.
|
||||
// extended_path() is the identity off Windows.
|
||||
fs::path io_dir(dir_path);
|
||||
if (!io_dir.empty() && !module_entry_reachable(io_dir, pkg_name))
|
||||
io_dir = extended_path(io_dir);
|
||||
|
||||
if (!fs::exists(dir) || !fs::is_directory(dir)) {
|
||||
boost::system::error_code ec;
|
||||
if (!fs::is_directory(io_dir, ec) || ec) {
|
||||
error = "Directory does not exist: " + dir_path;
|
||||
return nullptr;
|
||||
}
|
||||
@@ -1183,7 +1381,7 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const std::string directory = dir.string();
|
||||
const std::string directory = io_dir.string();
|
||||
if (!add_plugin_sys_path_locked(directory, error))
|
||||
return nullptr;
|
||||
if (plugin_paths)
|
||||
@@ -1206,34 +1404,4 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p
|
||||
return module;
|
||||
}
|
||||
|
||||
PyObject* PythonInterpreter::load_module_from_whl(const std::string& file_path,
|
||||
const std::string& pkg_name,
|
||||
std::string& error,
|
||||
std::vector<std::string>* plugin_paths,
|
||||
std::vector<std::string>* plugin_modules)
|
||||
{
|
||||
if (!m_initialized.load(std::memory_order_acquire)) {
|
||||
error = "Python interpreter not initialized";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
fs::path whl_path(file_path);
|
||||
|
||||
if (!fs::exists(whl_path)) {
|
||||
error = "File does not exist: " + file_path;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
fs::path extract_dir = whl_path.parent_path() / "__whl_extracted__" / pkg_name;
|
||||
|
||||
if (!fs::exists(extract_dir)) {
|
||||
if (!extract_zip_to_directory(whl_path, extract_dir, error))
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return load_module_from_directory(extract_dir.string(), pkg_name, error, plugin_paths, plugin_modules);
|
||||
}
|
||||
|
||||
} // namespace Slic3r
|
||||
@@ -62,6 +62,14 @@ public:
|
||||
// Bundled uv executable path, or empty when uv is not bundled/found.
|
||||
static std::string bundled_uv_path();
|
||||
|
||||
// Run the bundled uv with `args` (everything after the executable), capturing its stderr.
|
||||
// Blocks the calling thread until the child exits or `timeout` elapses.
|
||||
//
|
||||
// `error` is set to an actionable message on failure: a missing bundled uv, a failed wait, a
|
||||
// timeout, a non-zero exit status, or the exception thrown while spawning the child. Arguments
|
||||
// are passed as an array; nothing is routed through a shell.
|
||||
static bool run_uv(const std::vector<std::string>& args, std::chrono::seconds timeout, std::string& error);
|
||||
|
||||
// Python ABI tag for the bundled interpreter, e.g. "cp312".
|
||||
static std::string python_abi_tag();
|
||||
|
||||
@@ -86,11 +94,6 @@ public:
|
||||
std::string& error,
|
||||
std::vector<std::string>* plugin_paths = nullptr,
|
||||
std::vector<std::string>* plugin_modules = nullptr);
|
||||
PyObject* load_module_from_whl(const std::string& whl_path,
|
||||
const std::string& pkg_name,
|
||||
std::string& error,
|
||||
std::vector<std::string>* plugin_paths = nullptr,
|
||||
std::vector<std::string>* plugin_modules = nullptr);
|
||||
PyObject* load_module_from_directory(const std::string& dir_path,
|
||||
const std::string& pkg_name,
|
||||
std::string& error,
|
||||
|
||||
@@ -663,8 +663,8 @@ void bind_python_api(pybind11::module_& m)
|
||||
|
||||
Each bucket takes the target strings the plugin expects the corresponding audit event to
|
||||
report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, socket addresses
|
||||
for network_socket, and commands for process. threading=True requests permission to start
|
||||
threads. Targets already granted to the plugin are not asked for again.
|
||||
for network_socket, and executables or command names for process. threading=True requests
|
||||
permission to start threads. Targets already granted to the plugin are not asked for again.
|
||||
|
||||
fs_create and fs_delete take folders rather than files. A literal folder entry grants creating
|
||||
or deleting entries directly inside that folder, not inside its subfolders. An entry ending in
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
ISO-10303-21;
|
||||
HEADER;
|
||||
FILE_DESCRIPTION(('Open CASCADE Model'),'2;1');
|
||||
FILE_NAME('Open CASCADE Shape Model','2026-11-19T16:06:59',('Author'),(
|
||||
'Open CASCADE'),'Open CASCADE STEP processor 8.0','Open CASCADE 8.0'
|
||||
,'Unknown');
|
||||
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
|
||||
ENDSEC;
|
||||
DATA;
|
||||
#1 = APPLICATION_PROTOCOL_DEFINITION('international standard',
|
||||
'automotive_design',2000,#2);
|
||||
#2 = APPLICATION_CONTEXT(
|
||||
'core data for automotive mechanical design processes');
|
||||
#3 = SHAPE_DEFINITION_REPRESENTATION(#4,#10);
|
||||
#4 = PRODUCT_DEFINITION_SHAPE('','',#5);
|
||||
#5 = PRODUCT_DEFINITION('design','',#6,#9);
|
||||
#6 = PRODUCT_DEFINITION_FORMATION('','',#7);
|
||||
#7 = PRODUCT('Open CASCADE STEP translator 8.0 1',
|
||||
'Open CASCADE STEP translator 8.0 1','',(#8));
|
||||
#8 = PRODUCT_CONTEXT('',#2,'mechanical');
|
||||
#9 = PRODUCT_DEFINITION_CONTEXT('part definition',#2,'design');
|
||||
#10 = MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#11,#15),#225);
|
||||
#11 = AXIS2_PLACEMENT_3D('',#12,#13,#14);
|
||||
#12 = CARTESIAN_POINT('',(0.,0.,0.));
|
||||
#13 = DIRECTION('',(0.,0.,1.));
|
||||
#14 = DIRECTION('',(1.,0.,-0.));
|
||||
#15 = SHELL_BASED_SURFACE_MODEL('',(#16));
|
||||
#16 = OPEN_SHELL('',(#17));
|
||||
#17 = ADVANCED_FACE('',(#18),#51,.T.);
|
||||
#18 = FACE_BOUND('',#19,.T.);
|
||||
#19 = EDGE_LOOP('',(#20,#61,#84,#118,#136,#171,#172,#209));
|
||||
#20 = ORIENTED_EDGE('',*,*,#21,.T.);
|
||||
#21 = EDGE_CURVE('',#22,#24,#26,.T.);
|
||||
#22 = VERTEX_POINT('',#23);
|
||||
#23 = CARTESIAN_POINT('',(4.143759803741,-4.874444458849,69.872014613543
|
||||
));
|
||||
#24 = VERTEX_POINT('',#25);
|
||||
#25 = CARTESIAN_POINT('',(-12.29864740029,-3.981026217535,
|
||||
68.506159421151));
|
||||
#26 = SURFACE_CURVE('',#27,(#50),.PCURVE_S1.);
|
||||
#27 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#28,#29,#30,#31,#32,#33,#34,#35,
|
||||
#36,#37,#38,#39,#40,#41,#42,#43,#44,#45,#46,#47,#48,#49),
|
||||
.UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3,4),(0.,0.37190743837,
|
||||
0.74381487674,1.11572231511,1.48762975348,1.983506337973,
|
||||
2.23144463022,2.529141946975),.UNSPECIFIED.);
|
||||
#28 = CARTESIAN_POINT('',(4.143759803725,-4.874444458851,69.872014613543
|
||||
));
|
||||
#29 = CARTESIAN_POINT('',(4.029039479458,-6.099264561044,69.754781673223
|
||||
));
|
||||
#30 = CARTESIAN_POINT('',(3.635412845026,-7.295135950986,69.615587068332
|
||||
));
|
||||
#31 = CARTESIAN_POINT('',(3.000986439986,-8.345127490291,69.468007573028
|
||||
));
|
||||
#32 = CARTESIAN_POINT('',(2.366560034947,-9.395119029597,69.320428077723
|
||||
));
|
||||
#33 = CARTESIAN_POINT('',(1.491333859301,-10.29923071826,69.164463692005
|
||||
));
|
||||
#34 = CARTESIAN_POINT('',(0.462690190863,-10.96670470189,69.015728860463
|
||||
));
|
||||
#35 = CARTESIAN_POINT('',(-0.565953477574,-11.63417868553,68.86699402892
|
||||
));
|
||||
#36 = CARTESIAN_POINT('',(-1.748014638803,-12.06501496412,
|
||||
68.725488751553));
|
||||
#37 = CARTESIAN_POINT('',(-2.968374982818,-12.21880646908,
|
||||
68.604858207553));
|
||||
#38 = CARTESIAN_POINT('',(-4.188735326832,-12.37259797405,
|
||||
68.484227663552));
|
||||
#39 = CARTESIAN_POINT('',(-5.447394853632,-12.24934470538,
|
||||
68.384471852918));
|
||||
#40 = CARTESIAN_POINT('',(-6.616838482239,-11.85783039067,68.31602103766
|
||||
));
|
||||
#41 = CARTESIAN_POINT('',(-8.176096653714,-11.33581130439,
|
||||
68.224753283981));
|
||||
#42 = CARTESIAN_POINT('',(-9.576748783956,-10.33688369181,
|
||||
68.189138855415));
|
||||
#43 = CARTESIAN_POINT('',(-10.58137693017,-9.031652960205,68.21510243469
|
||||
));
|
||||
#44 = CARTESIAN_POINT('',(-11.08369100327,-8.379037594403,
|
||||
68.228084224327));
|
||||
#45 = CARTESIAN_POINT('',(-11.48699908037,-7.649846448845,
|
||||
68.256460515925));
|
||||
#46 = CARTESIAN_POINT('',(-11.77442415228,-6.878633185846,
|
||||
68.298690442896));
|
||||
#47 = CARTESIAN_POINT('',(-12.11953289646,-5.952644235287,
|
||||
68.349395543072));
|
||||
#48 = CARTESIAN_POINT('',(-12.29757783178,-4.966073709505,68.42007286513
|
||||
));
|
||||
#49 = CARTESIAN_POINT('',(-12.29864740029,-3.981026217535,
|
||||
68.506159421151));
|
||||
#50 = PCURVE('',#51,#56);
|
||||
#51 = CONICAL_SURFACE('',#52,8.25,1.666512371394E-02);
|
||||
#52 = AXIS2_PLACEMENT_3D('',#53,#54,#55);
|
||||
#53 = CARTESIAN_POINT('',(-4.167416546478,-4.151558268342,
|
||||
70.452528145107));
|
||||
#54 = DIRECTION('',(8.715574274766E-02,8.682408883347E-02,
|
||||
-0.992403876506));
|
||||
#55 = DIRECTION('',(0.996194698092,-7.596123493896E-03,
|
||||
8.682408883347E-02));
|
||||
#56 = DEFINITIONAL_REPRESENTATION('',(#57),#60);
|
||||
#57 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#58,#59),.UNSPECIFIED.,.F.,.F.,(2,
|
||||
2),(0.,2.529141946975),.PIECEWISE_BEZIER_KNOTS.);
|
||||
#58 = CARTESIAN_POINT('',(6.376509579999,1.237706692175));
|
||||
#59 = CARTESIAN_POINT('',(9.424807694257,1.237705820714));
|
||||
#60 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#61 = ORIENTED_EDGE('',*,*,#62,.T.);
|
||||
#62 = EDGE_CURVE('',#24,#63,#65,.T.);
|
||||
#63 = VERTEX_POINT('',#64);
|
||||
#64 = CARTESIAN_POINT('',(-11.8668393524,-3.459571861966,62.542838503986
|
||||
));
|
||||
#65 = SEAM_CURVE('',#66,(#70,#77),.PCURVE_S1.);
|
||||
#66 = LINE('',#67,#68);
|
||||
#67 = CARTESIAN_POINT('',(-12.38602280573,-4.088890249517,
|
||||
69.736229412231));
|
||||
#68 = VECTOR('',#69,1.);
|
||||
#69 = DIRECTION('',(7.054270086241E-02,8.69386169222E-02,-0.993712938551
|
||||
));
|
||||
#70 = PCURVE('',#51,#71);
|
||||
#71 = DEFINITIONAL_REPRESENTATION('',(#72),#76);
|
||||
#72 = LINE('',#73,#74);
|
||||
#73 = CARTESIAN_POINT('',(9.424777960769,-3.3302065773E-15));
|
||||
#74 = VECTOR('',#75,1.);
|
||||
#75 = DIRECTION('',(0.,1.));
|
||||
#76 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#77 = PCURVE('',#51,#78);
|
||||
#78 = DEFINITIONAL_REPRESENTATION('',(#79),#83);
|
||||
#79 = LINE('',#80,#81);
|
||||
#80 = CARTESIAN_POINT('',(3.14159265359,-3.3302065773E-15));
|
||||
#81 = VECTOR('',#82,1.);
|
||||
#82 = DIRECTION('',(0.,1.));
|
||||
#83 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#84 = ORIENTED_EDGE('',*,*,#85,.T.);
|
||||
#85 = EDGE_CURVE('',#63,#86,#88,.T.);
|
||||
#86 = VERTEX_POINT('',#87);
|
||||
#87 = CARTESIAN_POINT('',(4.75702271724,-4.453754621641,63.91581382788)
|
||||
);
|
||||
#88 = SURFACE_CURVE('',#89,(#112),.PCURVE_S1.);
|
||||
#89 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#90,#91,#92,#93,#94,#95,#96,#97,
|
||||
#98,#99,#100,#101,#102,#103,#104,#105,#106,#107,#108,#109,#110,#111)
|
||||
,.UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3,4),(2.718902929729,
|
||||
3.010964145992,3.261821852983,3.763537266966,4.139823827454,
|
||||
4.516110387941,4.892396948428,5.268683508916),.UNSPECIFIED.);
|
||||
#90 = CARTESIAN_POINT('',(-11.86683935239,-3.459571861965,
|
||||
62.542838503986));
|
||||
#91 = CARTESIAN_POINT('',(-11.86937709332,-4.426034233901,
|
||||
62.458061131061));
|
||||
#92 = CARTESIAN_POINT('',(-11.70896301475,-5.393774766903,
|
||||
62.387482827713));
|
||||
#93 = CARTESIAN_POINT('',(-11.38149547781,-6.306025299713,62.33643038214
|
||||
));
|
||||
#94 = CARTESIAN_POINT('',(-11.10022651481,-7.089577048867,62.29258033044
|
||||
));
|
||||
#95 = CARTESIAN_POINT('',(-10.69571445902,-7.832191248394,
|
||||
62.263135410637));
|
||||
#96 = CARTESIAN_POINT('',(-10.19237858665,-8.49827843209,62.249064726986
|
||||
));
|
||||
#97 = CARTESIAN_POINT('',(-9.185706841918,-9.83045279948,62.220923359685
|
||||
));
|
||||
#98 = CARTESIAN_POINT('',(-7.783739830833,-10.85651910354,
|
||||
62.254278936995));
|
||||
#99 = CARTESIAN_POINT('',(-6.211992111038,-11.40193452483,
|
||||
62.344596644395));
|
||||
#100 = CARTESIAN_POINT('',(-5.033181321192,-11.8109960908,
|
||||
62.412334924946));
|
||||
#101 = CARTESIAN_POINT('',(-3.758868882695,-11.9496915352,
|
||||
62.512114403672));
|
||||
#102 = CARTESIAN_POINT('',(-2.521619747312,-11.80753342024,
|
||||
62.633210379822));
|
||||
#103 = CARTESIAN_POINT('',(-1.284370611928,-11.66537530528,
|
||||
62.754306355971));
|
||||
#104 = CARTESIAN_POINT('',(-8.418477965762E-02,-11.24236363094,
|
||||
62.896718829545));
|
||||
#105 = CARTESIAN_POINT('',(0.964036704717,-10.57823477998,63.04688037961
|
||||
));
|
||||
#106 = CARTESIAN_POINT('',(2.012258189092,-9.91410592903,63.197041929676
|
||||
));
|
||||
#107 = CARTESIAN_POINT('',(2.908515325572,-9.008859901449,
|
||||
63.354952556234));
|
||||
#108 = CARTESIAN_POINT('',(3.562304174523,-7.953319785154,
|
||||
63.504717954247));
|
||||
#109 = CARTESIAN_POINT('',(4.216093023475,-6.897779668859,63.65448335226
|
||||
));
|
||||
#110 = CARTESIAN_POINT('',(4.627413584898,-5.691945463852,
|
||||
63.796103521729));
|
||||
#111 = CARTESIAN_POINT('',(4.757022717202,-4.453754621644,
|
||||
63.915813827868));
|
||||
#112 = PCURVE('',#51,#113);
|
||||
#113 = DEFINITIONAL_REPRESENTATION('',(#114),#117);
|
||||
#114 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#115,#116),.UNSPECIFIED.,.F.,.F.,
|
||||
(2,2),(2.718902929729,5.268683508916),.PIECEWISE_BEZIER_KNOTS.);
|
||||
#115 = CARTESIAN_POINT('',(9.424775367365,7.238497013832));
|
||||
#116 = CARTESIAN_POINT('',(6.387399122293,7.238638837649));
|
||||
#117 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#118 = ORIENTED_EDGE('',*,*,#119,.T.);
|
||||
#119 = EDGE_CURVE('',#86,#120,#122,.T.);
|
||||
#120 = VERTEX_POINT('',#121);
|
||||
#121 = CARTESIAN_POINT('',(4.763507424532,-4.389388517509,
|
||||
63.922014637813));
|
||||
#122 = SURFACE_CURVE('',#123,(#130),.PCURVE_S1.);
|
||||
#123 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#124,#125,#126,#127,#128,#129),
|
||||
.UNSPECIFIED.,.F.,.F.,(4,2,4),(0.,3.249430989361E-03,
|
||||
6.498861978722E-03),.UNSPECIFIED.);
|
||||
#124 = CARTESIAN_POINT('',(4.757022717206,-4.453754621644,
|
||||
63.915813827868));
|
||||
#125 = CARTESIAN_POINT('',(4.758145172852,-4.443031501464,
|
||||
63.916850556582));
|
||||
#126 = CARTESIAN_POINT('',(4.759246797592,-4.432306053903,
|
||||
63.917885659486));
|
||||
#127 = CARTESIAN_POINT('',(4.761408372809,-4.410850625235,
|
||||
63.919952601975));
|
||||
#128 = CARTESIAN_POINT('',(4.762468321249,-4.400120664336,
|
||||
63.920984439613));
|
||||
#129 = CARTESIAN_POINT('',(4.763507424532,-4.389388517509,
|
||||
63.922014637813));
|
||||
#130 = PCURVE('',#51,#131);
|
||||
#131 = DEFINITIONAL_REPRESENTATION('',(#132),#135);
|
||||
#132 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#133,#134),.UNSPECIFIED.,.F.,.F.,
|
||||
(2,2),(0.,6.498861978722E-03),.PIECEWISE_BEZIER_KNOTS.);
|
||||
#133 = CARTESIAN_POINT('',(6.387399122293,7.238638837649));
|
||||
#134 = CARTESIAN_POINT('',(6.379635251372,7.238638837649));
|
||||
#135 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#136 = ORIENTED_EDGE('',*,*,#137,.T.);
|
||||
#137 = EDGE_CURVE('',#120,#63,#138,.T.);
|
||||
#138 = SURFACE_CURVE('',#139,(#165),.PCURVE_S1.);
|
||||
#139 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#140,#141,#142,#143,#144,#145,
|
||||
#146,#147,#148,#149,#150,#151,#152,#153,#154,#155,#156,#157,#158,
|
||||
#159,#160,#161,#162,#163,#164),.UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3,
|
||||
3,4),(0.,0.376379539117,0.752759078234,1.129138617351,1.505518156469
|
||||
,1.881897695586,2.164182349923,2.258277234703,2.718902929729),
|
||||
.UNSPECIFIED.);
|
||||
#140 = CARTESIAN_POINT('',(4.763507424532,-4.389388517509,
|
||||
63.922014637813));
|
||||
#141 = CARTESIAN_POINT('',(4.883491920427,-3.150155374883,
|
||||
64.040970870365));
|
||||
#142 = CARTESIAN_POINT('',(4.720833010841,-1.881926911817,
|
||||
64.137641313649));
|
||||
#143 = CARTESIAN_POINT('',(4.29177713392,-0.709212197811,64.202559644177
|
||||
));
|
||||
#144 = CARTESIAN_POINT('',(3.862721257,0.463502516196,64.267477974704));
|
||||
#145 = CARTESIAN_POINT('',(3.167268412747,1.540703481143,64.300644192476
|
||||
));
|
||||
#146 = CARTESIAN_POINT('',(2.273495756837,2.415374288815,64.298674305201
|
||||
));
|
||||
#147 = CARTESIAN_POINT('',(1.379723100927,3.290045096488,64.296704417926
|
||||
));
|
||||
#148 = CARTESIAN_POINT('',(0.287630633361,3.962185746887,64.259598425604
|
||||
));
|
||||
#149 = CARTESIAN_POINT('',(-0.893605154041,4.365900727323,64.19117940922
|
||||
));
|
||||
#150 = CARTESIAN_POINT('',(-2.074840941442,4.769615707759,
|
||||
64.122760392836));
|
||||
#151 = CARTESIAN_POINT('',(-3.345220048677,4.904905018232,
|
||||
64.023028352389));
|
||||
#152 = CARTESIAN_POINT('',(-4.58171278018,4.758163349392,63.901597796786
|
||||
));
|
||||
#153 = CARTESIAN_POINT('',(-5.818205511682,4.611421680552,
|
||||
63.780167241183));
|
||||
#154 = CARTESIAN_POINT('',(-7.02081186745,4.1826490324,63.637038170423)
|
||||
);
|
||||
#155 = CARTESIAN_POINT('',(-8.065522144736,3.514301141115,
|
||||
63.486815866392));
|
||||
#156 = CARTESIAN_POINT('',(-8.849054852701,3.013040222651,63.37414913837
|
||||
));
|
||||
#157 = CARTESIAN_POINT('',(-9.543771016519,2.377018229924,
|
||||
63.257492466632));
|
||||
#158 = CARTESIAN_POINT('',(-10.1208386321,1.644000024014,63.142681957346
|
||||
));
|
||||
#159 = CARTESIAN_POINT('',(-10.31319450396,1.399660622043,
|
||||
63.104411787584));
|
||||
#160 = CARTESIAN_POINT('',(-10.49247831491,1.144543863053,
|
||||
63.066346746984));
|
||||
#161 = CARTESIAN_POINT('',(-10.6555275489,0.880008227365,63.028883428364
|
||||
));
|
||||
#162 = CARTESIAN_POINT('',(-11.45370767211,-0.41498151978,
|
||||
62.845488048078));
|
||||
#163 = CARTESIAN_POINT('',(-11.86283793131,-1.935687816598,
|
||||
62.676512498712));
|
||||
#164 = CARTESIAN_POINT('',(-11.8668393524,-3.459571861966,
|
||||
62.542838503986));
|
||||
#165 = PCURVE('',#51,#166);
|
||||
#166 = DEFINITIONAL_REPRESENTATION('',(#167),#170);
|
||||
#167 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#168,#169),.UNSPECIFIED.,.F.,.F.,
|
||||
(2,2),(0.,2.718902929729),.PIECEWISE_BEZIER_KNOTS.);
|
||||
#168 = CARTESIAN_POINT('',(6.379635251372,7.238638837649));
|
||||
#169 = CARTESIAN_POINT('',(3.141590060185,7.238497013832));
|
||||
#170 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#171 = ORIENTED_EDGE('',*,*,#62,.F.);
|
||||
#172 = ORIENTED_EDGE('',*,*,#173,.T.);
|
||||
#173 = EDGE_CURVE('',#24,#174,#176,.T.);
|
||||
#174 = VERTEX_POINT('',#175);
|
||||
#175 = CARTESIAN_POINT('',(4.149473588578,-4.810776140259,69.87808667055
|
||||
));
|
||||
#176 = SURFACE_CURVE('',#177,(#203),.PCURVE_S1.);
|
||||
#177 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#178,#179,#180,#181,#182,#183,
|
||||
#184,#185,#186,#187,#188,#189,#190,#191,#192,#193,#194,#195,#196,
|
||||
#197,#198,#199,#200,#201,#202),.UNSPECIFIED.,.F.,.F.,(4,3,3,3,3,3,3,
|
||||
3,4),(2.529141946975,2.603325106943,2.975097425779,3.346869744615,
|
||||
3.718642063451,4.090414382287,4.462186701123,4.833959019959,
|
||||
5.205731338795),.UNSPECIFIED.);
|
||||
#178 = CARTESIAN_POINT('',(-12.29864740029,-3.981026217535,
|
||||
68.506159421151));
|
||||
#179 = CARTESIAN_POINT('',(-12.29891402281,-3.73547313371,
|
||||
68.527619116728));
|
||||
#180 = CARTESIAN_POINT('',(-12.28818326443,-3.490014692339,
|
||||
68.550036353563));
|
||||
#181 = CARTESIAN_POINT('',(-12.26630159044,-3.24561292317,
|
||||
68.573340448815));
|
||||
#182 = CARTESIAN_POINT('',(-12.15664057458,-2.020782213733,
|
||||
68.690129994234));
|
||||
#183 = CARTESIAN_POINT('',(-11.76691769672,-0.8224904536,68.829193515027
|
||||
));
|
||||
#184 = CARTESIAN_POINT('',(-11.13645348098,0.229933555183,
|
||||
68.976637853055));
|
||||
#185 = CARTESIAN_POINT('',(-10.50598926524,1.282357563966,
|
||||
69.124082191083));
|
||||
#186 = CARTESIAN_POINT('',(-9.634783711627,2.188913821399,
|
||||
69.279907346346));
|
||||
#187 = CARTESIAN_POINT('',(-8.608543800092,2.860523259039,
|
||||
69.428792878436));
|
||||
#188 = CARTESIAN_POINT('',(-7.582303888557,3.532132696679,
|
||||
69.577678410526));
|
||||
#189 = CARTESIAN_POINT('',(-6.401029619107,3.968795314526,
|
||||
69.719624319445));
|
||||
#190 = CARTESIAN_POINT('',(-5.181669553845,4.127115459444,
|
||||
69.840563220766));
|
||||
#191 = CARTESIAN_POINT('',(-3.962309488584,4.285435604362,
|
||||
69.961502122087));
|
||||
#192 = CARTESIAN_POINT('',(-2.70486362751,4.165413276351,70.06143401581)
|
||||
);
|
||||
#193 = CARTESIAN_POINT('',(-1.533296826342,3.779222761759,
|
||||
70.130537066304));
|
||||
#194 = CARTESIAN_POINT('',(-0.361730025175,3.393032247166,
|
||||
70.199640116798));
|
||||
#195 = CARTESIAN_POINT('',(0.723957716087,2.740673545991,70.237914324062
|
||||
));
|
||||
#196 = CARTESIAN_POINT('',(1.616230879826,1.886055040854,70.241506870802
|
||||
));
|
||||
#197 = CARTESIAN_POINT('',(2.508504043565,1.031436535718,70.245099417541
|
||||
));
|
||||
#198 = CARTESIAN_POINT('',(3.207362629782,-2.544177338112E-02,
|
||||
70.214010303756));
|
||||
#199 = CARTESIAN_POINT('',(3.64390522245,-1.179558338951,70.151376605138
|
||||
));
|
||||
#200 = CARTESIAN_POINT('',(4.080447815118,-2.333674904522,70.08874290652
|
||||
));
|
||||
#201 = CARTESIAN_POINT('',(4.254674414237,-3.585029726563,69.99456462307
|
||||
));
|
||||
#202 = CARTESIAN_POINT('',(4.149473588575,-4.810776140259,69.87808667055
|
||||
));
|
||||
#203 = PCURVE('',#51,#204);
|
||||
#204 = DEFINITIONAL_REPRESENTATION('',(#205),#208);
|
||||
#205 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#206,#207),.UNSPECIFIED.,.F.,.F.,
|
||||
(2,2),(2.529141946975,5.205731338795),.PIECEWISE_BEZIER_KNOTS.);
|
||||
#206 = CARTESIAN_POINT('',(3.141622387077,1.237705820714));
|
||||
#207 = CARTESIAN_POINT('',(6.368745709079,1.237706692175));
|
||||
#208 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#209 = ORIENTED_EDGE('',*,*,#210,.T.);
|
||||
#210 = EDGE_CURVE('',#174,#22,#211,.T.);
|
||||
#211 = SURFACE_CURVE('',#212,(#219),.PCURVE_S1.);
|
||||
#212 = B_SPLINE_CURVE_WITH_KNOTS('',3,(#213,#214,#215,#216,#217,#218),
|
||||
.UNSPECIFIED.,.F.,.F.,(4,2,4),(0.,3.21060559169E-03,6.42121118338E-03)
|
||||
,.UNSPECIFIED.);
|
||||
#213 = CARTESIAN_POINT('',(4.149473588578,-4.810776140259,69.87808667055
|
||||
));
|
||||
#214 = CARTESIAN_POINT('',(4.148562516505,-4.821391487794,69.87707793503
|
||||
));
|
||||
#215 = CARTESIAN_POINT('',(4.147630827754,-4.832004899757,
|
||||
69.876067558235));
|
||||
#216 = CARTESIAN_POINT('',(4.145726227421,-4.853227732586,
|
||||
69.874043533514));
|
||||
#217 = CARTESIAN_POINT('',(4.144753317635,-4.863837133464,
|
||||
69.873029887494));
|
||||
#218 = CARTESIAN_POINT('',(4.143759803725,-4.874444458851,
|
||||
69.872014613543));
|
||||
#219 = PCURVE('',#51,#220);
|
||||
#220 = DEFINITIONAL_REPRESENTATION('',(#221),#224);
|
||||
#221 = B_SPLINE_CURVE_WITH_KNOTS('',1,(#222,#223),.UNSPECIFIED.,.F.,.F.,
|
||||
(2,2),(0.,6.42121118338E-03),.PIECEWISE_BEZIER_KNOTS.);
|
||||
#222 = CARTESIAN_POINT('',(6.368745709079,1.237706692175));
|
||||
#223 = CARTESIAN_POINT('',(6.376509579999,1.237706692175));
|
||||
#224 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
|
||||
PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
|
||||
) );
|
||||
#225 = ( GEOMETRIC_REPRESENTATION_CONTEXT(3)
|
||||
GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#229)) GLOBAL_UNIT_ASSIGNED_CONTEXT
|
||||
((#226,#227,#228)) REPRESENTATION_CONTEXT('Context #1',
|
||||
'3D Context with UNIT and UNCERTAINTY') );
|
||||
#226 = ( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );
|
||||
#227 = ( NAMED_UNIT(*) PLANE_ANGLE_UNIT() SI_UNIT($,.RADIAN.) );
|
||||
#228 = ( NAMED_UNIT(*) SI_UNIT($,.STERADIAN.) SOLID_ANGLE_UNIT() );
|
||||
#229 = UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(5.E-03),#226,
|
||||
'distance_accuracy_value','confusion accuracy');
|
||||
#230 = PRODUCT_RELATED_PRODUCT_CATEGORY('part',$,(#7));
|
||||
ENDSEC;
|
||||
END-ISO-10303-21;
|
||||
@@ -6,6 +6,7 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_adaptive_pressure_advance.cpp
|
||||
test_bridge.cpp
|
||||
test_calib.cpp
|
||||
test_conflict_checker.cpp
|
||||
test_cooling.cpp
|
||||
test_extrusion_entity.cpp
|
||||
test_extrusion_processor.cpp
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <catch2/generators/catch_generators.hpp>
|
||||
|
||||
#include "libslic3r/Config.hpp"
|
||||
#include "libslic3r/GCode/GCodeProcessor.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "libslic3r/TriangleMesh.hpp"
|
||||
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "test_helpers.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::Test;
|
||||
|
||||
namespace {
|
||||
|
||||
// Two 10 mm cubes printed as separate objects, the second shifted along X by `offset`, at the
|
||||
// positions given (not arranged apart).
|
||||
ConflictResultOpt conflict_between_cubes(double offset)
|
||||
{
|
||||
TriangleMesh first = make_cube(10., 10., 10.);
|
||||
TriangleMesh second = make_cube(10., 10., 10.);
|
||||
first.translate(50.f, 50.f, 0.f);
|
||||
second.translate(float(50. + offset), 50.f, 0.f);
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({ { "layer_height", "0.2" }, { "initial_layer_print_height", "0.2" } });
|
||||
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({ std::move(first), std::move(second) }, print, model, config, nullptr, false);
|
||||
print.process();
|
||||
return print.get_conflict_result();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Objects whose extrusions cross are reported as a path conflict", "[ConflictChecker]")
|
||||
{
|
||||
// A 5 mm shift puts half of each cube inside the other, so their walls cross on every layer of the
|
||||
// 10 mm high cubes.
|
||||
const ConflictResultOpt conflict = conflict_between_cubes(5.);
|
||||
REQUIRE(conflict.has_value());
|
||||
CHECK(conflict->_obj1 != conflict->_obj2);
|
||||
CHECK(conflict->_height <= 10.);
|
||||
}
|
||||
|
||||
TEST_CASE("Objects apart from each other have no path conflict", "[ConflictChecker]")
|
||||
{
|
||||
// 30 mm between the cube origins leaves a 20 mm gap between the 10 mm cubes.
|
||||
CHECK_FALSE(conflict_between_cubes(30.).has_value());
|
||||
}
|
||||
|
||||
TEST_CASE("Copies of an object printed over each other are reported as a path conflict", "[ConflictChecker]")
|
||||
{
|
||||
// Two instances of one 10 mm cube: not arranged, both stay at the origin of the object; arranged, they are
|
||||
// placed apart.
|
||||
const bool arranged = GENERATE(false, true);
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({ { "layer_height", "0.2" }, { "initial_layer_print_height", "0.2" } });
|
||||
|
||||
TriangleMesh cube = make_cube(10., 10., 10.);
|
||||
cube.translate(50.f, 50.f, 0.f);
|
||||
Print print;
|
||||
Model model;
|
||||
std::vector<TriangleMesh> meshes;
|
||||
meshes.emplace_back(std::move(cube));
|
||||
init_print(std::move(meshes), print, model, config, nullptr, arranged, 2);
|
||||
print.process();
|
||||
CHECK(print.get_conflict_result().has_value() == ! arranged);
|
||||
}
|
||||
@@ -828,6 +828,36 @@ TEST_CASE("Inner walls of an exported sphere are not tagged", "[GCodeProcessor][
|
||||
CHECK(layers.size() == seams.size());
|
||||
}
|
||||
|
||||
TEST_CASE("A reset processor does not keep the previous G-code's pressure advance", "[GCodeProcessor][Regression]")
|
||||
{
|
||||
FullPrintConfig config;
|
||||
config.gcode_flavor.value = gcfMarlinFirmware;
|
||||
GCodeProcessor processor;
|
||||
// Streams G-code through the same processor, resetting it first as a reused one is.
|
||||
const auto process = [&](const std::string &gcode) {
|
||||
processor.reset();
|
||||
processor.initialize("stream.gcode");
|
||||
processor.initialize_result_moves();
|
||||
processor.apply_config(config);
|
||||
processor.process_buffer(gcode);
|
||||
processor.finalize(false);
|
||||
return processor.result().moves;
|
||||
};
|
||||
const auto is_extrusion = [](const GCodeProcessorResult::MoveVertex &move) { return move.type == EMoveType::Extrude; };
|
||||
const std::string square = "M83\nG90\nG1 X10 Y10 Z0.2 F12000\nG1 X50 Y10 E2 F3000\nG1 X50 Y50 E2\nG1 X10 Y50 E2\nG1 X10 Y10 E2\n";
|
||||
|
||||
const std::vector<GCodeProcessorResult::MoveVertex> with_pa = process("M900 K0.05\n" + square);
|
||||
REQUIRE(std::any_of(with_pa.begin(), with_pa.end(), is_extrusion));
|
||||
for (const GCodeProcessorResult::MoveVertex &move : with_pa)
|
||||
if (is_extrusion(move))
|
||||
CHECK_THAT(move.pressure_advance, Catch::Matchers::WithinAbs(0.05, 1e-6));
|
||||
|
||||
const std::vector<GCodeProcessorResult::MoveVertex> without_pa = process(square);
|
||||
REQUIRE(std::any_of(without_pa.begin(), without_pa.end(), is_extrusion));
|
||||
for (const GCodeProcessorResult::MoveVertex &move : without_pa)
|
||||
CHECK(move.pressure_advance == 0.0f);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// A printer with `nozzles` nozzles over a 200 mm square bed: nozzle `filament_1_nozzle` reaches only
|
||||
|
||||
@@ -36,6 +36,8 @@
|
||||
#include "libslic3r/Support/BeltFloorContext.hpp"
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/ExtrusionEntity.hpp"
|
||||
#include "libslic3r/ExtrusionEntityCollection.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/Polyline.hpp"
|
||||
#include <limits>
|
||||
#include <cmath>
|
||||
@@ -56,11 +58,15 @@
|
||||
#include <boost/algorithm/string/predicate.hpp>
|
||||
#include <cstdlib>
|
||||
#include <sstream>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <limits>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <ios>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -69,6 +75,7 @@
|
||||
#include "libslic3r/SurfaceCollection.hpp"
|
||||
#include "libslic3r/BoundingBox.hpp"
|
||||
#include "libslic3r/ExPolygon.hpp"
|
||||
#include "libslic3r/Geometry.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::Test;
|
||||
@@ -3517,6 +3524,128 @@ TEST_CASE("Height range settings follow a Z shrinkage change that comes with a m
|
||||
|
||||
namespace {
|
||||
|
||||
// Four distinct objects: they run each slicing step together.
|
||||
std::vector<TriangleMesh> distinct_objects()
|
||||
{
|
||||
std::vector<TriangleMesh> meshes;
|
||||
for (TestMesh m : { TestMesh::cube_with_hole, TestMesh::pyramid, TestMesh::sphere_50mm, TestMesh::overhang })
|
||||
meshes.emplace_back(Test::mesh(m));
|
||||
return meshes;
|
||||
}
|
||||
|
||||
// The moves of a G-code, without the export time in the header or the configuration block. The block also lists the
|
||||
// filament maps slicing writes back, which the GUI passes to the next apply() and these tests do not.
|
||||
std::string toolpaths(const std::string &gcode)
|
||||
{
|
||||
std::istringstream in(gcode);
|
||||
std::string out, line;
|
||||
bool config = false;
|
||||
while (std::getline(in, line)) {
|
||||
if (line.rfind("; CONFIG_BLOCK_START", 0) == 0)
|
||||
config = true;
|
||||
else if (line.rfind("; CONFIG_BLOCK_END", 0) == 0)
|
||||
config = false;
|
||||
else if (! config && line.rfind("; generated by", 0) != 0)
|
||||
out += line + '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string fresh_slice_toolpaths(const DynamicPrintConfig &config)
|
||||
{
|
||||
Print print;
|
||||
Model model;
|
||||
Test::init_print(distinct_objects(), print, model, config);
|
||||
return toolpaths(Test::gcode(print));
|
||||
}
|
||||
|
||||
// Copies of a model of a cube with a hole, one at each scale, sliced together. Each scale gets a PrintObject of its
|
||||
// own, all of them made from the one ModelObject. With `only` set, the other copies stay in the model but do not
|
||||
// print, so that copy's PrintObject is the only one and keeps the coordinates it has among the others.
|
||||
void slice_copies_at_scales(const std::vector<double> &scales, const DynamicPrintConfig &config, Model &model, Print &print,
|
||||
std::optional<size_t> only = std::nullopt)
|
||||
{
|
||||
ModelObject *object = model.add_object();
|
||||
object->add_volume(Test::mesh(TestMesh::cube_with_hole));
|
||||
for (size_t i = 0; i < scales.size(); ++ i) {
|
||||
ModelInstance *instance = object->add_instance();
|
||||
instance->set_scaling_factor(Vec3d(scales[i], scales[i], scales[i]));
|
||||
instance->set_offset(Vec3d(40. + 30. * double(i), 100., 0.));
|
||||
instance->printable = ! only || *only == i;
|
||||
}
|
||||
object->ensure_on_bed();
|
||||
print.auto_assign_extruders(object);
|
||||
print.apply(model, config);
|
||||
print.set_status_silent();
|
||||
print.process();
|
||||
}
|
||||
|
||||
// The perimeters and the infill of every layer of a PrintObject, in its own coordinates.
|
||||
std::string layer_extrusions(const PrintObject &object)
|
||||
{
|
||||
std::ostringstream out;
|
||||
for (const Layer *layer : object.layers()) {
|
||||
out << "layer " << layer->print_z << '\n';
|
||||
for (const LayerRegion *layerm : layer->regions())
|
||||
for (const ExtrusionEntityCollection *extrusions : { &layerm->perimeters, &layerm->fills })
|
||||
for (const ExtrusionEntity *extrusion : extrusions->flatten().entities) {
|
||||
for (const Point &point : extrusion->as_polyline().points)
|
||||
out << point.x() << ',' << point.y() << ' ';
|
||||
out << '\n';
|
||||
}
|
||||
}
|
||||
return out.str();
|
||||
}
|
||||
|
||||
// The project of an Assembly crash report: one object of a 27 mm cube and a cylinder of the same size lying along X,
|
||||
// in an instance scaled 2x along X, on the bed.
|
||||
ModelObject *add_cube_and_lying_cylinder(Model &model)
|
||||
{
|
||||
ModelObject *object = model.add_object();
|
||||
object->add_volume(cube(27.))->set_offset(Vec3d(0., 18., 0.));
|
||||
ModelVolume *cylinder = object->add_volume(make_cylinder(13.5, 27.));
|
||||
cylinder->set_rotation(Vec3d(0., 0.5 * PI, 0.));
|
||||
cylinder->set_offset(Vec3d(0., -18., 0.));
|
||||
ModelInstance *instance = object->add_instance();
|
||||
instance->set_scaling_factor(Vec3d(2., 1., 1.));
|
||||
instance->set_offset(Vec3d(100., 100., 13.5));
|
||||
return object;
|
||||
}
|
||||
|
||||
// The Assembly tool's Parallel with the cube's top face picked first and an end face of the cylinder second, which
|
||||
// GLGizmoMeasure::set_to_parallel() does by turning the cylinder until that end face points down.
|
||||
// - Turning its whole world transformation about its origin, as set_to_parallel() does now, keeps the cylinder round
|
||||
// and 54 mm long. It stands about its centre, 13.5 mm above the bed, so 13.5 mm of it goes below the bed.
|
||||
// - Setting its rotation only, as the crash build's set_to_parallel() did, lets the instance's scaling stretch it
|
||||
// along X instead: it stands 27 mm tall on the bed, an ellipse twice as wide as it is deep.
|
||||
void turn_cylinder_end_face_down(ModelObject &object, const Vec3d &end_face_normal, bool whole_transformation)
|
||||
{
|
||||
ModelVolume &cylinder = *object.volumes.back();
|
||||
const Transform3d instance = object.instances.front()->get_matrix();
|
||||
Transform3d world = instance * cylinder.get_matrix();
|
||||
Vec3d axis;
|
||||
double angle;
|
||||
Matrix3d rotation;
|
||||
Geometry::rotation_from_two_vectors(end_face_normal, -Vec3d::UnitZ(), axis, angle, &rotation);
|
||||
if (whole_transformation) {
|
||||
world.linear() = rotation * world.linear().eval();
|
||||
cylinder.set_transformation(instance.inverse() * world);
|
||||
} else {
|
||||
const Transform3d turned = Transform3d(rotation) * Geometry::Transformation(world).get_rotation_matrix();
|
||||
const Transform3d instance_rotation = object.instances.front()->get_transformation().get_rotation_matrix();
|
||||
cylinder.set_rotation(Geometry::extract_euler_angles(instance_rotation.inverse() * turned));
|
||||
}
|
||||
object.invalidate_bounding_box();
|
||||
}
|
||||
|
||||
// The area of the islands of the lowest layer at or above z, in mm².
|
||||
double island_area_at(const PrintObject &object, double z)
|
||||
{
|
||||
const auto it = std::find_if(object.layers().begin(), object.layers().end(), [z](const Layer *layer) { return layer->print_z >= z; });
|
||||
REQUIRE(it != object.layers().end());
|
||||
return area((*it)->lslices) * SCALING_FACTOR * SCALING_FACTOR;
|
||||
}
|
||||
|
||||
// One tray of the device AMS inventory, with the keys build_filament_ams_list() puts in the payload.
|
||||
DynamicPrintConfig loaded_filament_tray(const std::string &colour, const std::string &type, const std::string &tray_name)
|
||||
{
|
||||
@@ -3560,6 +3689,184 @@ DynamicPrintConfig machine_inventory_config()
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Re-processing several objects after a setting change gives the toolpaths of a fresh slice", "[Print]")
|
||||
{
|
||||
// The settings invalidate the perimeters, the infill regions and everything after them, the infill, the ironing,
|
||||
// or only the G-code export.
|
||||
const auto [key, before, after] = GENERATE(table<std::string, std::string, std::string>({
|
||||
{ "wall_loops", "2", "3" },
|
||||
{ "top_shell_layers", "3", "5" },
|
||||
{ "sparse_infill_density", "15%", "40%" },
|
||||
{ "sparse_infill_pattern", "grid", "gyroid" },
|
||||
{ "ironing_type", "no ironing", "top" },
|
||||
{ "seam_position", "aligned", "nearest" },
|
||||
{ "outer_wall_speed", "60", "40" },
|
||||
}));
|
||||
INFO(key << ": " << before << " -> " << after);
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
// init_print() turns the G-code comments on, the second apply() has to keep them.
|
||||
config.set_deserialize_strict({ { "gcode_comments", "1" }, { key, before } });
|
||||
Print print;
|
||||
Model model;
|
||||
Test::init_print(distinct_objects(), print, model, config);
|
||||
REQUIRE(print.objects().size() == 4);
|
||||
Test::gcode(print);
|
||||
|
||||
config.set_deserialize_strict(key, after);
|
||||
print.apply(model, config);
|
||||
const std::string reprocessed = toolpaths(Test::gcode(print));
|
||||
|
||||
REQUIRE(! reprocessed.empty());
|
||||
CHECK(reprocessed == fresh_slice_toolpaths(config));
|
||||
}
|
||||
|
||||
TEST_CASE("Slicing several objects cancelled from another thread and run again gives the toolpaths of a fresh slice", "[Print]")
|
||||
{
|
||||
// As the GUI does it: the print is processed on a thread of its own, which the status updates reach from the
|
||||
// threads processing the objects, and a cancel makes process() throw before the print is processed again.
|
||||
const int cancel_at_update = GENERATE(1, 3, 6, 9);
|
||||
INFO("cancelled at status update " << cancel_at_update);
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({ { "gcode_comments", "1" } });
|
||||
Print print;
|
||||
Model model;
|
||||
Test::init_print(distinct_objects(), print, model, config);
|
||||
REQUIRE(print.objects().size() == 4);
|
||||
|
||||
std::atomic<int> updates { 0 };
|
||||
print.set_status_callback([&print, &updates, cancel_at_update](const PrintBase::SlicingStatus &) {
|
||||
if (++ updates == cancel_at_update)
|
||||
print.cancel();
|
||||
});
|
||||
bool canceled = false;
|
||||
bool other_error = false;
|
||||
std::thread background([&print, &canceled, &other_error] {
|
||||
try {
|
||||
print.process();
|
||||
} catch (const CanceledException &) {
|
||||
canceled = true;
|
||||
} catch (...) {
|
||||
other_error = true;
|
||||
}
|
||||
});
|
||||
background.join();
|
||||
CHECK(canceled);
|
||||
CHECK_FALSE(other_error);
|
||||
|
||||
print.restart();
|
||||
const std::string resumed = toolpaths(Test::gcode(print));
|
||||
REQUIRE(! resumed.empty());
|
||||
CHECK(resumed == fresh_slice_toolpaths(config));
|
||||
}
|
||||
|
||||
TEST_CASE("Slicing several objects calls the status callback one status at a time", "[Print]")
|
||||
{
|
||||
// The objects run their steps concurrently, while a callback such as the command line's appends the warnings
|
||||
// to a vector of its own.
|
||||
Print print;
|
||||
Model model;
|
||||
Test::init_print(distinct_objects(), print, model, DynamicPrintConfig::full_print_config());
|
||||
REQUIRE(print.objects().size() == 4);
|
||||
|
||||
std::atomic<int> calls { 0 };
|
||||
std::atomic<int> running { 0 };
|
||||
std::atomic<bool> overlapped { false };
|
||||
print.set_status_callback([&calls, &running, &overlapped](const PrintBase::SlicingStatus &) {
|
||||
++ calls;
|
||||
if (++ running > 1)
|
||||
overlapped = true;
|
||||
// Stay in the callback long enough for the other objects to report meanwhile.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
-- running;
|
||||
});
|
||||
print.process();
|
||||
|
||||
REQUIRE(calls > 1);
|
||||
CHECK_FALSE(overlapped);
|
||||
}
|
||||
|
||||
TEST_CASE("Slicing copies of one object at different scales gives each copy the layers it gets alone", "[Print]")
|
||||
{
|
||||
// The PrintObjects of the copies share the volumes of their ModelObject and run each slicing step together, while
|
||||
// a copy that is the only one printing runs its steps by itself.
|
||||
const std::vector<double> scales { 1., 0.9, 0.8, 0.7 };
|
||||
const DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
Model model;
|
||||
Print print;
|
||||
slice_copies_at_scales(scales, config, model, print);
|
||||
REQUIRE(print.objects().size() == scales.size());
|
||||
|
||||
for (size_t i = 0; i < scales.size(); ++ i) {
|
||||
const double scale = scales[i];
|
||||
INFO("scale " << scale);
|
||||
Model alone_model;
|
||||
Print alone;
|
||||
slice_copies_at_scales(scales, config, alone_model, alone, i);
|
||||
REQUIRE(alone.objects().size() == 1);
|
||||
const auto copy = std::find_if(print.objects().begin(), print.objects().end(), [scale](const PrintObject *object) {
|
||||
return std::abs(object->instances().front().model_instance->get_scaling_factor().x() - scale) < EPSILON;
|
||||
});
|
||||
REQUIRE(copy != print.objects().end());
|
||||
// The copy has walls, so the layers compare extrusions and not only their heights.
|
||||
REQUIRE(std::any_of((*copy)->layers().begin(), (*copy)->layers().end(), [](const Layer *layer) {
|
||||
return ! layer->regions().empty() && ! layer->regions().front()->perimeters.empty();
|
||||
}));
|
||||
CHECK(layer_extrusions(**copy) == layer_extrusions(*alone.objects().front()));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Slicing after the Assembly tool's Parallel turns a part of a scaled object gives the toolpaths of a fresh slice", "[Print]")
|
||||
{
|
||||
// The steps of a crash report: Parallel turns the cylinder, and the GUI applies and validates the changed model.
|
||||
// The GUI processes the print only while the Preview is open, so it may have been processed before or not. The
|
||||
// crash build set the cylinder's rotation only, and either end face can be the one picked.
|
||||
const bool whole_transformation = GENERATE(false, true);
|
||||
const double end_face = GENERATE(1., -1.);
|
||||
const bool processed_before = GENERATE(false, true);
|
||||
INFO((whole_transformation ? "whole transformation" : "rotation only") << ", end face normal " << end_face << " * X, "
|
||||
<< (processed_before ? "processed" : "not processed") << " before");
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({
|
||||
{ "layer_height", "0.2" },
|
||||
{ "initial_layer_print_height", "0.2" },
|
||||
// validate() wants the extruder position reset at each layer for the default relative extrusion.
|
||||
{ "layer_change_gcode", "G92 E0" },
|
||||
});
|
||||
Model model;
|
||||
ModelObject *object = add_cube_and_lying_cylinder(model);
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
REQUIRE_THAT(print.validate().string, Catch::Matchers::Equals(std::string()));
|
||||
if (processed_before)
|
||||
Test::gcode(print);
|
||||
|
||||
turn_cylinder_end_face_down(*object, end_face * Vec3d::UnitX(), whole_transformation);
|
||||
print.apply(model, config);
|
||||
CHECK_THAT(print.validate().string, Catch::Matchers::Equals(std::string()));
|
||||
const std::string sliced = toolpaths(Test::gcode(print));
|
||||
|
||||
// Only what is above the bed prints. Up to the cube's top at 27 mm, that is its 54 x 27 mm and the cylinder's
|
||||
// cross-section: the round cylinder's circle of radius 13.5 mm, alone above the cube up to 40.5 mm, or the stretched
|
||||
// cylinder's ellipse, twice as wide, which ends at 27 mm.
|
||||
REQUIRE(print.objects().size() == 1);
|
||||
const PrintObject &print_object = *print.objects().front();
|
||||
REQUIRE(! print_object.layers().empty());
|
||||
const double cylinder_area = whole_transformation ? PI * 13.5 * 13.5 : PI * 27. * 13.5;
|
||||
CHECK_THAT(print_object.layers().back()->print_z, Catch::Matchers::WithinAbs(whole_transformation ? 40.5 : 27., 0.2));
|
||||
CHECK_THAT(island_area_at(print_object, 13.5), Catch::Matchers::WithinRel(54. * 27. + cylinder_area, 0.01));
|
||||
if (whole_transformation)
|
||||
CHECK_THAT(island_area_at(print_object, 34.), Catch::Matchers::WithinRel(cylinder_area, 0.01));
|
||||
|
||||
Model fresh_model;
|
||||
turn_cylinder_end_face_down(*add_cube_and_lying_cylinder(fresh_model), end_face * Vec3d::UnitX(), whole_transformation);
|
||||
Print fresh;
|
||||
fresh.apply(fresh_model, config);
|
||||
REQUIRE(! sliced.empty());
|
||||
CHECK(sliced == toolpaths(Test::gcode(fresh)));
|
||||
}
|
||||
|
||||
// The AMS inventory is device state that only feeds filament grouping. A changed inventory has to
|
||||
// invalidate the grouping steps, while the refreshes a connected device keeps sending -- the same
|
||||
// trays, volatile metadata, or an empty payload while it reconnects -- must not.
|
||||
|
||||
@@ -1587,3 +1587,37 @@ TEST_CASE("Staggered inner seam stays next to a seam on a hairpin corner", "[Sea
|
||||
// Staggering moves the inner seam about a line width along the wall, never around the loop at random.
|
||||
CHECK_THAT((unscale(placed.first_point()) - unscale(tip)).norm(), Catch::Matchers::WithinAbs(0.0, 1.0));
|
||||
}
|
||||
|
||||
TEST_CASE("Seams are picked on every loop of every object when init() places several objects at once", "[SeamPlacer]")
|
||||
{
|
||||
// Random seams are picked by the workers of each object alone, and they finalize every loop. Sixteen objects make
|
||||
// four tasks of four objects each.
|
||||
const size_t object_count = 16;
|
||||
std::vector<TriangleMesh> meshes;
|
||||
for (size_t i = 0; i < object_count; ++ i)
|
||||
meshes.emplace_back(its_make_cube(10, 10, 1));
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict("seam_position", "random"); // Random needs no visibility ray tracing.
|
||||
Model model;
|
||||
Print print;
|
||||
Test::init_print(std::move(meshes), print, model, config);
|
||||
REQUIRE(print.objects().size() == object_count);
|
||||
print.process();
|
||||
|
||||
SeamPlacer placer;
|
||||
placer.init(print, [] {});
|
||||
|
||||
size_t loops = 0, picked = 0;
|
||||
for (const PrintObject *object : print.objects()) {
|
||||
const std::vector<PrintObjectSeamData::LayerSeams> &layers = placer.m_seam_per_object.at(object).layers;
|
||||
REQUIRE(layers.size() == object->layers().size());
|
||||
for (const PrintObjectSeamData::LayerSeams &layer : layers)
|
||||
for (const SeamPlacerImpl::Perimeter &perimeter : layer.perimeters) {
|
||||
++ loops;
|
||||
if (perimeter.finalized)
|
||||
++ picked;
|
||||
}
|
||||
}
|
||||
REQUIRE(loops >= object_count);
|
||||
CHECK(picked == loops);
|
||||
}
|
||||
@@ -472,6 +472,120 @@ TEST_CASE("Outer-only painted brim ears stay out of model holes", "[SkirtBrim]")
|
||||
CHECK_FALSE(brim_enters_first_layer_hole(print));
|
||||
}
|
||||
|
||||
// A 40 mm wide, 3 mm tall prism whose 70 degree apex is rounded by a 1.5 mm fillet in six chords: the
|
||||
// outline test_brim.cpp builds, as a mesh the pipeline can slice.
|
||||
// Same outline as filleted_triangle_outline(1.5, 6) in the libslic3r test_brim.cpp fixture.
|
||||
static TriangleMesh triangle_with_rounded_apex()
|
||||
{
|
||||
const std::vector<Vec2d> outline{
|
||||
Vec2d(0., 0.), Vec2d(40., 0.), Vec2d(17.6811, 26.5986), Vec2d(17.3195, 26.9111),
|
||||
Vec2d(16.8780, 27.0940), Vec2d(16.4013, 27.1287), Vec2d(15.9380, 27.0117), Vec2d(15.5349, 26.7549),
|
||||
Vec2d(15.2330, 26.3844),
|
||||
};
|
||||
const float height = 3.f;
|
||||
std::vector<Vec3f> vertices;
|
||||
std::vector<Vec3i32> faces;
|
||||
const size_t n = outline.size();
|
||||
for (const Vec2d &p : outline) {
|
||||
vertices.emplace_back(float(p.x()), float(p.y()), 0.f);
|
||||
vertices.emplace_back(float(p.x()), float(p.y()), height);
|
||||
}
|
||||
// Fan from rim vertex 0, so the first triangle is i = 1; starting at 0 would emit a face with a
|
||||
// repeated vertex on both caps.
|
||||
for (size_t i = 1; i + 1 < n; ++ i) {
|
||||
faces.emplace_back(0, int(2 * (i + 1)), int(2 * i)); // bottom cap, facing down
|
||||
faces.emplace_back(1, int(2 * i + 1), int(2 * (i + 1) + 1)); // top cap, facing up
|
||||
}
|
||||
for (size_t i = 0; i < n; ++ i) {
|
||||
const size_t j = (i + 1) % n;
|
||||
faces.emplace_back(int(2 * i), int(2 * j), int(2 * j + 1));
|
||||
faces.emplace_back(int(2 * i), int(2 * j + 1), int(2 * i + 1));
|
||||
}
|
||||
return TriangleMesh(vertices, faces);
|
||||
}
|
||||
|
||||
// One entry per ear. The slicer clips each ear disc against the object, so an ear is a half disc, not a
|
||||
// ring; its axis-aligned bounding box centre still identifies it, and that centre stays valid under the
|
||||
// turns used below. Coordinates are scaled, hence scaled() tolerances.
|
||||
static std::vector<Vec2d> brim_ear_centres(Print &print)
|
||||
{
|
||||
std::vector<Vec2d> centres;
|
||||
for (const auto &kv : print.get_brimMap()) {
|
||||
Polylines paths;
|
||||
kv.second.collect_polylines(paths);
|
||||
for (const Polyline &path : paths) {
|
||||
if (path.points.empty())
|
||||
continue;
|
||||
const BoundingBox box = path.bounding_box();
|
||||
const Vec2d centre = (box.min.cast<double>() + box.max.cast<double>()) * 0.5;
|
||||
if (std::none_of(centres.begin(), centres.end(), [¢re](const Vec2d &e) { return (e - centre).norm() < scaled(1.); }))
|
||||
centres.push_back(centre);
|
||||
}
|
||||
}
|
||||
return centres;
|
||||
}
|
||||
|
||||
// Sorted distances between every pair of ear centres: independent of where the part ends up on the plate.
|
||||
static std::vector<double> ear_centre_distances(const std::vector<Vec2d> ¢res)
|
||||
{
|
||||
std::vector<double> distances;
|
||||
for (size_t i = 0; i < centres.size(); ++ i)
|
||||
for (size_t j = i + 1; j < centres.size(); ++ j)
|
||||
distances.push_back((centres[i] - centres[j]).norm());
|
||||
std::sort(distances.begin(), distances.end());
|
||||
return distances;
|
||||
}
|
||||
|
||||
// A rounded corner must keep its ear whatever the part's orientation: the corner used to be measured after
|
||||
// a decimation anchored on the contour's start vertex, which moves when the object is rotated.
|
||||
TEST_CASE("Mouse ears stay on the same corners when the object rotates", "[SkirtBrim]")
|
||||
{
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({
|
||||
{ "skirt_loops", 0 },
|
||||
{ "brim_type", "brim_ears" },
|
||||
{ "brim_width", 3 },
|
||||
{ "brim_ears_max_angle", 125 },
|
||||
{ "brim_ears_detection_length", 1 },
|
||||
{ "initial_layer_line_width", 0.5 },
|
||||
});
|
||||
|
||||
// Not auto-arranged, so the part is rotated about its own footprint centre and stays on the bed.
|
||||
auto slice_rotated = [&config](double rotation) {
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({ triangle_with_rounded_apex() }, print, model, config, nullptr, false);
|
||||
const Vec3d pivot = model.objects.front()->raw_mesh_bounding_box().center();
|
||||
const Transform3d about_pivot = Geometry::translation_transform(Vec3d(pivot.x(), pivot.y(), 0.)) *
|
||||
Geometry::rotation_transform(Vec3d(0., 0., Geometry::deg2rad(rotation))) *
|
||||
Geometry::translation_transform(Vec3d(-pivot.x(), -pivot.y(), 0.));
|
||||
model.objects.front()->instances.front()->set_transformation(Geometry::Transformation(about_pivot));
|
||||
print.apply(model, config);
|
||||
print.process();
|
||||
return std::make_pair(brim_loop_count(print), brim_ear_centres(print));
|
||||
};
|
||||
|
||||
const std::pair<size_t, std::vector<Vec2d>> base = slice_rotated(0.);
|
||||
REQUIRE(base.first > 0);
|
||||
// Two sharp base corners plus the rounded apex, at every orientation.
|
||||
REQUIRE(base.second.size() == 3);
|
||||
const std::vector<double> base_distances = ear_centre_distances(base.second);
|
||||
|
||||
for (double rotation : { 37., 90., 180. }) {
|
||||
DYNAMIC_SECTION("rotation " << rotation) {
|
||||
const std::pair<size_t, std::vector<Vec2d>> rotated = slice_rotated(rotation);
|
||||
REQUIRE(rotated.second.size() == base.second.size());
|
||||
CHECK(rotated.first == base.first);
|
||||
// The ear positions are compared up to the rigid motion the rotation applies, so the plate
|
||||
// placement the slicer chooses for the rotated footprint does not enter the comparison.
|
||||
const std::vector<double> distances = ear_centre_distances(rotated.second);
|
||||
REQUIRE(distances.size() == base_distances.size());
|
||||
for (size_t i = 0; i < distances.size(); ++ i)
|
||||
CHECK_THAT(distances[i], Catch::Matchers::WithinAbs(base_distances[i], scaled(0.5)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("Skirt has the configured number of loops", "[SkirtBrim]") {
|
||||
GIVEN("20mm cube and default config") {
|
||||
WHEN("skirt_loops is set to 2") {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <initializer_list>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include "libslic3r/Config.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
@@ -20,6 +22,7 @@
|
||||
#include "test_helpers.hpp"
|
||||
#include "libslic3r/ExtrusionEntity.hpp"
|
||||
#include "libslic3r/ExtrusionEntityCollection.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
|
||||
using namespace Slic3r::Test;
|
||||
@@ -339,3 +342,46 @@ TEST_CASE("Tree support reaches every overhang that joins a cluster on the same
|
||||
REQUIRE(2 * under_front > under_back);
|
||||
REQUIRE(2 * under_back > under_front);
|
||||
}
|
||||
|
||||
// Hybrid tree support grows its first layer by raft_first_layer_expansion after the support was clipped to
|
||||
// the bed, so the grown footprint must be clipped again.
|
||||
TEST_CASE("Hybrid tree support first layer expansion stays on the bed", "[TreeSupport][Regression]")
|
||||
{
|
||||
const double bed_max_x = 56.;
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({
|
||||
{ "printable_area", "0x0,56x0,56x100,0x100" },
|
||||
{ "enable_support", 1 },
|
||||
{ "support_type", "tree(auto)" },
|
||||
{ "support_style", "tree_hybrid" },
|
||||
{ "raft_layers", 0 },
|
||||
{ "raft_first_layer_expansion", 5 },
|
||||
{ "layer_height", 0.2 },
|
||||
{ "initial_layer_print_height", 0.2 },
|
||||
});
|
||||
// A block with a ledge that overhangs to 2 mm from the bed's right edge, closer than the expansion.
|
||||
TriangleMesh block = make_cube(20, 40, 8);
|
||||
TriangleMesh ledge = make_cube(9.1, 40, 1.9);
|
||||
block.translate(25.f, 30.f, 0.f);
|
||||
// The ledge overlaps the block rather than touching it; a coplanar join slices ambiguously.
|
||||
ledge.translate(44.9f, 30.f, 6.f);
|
||||
block.merge(ledge);
|
||||
|
||||
Slic3r::Print print;
|
||||
Slic3r::Model model;
|
||||
Slic3r::Test::init_print(std::vector<TriangleMesh>{ std::move(block) }, print, model, config, nullptr, false);
|
||||
print.process();
|
||||
|
||||
const PrintObject *object = print.objects().front();
|
||||
REQUIRE(!object->support_layers().empty());
|
||||
Points first_layer;
|
||||
object->support_layers().front()->support_fills.collect_points(first_layer);
|
||||
REQUIRE(!first_layer.empty());
|
||||
const Point shift = object->instances().front().shift;
|
||||
double max_x = 0.;
|
||||
for (const Point &pt : first_layer)
|
||||
max_x = std::max(max_x, unscale<double>(pt.x() + shift.x()));
|
||||
// Without the expansion the support stops near the ledge's edge at 54 mm, so this shows the expansion ran.
|
||||
REQUIRE(max_x > 55.);
|
||||
CHECK(max_x <= bed_max_x);
|
||||
}
|
||||
@@ -432,6 +432,46 @@ static DynamicPrintConfig tower_estimate_config(const char *wall_type, unsigned
|
||||
{ "raft_layers", "0" } });
|
||||
}
|
||||
|
||||
// The filament a Type 1 tower extrudes for two 20 mm cubes on filaments 1 and 2, so every layer changes
|
||||
// filament, given the process prime volume and the prime volume of each filament.
|
||||
static double type1_tower_filament(const char *prime_volume, const char *filament_prime_volume)
|
||||
{
|
||||
DynamicPrintConfig config = tower_estimate_config("rectangle");
|
||||
config.set_deserialize_strict({ { "wipe_tower_type", "type1" },
|
||||
{ "prime_volume", prime_volume },
|
||||
{ "filament_prime_volume", filament_prime_volume },
|
||||
{ "wipe_tower_x", "120" },
|
||||
{ "wipe_tower_y", "120" } });
|
||||
const std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides = { {}, { { "extruder", "2" } } };
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({ cube(20), cube(20) }, print, model, config, &overrides);
|
||||
const std::string gcode = Slic3r::Test::gcode(print);
|
||||
|
||||
// The filament extruded under the prime tower's role tag.
|
||||
double extruded = 0.;
|
||||
bool in_tower = false;
|
||||
GCodeReader parser;
|
||||
parser.apply_config(print.config());
|
||||
parser.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
|
||||
const std::string_view raw = line.raw();
|
||||
if (raw.rfind(";TYPE:", 0) == 0 || raw.rfind("; FEATURE: ", 0) == 0)
|
||||
in_tower = raw.find("Prime tower") != std::string_view::npos;
|
||||
else if (in_tower && line.extruding(self))
|
||||
extruded += line.dist_E(self);
|
||||
});
|
||||
return extruded;
|
||||
}
|
||||
|
||||
TEST_CASE("The Type 1 tower purges the prime volume of each filament, not the process one", "[WipeTower]")
|
||||
{
|
||||
const double filament_45 = type1_tower_filament("45", "45,45");
|
||||
REQUIRE(filament_45 > 0.);
|
||||
CHECK_THAT(type1_tower_filament("5", "45,45"), Catch::Matchers::WithinRel(filament_45, 1e-6));
|
||||
CHECK_THAT(type1_tower_filament("60", "45,45"), Catch::Matchers::WithinRel(filament_45, 1e-6));
|
||||
CHECK(type1_tower_filament("45", "15,15") < filament_45);
|
||||
}
|
||||
|
||||
TEST_CASE("The tower is sized for the thinnest layer any object on the plate is sliced at", "[WipeTower]")
|
||||
{
|
||||
// The tower has to survive its thinnest layer, so an override finer than the preset drives
|
||||
|
||||
@@ -23,6 +23,8 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_assemble_list.cpp
|
||||
test_bambu_networking.cpp
|
||||
test_belt_brim.cpp
|
||||
# Mouse ear detection is pure contour geometry; the slicing pipeline stays in fff_print.
|
||||
test_brim.cpp
|
||||
test_buildvolume.cpp
|
||||
test_calib.cpp
|
||||
test_clipper_offset.cpp
|
||||
@@ -35,6 +37,7 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_drc.cpp
|
||||
test_gcodereader.cpp
|
||||
test_toolordering_nozzle_group.cpp
|
||||
test_parallel_for_first_error.cpp
|
||||
test_parallel_resolve.cpp
|
||||
test_preset_bundle_loading.cpp
|
||||
test_preset_collection.cpp
|
||||
@@ -45,6 +48,7 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_preset_options.cpp
|
||||
test_edge_grid.cpp
|
||||
test_elephant_foot_compensation.cpp
|
||||
test_expolygon.cpp
|
||||
test_exclusion_volumes.cpp
|
||||
test_fill_corner_smoothing.cpp
|
||||
test_filament_mixer.cpp
|
||||
|
||||
@@ -1553,6 +1553,7 @@ SCENARIO("BBS 3MF round-trips per-plate IMEX state (parallel mode + head filamen
|
||||
plate0->plate_index = 0;
|
||||
plate0->config.set_key_value("imex_parallel_mode", new ConfigOptionString(hostile_mode));
|
||||
plate0->config.set_key_value("imex_head_filament_map", new ConfigOptionString(hostile_hfm));
|
||||
plate0->config.set_key_value("skirt_start_angle", new ConfigOptionFloat(12.5));
|
||||
src_plates.push_back(plate0);
|
||||
|
||||
WHEN("the model is saved to BBS 3MF and loaded back") {
|
||||
@@ -1595,6 +1596,12 @@ SCENARIO("BBS 3MF round-trips per-plate IMEX state (parallel mode + head filamen
|
||||
REQUIRE(hfm_opt != nullptr);
|
||||
REQUIRE(hfm_opt->value == hostile_hfm);
|
||||
}
|
||||
THEN("skirt_start_angle round-trips with its fraction") {
|
||||
REQUIRE(dst_plates.size() >= 1);
|
||||
auto *angle_opt = dst_plates[0]->config.option<ConfigOptionFloat>("skirt_start_angle");
|
||||
REQUIRE(angle_opt != nullptr);
|
||||
REQUIRE_THAT(angle_opt->value, Catch::Matchers::WithinAbs(12.5, 1e-6));
|
||||
}
|
||||
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <catch2/catch_approx.hpp>
|
||||
#include <catch2/generators/catch_generators.hpp>
|
||||
|
||||
#include <igl/Hit.h>
|
||||
#include <cstddef>
|
||||
#include <libslic3r/TriangleMesh.hpp>
|
||||
#include <libslic3r/AABBTreeIndirect.hpp>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/libslic3r.h"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
@@ -63,3 +68,125 @@ TEST_CASE("Building a tree over a box, ray caster and closest query", "[AABBIndi
|
||||
REQUIRE(closest_point.y() == Catch::Approx(0.5));
|
||||
REQUIRE(closest_point.z() == Catch::Approx(1.));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The depth-first, left to right traversal intersect_ray_first_hit() used before it visited the nearest
|
||||
// child first. The ordered traversal must return the very same hit.
|
||||
template<typename RayIntersectorType, typename Scalar>
|
||||
bool reference_first_hit(const RayIntersectorType &ray_intersector, size_t node_idx, Scalar min_t, igl::Hit<float> &hit)
|
||||
{
|
||||
const auto &node = ray_intersector.tree.node(node_idx);
|
||||
if (! AABBTreeIndirect::detail::ray_box_intersect_invdir(ray_intersector.origin, ray_intersector.invdir,
|
||||
node.bbox.template cast<Scalar>(), Scalar(0), min_t))
|
||||
return false;
|
||||
if (node.is_leaf()) {
|
||||
auto face = ray_intersector.faces[node.idx];
|
||||
double t, u, v;
|
||||
if (AABBTreeIndirect::detail::intersect_triangle(ray_intersector.origin, ray_intersector.dir,
|
||||
ray_intersector.vertices[face(0)], ray_intersector.vertices[face(1)],
|
||||
ray_intersector.vertices[face(2)], t, u, v, ray_intersector.eps) &&
|
||||
t > 0.) {
|
||||
hit = igl::Hit<float>{int(node.idx), -1, float(u), float(v), float(t)};
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
igl::Hit<float> left_hit;
|
||||
igl::Hit<float> right_hit;
|
||||
bool left_ret = reference_first_hit(ray_intersector, node_idx * 2 + 1, min_t, left_hit);
|
||||
if (left_ret && left_hit.t < min_t) {
|
||||
min_t = left_hit.t;
|
||||
hit = left_hit;
|
||||
} else
|
||||
left_ret = false;
|
||||
bool right_ret = reference_first_hit(ray_intersector, node_idx * 2 + 2, min_t, right_hit);
|
||||
if (right_ret && right_hit.t < min_t)
|
||||
hit = right_hit;
|
||||
else
|
||||
right_ret = false;
|
||||
return left_ret || right_ret;
|
||||
}
|
||||
|
||||
// Unit cube faces split into an n x n grid of triangles: many coplanar triangles sharing edges, so rays
|
||||
// through edges and vertices hit several triangles at the same distance.
|
||||
indexed_triangle_set grid_cube(int n)
|
||||
{
|
||||
indexed_triangle_set its;
|
||||
for (int axis = 0; axis < 3; ++axis)
|
||||
for (int side = 0; side < 2; ++side)
|
||||
for (int i = 0; i < n; ++i)
|
||||
for (int j = 0; j < n; ++j) {
|
||||
auto vertex = [&](int a, int b) {
|
||||
Vec3f p;
|
||||
p[axis] = float(side);
|
||||
p[(axis + 1) % 3] = float(a) / n;
|
||||
p[(axis + 2) % 3] = float(b) / n;
|
||||
its.vertices.emplace_back(p);
|
||||
return int(its.vertices.size()) - 1;
|
||||
};
|
||||
int v0 = vertex(i, j), v1 = vertex(i + 1, j), v2 = vertex(i + 1, j + 1), v3 = vertex(i, j + 1);
|
||||
its.indices.emplace_back(v0, v1, v2);
|
||||
its.indices.emplace_back(v0, v2, v3);
|
||||
}
|
||||
return its;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("First ray hit matches the depth-first search", "[AABBIndirect]")
|
||||
{
|
||||
std::mt19937 rng(42);
|
||||
std::uniform_real_distribution<double> coord(-1.5, 2.5);
|
||||
std::uniform_real_distribution<double> unit(-1., 1.);
|
||||
|
||||
indexed_triangle_set soup;
|
||||
for (int i = 0; i < 300; ++i) {
|
||||
Vec3f a(coord(rng), coord(rng), coord(rng));
|
||||
int base = int(soup.vertices.size());
|
||||
soup.vertices.emplace_back(a);
|
||||
soup.vertices.emplace_back(a + Vec3f(unit(rng), unit(rng), unit(rng)) * 0.5f);
|
||||
soup.vertices.emplace_back(a + Vec3f(unit(rng), unit(rng), unit(rng)) * 0.5f);
|
||||
soup.indices.emplace_back(base, base + 1, base + 2);
|
||||
}
|
||||
const indexed_triangle_set mesh = GENERATE_COPY(grid_cube(8), its_make_sphere(1., PI / 20.), soup);
|
||||
|
||||
const auto tree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(mesh.vertices, mesh.indices);
|
||||
REQUIRE(! tree.empty());
|
||||
|
||||
// Directions with zero components make the inverse direction infinite. Origins on the grid, aimed
|
||||
// along the axes or the diagonals, put the rays through shared edges and vertices.
|
||||
std::vector<std::pair<Vec3d, Vec3d>> rays;
|
||||
const Vec3d axis_dirs[] = {Vec3d::UnitX(), -Vec3d::UnitX(), Vec3d::UnitY(), -Vec3d::UnitY(), Vec3d::UnitZ(), -Vec3d::UnitZ(),
|
||||
Vec3d(1., 1., 0.).normalized(), Vec3d(1., 1., 1.).normalized(), Vec3d(-1., 0., 1.).normalized()};
|
||||
for (int i = -2; i <= 10; ++i)
|
||||
for (int j = -2; j <= 10; ++j)
|
||||
for (const Vec3d &dir : axis_dirs)
|
||||
rays.emplace_back(Vec3d(i / 8., j / 8., -1.) - dir * 2., dir);
|
||||
// Random rays aimed at random mesh vertices, so that most of them hit.
|
||||
std::uniform_int_distribution<size_t> vertex_idx(0, mesh.vertices.size() - 1);
|
||||
for (int i = 0; i < 20000; ++i) {
|
||||
const Vec3d origin(coord(rng), coord(rng), coord(rng));
|
||||
const Vec3d target = mesh.vertices[vertex_idx(rng)].cast<double>() + Vec3d(unit(rng), unit(rng), unit(rng)) * 0.01;
|
||||
if ((target - origin).squaredNorm() > 1e-6)
|
||||
rays.emplace_back(origin, (target - origin).normalized());
|
||||
}
|
||||
|
||||
size_t hits = 0;
|
||||
size_t mismatches = 0;
|
||||
for (const auto &[origin, dir] : rays) {
|
||||
igl::Hit<float> hit{-1, -1, 0.f, 0.f, 0.f};
|
||||
const bool found = AABBTreeIndirect::intersect_ray_first_hit(mesh.vertices, mesh.indices, tree, origin, dir, hit);
|
||||
|
||||
const auto ray_intersector = AABBTreeIndirect::detail::RayIntersector<stl_vertex, stl_triangle_vertex_indices, AABBTreeIndirect::Tree<3, float>, Vec3d>{
|
||||
mesh.vertices, mesh.indices, tree, origin, dir, Vec3d(dir.cwiseInverse()), 0.000001};
|
||||
igl::Hit<float> expected{-1, -1, 0.f, 0.f, 0.f};
|
||||
const bool expected_found = reference_first_hit(ray_intersector, size_t(0), std::numeric_limits<double>::infinity(), expected);
|
||||
|
||||
hits += found;
|
||||
if (found != expected_found || (found && (hit.id != expected.id || hit.t != expected.t || hit.u != expected.u || hit.v != expected.v)))
|
||||
++mismatches;
|
||||
}
|
||||
CHECK(hits > rays.size() / 2);
|
||||
CHECK(mismatches == 0);
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
#include <algorithm>
|
||||
#include <catch2/catch_all.hpp>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdlib>
|
||||
#include <initializer_list>
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
|
||||
#include "catch2/catch_test_macros.hpp"
|
||||
#include "catch2/matchers/catch_matchers.hpp"
|
||||
#include "catch2/matchers/catch_matchers_floating_point.hpp"
|
||||
#include "libslic3r/Brim.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/Polygon.hpp"
|
||||
#include "libslic3r/libslic3r.h"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
namespace {
|
||||
|
||||
// Ear points come back in no particular order, so compare them as a set.
|
||||
bool same_point_set(const Points &a, const Points &b, coord_t tolerance)
|
||||
{
|
||||
if (a.size() != b.size())
|
||||
return false;
|
||||
std::vector<bool> matched(b.size(), false);
|
||||
for (const Point &p : a) {
|
||||
bool found = false;
|
||||
for (size_t i = 0; i < b.size() && ! found; ++ i) {
|
||||
if (! matched[i] && std::abs(p.x() - b[i].x()) <= tolerance && std::abs(p.y() - b[i].y()) <= tolerance) {
|
||||
matched[i] = true;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (! found)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool contains_point(const Points &points, const Point &expected, coord_t tolerance)
|
||||
{
|
||||
return std::any_of(points.begin(), points.end(), [&expected, tolerance](const Point &p) {
|
||||
return std::abs(p.x() - expected.x()) <= tolerance && std::abs(p.y() - expected.y()) <= tolerance;
|
||||
});
|
||||
}
|
||||
|
||||
bool is_finite(const Point &p)
|
||||
{
|
||||
return std::isfinite(unscale<double>(p.x())) && std::isfinite(unscale<double>(p.y()));
|
||||
}
|
||||
|
||||
// Arc that replaces `corner` between `prev` and `next`, as `segments` chords of the given radius, in mm.
|
||||
std::vector<Vec2d> fillet_arc(const Vec2d &prev, const Vec2d &corner, const Vec2d &next, double radius, int segments)
|
||||
{
|
||||
const Vec2d to_prev = (prev - corner).normalized();
|
||||
const Vec2d to_next = (next - corner).normalized();
|
||||
const double half = std::acos(std::clamp(to_prev.dot(to_next), -1., 1.)) / 2.;
|
||||
const double tangent = radius / std::tan(half);
|
||||
const Vec2d start = corner + to_prev * tangent;
|
||||
const Vec2d end = corner + to_next * tangent;
|
||||
const Vec2d centre = corner + (to_prev + to_next).normalized() * (radius / std::sin(half));
|
||||
const double from = std::atan2(start.y() - centre.y(), start.x() - centre.x());
|
||||
const double to = std::atan2(end.y() - centre.y(), end.x() - centre.x());
|
||||
double sweep = to - from;
|
||||
while (sweep > PI)
|
||||
sweep -= 2. * PI;
|
||||
while (sweep < -PI)
|
||||
sweep += 2. * PI;
|
||||
std::vector<Vec2d> arc;
|
||||
for (int i = 0; i <= segments; ++ i) {
|
||||
const double angle = from + sweep * i / segments;
|
||||
arc.emplace_back(centre.x() + radius * std::cos(angle), centre.y() + radius * std::sin(angle));
|
||||
}
|
||||
return arc;
|
||||
}
|
||||
|
||||
// The arc that fillet_arc puts at a corner: its middle point in mm, and the angle it sweeps in radians.
|
||||
struct Fillet {
|
||||
Vec2d midpoint;
|
||||
double sweep;
|
||||
};
|
||||
|
||||
Fillet fillet_geometry(const Vec2d &prev, const Vec2d &corner, const Vec2d &next, double radius)
|
||||
{
|
||||
const Vec2d to_prev = (prev - corner).normalized();
|
||||
const Vec2d to_next = (next - corner).normalized();
|
||||
const double half = std::acos(std::clamp(to_prev.dot(to_next), -1., 1.)) / 2.;
|
||||
const Vec2d midpoint = corner + (to_prev + to_next).normalized() * (radius / std::sin(half) - radius);
|
||||
return Fillet{ midpoint, PI - 2. * half };
|
||||
}
|
||||
|
||||
// A closed outline plus the geometry of the arc that replaced each of its corners.
|
||||
struct FilletedOutline {
|
||||
std::vector<Vec2d> outline;
|
||||
std::vector<Fillet> corners;
|
||||
};
|
||||
|
||||
// Replace every corner of the closed `corners` polygon with an arc of `radius` in `chords` chords.
|
||||
FilletedOutline filleted_outline(const std::vector<Vec2d> &corners, double radius, int chords)
|
||||
{
|
||||
FilletedOutline filleted;
|
||||
filleted.outline.reserve(corners.size() * size_t(chords + 1));
|
||||
filleted.corners.reserve(corners.size());
|
||||
for (size_t i = 0; i < corners.size(); ++ i) {
|
||||
const Vec2d &prev = corners[(i + corners.size() - 1) % corners.size()];
|
||||
const Vec2d &next = corners[(i + 1) % corners.size()];
|
||||
const std::vector<Vec2d> arc = fillet_arc(prev, corners[i], next, radius, chords);
|
||||
filleted.outline.insert(filleted.outline.end(), arc.begin(), arc.end());
|
||||
filleted.corners.push_back(fillet_geometry(prev, corners[i], next, radius));
|
||||
}
|
||||
return filleted;
|
||||
}
|
||||
|
||||
// 40 mm wide triangle with a 70 degree apex rounded by a fillet of `radius` in `chords` chords, counter-clockwise.
|
||||
// The 60 / 50 degree base corners are deliberately unequal: a mirror symmetric outline ties the fillet's
|
||||
// two sharpest vertices exactly, and the tie is then broken by vertex index.
|
||||
struct FilletedTriangle {
|
||||
std::vector<Vec2d> outline;
|
||||
Fillet apex;
|
||||
};
|
||||
|
||||
FilletedTriangle filleted_triangle(double radius, int chords)
|
||||
{
|
||||
const Vec2d a(0., 0.);
|
||||
const Vec2d b(40., 0.);
|
||||
const double to_apex = 40. * std::sin(50. * PI / 180.) / std::sin(70. * PI / 180.);
|
||||
const Vec2d apex = a + Vec2d(std::cos(60. * PI / 180.), std::sin(60. * PI / 180.)) * to_apex;
|
||||
const std::vector<Vec2d> arc = fillet_arc(a, apex, b, radius, chords);
|
||||
std::vector<Vec2d> outline{ a, b };
|
||||
outline.insert(outline.end(), arc.rbegin(), arc.rend());
|
||||
return { outline, fillet_geometry(a, apex, b, radius) };
|
||||
}
|
||||
|
||||
std::vector<Vec2d> filleted_triangle_outline(double radius, int chords)
|
||||
{
|
||||
return filleted_triangle(radius, chords).outline;
|
||||
}
|
||||
|
||||
// Axis-aligned CCW square (0, 0)..(side, side) with every corner filleted.
|
||||
FilletedOutline filleted_square_outline(double side, double radius, int chords)
|
||||
{
|
||||
return filleted_outline({ Vec2d(0., 0.), Vec2d(side, 0.), Vec2d(side, side), Vec2d(0., side) }, radius, chords);
|
||||
}
|
||||
|
||||
// Regular polygon with `sides` vertices on a circle of the given radius, counter-clockwise.
|
||||
std::vector<Vec2d> regular_polygon_outline(int sides, double radius)
|
||||
{
|
||||
std::vector<Vec2d> outline;
|
||||
outline.reserve(size_t(sides));
|
||||
for (int i = 0; i < sides; ++ i) {
|
||||
const double angle = 2. * PI * i / sides;
|
||||
outline.emplace_back(radius * std::cos(angle), radius * std::sin(angle));
|
||||
}
|
||||
return outline;
|
||||
}
|
||||
|
||||
// Regular `chords`-gon approximating a circle of the given radius.
|
||||
std::vector<Vec2d> circle_outline(double radius, int chords)
|
||||
{
|
||||
return regular_polygon_outline(chords, radius);
|
||||
}
|
||||
|
||||
// Half disc of `radius`: a flat side and a `chords`-chord semicircular wall meeting it at two right angles.
|
||||
std::vector<Vec2d> half_disc_outline(double radius, int chords)
|
||||
{
|
||||
std::vector<Vec2d> outline;
|
||||
outline.reserve(size_t(chords) + 1);
|
||||
outline.emplace_back(-radius, 0.);
|
||||
for (int i = 1; i <= chords; ++ i) {
|
||||
const double angle = PI + PI * i / chords;
|
||||
outline.emplace_back(radius * std::cos(angle), radius * std::sin(angle));
|
||||
}
|
||||
return outline;
|
||||
}
|
||||
|
||||
// Ellipse with semi-axes `a` and `b` in `chords` chords.
|
||||
std::vector<Vec2d> ellipse_outline(double a, double b, int chords)
|
||||
{
|
||||
std::vector<Vec2d> outline;
|
||||
outline.reserve(size_t(chords));
|
||||
for (int i = 0; i < chords; ++ i) {
|
||||
const double angle = 2. * PI * i / chords;
|
||||
outline.emplace_back(a * std::cos(angle), b * std::sin(angle));
|
||||
}
|
||||
return outline;
|
||||
}
|
||||
|
||||
// Mean of the outline's vertices, in mm.
|
||||
Vec2d outline_centroid(const std::vector<Vec2d> &points)
|
||||
{
|
||||
Vec2d sum = Vec2d::Zero();
|
||||
for (const Vec2d &p : points)
|
||||
sum += p;
|
||||
return sum / double(points.size());
|
||||
}
|
||||
|
||||
std::vector<Vec2d> to_mm(const Points &points)
|
||||
{
|
||||
std::vector<Vec2d> out;
|
||||
out.reserve(points.size());
|
||||
for (const Point &p : points)
|
||||
out.emplace_back(unscale<double>(p.x()), unscale<double>(p.y()));
|
||||
return out;
|
||||
}
|
||||
|
||||
// Sorted distances between every pair of points, in mm: unchanged by a rigid motion of the whole set.
|
||||
std::vector<double> pairwise_distances(const std::vector<Vec2d> &points)
|
||||
{
|
||||
std::vector<double> distances;
|
||||
distances.reserve(points.size() * (points.size() - 1) / 2);
|
||||
for (size_t i = 0; i < points.size(); ++ i)
|
||||
for (size_t j = i + 1; j < points.size(); ++ j)
|
||||
distances.push_back((points[i] - points[j]).norm());
|
||||
std::sort(distances.begin(), distances.end());
|
||||
return distances;
|
||||
}
|
||||
|
||||
// Ears sitting on one rounded corner: within half a chord of the arc's midpoint, which is the closest any
|
||||
// point of the fillet gets to an ear placed on it.
|
||||
size_t ears_on_corner(const Points &ears, const Fillet &corner, double radius, int chords)
|
||||
{
|
||||
const Point midpoint = Point::new_scale(corner.midpoint);
|
||||
const coord_t tolerance = coord_t(scale_(radius + 0.5 * radius * corner.sweep / chords));
|
||||
return size_t(std::count_if(ears.begin(), ears.end(), [&midpoint, tolerance](const Point &ear) {
|
||||
return (ear - midpoint).cast<double>().norm() <= double(tolerance);
|
||||
}));
|
||||
}
|
||||
|
||||
// A quarter turn about the origin is exact in scaled integer coordinates.
|
||||
Point rotated_quarter_turns(const Point &p, int quarter)
|
||||
{
|
||||
Point rotated = p;
|
||||
for (int i = 0; i < quarter; ++ i)
|
||||
rotated = Point(-rotated.y(), rotated.x());
|
||||
return rotated;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// The detection must read the corner, not the contour's start vertex: a decimation anchored on the first
|
||||
// vertex used to place an ear on a rounded corner for some vertex orders and not for others.
|
||||
TEST_CASE("Brim ear detection is independent of the contour start vertex", "[Brim][Regression]")
|
||||
{
|
||||
struct Case { double radius; int chords; };
|
||||
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
for (const Case &c : { Case{ 1.5, 6 }, Case{ 2.0, 12 }, Case{ 5.0, 12 } }) {
|
||||
DYNAMIC_SECTION("fillet " << c.radius << " mm in " << c.chords << " chords") {
|
||||
const Points contour = Polygon::new_scale(filleted_triangle_outline(c.radius, c.chords)).points;
|
||||
const Points found = make_brim_ear_points(Polygon(contour), detection, 125., true);
|
||||
// Two sharp base corners plus the rounded apex.
|
||||
REQUIRE(found.size() == 3);
|
||||
|
||||
for (size_t shift = 1; shift < contour.size(); ++ shift) {
|
||||
Points shifted;
|
||||
shifted.reserve(contour.size());
|
||||
std::rotate_copy(contour.begin(), contour.begin() + shift, contour.end(), std::back_inserter(shifted));
|
||||
const Points ears = make_brim_ear_points(Polygon(shifted), detection, 125., true);
|
||||
CHECK(ears.size() == found.size());
|
||||
CHECK(same_point_set(ears, found, 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Brim ear detection rotates with the contour", "[Brim]")
|
||||
{
|
||||
const std::vector<Vec2d> outline = filleted_triangle_outline(1.5, 6);
|
||||
const Points contour = Polygon::new_scale(outline).points;
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
const Points base = make_brim_ear_points(Polygon(contour), detection, 125., true);
|
||||
REQUIRE(base.size() == 3);
|
||||
|
||||
for (int quarter : { 1, 2, 3 }) {
|
||||
DYNAMIC_SECTION("quarter turns " << quarter) {
|
||||
Points rotated_contour;
|
||||
rotated_contour.reserve(contour.size());
|
||||
for (const Point &p : contour)
|
||||
rotated_contour.push_back(rotated_quarter_turns(p, quarter));
|
||||
Points expected;
|
||||
expected.reserve(base.size());
|
||||
for (const Point &p : base)
|
||||
expected.push_back(rotated_quarter_turns(p, quarter));
|
||||
|
||||
const Points ears = make_brim_ear_points(Polygon(rotated_contour), detection, 125., true);
|
||||
CHECK(ears.size() == base.size());
|
||||
CHECK(same_point_set(ears, expected, 2));
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("37 degrees") {
|
||||
// 37 degrees is not exact in scaled integer coordinates, so compare ear distances instead of positions.
|
||||
const Vec2d centre = outline_centroid(outline);
|
||||
const double angle = 37. * PI / 180.;
|
||||
const auto rotate = [¢re, angle](const Vec2d &p) -> Vec2d {
|
||||
const Vec2d d(p.x() - centre.x(), p.y() - centre.y());
|
||||
return Vec2d(centre.x() + d.x() * std::cos(angle) - d.y() * std::sin(angle),
|
||||
centre.y() + d.x() * std::sin(angle) + d.y() * std::cos(angle));
|
||||
};
|
||||
|
||||
Points rotated_contour;
|
||||
rotated_contour.reserve(outline.size());
|
||||
for (const Vec2d &p : outline)
|
||||
rotated_contour.push_back(Point::new_scale(rotate(p)));
|
||||
|
||||
std::vector<Vec2d> expected = to_mm(base);
|
||||
for (Vec2d &p : expected)
|
||||
p = rotate(p);
|
||||
|
||||
const Points ears = make_brim_ear_points(Polygon(rotated_contour), detection, 125., true);
|
||||
const std::vector<double> found_distances = pairwise_distances(to_mm(ears));
|
||||
const std::vector<double> expected_distances = pairwise_distances(expected);
|
||||
REQUIRE(found_distances.size() == expected_distances.size());
|
||||
for (size_t i = 0; i < found_distances.size(); ++ i)
|
||||
CHECK_THAT(found_distances[i], Catch::Matchers::WithinAbs(expected_distances[i], 0.01));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("A rounded apex carries a single brim ear", "[Brim]")
|
||||
{
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
|
||||
for (double radius : { 0.5, 1.5, 3.0, 5.0 }) {
|
||||
for (int chords : { 3, 6, 12, 24 }) {
|
||||
DYNAMIC_SECTION("fillet " << radius << " mm in " << chords << " chords") {
|
||||
const FilletedTriangle triangle = filleted_triangle(radius, chords);
|
||||
const Points ears = make_brim_ear_points(Polygon::new_scale(triangle.outline), detection, 125., true);
|
||||
// Two sharp base corners plus the rounded apex.
|
||||
REQUIRE(ears.size() == 3);
|
||||
|
||||
// A fillet is one corner, so exactly one ear sits on it, never a row along its chords.
|
||||
CHECK(ears_on_corner(ears, triangle.apex, radius, chords) == 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("A square keeps one brim ear per rounded corner", "[Brim][Regression]")
|
||||
{
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
const double radius = 5.;
|
||||
const int chords = 12;
|
||||
const FilletedOutline square = filleted_square_outline(40., radius, chords);
|
||||
const Points ears = make_brim_ear_points(Polygon::new_scale(square.outline), detection, 125., true);
|
||||
|
||||
// Four 90 degree corners, each rounded by one fillet: four ears, not one per chord.
|
||||
REQUIRE(ears.size() == 4);
|
||||
|
||||
for (const Fillet &corner : square.corners)
|
||||
CHECK(ears_on_corner(ears, corner, radius, chords) == 1);
|
||||
}
|
||||
|
||||
// A part whose fillets take up most of the perimeter: the ladder stops at its cap of perimeter/8, so the
|
||||
// saturation lookahead already reaches the neighbouring corner, and twice the window reaches the
|
||||
// neighbouring ear. Detection used to return two ears at some orientations and none at others.
|
||||
TEST_CASE("A small part keeps one brim ear per rounded corner", "[Brim][Regression]")
|
||||
{
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
|
||||
SECTION("12 mm square with 4 mm fillets") {
|
||||
const double radius = 4.;
|
||||
const int chords = 12;
|
||||
const FilletedOutline square = filleted_square_outline(12., radius, chords);
|
||||
const Points ears = make_brim_ear_points(Polygon::new_scale(square.outline), detection, 125., true);
|
||||
|
||||
REQUIRE(ears.size() == 4);
|
||||
for (const Fillet &corner : square.corners)
|
||||
CHECK(ears_on_corner(ears, corner, radius, chords) == 1);
|
||||
}
|
||||
|
||||
SECTION("10 mm hexagon with 2 mm fillets") {
|
||||
const double radius = 2.;
|
||||
const int chords = 6;
|
||||
const FilletedOutline hexagon = filleted_outline(regular_polygon_outline(6, 10.), radius, chords);
|
||||
const Points ears = make_brim_ear_points(Polygon::new_scale(hexagon.outline), detection, 125., true);
|
||||
|
||||
REQUIRE(ears.size() == 6);
|
||||
for (const Fillet &corner : hexagon.corners)
|
||||
CHECK(ears_on_corner(ears, corner, radius, chords) == 1);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("A smooth contour has no brim ears", "[Brim]")
|
||||
{
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
|
||||
// A circle's turn is spread evenly, so no vertex turns past the threshold at any measurement scale.
|
||||
CHECK(make_brim_ear_points(Polygon::new_scale(circle_outline(5., 48)), detection, 125., true).empty());
|
||||
// A 24-gon is as smooth as the detector can tell at the default 1 mm detection length.
|
||||
CHECK(make_brim_ear_points(Polygon::new_scale(regular_polygon_outline(24, 10.)), detection, 125., true).empty());
|
||||
}
|
||||
|
||||
// A corner that meets a curved wall is one corner. A point on the curve accepts only once its window reaches
|
||||
// that corner, so its candidate is the same corner seen from further away; keeping it puts a second ear 2 to
|
||||
// 7 mm from the first.
|
||||
TEST_CASE("A corner next to a curve carries one brim ear", "[Brim][Regression]")
|
||||
{
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
|
||||
for (double radius : { 5., 10. }) {
|
||||
DYNAMIC_SECTION("half disc of " << radius << " mm") {
|
||||
const Points ears = make_brim_ear_points(Polygon::new_scale(half_disc_outline(radius, 64)),
|
||||
detection, 125., true);
|
||||
// Two right angles, one at each end of the flat side, and nothing on the semicircle between them.
|
||||
REQUIRE(ears.size() == 2);
|
||||
for (const Point &ear : ears) {
|
||||
CHECK_THAT(std::abs(unscale<double>(ear.x())), Catch::Matchers::WithinAbs(radius, 1.));
|
||||
CHECK_THAT(unscale<double>(ear.y()), Catch::Matchers::WithinAbs(0., 1.));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int chords : { 64, 128 }) {
|
||||
DYNAMIC_SECTION("60 x 10 mm ellipse in " << chords << " chords") {
|
||||
const Points ears = make_brim_ear_points(Polygon::new_scale(ellipse_outline(30., 5., chords)),
|
||||
detection, 125., true);
|
||||
// One ear at each end of the long axis, none on the flanks.
|
||||
REQUIRE(ears.size() == 2);
|
||||
for (const Point &ear : ears)
|
||||
CHECK(std::abs(unscale<double>(ear.x())) > 25.);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("A pentagon keeps one brim ear per rounded corner", "[Brim][Regression]")
|
||||
{
|
||||
// Side 20 mm: circumradius 20 / (2 sin 36 degrees), every corner rounded by 1 mm in six chords.
|
||||
const std::vector<Vec2d> corners = regular_polygon_outline(5, 20. / (2. * std::sin(PI / 5.)));
|
||||
const FilletedOutline filleted = filleted_outline(corners, 1., 6);
|
||||
const Points ears = make_brim_ear_points(Polygon::new_scale(filleted.outline),
|
||||
coord_t(scale_(1.0)), 125., true);
|
||||
|
||||
// Five 72 degree corners: a decimation that collapsed the outline to a triangle would report three.
|
||||
REQUIRE(ears.size() == 5);
|
||||
}
|
||||
|
||||
TEST_CASE("Zero detection length still finds the sharp corners", "[Brim]")
|
||||
{
|
||||
const std::vector<Vec2d> outline = filleted_triangle_outline(1.5, 6);
|
||||
const Points contour = Polygon::new_scale(outline).points;
|
||||
const Points ears = make_brim_ear_points(Polygon(contour), 0, 125., true);
|
||||
|
||||
// With immediate neighbours only, the two base corners turn far past the threshold and the fillet does not.
|
||||
REQUIRE(ears.size() == 2);
|
||||
CHECK(contains_point(ears, contour[0], 2));
|
||||
CHECK(contains_point(ears, contour[1], 2));
|
||||
for (const Point &ear : ears)
|
||||
CHECK(is_finite(ear));
|
||||
}
|
||||
|
||||
TEST_CASE("A concave notch takes brim ears on an inner contour", "[Brim]")
|
||||
{
|
||||
// 40 x 40 mm plate with a 10 x 10 mm notch in its top edge, given in the winding a hole is stored in.
|
||||
const std::vector<Vec2d> stored_outline{
|
||||
Vec2d(0., 40.), Vec2d(20., 40.), Vec2d(20., 30.), Vec2d(30., 30.),
|
||||
Vec2d(30., 40.), Vec2d(40., 40.), Vec2d(40., 0.), Vec2d(0., 0.),
|
||||
};
|
||||
Polygons holes{ Polygon::new_scale(stored_outline) };
|
||||
// outer_inner_brim_area reverses hole contours before its concave pass, so the test does the same.
|
||||
polygons_reverse(holes);
|
||||
const Polygon &contour = holes.front();
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
|
||||
const auto on_notch_floor = [](const Point &ear) {
|
||||
const double x = unscale<double>(ear.x());
|
||||
const double y = unscale<double>(ear.y());
|
||||
return std::abs(y - 30.) < 1. && x > 19. && x < 31.;
|
||||
};
|
||||
|
||||
const Points concave_ears = make_brim_ear_points(contour, detection, 125., false);
|
||||
REQUIRE(! concave_ears.empty());
|
||||
CHECK(std::all_of(concave_ears.begin(), concave_ears.end(), on_notch_floor));
|
||||
|
||||
const Points convex_ears = make_brim_ear_points(contour, detection, 125., true);
|
||||
CHECK(! convex_ears.empty());
|
||||
CHECK(std::none_of(convex_ears.begin(), convex_ears.end(), on_notch_floor));
|
||||
}
|
||||
|
||||
TEST_CASE("A clockwise contour keeps brim ear detection well defined", "[Brim]")
|
||||
{
|
||||
Points contour = Polygon::new_scale(filleted_triangle_outline(1.5, 6)).points;
|
||||
std::reverse(contour.begin(), contour.end());
|
||||
|
||||
Points ears;
|
||||
REQUIRE_NOTHROW(ears = make_brim_ear_points(Polygon(contour), coord_t(scale_(1.0)), 125., true));
|
||||
// The convexity predicate is winding sensitive, so a reversed outer contour has no convex corner left.
|
||||
CHECK(ears.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("Brim ear max angle excludes a corner at exactly the bound", "[Brim]")
|
||||
{
|
||||
// A rectangle's corners turn by exactly 90 degrees.
|
||||
const std::vector<Vec2d> rectangle{ Vec2d(0., 0.), Vec2d(40., 0.), Vec2d(40., 20.), Vec2d(0., 20.) };
|
||||
const Polygon contour = Polygon::new_scale(rectangle);
|
||||
const coord_t detection = coord_t(scale_(1.0));
|
||||
|
||||
CHECK(make_brim_ear_points(contour, detection, 91., true).size() == 4);
|
||||
CHECK(make_brim_ear_points(contour, detection, 90., true).empty());
|
||||
CHECK(make_brim_ear_points(contour, detection, 89., true).empty());
|
||||
}
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user