diff --git a/CMakeLists.txt b/CMakeLists.txt
index 48ad5033e0..1d4576c37d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -35,6 +35,11 @@ option(SLIC3R_ASAN "Enable ASan on Clang and GCC" 0)
set(SLIC3R_GTK "2" CACHE STRING "GTK version to use with wxWidgets on Linux")
+if (APPLE)
+ set(CMAKE_FIND_FRAMEWORK LAST)
+ set(CMAKE_FIND_APPBUNDLE LAST)
+endif ()
+
# Proposal for C++ unit tests and sandboxes
option(SLIC3R_BUILD_SANDBOXES "Build development sandboxes" OFF)
option(SLIC3R_BUILD_TESTS "Build unit tests" ON)
@@ -386,7 +391,7 @@ if (NOT EXPAT_FOUND)
set(EXPAT_LIBRARIES expat)
endif ()
-find_package(PNG)
+find_package(PNG REQUIRED)
find_package(OpenGL REQUIRED)
diff --git a/deps/deps-linux.cmake b/deps/deps-linux.cmake
index 3ad3cca64f..ae972327f8 100644
--- a/deps/deps-linux.cmake
+++ b/deps/deps-linux.cmake
@@ -3,10 +3,11 @@ set(DEP_CMAKE_OPTS "-DCMAKE_POSITION_INDEPENDENT_CODE=ON")
include("deps-unix-common.cmake")
-find_package(PNG QUIET)
-if (NOT PNG_FOUND)
- message(WARNING "No PNG dev package found in system, building static library. You should install the system package.")
-endif ()
+# Some Linuxes may have very old libpng, so it's best to bundle it instead of relying on the system version.
+# find_package(PNG QUIET)
+# if (NOT PNG_FOUND)
+# message(WARNING "No PNG dev package found in system, building static library. You should install the system package.")
+# endif ()
#TODO UDEV
diff --git a/doc/How to build - Mac OS.md b/doc/How to build - Mac OS.md
index 082c560b7a..bab40ea265 100644
--- a/doc/How to build - Mac OS.md
+++ b/doc/How to build - Mac OS.md
@@ -79,3 +79,29 @@ This is set in the property list file
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Info.plist
To remove the limitation, simply delete the key `MinimumSDKVersion` from that file.
+
+
+# TL; DR
+
+Works on a fresh installation of MacOS Catalina 10.15.6
+
+- Install [brew](https://brew.sh/):
+- Open Terminal
+
+- Enter:
+
+```brew install cmake git gettext
+brew update
+brew upgrade
+git clone https://github.com/prusa3d/PrusaSlicer/
+cd PrusaSlicer/deps
+mkdir build
+cd build
+cmake ..
+make
+cd ../..
+mkdir build
+cd build
+cmake .. -DCMAKE_PREFIX_PATH="$PWD/../deps/build/destdir/usr/local"
+make
+src/prusa-slicer
diff --git a/resources/icons/PrusaSlicer-gcodeviewer.ico b/resources/icons/PrusaSlicer-gcodeviewer.ico
new file mode 100644
index 0000000000..2c9272369f
Binary files /dev/null and b/resources/icons/PrusaSlicer-gcodeviewer.ico differ
diff --git a/resources/icons/PrusaSlicer-gcodeviewer_128px.png b/resources/icons/PrusaSlicer-gcodeviewer_128px.png
new file mode 100644
index 0000000000..d8e3e438be
Binary files /dev/null and b/resources/icons/PrusaSlicer-gcodeviewer_128px.png differ
diff --git a/resources/icons/PrusaSlicer-gcodeviewer_192px.png b/resources/icons/PrusaSlicer-gcodeviewer_192px.png
new file mode 100644
index 0000000000..0e02430127
Binary files /dev/null and b/resources/icons/PrusaSlicer-gcodeviewer_192px.png differ
diff --git a/resources/icons/add.svg b/resources/icons/add.svg
index 8a9b253de7..37050d7481 100644
--- a/resources/icons/add.svg
+++ b/resources/icons/add.svg
@@ -1,17 +1,22 @@
-
+
diff --git a/resources/icons/arrange.svg b/resources/icons/arrange.svg
index 4f30e979e3..62cf939e9f 100644
--- a/resources/icons/arrange.svg
+++ b/resources/icons/arrange.svg
@@ -1,24 +1,23 @@
-
+
diff --git a/resources/icons/cancel.svg b/resources/icons/cancel.svg
new file mode 100644
index 0000000000..da44606a08
--- /dev/null
+++ b/resources/icons/cancel.svg
@@ -0,0 +1,10 @@
+
+
+
diff --git a/resources/icons/copy.svg b/resources/icons/copy.svg
index 9b8430dd79..345c2590be 100644
--- a/resources/icons/copy.svg
+++ b/resources/icons/copy.svg
@@ -1,37 +1,29 @@
-
+
diff --git a/resources/icons/cross_focus_large.svg b/resources/icons/cross_focus_large.svg
new file mode 100644
index 0000000000..c246f2bd9e
--- /dev/null
+++ b/resources/icons/cross_focus_large.svg
@@ -0,0 +1,81 @@
+
+
diff --git a/resources/icons/delete_all.svg b/resources/icons/delete_all.svg
index 80e2e503cb..dfa9438129 100644
--- a/resources/icons/delete_all.svg
+++ b/resources/icons/delete_all.svg
@@ -1,31 +1,17 @@
-
+
diff --git a/resources/icons/instance_add.svg b/resources/icons/instance_add.svg
index 5ef492cfae..a466c51dbf 100644
--- a/resources/icons/instance_add.svg
+++ b/resources/icons/instance_add.svg
@@ -1,50 +1,46 @@
-
+
diff --git a/resources/icons/instance_remove.svg b/resources/icons/instance_remove.svg
index 466752ea89..7f9b4f7e1c 100644
--- a/resources/icons/instance_remove.svg
+++ b/resources/icons/instance_remove.svg
@@ -1,49 +1,42 @@
-
+
diff --git a/resources/icons/ironing.svg b/resources/icons/ironing.svg
new file mode 100644
index 0000000000..94917d6bfe
--- /dev/null
+++ b/resources/icons/ironing.svg
@@ -0,0 +1,27 @@
+
+
+
diff --git a/resources/icons/notification_close.svg b/resources/icons/notification_close.svg
new file mode 100644
index 0000000000..708d8bfef1
--- /dev/null
+++ b/resources/icons/notification_close.svg
@@ -0,0 +1,18 @@
+
+
+
diff --git a/resources/icons/notification_close_hover.svg b/resources/icons/notification_close_hover.svg
new file mode 100644
index 0000000000..a04dce21ad
--- /dev/null
+++ b/resources/icons/notification_close_hover.svg
@@ -0,0 +1,66 @@
+
+
diff --git a/resources/icons/notification_error.svg b/resources/icons/notification_error.svg
new file mode 100644
index 0000000000..5356e7af6e
--- /dev/null
+++ b/resources/icons/notification_error.svg
@@ -0,0 +1,71 @@
+
+
diff --git a/resources/icons/notification_minimalize.svg b/resources/icons/notification_minimalize.svg
new file mode 100644
index 0000000000..bb3ae9b7a1
--- /dev/null
+++ b/resources/icons/notification_minimalize.svg
@@ -0,0 +1,14 @@
+
+
+
diff --git a/resources/icons/notification_minimalize_hover.svg b/resources/icons/notification_minimalize_hover.svg
new file mode 100644
index 0000000000..bc5bc6cca1
--- /dev/null
+++ b/resources/icons/notification_minimalize_hover.svg
@@ -0,0 +1,58 @@
+
+
diff --git a/resources/icons/notification_warning.svg b/resources/icons/notification_warning.svg
new file mode 100644
index 0000000000..6ba7a046d8
--- /dev/null
+++ b/resources/icons/notification_warning.svg
@@ -0,0 +1,70 @@
+
+
diff --git a/resources/icons/paste.svg b/resources/icons/paste.svg
index 028ffb8ea0..bcfe567de3 100644
--- a/resources/icons/paste.svg
+++ b/resources/icons/paste.svg
@@ -1,27 +1,22 @@
-
+
diff --git a/resources/icons/prusa_slicer_logo.svg b/resources/icons/prusa_slicer_logo.svg
new file mode 100644
index 0000000000..927c3e70ba
--- /dev/null
+++ b/resources/icons/prusa_slicer_logo.svg
@@ -0,0 +1,5 @@
+
diff --git a/resources/icons/redo_toolbar.svg b/resources/icons/redo_toolbar.svg
index d005f83736..d2aca2cc7d 100644
--- a/resources/icons/redo_toolbar.svg
+++ b/resources/icons/redo_toolbar.svg
@@ -1,13 +1,17 @@
-
+
diff --git a/resources/icons/remove.svg b/resources/icons/remove.svg
index acd21256cd..1bb830d91c 100644
--- a/resources/icons/remove.svg
+++ b/resources/icons/remove.svg
@@ -1,44 +1,60 @@
-
+
diff --git a/resources/icons/seam.svg b/resources/icons/seam.svg
new file mode 100644
index 0000000000..a7e7980cc0
--- /dev/null
+++ b/resources/icons/seam.svg
@@ -0,0 +1,35 @@
+
+
+
diff --git a/resources/icons/search_.svg b/resources/icons/search_.svg
index 679bb30f71..2985ceb561 100644
--- a/resources/icons/search_.svg
+++ b/resources/icons/search_.svg
@@ -1,4 +1,26 @@
-
\ No newline at end of file
+
+
+
diff --git a/resources/icons/search_blink.svg b/resources/icons/search_blink.svg
new file mode 100644
index 0000000000..d005f83736
--- /dev/null
+++ b/resources/icons/search_blink.svg
@@ -0,0 +1,13 @@
+
+
+
diff --git a/resources/icons/settings.svg b/resources/icons/settings.svg
new file mode 100644
index 0000000000..db5bf458d7
--- /dev/null
+++ b/resources/icons/settings.svg
@@ -0,0 +1,68 @@
+
+
+
diff --git a/resources/icons/splashscreen-gcodeviewer.jpg b/resources/icons/splashscreen-gcodeviewer.jpg
new file mode 100644
index 0000000000..f170f390c2
Binary files /dev/null and b/resources/icons/splashscreen-gcodeviewer.jpg differ
diff --git a/resources/icons/splashscreen.jpg b/resources/icons/splashscreen.jpg
new file mode 100644
index 0000000000..86c55f30f6
Binary files /dev/null and b/resources/icons/splashscreen.jpg differ
diff --git a/resources/icons/split_objects.svg b/resources/icons/split_objects.svg
index a7ccc5df86..e822fd35aa 100644
--- a/resources/icons/split_objects.svg
+++ b/resources/icons/split_objects.svg
@@ -1,19 +1,20 @@
-
+
diff --git a/resources/icons/split_parts.svg b/resources/icons/split_parts.svg
index 82a2927706..5cfef0f330 100644
--- a/resources/icons/split_parts.svg
+++ b/resources/icons/split_parts.svg
@@ -1,18 +1,20 @@
-
+
diff --git a/resources/icons/thumb_left.svg b/resources/icons/thumb_left.svg
new file mode 100644
index 0000000000..ef78bd1410
--- /dev/null
+++ b/resources/icons/thumb_left.svg
@@ -0,0 +1,54 @@
+
+
diff --git a/resources/icons/thumb_right.svg b/resources/icons/thumb_right.svg
new file mode 100644
index 0000000000..f3748525d2
--- /dev/null
+++ b/resources/icons/thumb_right.svg
@@ -0,0 +1,54 @@
+
+
diff --git a/resources/icons/tick_mark.svg b/resources/icons/tick_mark.svg
new file mode 100644
index 0000000000..4ccab2192d
--- /dev/null
+++ b/resources/icons/tick_mark.svg
@@ -0,0 +1,6 @@
+
+
diff --git a/resources/icons/timer_dot.svg b/resources/icons/timer_dot.svg
new file mode 100644
index 0000000000..3a77962b60
--- /dev/null
+++ b/resources/icons/timer_dot.svg
@@ -0,0 +1,72 @@
+
+
diff --git a/resources/icons/timer_dot_empty.svg b/resources/icons/timer_dot_empty.svg
new file mode 100644
index 0000000000..a8e776b49e
--- /dev/null
+++ b/resources/icons/timer_dot_empty.svg
@@ -0,0 +1,73 @@
+
+
+
+
\ No newline at end of file
diff --git a/resources/icons/undo_toolbar.svg b/resources/icons/undo_toolbar.svg
index 15778a7baf..2fc25bf737 100644
--- a/resources/icons/undo_toolbar.svg
+++ b/resources/icons/undo_toolbar.svg
@@ -1,13 +1,17 @@
-
+
diff --git a/resources/shaders/gouraud_light.fs b/resources/shaders/gouraud_light.fs
new file mode 100644
index 0000000000..1a58abc852
--- /dev/null
+++ b/resources/shaders/gouraud_light.fs
@@ -0,0 +1,11 @@
+#version 110
+
+uniform vec4 uniform_color;
+
+// x = tainted, y = specular;
+varying vec2 intensity;
+
+void main()
+{
+ gl_FragColor = vec4(vec3(intensity.y, intensity.y, intensity.y) + uniform_color.rgb * intensity.x, uniform_color.a);
+}
diff --git a/resources/shaders/gouraud_light.vs b/resources/shaders/gouraud_light.vs
new file mode 100644
index 0000000000..d4f71938a9
--- /dev/null
+++ b/resources/shaders/gouraud_light.vs
@@ -0,0 +1,38 @@
+#version 110
+
+#define INTENSITY_CORRECTION 0.6
+
+// normalized values for (-0.6/1.31, 0.6/1.31, 1./1.31)
+const vec3 LIGHT_TOP_DIR = vec3(-0.4574957, 0.4574957, 0.7624929);
+#define LIGHT_TOP_DIFFUSE (0.8 * INTENSITY_CORRECTION)
+#define LIGHT_TOP_SPECULAR (0.125 * INTENSITY_CORRECTION)
+#define LIGHT_TOP_SHININESS 20.0
+
+// normalized values for (1./1.43, 0.2/1.43, 1./1.43)
+const vec3 LIGHT_FRONT_DIR = vec3(0.6985074, 0.1397015, 0.6985074);
+#define LIGHT_FRONT_DIFFUSE (0.3 * INTENSITY_CORRECTION)
+
+#define INTENSITY_AMBIENT 0.3
+
+// x = tainted, y = specular;
+varying vec2 intensity;
+
+void main()
+{
+ // First transform the normal into camera space and normalize the result.
+ vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
+
+ // Compute the cos of the angle between the normal and lights direction. The light is directional so the direction is constant for every vertex.
+ // Since these two are normalized the cosine is the dot product. We also need to clamp the result to the [0,1] range.
+ float NdotL = max(dot(normal, LIGHT_TOP_DIR), 0.0);
+
+ intensity.x = INTENSITY_AMBIENT + NdotL * LIGHT_TOP_DIFFUSE;
+ vec3 position = (gl_ModelViewMatrix * gl_Vertex).xyz;
+ intensity.y = LIGHT_TOP_SPECULAR * pow(max(dot(-normalize(position), reflect(-LIGHT_TOP_DIR, normal)), 0.0), LIGHT_TOP_SHININESS);
+
+ // Perform the same lighting calculation for the 2nd light source (no specular applied).
+ NdotL = max(dot(normal, LIGHT_FRONT_DIR), 0.0);
+ intensity.x += NdotL * LIGHT_FRONT_DIFFUSE;
+
+ gl_Position = ftransform();
+}
diff --git a/resources/shaders/options_110.fs b/resources/shaders/options_110.fs
new file mode 100644
index 0000000000..ab656998df
--- /dev/null
+++ b/resources/shaders/options_110.fs
@@ -0,0 +1,8 @@
+#version 110
+
+uniform vec4 uniform_color;
+
+void main()
+{
+ gl_FragColor = uniform_color;
+}
diff --git a/resources/shaders/options_110.vs b/resources/shaders/options_110.vs
new file mode 100644
index 0000000000..7592f86a42
--- /dev/null
+++ b/resources/shaders/options_110.vs
@@ -0,0 +1,11 @@
+#version 110
+
+uniform float zoom;
+uniform float point_size;
+uniform float near_plane_height;
+
+void main()
+{
+ gl_Position = ftransform();
+ gl_PointSize = (gl_Position.w == 1.0) ? zoom * near_plane_height * point_size : near_plane_height * point_size / gl_Position.w;
+}
diff --git a/resources/shaders/options_120.fs b/resources/shaders/options_120.fs
new file mode 100644
index 0000000000..e9b61304f2
--- /dev/null
+++ b/resources/shaders/options_120.fs
@@ -0,0 +1,22 @@
+// version 120 is needed for gl_PointCoord
+#version 120
+
+uniform vec4 uniform_color;
+uniform float percent_outline_radius;
+uniform float percent_center_radius;
+
+vec4 calc_color(float radius, vec4 color)
+{
+ return ((radius < percent_center_radius) || (radius > 1.0 - percent_outline_radius)) ?
+ vec4(0.5 * color.rgb, color.a) : color;
+}
+
+void main()
+{
+ vec2 pos = (gl_PointCoord - 0.5) * 2.0;
+ float radius = length(pos);
+ if (radius > 1.0)
+ discard;
+
+ gl_FragColor = calc_color(radius, uniform_color);
+}
diff --git a/resources/shaders/options_120.vs b/resources/shaders/options_120.vs
new file mode 100644
index 0000000000..baf3cd3a7f
--- /dev/null
+++ b/resources/shaders/options_120.vs
@@ -0,0 +1,11 @@
+#version 120
+
+uniform float zoom;
+uniform float point_size;
+uniform float near_plane_height;
+
+void main()
+{
+ gl_Position = ftransform();
+ gl_PointSize = (gl_Position.w == 1.0) ? zoom * near_plane_height * point_size : near_plane_height * point_size / gl_Position.w;
+}
diff --git a/resources/shaders/toolpaths_lines.fs b/resources/shaders/toolpaths_lines.fs
new file mode 100644
index 0000000000..31151cdc17
--- /dev/null
+++ b/resources/shaders/toolpaths_lines.fs
@@ -0,0 +1,28 @@
+#version 110
+
+// normalized values for (-0.6/1.31, 0.6/1.31, 1./1.31)
+const vec3 LIGHT_TOP_DIR = vec3(-0.4574957, 0.4574957, 0.7624929);
+const vec3 LIGHT_FRONT_DIR = vec3(0.0, 0.0, 1.0);
+
+// x = ambient, y = top diffuse, z = front diffuse, w = global
+uniform vec4 light_intensity;
+uniform vec4 uniform_color;
+
+varying vec3 eye_normal;
+
+void main()
+{
+ vec3 normal = normalize(eye_normal);
+
+ // Compute the cos of the angle between the normal and lights direction. The light is directional so the direction is constant for every vertex.
+ // Since these two are normalized the cosine is the dot product. Take the abs value to light the lines no matter in which direction the normal points.
+ float NdotL = abs(dot(normal, LIGHT_TOP_DIR));
+
+ float intensity = light_intensity.x + NdotL * light_intensity.y;
+
+ // Perform the same lighting calculation for the 2nd light source.
+ NdotL = abs(dot(normal, LIGHT_FRONT_DIR));
+ intensity += NdotL * light_intensity.z;
+
+ gl_FragColor = vec4(uniform_color.rgb * light_intensity.w * intensity, uniform_color.a);
+}
diff --git a/resources/shaders/toolpaths_lines.vs b/resources/shaders/toolpaths_lines.vs
new file mode 100644
index 0000000000..85d5c641f3
--- /dev/null
+++ b/resources/shaders/toolpaths_lines.vs
@@ -0,0 +1,19 @@
+#version 110
+
+varying vec3 eye_normal;
+
+vec3 world_normal()
+{
+ // the world normal is always parallel to the world XY plane
+ // the x component is stored into gl_Vertex.w
+ float x = gl_Vertex.w;
+ float y = sqrt(1.0 - x * x);
+ return vec3(x, y, 0.0);
+}
+
+void main()
+{
+ vec4 world_position = vec4(gl_Vertex.xyz, 1.0);
+ gl_Position = gl_ModelViewProjectionMatrix * world_position;
+ eye_normal = gl_NormalMatrix * world_normal();
+}
diff --git a/sandboxes/opencsg/CMakeLists.txt b/sandboxes/opencsg/CMakeLists.txt
index ec1f4cae91..ace8f4d539 100644
--- a/sandboxes/opencsg/CMakeLists.txt
+++ b/sandboxes/opencsg/CMakeLists.txt
@@ -6,6 +6,7 @@ add_executable(opencsg_example WIN32
main.cpp
Engine.hpp Engine.cpp
ShaderCSGDisplay.hpp ShaderCSGDisplay.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../src/slic3r/GUI/Jobs/Job.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../../src/slic3r/GUI/ProgressStatusBar.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../../src/slic3r/GUI/I18N.hpp
${CMAKE_CURRENT_SOURCE_DIR}/../../src/slic3r/GUI/I18N.cpp)
diff --git a/sandboxes/opencsg/main.cpp b/sandboxes/opencsg/main.cpp
index adf9cc457f..f5fb124935 100644
--- a/sandboxes/opencsg/main.cpp
+++ b/sandboxes/opencsg/main.cpp
@@ -26,7 +26,7 @@
#include "libslic3r/Format/3mf.hpp"
#include "libslic3r/SLAPrint.hpp"
-#include "slic3r/GUI/Job.hpp"
+#include "slic3r/GUI/Jobs/Job.hpp"
#include "slic3r/GUI/ProgressStatusBar.hpp"
using namespace Slic3r::GL;
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index e170ea8d32..ca57ca5531 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -92,6 +92,7 @@ endif()
# Create a slic3r executable
# Process mainfests for various platforms.
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/platform/msw/PrusaSlicer.rc.in ${CMAKE_CURRENT_BINARY_DIR}/PrusaSlicer.rc @ONLY)
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/platform/msw/PrusaSlicer-gcodeviewer.rc.in ${CMAKE_CURRENT_BINARY_DIR}/PrusaSlicer-gcodeviewer.rc @ONLY)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/platform/msw/PrusaSlicer.manifest.in ${CMAKE_CURRENT_BINARY_DIR}/PrusaSlicer.manifest @ONLY)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/platform/osx/Info.plist.in ${CMAKE_CURRENT_BINARY_DIR}/Info.plist @ONLY)
if (WIN32)
@@ -105,9 +106,9 @@ if (MINGW)
set_target_properties(PrusaSlicer PROPERTIES PREFIX "")
endif (MINGW)
-if (NOT WIN32)
- # Binary name on unix like systems (OSX, Linux)
- set_target_properties(PrusaSlicer PROPERTIES OUTPUT_NAME "prusa-slicer")
+if (NOT WIN32 AND NOT APPLE)
+ # Binary name on unix like systems (Linux, Unix)
+ set_target_properties(PrusaSlicer PROPERTIES OUTPUT_NAME "prusa-slicer")
endif ()
target_link_libraries(PrusaSlicer libslic3r cereal)
@@ -161,12 +162,22 @@ if (WIN32)
add_executable(PrusaSlicer_app_console PrusaSlicer_app_msvc.cpp ${CMAKE_CURRENT_BINARY_DIR}/PrusaSlicer.rc)
# Generate debug symbols even in release mode.
if (MSVC)
- target_link_options(PrusaSlicer_app_console PUBLIC "$<$:/DEBUG>")
+ target_link_options(PrusaSlicer_app_console PUBLIC "$<$:/DEBUG>")
endif ()
target_compile_definitions(PrusaSlicer_app_console PRIVATE -DSLIC3R_WRAPPER_CONSOLE)
add_dependencies(PrusaSlicer_app_console PrusaSlicer)
set_target_properties(PrusaSlicer_app_console PROPERTIES OUTPUT_NAME "prusa-slicer-console")
target_link_libraries(PrusaSlicer_app_console PRIVATE boost_headeronly)
+
+ add_executable(PrusaSlicer_app_gcodeviewer WIN32 PrusaSlicer_app_msvc.cpp ${CMAKE_CURRENT_BINARY_DIR}/PrusaSlicer-gcodeviewer.rc)
+ # Generate debug symbols even in release mode.
+ if (MSVC)
+ target_link_options(PrusaSlicer_app_gcodeviewer PUBLIC "$<$:/DEBUG>")
+ endif ()
+ target_compile_definitions(PrusaSlicer_app_gcodeviewer PRIVATE -DSLIC3R_WRAPPER_NOCONSOLE -DSLIC3R_WRAPPER_GCODEVIEWER)
+ add_dependencies(PrusaSlicer_app_gcodeviewer PrusaSlicer)
+ set_target_properties(PrusaSlicer_app_gcodeviewer PROPERTIES OUTPUT_NAME "prusa-gcodeviewer")
+ target_link_libraries(PrusaSlicer_app_gcodeviewer PRIVATE boost_headeronly)
endif ()
# Link the resources dir to where Slic3r GUI expects it
@@ -198,20 +209,34 @@ if (WIN32)
add_custom_target(PrusaSlicerDllsCopy ALL DEPENDS PrusaSlicer)
prusaslicer_copy_dlls(PrusaSlicerDllsCopy)
-elseif (XCODE)
- # Because of Debug/Release/etc. configurations (similar to MSVC) the slic3r binary is located in an extra level
- add_custom_command(TARGET PrusaSlicer POST_BUILD
- COMMAND ln -sfn "${SLIC3R_RESOURCES_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/resources"
- COMMENT "Symlinking the resources directory into the build tree"
- VERBATIM
- )
else ()
+ if (APPLE)
+ # On OSX, the name of the binary matches the name of the Application.
+ add_custom_command(TARGET PrusaSlicer POST_BUILD
+ COMMAND ln -sf PrusaSlicer prusa-slicer
+ COMMAND ln -sf PrusaSlicer prusa-gcodeviewer
+ COMMAND ln -sf PrusaSlicer PrusaGCodeViewer
+ WORKING_DIRECTORY "$"
+ COMMENT "Symlinking the G-code viewer to PrusaSlicer, symlinking to prusa-slicer and prusa-gcodeviewer"
+ VERBATIM)
+ else ()
+ add_custom_command(TARGET PrusaSlicer POST_BUILD
+ COMMAND ln -sf prusa-slicer prusa-gcodeviewer
+ WORKING_DIRECTORY "$"
+ COMMENT "Symlinking the G-code viewer to PrusaSlicer"
+ VERBATIM)
+ endif ()
+ if (XCODE)
+ # Because of Debug/Release/etc. configurations (similar to MSVC) the slic3r binary is located in an extra level
+ set(BIN_RESOURCES_DIR "${CMAKE_CURRENT_BINARY_DIR}/resources")
+ else ()
+ set(BIN_RESOURCES_DIR "${CMAKE_CURRENT_BINARY_DIR}/../resources")
+ endif ()
add_custom_command(TARGET PrusaSlicer POST_BUILD
- COMMAND ln -sfn "${SLIC3R_RESOURCES_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/../resources"
+ COMMAND ln -sfn "${SLIC3R_RESOURCES_DIR}" "${BIN_RESOURCES_DIR}"
COMMENT "Symlinking the resources directory into the build tree"
- VERBATIM
- )
-endif()
+ VERBATIM)
+endif ()
# Slic3r binary install target
if (WIN32)
diff --git a/src/PrusaSlicer.cpp b/src/PrusaSlicer.cpp
index a0422f5fa0..a12ad8bb73 100644
--- a/src/PrusaSlicer.cpp
+++ b/src/PrusaSlicer.cpp
@@ -22,6 +22,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -44,6 +45,7 @@
#include "libslic3r/Format/OBJ.hpp"
#include "libslic3r/Format/SL1.hpp"
#include "libslic3r/Utils.hpp"
+#include "libslic3r/AppConfig.hpp"
#include "PrusaSlicer.hpp"
@@ -52,7 +54,6 @@
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/3DScene.hpp"
#include "slic3r/GUI/InstanceCheck.hpp"
- #include "slic3r/GUI/AppConfig.hpp"
#include "slic3r/GUI/MainFrame.hpp"
#include "slic3r/GUI/Plater.hpp"
#endif /* SLIC3R_GUI */
@@ -101,7 +102,14 @@ int CLI::run(int argc, char **argv)
std::find(m_transforms.begin(), m_transforms.end(), "cut") == m_transforms.end() &&
std::find(m_transforms.begin(), m_transforms.end(), "cut_x") == m_transforms.end() &&
std::find(m_transforms.begin(), m_transforms.end(), "cut_y") == m_transforms.end();
-
+ bool start_as_gcodeviewer =
+#ifdef _WIN32
+ false;
+#else
+ // On Unix systems, the prusa-slicer binary may be symlinked to give the application a different meaning.
+ boost::algorithm::iends_with(boost::filesystem::path(argv[0]).filename().string(), "gcodeviewer");
+#endif // _WIN32
+
const std::vector &load_configs = m_config.option("load", true)->values;
// load config files supplied via --load
@@ -132,37 +140,57 @@ int CLI::run(int argc, char **argv)
m_print_config.apply(config);
}
- // Read input file(s) if any.
- for (const std::string &file : m_input_files) {
- if (! boost::filesystem::exists(file)) {
- boost::nowide::cerr << "No such file: " << file << std::endl;
- exit(1);
+#if ENABLE_GCODE_VIEWER
+ // are we starting as gcodeviewer ?
+ for (auto it = m_actions.begin(); it != m_actions.end(); ++it) {
+ if (*it == "gcodeviewer") {
+ start_gui = true;
+ start_as_gcodeviewer = true;
+ m_actions.erase(it);
+ break;
}
- Model model;
- try {
- // When loading an AMF or 3MF, config is imported as well, including the printer technology.
- DynamicPrintConfig config;
- model = Model::read_from_file(file, &config, true);
- PrinterTechnology other_printer_technology = Slic3r::printer_technology(config);
- if (printer_technology == ptUnknown) {
- printer_technology = other_printer_technology;
- } else if (printer_technology != other_printer_technology && other_printer_technology != ptUnknown) {
- boost::nowide::cerr << "Mixing configurations for FFF and SLA technologies" << std::endl;
+ }
+#endif // ENABLE_GCODE_VIEWER
+
+ // Read input file(s) if any.
+#if ENABLE_GCODE_VIEWER
+ if (!start_as_gcodeviewer) {
+#endif // ENABLE_GCODE_VIEWER
+ for (const std::string& file : m_input_files) {
+ if (!boost::filesystem::exists(file)) {
+ boost::nowide::cerr << "No such file: " << file << std::endl;
+ exit(1);
+ }
+ Model model;
+ try {
+ // When loading an AMF or 3MF, config is imported as well, including the printer technology.
+ DynamicPrintConfig config;
+ model = Model::read_from_file(file, &config, true);
+ PrinterTechnology other_printer_technology = Slic3r::printer_technology(config);
+ if (printer_technology == ptUnknown) {
+ printer_technology = other_printer_technology;
+ }
+ else if (printer_technology != other_printer_technology && other_printer_technology != ptUnknown) {
+ boost::nowide::cerr << "Mixing configurations for FFF and SLA technologies" << std::endl;
+ return 1;
+ }
+ // config is applied to m_print_config before the current m_config values.
+ config += std::move(m_print_config);
+ m_print_config = std::move(config);
+ }
+ catch (std::exception& e) {
+ boost::nowide::cerr << file << ": " << e.what() << std::endl;
return 1;
}
- // config is applied to m_print_config before the current m_config values.
- config += std::move(m_print_config);
- m_print_config = std::move(config);
- } catch (std::exception &e) {
- boost::nowide::cerr << file << ": " << e.what() << std::endl;
- return 1;
+ if (model.objects.empty()) {
+ boost::nowide::cerr << "Error: file is empty: " << file << std::endl;
+ continue;
+ }
+ m_models.push_back(model);
}
- if (model.objects.empty()) {
- boost::nowide::cerr << "Error: file is empty: " << file << std::endl;
- continue;
- }
- m_models.push_back(model);
+#if ENABLE_GCODE_VIEWER
}
+#endif // ENABLE_GCODE_VIEWER
// Apply command line options to a more specific DynamicPrintConfig which provides normalize()
// (command line options override --load files)
@@ -469,7 +497,11 @@ int CLI::run(int argc, char **argv)
print->process();
if (printer_technology == ptFFF) {
// The outfile is processed by a PlaceholderParser.
+#if ENABLE_GCODE_VIEWER
+ outfile = fff_print.export_gcode(outfile, nullptr, nullptr);
+#else
outfile = fff_print.export_gcode(outfile, nullptr);
+#endif // ENABLE_GCODE_VIEWER
outfile_final = fff_print.print_statistics().finalize_output_path(outfile);
} else {
outfile = sla_print.output_filepath(outfile);
@@ -517,6 +549,11 @@ int CLI::run(int argc, char **argv)
<< " (" << print.total_extruded_volume()/1000 << "cm3)" << std::endl;
*/
}
+#if !ENABLE_GCODE_VIEWER
+ } else if (opt_key == "gcodeviewer") {
+ start_gui = true;
+ start_as_gcodeviewer = true;
+#endif // !ENABLE_GCODE_VIEWER
} else {
boost::nowide::cerr << "error: option not supported yet: " << opt_key << std::endl;
return 1;
@@ -526,7 +563,11 @@ int CLI::run(int argc, char **argv)
if (start_gui) {
#ifdef SLIC3R_GUI
// #ifdef USE_WX
+#if ENABLE_GCODE_VIEWER
+ GUI::GUI_App* gui = new GUI::GUI_App(start_as_gcodeviewer ? GUI::GUI_App::EAppMode::GCodeViewer : GUI::GUI_App::EAppMode::Editor);
+#else
GUI::GUI_App *gui = new GUI::GUI_App();
+#endif // ENABLE_GCODE_VIEWER
bool gui_single_instance_setting = gui->app_config->get("single_instance") == "1";
if (Slic3r::instance_check(argc, argv, gui_single_instance_setting)) {
@@ -536,28 +577,42 @@ int CLI::run(int argc, char **argv)
// gui->autosave = m_config.opt_string("autosave");
GUI::GUI_App::SetInstance(gui);
+#if ENABLE_GCODE_VIEWER
+ gui->CallAfter([gui, this, &load_configs, start_as_gcodeviewer] {
+#else
gui->CallAfter([gui, this, &load_configs] {
+#endif // ENABLE_GCODE_VIEWER
if (!gui->initialized()) {
return;
}
+
+#if ENABLE_GCODE_VIEWER
+ if (start_as_gcodeviewer) {
+ if (!m_input_files.empty())
+ gui->plater()->load_gcode(wxString::FromUTF8(m_input_files[0].c_str()));
+ } else {
+#endif // ENABLE_GCODE_VIEWER_AS
#if 0
- // Load the cummulative config over the currently active profiles.
- //FIXME if multiple configs are loaded, only the last one will have an effect.
- // We need to decide what to do about loading of separate presets (just print preset, just filament preset etc).
- // As of now only the full configs are supported here.
- if (!m_print_config.empty())
- gui->mainframe->load_config(m_print_config);
+ // Load the cummulative config over the currently active profiles.
+ //FIXME if multiple configs are loaded, only the last one will have an effect.
+ // We need to decide what to do about loading of separate presets (just print preset, just filament preset etc).
+ // As of now only the full configs are supported here.
+ if (!m_print_config.empty())
+ gui->mainframe->load_config(m_print_config);
#endif
- if (! load_configs.empty())
- // Load the last config to give it a name at the UI. The name of the preset may be later
- // changed by loading an AMF or 3MF.
- //FIXME this is not strictly correct, as one may pass a print/filament/printer profile here instead of a full config.
- gui->mainframe->load_config_file(load_configs.back());
- // If loading a 3MF file, the config is loaded from the last one.
- if (! m_input_files.empty())
- gui->plater()->load_files(m_input_files, true, true);
- if (! m_extra_config.empty())
- gui->mainframe->load_config(m_extra_config);
+ if (!load_configs.empty())
+ // Load the last config to give it a name at the UI. The name of the preset may be later
+ // changed by loading an AMF or 3MF.
+ //FIXME this is not strictly correct, as one may pass a print/filament/printer profile here instead of a full config.
+ gui->mainframe->load_config_file(load_configs.back());
+ // If loading a 3MF file, the config is loaded from the last one.
+ if (!m_input_files.empty())
+ gui->plater()->load_files(m_input_files, true, true);
+ if (!m_extra_config.empty())
+ gui->mainframe->load_config(m_extra_config);
+#if ENABLE_GCODE_VIEWER
+ }
+#endif // ENABLE_GCODE_VIEWER
});
int result = wxEntry(argc, argv);
return result;
diff --git a/src/PrusaSlicer_app_msvc.cpp b/src/PrusaSlicer_app_msvc.cpp
index 712cff687d..5f12c91479 100644
--- a/src/PrusaSlicer_app_msvc.cpp
+++ b/src/PrusaSlicer_app_msvc.cpp
@@ -221,6 +221,11 @@ int wmain(int argc, wchar_t **argv)
std::vector argv_extended;
argv_extended.emplace_back(argv[0]);
+#ifdef SLIC3R_WRAPPER_GCODEVIEWER
+ wchar_t gcodeviewer_param[] = L"--gcodeviewer";
+ argv_extended.emplace_back(gcodeviewer_param);
+#endif /* SLIC3R_WRAPPER_GCODEVIEWER */
+
#ifdef SLIC3R_GUI
// Here one may push some additional parameters based on the wrapper type.
bool force_mesa = false;
diff --git a/src/clipper/clipper.cpp b/src/clipper/clipper.cpp
index b85cf9025e..be4cb4a6a8 100644
--- a/src/clipper/clipper.cpp
+++ b/src/clipper/clipper.cpp
@@ -48,9 +48,19 @@
#include
#include
#include
-#include
#include
+// Profiling support using the Shiny intrusive profiler
+//#define CLIPPERLIB_PROFILE
+#if defined(SLIC3R_PROFILE) && defined(CLIPPERLIB_PROFILE)
+ #include
+ #define CLIPPERLIB_PROFILE_FUNC() PROFILE_FUNC()
+ #define CLIPPERLIB_PROFILE_BLOCK(name) PROFILE_BLOCK(name)
+#else
+ #define CLIPPERLIB_PROFILE_FUNC()
+ #define CLIPPERLIB_PROFILE_BLOCK(name)
+#endif
+
#ifdef use_xyz
namespace ClipperLib_Z {
#else /* use_xyz */
@@ -263,7 +273,7 @@ int PointInPolygon (const IntPoint &pt, OutPt *op)
// This is potentially very expensive! O(n^2)!
bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
OutPt* op = OutPt1;
do
{
@@ -714,7 +724,7 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
// Remove duplicate end point from a closed input path.
// Remove duplicate points from the end of the input path.
int highI = (int)pg.size() -1;
@@ -738,7 +748,7 @@ bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
std::vector num_edges(ppg.size(), 0);
int num_edges_total = 0;
for (size_t i = 0; i < ppg.size(); ++ i) {
@@ -780,7 +790,7 @@ bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
bool ClipperBase::AddPathInternal(const Path &pg, int highI, PolyType PolyTyp, bool Closed, TEdge* edges)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
#ifdef use_lines
if (!Closed && PolyTyp == ptClip)
throw clipperException("AddPath: Open paths must be subject.");
@@ -954,7 +964,7 @@ bool ClipperBase::AddPathInternal(const Path &pg, int highI, PolyType PolyTyp, b
void ClipperBase::Clear()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
m_MinimaList.clear();
m_edges.clear();
m_UseFullRange = false;
@@ -966,7 +976,7 @@ void ClipperBase::Clear()
// Sort the LML entries, initialize the left / right bound edges of each Local Minima.
void ClipperBase::Reset()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
if (m_MinimaList.empty()) return; //ie nothing to process
std::sort(m_MinimaList.begin(), m_MinimaList.end(), [](const LocalMinimum& lm1, const LocalMinimum& lm2){ return lm1.Y < lm2.Y; });
@@ -995,7 +1005,7 @@ void ClipperBase::Reset()
// Returns (0,0,0,0) for an empty rectangle.
IntRect ClipperBase::GetBounds()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
IntRect result;
auto lm = m_MinimaList.begin();
if (lm == m_MinimaList.end())
@@ -1056,7 +1066,7 @@ Clipper::Clipper(int initOptions) :
void Clipper::Reset()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
ClipperBase::Reset();
m_Scanbeam = std::priority_queue();
m_Maxima.clear();
@@ -1071,7 +1081,7 @@ void Clipper::Reset()
bool Clipper::Execute(ClipType clipType, Paths &solution,
PolyFillType subjFillType, PolyFillType clipFillType)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
if (m_HasOpenPaths)
throw clipperException("Error: PolyTree struct is needed for open path clipping.");
solution.resize(0);
@@ -1089,7 +1099,7 @@ bool Clipper::Execute(ClipType clipType, Paths &solution,
bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
PolyFillType subjFillType, PolyFillType clipFillType)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
@@ -1103,10 +1113,10 @@ bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
bool Clipper::ExecuteInternal()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
bool succeeded = true;
try {
- PROFILE_BLOCK(Clipper_ExecuteInternal_Process);
+ CLIPPERLIB_PROFILE_BLOCK(Clipper_ExecuteInternal_Process);
Reset();
if (m_MinimaList.empty()) return true;
cInt botY = m_Scanbeam.top();
@@ -1131,13 +1141,13 @@ bool Clipper::ExecuteInternal()
if (succeeded)
{
- PROFILE_BLOCK(Clipper_ExecuteInternal_Fix);
+ CLIPPERLIB_PROFILE_BLOCK(Clipper_ExecuteInternal_Fix);
//fix orientations ...
//FIXME Vojtech: Does it not invalidate the loop hierarchy maintained as OutRec::FirstLeft pointers?
//FIXME Vojtech: The area is calculated with floats, it may not be numerically stable!
{
- PROFILE_BLOCK(Clipper_ExecuteInternal_Fix_orientations);
+ CLIPPERLIB_PROFILE_BLOCK(Clipper_ExecuteInternal_Fix_orientations);
for (OutRec *outRec : m_PolyOuts)
if (outRec->Pts && !outRec->IsOpen && (outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
ReversePolyPtLinks(outRec->Pts);
@@ -1147,7 +1157,7 @@ bool Clipper::ExecuteInternal()
//unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
{
- PROFILE_BLOCK(Clipper_ExecuteInternal_Fix_fixup);
+ CLIPPERLIB_PROFILE_BLOCK(Clipper_ExecuteInternal_Fix_fixup);
for (OutRec *outRec : m_PolyOuts)
if (outRec->Pts) {
if (outRec->IsOpen)
@@ -1401,7 +1411,7 @@ bool Clipper::IsContributing(const TEdge& edge) const
// Called from Clipper::InsertLocalMinimaIntoAEL() and Clipper::IntersectEdges().
OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
OutPt* result;
TEdge *e, *prevE;
if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
@@ -1493,7 +1503,7 @@ void Clipper::CopyAELToSEL()
// Called from Clipper::ExecuteInternal()
void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
while (!m_MinimaList.empty() && m_MinimaList.back().Y == botY)
{
TEdge* lb = m_MinimaList.back().LeftBound;
@@ -2043,7 +2053,7 @@ OutPt* Clipper::GetLastOutPt(TEdge *e)
void Clipper::ProcessHorizontals()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
TEdge* horzEdge = m_SortedEdges;
while(horzEdge)
{
@@ -2414,7 +2424,7 @@ void Clipper::UpdateEdgeIntoAEL(TEdge *&e)
bool Clipper::ProcessIntersections(const cInt topY)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
if( !m_ActiveEdges ) return true;
try {
BuildIntersectList(topY);
@@ -2569,7 +2579,7 @@ void Clipper::DoMaxima(TEdge *e)
void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
TEdge* e = m_ActiveEdges;
while( e )
{
@@ -3177,7 +3187,7 @@ bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
// This is potentially very expensive! O(n^3)!
void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec) const
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
//tests if NewOutRec contains the polygon before reassigning FirstLeft
for (OutRec *outRec : m_PolyOuts)
{
@@ -3201,7 +3211,7 @@ void Clipper::FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec) const
void Clipper::JoinCommonEdges()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
for (Join &join : m_Joins)
{
OutRec *outRec1 = GetOutRec(join.OutPt1->Idx);
@@ -3771,7 +3781,7 @@ void ClipperOffset::DoRound(int j, int k)
// http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Classes/Clipper/Properties/StrictlySimple.htm
void Clipper::DoSimplePolygons()
{
- PROFILE_FUNC();
+ CLIPPERLIB_PROFILE_FUNC();
size_t i = 0;
while (i < m_PolyOuts.size())
{
diff --git a/src/imgui/imconfig.h b/src/imgui/imconfig.h
index d32f64aa4b..4a1d1faa0c 100644
--- a/src/imgui/imconfig.h
+++ b/src/imgui/imconfig.h
@@ -108,12 +108,19 @@ namespace ImGui
const char ColorMarkerEnd = 0x3; // ETX
// Special ASCII characters are used here as an ikons markers
- const char PrintIconMarker = 0x4;
- const char PrinterIconMarker = 0x5;
- const char PrinterSlaIconMarker = 0x6;
- const char FilamentIconMarker = 0x7;
- const char MaterialIconMarker = 0x8;
-
+ const char PrintIconMarker = 0x4;
+ const char PrinterIconMarker = 0x5;
+ const char PrinterSlaIconMarker = 0x6;
+ const char FilamentIconMarker = 0x7;
+ const char MaterialIconMarker = 0x8;
+ const char CloseIconMarker = 0xB;
+ const char CloseIconHoverMarker = 0xC;
+// const char TimerDotMarker = 0xE;
+// const char TimerDotEmptyMarker = 0xF;
+ const char MinimalizeMarker = 0xE;
+ const char MinimalizeHoverMarker = 0xF;
+ const char WarningMarker = 0x10;
+ const char ErrorMarker = 0x11;
// void MyFunction(const char* name, const MyMatrix44& v);
}
diff --git a/src/libnest2d/LICENSE.txt b/src/libnest2d/LICENSE.txt
index dba13ed2dd..07b1d92c0e 100644
--- a/src/libnest2d/LICENSE.txt
+++ b/src/libnest2d/LICENSE.txt
@@ -1,661 +1,165 @@
- GNU AFFERO GENERAL PUBLIC LICENSE
- Version 3, 19 November 2007
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
- Preamble
-
- The GNU Affero General Public License is a free, copyleft license for
-software and other kinds of works, specifically designed to ensure
-cooperation with the community in the case of network server software.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-our General Public Licenses are intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- Developers that use our General Public Licenses protect your rights
-with two steps: (1) assert copyright on the software, and (2) offer
-you this License which gives you legal permission to copy, distribute
-and/or modify the software.
-
- A secondary benefit of defending all users' freedom is that
-improvements made in alternate versions of the program, if they
-receive widespread use, become available for other developers to
-incorporate. Many developers of free software are heartened and
-encouraged by the resulting cooperation. However, in the case of
-software used on network servers, this result may fail to come about.
-The GNU General Public License permits making a modified version and
-letting the public access it on a server without ever releasing its
-source code to the public.
-
- The GNU Affero General Public License is designed specifically to
-ensure that, in such cases, the modified source code becomes available
-to the community. It requires the operator of a network server to
-provide the source code of the modified version running there to the
-users of that server. Therefore, public use of a modified version, on
-a publicly accessible server, gives the public access to the source
-code of the modified version.
-
- An older license, called the Affero General Public License and
-published by Affero, was designed to accomplish similar goals. This is
-a different license, not a version of the Affero GPL, but Affero has
-released a new version of the Affero GPL which permits relicensing under
-this license.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU Affero General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Remote Network Interaction; Use with the GNU General Public License.
-
- Notwithstanding any other provision of this License, if you modify the
-Program, your modified version must prominently offer all users
-interacting with it remotely through a computer network (if your version
-supports such interaction) an opportunity to receive the Corresponding
-Source of your version by providing access to the Corresponding Source
-from a network server at no charge, through some standard or customary
-means of facilitating copying of software. This Corresponding Source
-shall include the Corresponding Source for any work covered by version 3
-of the GNU General Public License that is incorporated pursuant to the
-following paragraph.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the work with which it is combined will remain governed by version
-3 of the GNU General Public License.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU Affero General Public License from time to time. Such new versions
-will be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU Affero General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU Affero General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU Affero General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If your software can interact with users remotely through a computer
-network, you should also make sure that it provides a way for users to
-get its source. For example, if your program is a web application, its
-interface could display a "Source" link that leads users to an archive
-of the code. There are many ways you could offer source, and different
-solutions will be better for different programs; see section 13 for the
-specific requirements.
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU AGPL, see
-.
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
\ No newline at end of file
diff --git a/src/libslic3r/AABBTreeIndirect.hpp b/src/libslic3r/AABBTreeIndirect.hpp
index ec9b14a7ae..17d918aeb3 100644
--- a/src/libslic3r/AABBTreeIndirect.hpp
+++ b/src/libslic3r/AABBTreeIndirect.hpp
@@ -692,6 +692,40 @@ inline typename VectorType::Scalar squared_distance_to_indexed_triangle_set(
detail::squared_distance_to_indexed_triangle_set_recursive(distancer, size_t(0), Scalar(0), std::numeric_limits::infinity(), hit_idx_out, hit_point_out);
}
+// Decides if exists some triangle in defined radius on a 3D indexed triangle set using a pre-built AABBTreeIndirect::Tree.
+// Closest point to triangle test will be performed with the accuracy of VectorType::Scalar
+// even if the triangle mesh and the AABB Tree are built with floats.
+// Returns true if exists some triangle in defined radius, false otherwise.
+template
+inline bool is_any_triangle_in_radius(
+ // Indexed triangle set - 3D vertices.
+ const std::vector &vertices,
+ // Indexed triangle set - triangular faces, references to vertices.
+ const std::vector &faces,
+ // AABBTreeIndirect::Tree over vertices & faces, bounding boxes built with the accuracy of vertices.
+ const TreeType &tree,
+ // Point to which the closest point on the indexed triangle set is searched for.
+ const VectorType &point,
+ // Maximum distance in which triangle is search for
+ typename VectorType::Scalar &max_distance)
+{
+ using Scalar = typename VectorType::Scalar;
+ auto distancer = detail::IndexedTriangleSetDistancer
+ { vertices, faces, tree, point };
+
+ size_t hit_idx;
+ VectorType hit_point = VectorType::Ones() * (std::nan(""));
+
+ if(tree.empty())
+ {
+ return false;
+ }
+
+ detail::squared_distance_to_indexed_triangle_set_recursive(distancer, size_t(0), Scalar(0), max_distance, hit_idx, hit_point);
+
+ return hit_point.allFinite();
+}
+
} // namespace AABBTreeIndirect
} // namespace Slic3r
diff --git a/src/slic3r/GUI/AppConfig.cpp b/src/libslic3r/AppConfig.cpp
similarity index 96%
rename from src/slic3r/GUI/AppConfig.cpp
rename to src/libslic3r/AppConfig.cpp
index 93589e536e..72c4fd0e92 100644
--- a/src/slic3r/GUI/AppConfig.cpp
+++ b/src/libslic3r/AppConfig.cpp
@@ -1,6 +1,7 @@
#include "libslic3r/libslic3r.h"
#include "libslic3r/Utils.hpp"
#include "AppConfig.hpp"
+#include "Exception.hpp"
#include
#include
@@ -15,8 +16,8 @@
#include
#include
-#include
-#include "I18N.hpp"
+//#include
+//#include "I18N.hpp"
namespace Slic3r {
@@ -101,6 +102,9 @@ void AppConfig::set_defaults()
if (get("use_inches").empty())
set("use_inches", "0");
+ if (get("show_splash_screen").empty())
+ set("show_splash_screen", "1");
+
// Remove legacy window positions/sizes
erase("", "main_frame_maximized");
erase("", "main_frame_pos");
@@ -110,7 +114,7 @@ void AppConfig::set_defaults()
erase("", "object_settings_size");
}
-void AppConfig::load()
+std::string AppConfig::load()
{
// 1) Read the complete config file into a boost::property_tree.
namespace pt = boost::property_tree;
@@ -120,10 +124,15 @@ void AppConfig::load()
pt::read_ini(ifs, tree);
} catch (pt::ptree_error& ex) {
// Error while parsing config file. We'll customize the error message and rethrow to be displayed.
- throw std::runtime_error(
+ // ! But to avoid the use of _utf8 (related to use of wxWidgets)
+ // we will rethrow this exception from the place of load() call, if returned value wouldn't be empty
+ /*
+ throw Slic3r::RuntimeError(
_utf8(L("Error parsing PrusaSlicer config file, it is probably corrupted. "
"Try to manually delete the file to recover from the error. Your user profiles will not be affected.")) +
"\n\n" + AppConfig::config_path() + "\n\n" + ex.what());
+ */
+ return ex.what();
}
// 2) Parse the property_tree, extract the sections and key / value pairs.
@@ -169,10 +178,16 @@ void AppConfig::load()
// Override missing or keys with their defaults.
this->set_defaults();
m_dirty = false;
+ return "";
}
void AppConfig::save()
{
+#if ENABLE_GCODE_VIEWER
+ if (!m_save_enabled)
+ return;
+#endif // ENABLE_GCODE_VIEWER
+
// The config is first written to a file with a PID suffix and then moved
// to avoid race conditions with multiple instances of Slic3r
const auto path = config_path();
diff --git a/src/slic3r/GUI/AppConfig.hpp b/src/libslic3r/AppConfig.hpp
similarity index 94%
rename from src/slic3r/GUI/AppConfig.hpp
rename to src/libslic3r/AppConfig.hpp
index 1e90d32e00..f22a6314ab 100644
--- a/src/slic3r/GUI/AppConfig.hpp
+++ b/src/libslic3r/AppConfig.hpp
@@ -18,6 +18,9 @@ public:
AppConfig() :
m_dirty(false),
m_orig_version(Semver::invalid()),
+#if ENABLE_GCODE_VIEWER
+ m_save_enabled(true),
+#endif // ENABLE_GCODE_VIEWER
m_legacy_datadir(false)
{
this->reset();
@@ -29,7 +32,8 @@ public:
void set_defaults();
// Load the slic3r.ini from a user profile directory (or a datadir, if configured).
- void load();
+ // return error string or empty strinf
+ std::string load();
// Store the slic3r.ini into a user profile directory (or a datadir, if configured).
void save();
@@ -156,6 +160,10 @@ public:
bool get_mouse_device_swap_yz(const std::string& name, bool& swap) const
{ return get_3dmouse_device_numeric_value(name, "swap_yz", swap); }
+#if ENABLE_GCODE_VIEWER
+ void enable_save(bool enable) { m_save_enabled = enable; }
+#endif // ENABLE_GCODE_VIEWER
+
static const std::string SECTION_FILAMENTS;
static const std::string SECTION_MATERIALS;
@@ -182,6 +190,10 @@ private:
bool m_dirty;
// Original version found in the ini file before it was overwritten
Semver m_orig_version;
+#if ENABLE_GCODE_VIEWER
+ // Whether or not calls to save() should take effect
+ bool m_save_enabled;
+#endif // ENABLE_GCODE_VIEWER
// Whether the existing version is before system profiles & configuration updating
bool m_legacy_datadir;
};
diff --git a/src/libslic3r/BoundingBox.hpp b/src/libslic3r/BoundingBox.hpp
index f03733dd86..71746f32ed 100644
--- a/src/libslic3r/BoundingBox.hpp
+++ b/src/libslic3r/BoundingBox.hpp
@@ -2,6 +2,7 @@
#define slic3r_BoundingBox_hpp_
#include "libslic3r.h"
+#include "Exception.hpp"
#include "Point.hpp"
#include "Polygon.hpp"
@@ -22,7 +23,7 @@ public:
{
if (points.empty()) {
this->defined = false;
- // throw std::invalid_argument("Empty point set supplied to BoundingBoxBase constructor");
+ // throw Slic3r::InvalidArgument("Empty point set supplied to BoundingBoxBase constructor");
} else {
typename std::vector::const_iterator it = points.begin();
this->min = *it;
@@ -68,7 +69,7 @@ public:
BoundingBox3Base(const std::vector& points)
{
if (points.empty())
- throw std::invalid_argument("Empty point set supplied to BoundingBox3Base constructor");
+ throw Slic3r::InvalidArgument("Empty point set supplied to BoundingBox3Base constructor");
typename std::vector::const_iterator it = points.begin();
this->min = *it;
this->max = *it;
@@ -192,6 +193,20 @@ inline BoundingBox3 scaled(const BoundingBoxf3 &bb) { return {scaled(bb.min), sc
inline BoundingBoxf unscaled(const BoundingBox &bb) { return {unscaled(bb.min), unscaled(bb.max)}; }
inline BoundingBoxf3 unscaled(const BoundingBox3 &bb) { return {unscaled(bb.min), unscaled(bb.max)}; }
+template
+auto cast(const BoundingBoxBase &b)
+{
+ return BoundingBoxBase>{b.min.template cast(),
+ b.max.template cast()};
+}
+
+template
+auto cast(const BoundingBox3Base &b)
+{
+ return BoundingBox3Base>{b.min.template cast(),
+ b.max.template cast()};
+}
+
} // namespace Slic3r
// Serialization through the Cereal library
diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt
index 881466b399..e30811133a 100644
--- a/src/libslic3r/CMakeLists.txt
+++ b/src/libslic3r/CMakeLists.txt
@@ -46,6 +46,8 @@ add_library(libslic3r STATIC
Fill/Fill.hpp
Fill/Fill3DHoneycomb.cpp
Fill/Fill3DHoneycomb.hpp
+ Fill/FillAdaptive.cpp
+ Fill/FillAdaptive.hpp
Fill/FillBase.cpp
Fill/FillBase.hpp
Fill/FillConcentric.cpp
@@ -99,6 +101,8 @@ add_library(libslic3r STATIC
GCode/ToolOrdering.hpp
GCode/WipeTower.cpp
GCode/WipeTower.hpp
+ GCode/GCodeProcessor.cpp
+ GCode/GCodeProcessor.hpp
GCode.cpp
GCode.hpp
GCodeReader.cpp
@@ -147,6 +151,12 @@ add_library(libslic3r STATIC
PolygonTrimmer.hpp
Polyline.cpp
Polyline.hpp
+ Preset.cpp
+ Preset.hpp
+ PresetBundle.cpp
+ PresetBundle.hpp
+ AppConfig.cpp
+ AppConfig.hpp
Print.cpp
Print.hpp
PrintBase.cpp
@@ -155,6 +165,8 @@ add_library(libslic3r STATIC
PrintConfig.hpp
PrintObject.cpp
PrintRegion.cpp
+ PNGRead.hpp
+ PNGRead.cpp
Semver.cpp
ShortestPath.cpp
ShortestPath.hpp
@@ -187,6 +199,8 @@ add_library(libslic3r STATIC
Utils.hpp
Time.cpp
Time.hpp
+ TriangleSelector.cpp
+ TriangleSelector.hpp
MTUtils.hpp
VoronoiOffset.cpp
VoronoiOffset.hpp
@@ -201,12 +215,15 @@ add_library(libslic3r STATIC
SimplifyMeshImpl.hpp
SimplifyMesh.cpp
MarchingSquares.hpp
+ Optimize/Optimizer.hpp
+ Optimize/NLoptOptimizer.hpp
+ Optimize/BruteforceOptimizer.hpp
${OpenVDBUtils_SOURCES}
- SLA/Common.hpp
- SLA/Common.cpp
SLA/Pad.hpp
SLA/Pad.cpp
SLA/SupportTreeBuilder.hpp
+ SLA/SupportTreeMesher.hpp
+ SLA/SupportTreeMesher.cpp
SLA/SupportTreeBuildsteps.hpp
SLA/SupportTreeBuildsteps.cpp
SLA/SupportTreeBuilder.cpp
@@ -218,6 +235,7 @@ add_library(libslic3r STATIC
SLA/Rotfinder.cpp
SLA/BoostAdapter.hpp
SLA/SpatIndex.hpp
+ SLA/SpatIndex.cpp
SLA/RasterBase.hpp
SLA/RasterBase.cpp
SLA/AGGRaster.hpp
@@ -233,8 +251,10 @@ add_library(libslic3r STATIC
SLA/SupportPointGenerator.cpp
SLA/Contour3D.hpp
SLA/Contour3D.cpp
- SLA/EigenMesh3D.hpp
+ SLA/IndexedMesh.hpp
+ SLA/IndexedMesh.cpp
SLA/Clustering.hpp
+ SLA/Clustering.cpp
SLA/ReprojectPointsOnMesh.hpp
)
@@ -296,6 +316,8 @@ target_link_libraries(libslic3r
TBB::tbb
libslic3r_cgal
${CMAKE_DL_LIBS}
+ PNG::PNG
+ ZLIB::ZLIB
)
if (TARGET OpenVDB::openvdb)
diff --git a/src/libslic3r/ClipperUtils.cpp b/src/libslic3r/ClipperUtils.cpp
index d40d79b3d8..16d985e9c9 100644
--- a/src/libslic3r/ClipperUtils.cpp
+++ b/src/libslic3r/ClipperUtils.cpp
@@ -8,7 +8,16 @@
#include "SVG.hpp"
#endif /* CLIPPER_UTILS_DEBUG */
-#include
+// Profiling support using the Shiny intrusive profiler
+//#define CLIPPER_UTILS_PROFILE
+#if defined(SLIC3R_PROFILE) && defined(CLIPPER_UTILS_PROFILE)
+ #include
+ #define CLIPPERUTILS_PROFILE_FUNC() PROFILE_FUNC()
+ #define CLIPPERUTILS_PROFILE_BLOCK(name) PROFILE_BLOCK(name)
+#else
+ #define CLIPPERUTILS_PROFILE_FUNC()
+ #define CLIPPERUTILS_PROFILE_BLOCK(name)
+#endif
#define CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR (0.005f)
@@ -50,7 +59,7 @@ err:
void scaleClipperPolygon(ClipperLib::Path &polygon)
{
- PROFILE_FUNC();
+ CLIPPERUTILS_PROFILE_FUNC();
for (ClipperLib::Path::iterator pit = polygon.begin(); pit != polygon.end(); ++pit) {
pit->X <<= CLIPPER_OFFSET_POWER_OF_2;
pit->Y <<= CLIPPER_OFFSET_POWER_OF_2;
@@ -59,7 +68,7 @@ void scaleClipperPolygon(ClipperLib::Path &polygon)
void scaleClipperPolygons(ClipperLib::Paths &polygons)
{
- PROFILE_FUNC();
+ CLIPPERUTILS_PROFILE_FUNC();
for (ClipperLib::Paths::iterator it = polygons.begin(); it != polygons.end(); ++it)
for (ClipperLib::Path::iterator pit = (*it).begin(); pit != (*it).end(); ++pit) {
pit->X <<= CLIPPER_OFFSET_POWER_OF_2;
@@ -69,7 +78,7 @@ void scaleClipperPolygons(ClipperLib::Paths &polygons)
void unscaleClipperPolygon(ClipperLib::Path &polygon)
{
- PROFILE_FUNC();
+ CLIPPERUTILS_PROFILE_FUNC();
for (ClipperLib::Path::iterator pit = polygon.begin(); pit != polygon.end(); ++pit) {
pit->X += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA;
pit->Y += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA;
@@ -80,7 +89,7 @@ void unscaleClipperPolygon(ClipperLib::Path &polygon)
void unscaleClipperPolygons(ClipperLib::Paths &polygons)
{
- PROFILE_FUNC();
+ CLIPPERUTILS_PROFILE_FUNC();
for (ClipperLib::Paths::iterator it = polygons.begin(); it != polygons.end(); ++it)
for (ClipperLib::Path::iterator pit = (*it).begin(); pit != (*it).end(); ++pit) {
pit->X += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA;
@@ -790,7 +799,7 @@ ExPolygons simplify_polygons_ex(const Polygons &subject, bool preserve_collinear
void safety_offset(ClipperLib::Paths* paths)
{
- PROFILE_FUNC();
+ CLIPPERUTILS_PROFILE_FUNC();
// scale input
scaleClipperPolygons(*paths);
@@ -812,11 +821,11 @@ void safety_offset(ClipperLib::Paths* paths)
if (! ccw)
std::reverse(path.begin(), path.end());
{
- PROFILE_BLOCK(safety_offset_AddPaths);
+ CLIPPERUTILS_PROFILE_BLOCK(safety_offset_AddPaths);
co.AddPath((*paths)[i], ClipperLib::jtMiter, ClipperLib::etClosedPolygon);
}
{
- PROFILE_BLOCK(safety_offset_Execute);
+ CLIPPERUTILS_PROFILE_BLOCK(safety_offset_Execute);
// offset outside by 10um
ClipperLib::Paths out_this;
co.Execute(out_this, ccw ? 10.f * float(CLIPPER_OFFSET_SCALE) : -10.f * float(CLIPPER_OFFSET_SCALE));
diff --git a/src/libslic3r/Config.cpp b/src/libslic3r/Config.cpp
index f3f365b478..25ef93430f 100644
--- a/src/libslic3r/Config.cpp
+++ b/src/libslic3r/Config.cpp
@@ -5,7 +5,6 @@
#include
#include
#include
-#include // std::runtime_error
#include
#include
#include
@@ -218,7 +217,7 @@ ConfigOption* ConfigOptionDef::create_empty_option() const
case coInts: return new ConfigOptionIntsNullable();
case coPercents: return new ConfigOptionPercentsNullable();
case coBools: return new ConfigOptionBoolsNullable();
- default: throw std::runtime_error(std::string("Unknown option type for nullable option ") + this->label);
+ default: throw Slic3r::RuntimeError(std::string("Unknown option type for nullable option ") + this->label);
}
} else {
switch (this->type) {
@@ -238,7 +237,7 @@ ConfigOption* ConfigOptionDef::create_empty_option() const
case coBool: return new ConfigOptionBool();
case coBools: return new ConfigOptionBools();
case coEnum: return new ConfigOptionEnumGeneric(this->enum_keys_map);
- default: throw std::runtime_error(std::string("Unknown option type for option ") + this->label);
+ default: throw Slic3r::RuntimeError(std::string("Unknown option type for option ") + this->label);
}
}
}
@@ -535,7 +534,7 @@ double ConfigBase::get_abs_value(const t_config_option_key &opt_key) const
return opt_def->ratio_over.empty() ? 0. :
static_cast(raw_opt)->get_abs_value(this->get_abs_value(opt_def->ratio_over));
}
- throw std::runtime_error("ConfigBase::get_abs_value(): Not a valid option type for get_abs_value()");
+ throw Slic3r::RuntimeError("ConfigBase::get_abs_value(): Not a valid option type for get_abs_value()");
}
// Return an absolute value of a possibly relative config variable.
@@ -546,7 +545,7 @@ double ConfigBase::get_abs_value(const t_config_option_key &opt_key, double rati
const ConfigOption *raw_opt = this->option(opt_key);
assert(raw_opt != nullptr);
if (raw_opt->type() != coFloatOrPercent)
- throw std::runtime_error("ConfigBase::get_abs_value(): opt_key is not of coFloatOrPercent");
+ throw Slic3r::RuntimeError("ConfigBase::get_abs_value(): opt_key is not of coFloatOrPercent");
// Compute absolute value.
return static_cast(raw_opt)->get_abs_value(ratio_over);
}
@@ -609,7 +608,7 @@ void ConfigBase::load_from_gcode_file(const std::string &file)
std::getline(ifs, firstline);
if (strncmp(slic3r_gcode_header, firstline.c_str(), strlen(slic3r_gcode_header)) != 0 &&
strncmp(prusaslicer_gcode_header, firstline.c_str(), strlen(prusaslicer_gcode_header)) != 0)
- throw std::runtime_error("Not a PrusaSlicer / Slic3r PE generated g-code.");
+ throw Slic3r::RuntimeError("Not a PrusaSlicer / Slic3r PE generated g-code.");
}
ifs.seekg(0, ifs.end);
auto file_length = ifs.tellg();
@@ -621,7 +620,7 @@ void ConfigBase::load_from_gcode_file(const std::string &file)
size_t key_value_pairs = load_from_gcode_string(data.data());
if (key_value_pairs < 80)
- throw std::runtime_error(format("Suspiciously low number of configuration values extracted from %1%: %2%", file, key_value_pairs));
+ throw Slic3r::RuntimeError(format("Suspiciously low number of configuration values extracted from %1%: %2%", file, key_value_pairs));
}
// Load the config keys from the given string.
@@ -750,7 +749,7 @@ ConfigOption* DynamicConfig::optptr(const t_config_option_key &opt_key, bool cre
throw NoDefinitionException(opt_key);
const ConfigOptionDef *optdef = def->get(opt_key);
if (optdef == nullptr)
-// throw std::runtime_error(std::string("Invalid option name: ") + opt_key);
+// throw Slic3r::RuntimeError(std::string("Invalid option name: ") + opt_key);
// Let the parent decide what to do if the opt_key is not defined by this->def().
return nullptr;
ConfigOption *opt = optdef->create_default_option();
diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp
index 87e0208986..28b28b405a 100644
--- a/src/libslic3r/Config.hpp
+++ b/src/libslic3r/Config.hpp
@@ -13,6 +13,7 @@
#include
#include "libslic3r.h"
#include "clonable_ptr.hpp"
+#include "Exception.hpp"
#include "Point.hpp"
#include
@@ -34,31 +35,31 @@ extern bool unescape_string_cstyle(const std::string &str, std::string &
extern bool unescape_strings_cstyle(const std::string &str, std::vector &out);
/// Specialization of std::exception to indicate that an unknown config option has been encountered.
-class UnknownOptionException : public std::runtime_error {
+class UnknownOptionException : public Slic3r::RuntimeError {
public:
UnknownOptionException() :
- std::runtime_error("Unknown option exception") {}
+ Slic3r::RuntimeError("Unknown option exception") {}
UnknownOptionException(const std::string &opt_key) :
- std::runtime_error(std::string("Unknown option exception: ") + opt_key) {}
+ Slic3r::RuntimeError(std::string("Unknown option exception: ") + opt_key) {}
};
/// Indicate that the ConfigBase derived class does not provide config definition (the method def() returns null).
-class NoDefinitionException : public std::runtime_error
+class NoDefinitionException : public Slic3r::RuntimeError
{
public:
NoDefinitionException() :
- std::runtime_error("No definition exception") {}
+ Slic3r::RuntimeError("No definition exception") {}
NoDefinitionException(const std::string &opt_key) :
- std::runtime_error(std::string("No definition exception: ") + opt_key) {}
+ Slic3r::RuntimeError(std::string("No definition exception: ") + opt_key) {}
};
/// Indicate that an unsupported accessor was called on a config option.
-class BadOptionTypeException : public std::runtime_error
+class BadOptionTypeException : public Slic3r::RuntimeError
{
public:
- BadOptionTypeException() : std::runtime_error("Bad option type exception") {}
- BadOptionTypeException(const std::string &message) : std::runtime_error(message) {}
- BadOptionTypeException(const char* message) : std::runtime_error(message) {}
+ BadOptionTypeException() : Slic3r::RuntimeError("Bad option type exception") {}
+ BadOptionTypeException(const std::string &message) : Slic3r::RuntimeError(message) {}
+ BadOptionTypeException(const char* message) : Slic3r::RuntimeError(message) {}
};
// Type of a configuration value.
@@ -167,7 +168,7 @@ public:
void set(const ConfigOption *rhs) override
{
if (rhs->type() != this->type())
- throw std::runtime_error("ConfigOptionSingle: Assigning an incompatible type");
+ throw Slic3r::RuntimeError("ConfigOptionSingle: Assigning an incompatible type");
assert(dynamic_cast*>(rhs));
this->value = static_cast*>(rhs)->value;
}
@@ -175,7 +176,7 @@ public:
bool operator==(const ConfigOption &rhs) const override
{
if (rhs.type() != this->type())
- throw std::runtime_error("ConfigOptionSingle: Comparing incompatible types");
+ throw Slic3r::RuntimeError("ConfigOptionSingle: Comparing incompatible types");
assert(dynamic_cast*>(&rhs));
return this->value == static_cast*>(&rhs)->value;
}
@@ -239,7 +240,7 @@ public:
void set(const ConfigOption *rhs) override
{
if (rhs->type() != this->type())
- throw std::runtime_error("ConfigOptionVector: Assigning an incompatible type");
+ throw Slic3r::RuntimeError("ConfigOptionVector: Assigning an incompatible type");
assert(dynamic_cast*>(rhs));
this->values = static_cast*>(rhs)->values;
}
@@ -256,12 +257,12 @@ public:
if (opt->type() == this->type()) {
auto other = static_cast*>(opt);
if (other->values.empty())
- throw std::runtime_error("ConfigOptionVector::set(): Assigning from an empty vector");
+ throw Slic3r::RuntimeError("ConfigOptionVector::set(): Assigning from an empty vector");
this->values.emplace_back(other->values.front());
} else if (opt->type() == this->scalar_type())
this->values.emplace_back(static_cast*>(opt)->value);
else
- throw std::runtime_error("ConfigOptionVector::set():: Assigning an incompatible type");
+ throw Slic3r::RuntimeError("ConfigOptionVector::set():: Assigning an incompatible type");
}
}
@@ -280,12 +281,12 @@ public:
// Assign the first value of the rhs vector.
auto other = static_cast*>(rhs);
if (other->values.empty())
- throw std::runtime_error("ConfigOptionVector::set_at(): Assigning from an empty vector");
+ throw Slic3r::RuntimeError("ConfigOptionVector::set_at(): Assigning from an empty vector");
this->values[i] = other->get_at(j);
} else if (rhs->type() == this->scalar_type())
this->values[i] = static_cast*>(rhs)->value;
else
- throw std::runtime_error("ConfigOptionVector::set_at(): Assigning an incompatible type");
+ throw Slic3r::RuntimeError("ConfigOptionVector::set_at(): Assigning an incompatible type");
}
const T& get_at(size_t i) const
@@ -310,9 +311,9 @@ public:
else if (n > this->values.size()) {
if (this->values.empty()) {
if (opt_default == nullptr)
- throw std::runtime_error("ConfigOptionVector::resize(): No default value provided.");
+ throw Slic3r::RuntimeError("ConfigOptionVector::resize(): No default value provided.");
if (opt_default->type() != this->type())
- throw std::runtime_error("ConfigOptionVector::resize(): Extending with an incompatible type.");
+ throw Slic3r::RuntimeError("ConfigOptionVector::resize(): Extending with an incompatible type.");
this->values.resize(n, static_cast*>(opt_default)->values.front());
} else {
// Resize by duplicating the last value.
@@ -329,7 +330,7 @@ public:
bool operator==(const ConfigOption &rhs) const override
{
if (rhs.type() != this->type())
- throw std::runtime_error("ConfigOptionVector: Comparing incompatible types");
+ throw Slic3r::RuntimeError("ConfigOptionVector: Comparing incompatible types");
assert(dynamic_cast*>(&rhs));
return this->values == static_cast*>(&rhs)->values;
}
@@ -341,9 +342,9 @@ public:
// An option overrides another option if it is not nil and not equal.
bool overriden_by(const ConfigOption *rhs) const override {
if (this->nullable())
- throw std::runtime_error("Cannot override a nullable ConfigOption.");
+ throw Slic3r::RuntimeError("Cannot override a nullable ConfigOption.");
if (rhs->type() != this->type())
- throw std::runtime_error("ConfigOptionVector.overriden_by() applied to different types.");
+ throw Slic3r::RuntimeError("ConfigOptionVector.overriden_by() applied to different types.");
auto rhs_vec = static_cast*>(rhs);
if (! rhs->nullable())
// Overridding a non-nullable object with another non-nullable object.
@@ -361,9 +362,9 @@ public:
// Apply an override option, possibly a nullable one.
bool apply_override(const ConfigOption *rhs) override {
if (this->nullable())
- throw std::runtime_error("Cannot override a nullable ConfigOption.");
+ throw Slic3r::RuntimeError("Cannot override a nullable ConfigOption.");
if (rhs->type() != this->type())
- throw std::runtime_error("ConfigOptionVector.apply_override() applied to different types.");
+ throw Slic3r::RuntimeError("ConfigOptionVector.apply_override() applied to different types.");
auto rhs_vec = static_cast*>(rhs);
if (! rhs->nullable()) {
// Overridding a non-nullable object with another non-nullable object.
@@ -452,7 +453,7 @@ public:
bool operator==(const ConfigOptionFloatsTempl &rhs) const { return vectors_equal(this->values, rhs.values); }
bool operator==(const ConfigOption &rhs) const override {
if (rhs.type() != this->type())
- throw std::runtime_error("ConfigOptionFloatsTempl: Comparing incompatible types");
+ throw Slic3r::RuntimeError("ConfigOptionFloatsTempl: Comparing incompatible types");
assert(dynamic_cast*>(&rhs));
return vectors_equal(this->values, static_cast*>(&rhs)->values);
}
@@ -499,7 +500,7 @@ public:
if (NULLABLE)
this->values.push_back(nil_value());
else
- throw std::runtime_error("Deserializing nil into a non-nullable object");
+ throw Slic3r::RuntimeError("Deserializing nil into a non-nullable object");
} else {
std::istringstream iss(item_str);
double value;
@@ -524,9 +525,9 @@ protected:
if (NULLABLE)
ss << "nil";
else
- throw std::runtime_error("Serializing NaN");
+ throw Slic3r::RuntimeError("Serializing NaN");
} else
- throw std::runtime_error("Serializing invalid number");
+ throw Slic3r::RuntimeError("Serializing invalid number");
}
static bool vectors_equal(const std::vector &v1, const std::vector &v2) {
if (NULLABLE) {
@@ -645,7 +646,7 @@ public:
if (NULLABLE)
this->values.push_back(nil_value());
else
- throw std::runtime_error("Deserializing nil into a non-nullable object");
+ throw Slic3r::RuntimeError("Deserializing nil into a non-nullable object");
} else {
std::istringstream iss(item_str);
int value;
@@ -662,7 +663,7 @@ private:
if (NULLABLE)
ss << "nil";
else
- throw std::runtime_error("Serializing NaN");
+ throw Slic3r::RuntimeError("Serializing NaN");
} else
ss << v;
}
@@ -847,7 +848,7 @@ public:
bool operator==(const ConfigOption &rhs) const override
{
if (rhs.type() != this->type())
- throw std::runtime_error("ConfigOptionFloatOrPercent: Comparing incompatible types");
+ throw Slic3r::RuntimeError("ConfigOptionFloatOrPercent: Comparing incompatible types");
assert(dynamic_cast(&rhs));
return *this == *static_cast(&rhs);
}
@@ -858,7 +859,7 @@ public:
void set(const ConfigOption *rhs) override {
if (rhs->type() != this->type())
- throw std::runtime_error("ConfigOptionFloatOrPercent: Assigning an incompatible type");
+ throw Slic3r::RuntimeError("ConfigOptionFloatOrPercent: Assigning an incompatible type");
assert(dynamic_cast(rhs));
*this = *static_cast(rhs);
}
@@ -1126,7 +1127,7 @@ public:
if (NULLABLE)
this->values.push_back(nil_value());
else
- throw std::runtime_error("Deserializing nil into a non-nullable object");
+ throw Slic3r::RuntimeError("Deserializing nil into a non-nullable object");
} else
this->values.push_back(item_str.compare("1") == 0);
}
@@ -1139,7 +1140,7 @@ protected:
if (NULLABLE)
ss << "nil";
else
- throw std::runtime_error("Serializing NaN");
+ throw Slic3r::RuntimeError("Serializing NaN");
} else
ss << (v ? "1" : "0");
}
@@ -1175,14 +1176,14 @@ public:
bool operator==(const ConfigOption &rhs) const override
{
if (rhs.type() != this->type())
- throw std::runtime_error("ConfigOptionEnum: Comparing incompatible types");
+ throw Slic3r::RuntimeError("ConfigOptionEnum: Comparing incompatible types");
// rhs could be of the following type: ConfigOptionEnumGeneric or ConfigOptionEnum
return this->value == (T)rhs.getInt();
}
void set(const ConfigOption *rhs) override {
if (rhs->type() != this->type())
- throw std::runtime_error("ConfigOptionEnum: Assigning an incompatible type");
+ throw Slic3r::RuntimeError("ConfigOptionEnum: Assigning an incompatible type");
// rhs could be of the following type: ConfigOptionEnumGeneric or ConfigOptionEnum
this->value = (T)rhs->getInt();
}
@@ -1259,14 +1260,14 @@ public:
bool operator==(const ConfigOption &rhs) const override
{
if (rhs.type() != this->type())
- throw std::runtime_error("ConfigOptionEnumGeneric: Comparing incompatible types");
+ throw Slic3r::RuntimeError("ConfigOptionEnumGeneric: Comparing incompatible types");
// rhs could be of the following type: ConfigOptionEnumGeneric or ConfigOptionEnum
return this->value == rhs.getInt();
}
void set(const ConfigOption *rhs) override {
if (rhs->type() != this->type())
- throw std::runtime_error("ConfigOptionEnumGeneric: Assigning an incompatible type");
+ throw Slic3r::RuntimeError("ConfigOptionEnumGeneric: Assigning an incompatible type");
// rhs could be of the following type: ConfigOptionEnumGeneric or ConfigOptionEnum
this->value = rhs->getInt();
}
@@ -1321,7 +1322,7 @@ public:
case coInts: { auto opt = new ConfigOptionIntsNullable(); archive(*opt); return opt; }
case coPercents: { auto opt = new ConfigOptionPercentsNullable();archive(*opt); return opt; }
case coBools: { auto opt = new ConfigOptionBoolsNullable(); archive(*opt); return opt; }
- default: throw std::runtime_error(std::string("ConfigOptionDef::load_option_from_archive(): Unknown nullable option type for option ") + this->opt_key);
+ default: throw Slic3r::RuntimeError(std::string("ConfigOptionDef::load_option_from_archive(): Unknown nullable option type for option ") + this->opt_key);
}
} else {
switch (this->type) {
@@ -1340,7 +1341,7 @@ public:
case coBool: { auto opt = new ConfigOptionBool(); archive(*opt); return opt; }
case coBools: { auto opt = new ConfigOptionBools(); archive(*opt); return opt; }
case coEnum: { auto opt = new ConfigOptionEnumGeneric(this->enum_keys_map); archive(*opt); return opt; }
- default: throw std::runtime_error(std::string("ConfigOptionDef::load_option_from_archive(): Unknown option type for option ") + this->opt_key);
+ default: throw Slic3r::RuntimeError(std::string("ConfigOptionDef::load_option_from_archive(): Unknown option type for option ") + this->opt_key);
}
}
}
@@ -1352,7 +1353,7 @@ public:
case coInts: archive(*static_cast(opt)); break;
case coPercents: archive(*static_cast(opt));break;
case coBools: archive(*static_cast(opt)); break;
- default: throw std::runtime_error(std::string("ConfigOptionDef::save_option_to_archive(): Unknown nullable option type for option ") + this->opt_key);
+ default: throw Slic3r::RuntimeError(std::string("ConfigOptionDef::save_option_to_archive(): Unknown nullable option type for option ") + this->opt_key);
}
} else {
switch (this->type) {
@@ -1371,7 +1372,7 @@ public:
case coBool: archive(*static_cast(opt)); break;
case coBools: archive(*static_cast(opt)); break;
case coEnum: archive(*static_cast(opt)); break;
- default: throw std::runtime_error(std::string("ConfigOptionDef::save_option_to_archive(): Unknown option type for option ") + this->opt_key);
+ default: throw Slic3r::RuntimeError(std::string("ConfigOptionDef::save_option_to_archive(): Unknown option type for option ") + this->opt_key);
}
}
// Make the compiler happy, shut up the warnings.
diff --git a/src/libslic3r/CustomGCode.cpp b/src/libslic3r/CustomGCode.cpp
index ba1890a1ff..fb4f69d06a 100644
--- a/src/libslic3r/CustomGCode.cpp
+++ b/src/libslic3r/CustomGCode.cpp
@@ -1,6 +1,10 @@
#include "CustomGCode.hpp"
#include "Config.hpp"
+#if ENABLE_GCODE_VIEWER
+#include "GCode.hpp"
+#else
#include "GCode/PreviewData.hpp"
+#endif // ENABLE_GCODE_VIEWER
#include "GCodeWriter.hpp"
namespace Slic3r {
@@ -17,8 +21,12 @@ extern void update_custom_gcode_per_print_z_from_config(Info& info, DynamicPrint
return;
if (info.gcodes.empty() && ! colorprint_heights->values.empty()) {
// Convert the old colorprint_heighs only if there is no equivalent data in a new format.
- const std::vector& colors = GCodePreviewData::ColorPrintColors();
- const auto& colorprint_values = colorprint_heights->values;
+#if ENABLE_GCODE_VIEWER
+ const std::vector& colors = ColorPrintColors::get();
+#else
+ const std::vector& colors = GCodePreviewData::ColorPrintColors();
+#endif // ENABLE_GCODE_VIEWER
+ const auto& colorprint_values = colorprint_heights->values;
info.gcodes.clear();
info.gcodes.reserve(colorprint_values.size());
int i = 0;
diff --git a/src/libslic3r/ExPolygon.cpp b/src/libslic3r/ExPolygon.cpp
index daaab47555..5bdd5055ec 100644
--- a/src/libslic3r/ExPolygon.cpp
+++ b/src/libslic3r/ExPolygon.cpp
@@ -1,5 +1,6 @@
#include "BoundingBox.hpp"
#include "ExPolygon.hpp"
+#include "Exception.hpp"
#include "Geometry.hpp"
#include "Polygon.hpp"
#include "Line.hpp"
@@ -435,7 +436,7 @@ void ExPolygon::triangulate_pp(Polygons* polygons) const
std::list output;
int res = TPPLPartition().Triangulate_MONO(&input, &output);
if (res != 1)
- throw std::runtime_error("Triangulation failed");
+ throw Slic3r::RuntimeError("Triangulation failed");
// convert output polygons
for (std::list::iterator poly = output.begin(); poly != output.end(); ++poly) {
@@ -548,7 +549,7 @@ void ExPolygon::triangulate_pp(Points *triangles) const
int res = TPPLPartition().Triangulate_MONO(&input, &output);
// int TPPLPartition::Triangulate_EC(TPPLPolyList *inpolys, TPPLPolyList *triangles) {
if (res != 1)
- throw std::runtime_error("Triangulation failed");
+ throw Slic3r::RuntimeError("Triangulation failed");
*triangles = polypartition_output_to_triangles(output);
}
@@ -591,7 +592,7 @@ void ExPolygon::triangulate_p2t(Polygons* polygons) const
}
polygons->push_back(p);
}
- } catch (const std::runtime_error & /* err */) {
+ } catch (const Slic3r::RuntimeError & /* err */) {
assert(false);
// just ignore, don't triangulate
}
diff --git a/src/libslic3r/ExPolygon.hpp b/src/libslic3r/ExPolygon.hpp
index 4aad3603fc..373853f972 100644
--- a/src/libslic3r/ExPolygon.hpp
+++ b/src/libslic3r/ExPolygon.hpp
@@ -333,6 +333,14 @@ extern std::list expoly_to_polypartition_input(const ExPolygons &expp)
extern std::list expoly_to_polypartition_input(const ExPolygon &ex);
extern std::vector polypartition_output_to_triangles(const std::list &output);
+inline double area(const ExPolygons &polys)
+{
+ double s = 0.;
+ for (auto &p : polys) s += p.area();
+
+ return s;
+}
+
} // namespace Slic3r
// start Boost
diff --git a/src/libslic3r/Exception.hpp b/src/libslic3r/Exception.hpp
new file mode 100644
index 0000000000..8ec9f20c81
--- /dev/null
+++ b/src/libslic3r/Exception.hpp
@@ -0,0 +1,28 @@
+#ifndef _libslic3r_Exception_h_
+#define _libslic3r_Exception_h_
+
+#include
+
+namespace Slic3r {
+
+// PrusaSlicer's own exception hierarchy is derived from std::runtime_error.
+// Base for Slicer's own exceptions.
+class Exception : public std::runtime_error { using std::runtime_error::runtime_error; };
+#define SLIC3R_DERIVE_EXCEPTION(DERIVED_EXCEPTION, PARENT_EXCEPTION) \
+ class DERIVED_EXCEPTION : public PARENT_EXCEPTION { using PARENT_EXCEPTION::PARENT_EXCEPTION; }
+// Critical exception produced by Slicer, such exception shall never propagate up to the UI thread.
+// If that happens, an ugly fat message box with an ugly fat exclamation mark is displayed.
+SLIC3R_DERIVE_EXCEPTION(CriticalException, Exception);
+SLIC3R_DERIVE_EXCEPTION(RuntimeError, CriticalException);
+SLIC3R_DERIVE_EXCEPTION(LogicError, CriticalException);
+SLIC3R_DERIVE_EXCEPTION(InvalidArgument, LogicError);
+SLIC3R_DERIVE_EXCEPTION(OutOfRange, LogicError);
+SLIC3R_DERIVE_EXCEPTION(IOError, CriticalException);
+SLIC3R_DERIVE_EXCEPTION(FileIOError, IOError);
+// Runtime exception produced by Slicer. Such exception cancels the slicing process and it shall be shown in notifications.
+SLIC3R_DERIVE_EXCEPTION(SlicingError, Exception);
+#undef SLIC3R_DERIVE_EXCEPTION
+
+} // namespace Slic3r
+
+#endif // _libslic3r_Exception_h_
diff --git a/src/libslic3r/ExtrusionEntity.cpp b/src/libslic3r/ExtrusionEntity.cpp
index c482f7edba..b2c5e1350f 100644
--- a/src/libslic3r/ExtrusionEntity.cpp
+++ b/src/libslic3r/ExtrusionEntity.cpp
@@ -306,14 +306,18 @@ double ExtrusionLoop::min_mm3_per_mm() const
std::string ExtrusionEntity::role_to_string(ExtrusionRole role)
{
switch (role) {
+#if ENABLE_GCODE_VIEWER
+ case erNone : return L("Unknown");
+#else
case erNone : return L("None");
+#endif // ENABLE_GCODE_VIEWER
case erPerimeter : return L("Perimeter");
case erExternalPerimeter : return L("External perimeter");
case erOverhangPerimeter : return L("Overhang perimeter");
case erInternalInfill : return L("Internal infill");
case erSolidInfill : return L("Solid infill");
- case erIroning : return L("Ironing");
case erTopSolidInfill : return L("Top solid infill");
+ case erIroning : return L("Ironing");
case erBridgeInfill : return L("Bridge infill");
case erGapFill : return L("Gap fill");
case erSkirt : return L("Skirt");
@@ -327,4 +331,40 @@ std::string ExtrusionEntity::role_to_string(ExtrusionRole role)
return "";
}
+ExtrusionRole ExtrusionEntity::string_to_role(const std::string& role)
+{
+ if (role == L("Perimeter"))
+ return erPerimeter;
+ else if (role == L("External perimeter"))
+ return erExternalPerimeter;
+ else if (role == L("Overhang perimeter"))
+ return erOverhangPerimeter;
+ else if (role == L("Internal infill"))
+ return erInternalInfill;
+ else if (role == L("Solid infill"))
+ return erSolidInfill;
+ else if (role == L("Top solid infill"))
+ return erTopSolidInfill;
+ else if (role == L("Ironing"))
+ return erIroning;
+ else if (role == L("Bridge infill"))
+ return erBridgeInfill;
+ else if (role == L("Gap fill"))
+ return erGapFill;
+ else if (role == L("Skirt"))
+ return erSkirt;
+ else if (role == L("Support material"))
+ return erSupportMaterial;
+ else if (role == L("Support material interface"))
+ return erSupportMaterialInterface;
+ else if (role == L("Wipe tower"))
+ return erWipeTower;
+ else if (role == L("Custom"))
+ return erCustom;
+ else if (role == L("Mixed"))
+ return erMixed;
+ else
+ return erNone;
+}
+
}
diff --git a/src/libslic3r/ExtrusionEntity.hpp b/src/libslic3r/ExtrusionEntity.hpp
index 879f564b6c..0adb2019ee 100644
--- a/src/libslic3r/ExtrusionEntity.hpp
+++ b/src/libslic3r/ExtrusionEntity.hpp
@@ -106,6 +106,7 @@ public:
virtual double total_volume() const = 0;
static std::string role_to_string(ExtrusionRole role);
+ static ExtrusionRole string_to_role(const std::string& role);
};
typedef std::vector ExtrusionEntitiesPtr;
@@ -121,8 +122,8 @@ public:
// Height of the extrusion, used for visualization purposes.
float height;
- ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), m_role(role) {};
- ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), m_role(role) {};
+ ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), m_role(role) {}
+ ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), m_role(role) {}
ExtrusionPath(const ExtrusionPath& rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {}
ExtrusionPath(ExtrusionPath&& rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {}
ExtrusionPath(const Polyline &polyline, const ExtrusionPath &rhs) : polyline(polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {}
diff --git a/src/libslic3r/ExtrusionEntityCollection.hpp b/src/libslic3r/ExtrusionEntityCollection.hpp
index dfece6949b..5e40ab32ec 100644
--- a/src/libslic3r/ExtrusionEntityCollection.hpp
+++ b/src/libslic3r/ExtrusionEntityCollection.hpp
@@ -2,6 +2,7 @@
#define slic3r_ExtrusionEntityCollection_hpp_
#include "libslic3r.h"
+#include "Exception.hpp"
#include "ExtrusionEntity.hpp"
namespace Slic3r {
@@ -107,7 +108,7 @@ public:
// Following methods shall never be called on an ExtrusionEntityCollection.
Polyline as_polyline() const override {
- throw std::runtime_error("Calling as_polyline() on a ExtrusionEntityCollection");
+ throw Slic3r::RuntimeError("Calling as_polyline() on a ExtrusionEntityCollection");
return Polyline();
};
@@ -117,7 +118,7 @@ public:
}
double length() const override {
- throw std::runtime_error("Calling length() on a ExtrusionEntityCollection");
+ throw Slic3r::RuntimeError("Calling length() on a ExtrusionEntityCollection");
return 0.;
}
};
diff --git a/src/libslic3r/FileParserError.hpp b/src/libslic3r/FileParserError.hpp
index 3f560fa4f5..b7e63d84e0 100644
--- a/src/libslic3r/FileParserError.hpp
+++ b/src/libslic3r/FileParserError.hpp
@@ -10,14 +10,14 @@
namespace Slic3r {
// Generic file parser error, mostly copied from boost::property_tree::file_parser_error
-class file_parser_error: public std::runtime_error
+class file_parser_error: public Slic3r::RuntimeError
{
public:
file_parser_error(const std::string &msg, const std::string &file, unsigned long line = 0) :
- std::runtime_error(format_what(msg, file, line)),
+ Slic3r::RuntimeError(format_what(msg, file, line)),
m_message(msg), m_filename(file), m_line(line) {}
file_parser_error(const std::string &msg, const boost::filesystem::path &file, unsigned long line = 0) :
- std::runtime_error(format_what(msg, file.string(), line)),
+ Slic3r::RuntimeError(format_what(msg, file.string(), line)),
m_message(msg), m_filename(file.string()), m_line(line) {}
// gcc 3.4.2 complains about lack of throw specifier on compiler
// generated dtor
@@ -35,7 +35,7 @@ private:
std::string m_filename;
unsigned long m_line;
- // Format error message to be returned by std::runtime_error::what()
+ // Format error message to be returned by Slic3r::RuntimeError::what()
static std::string format_what(const std::string &msg, const std::string &file, unsigned long l)
{
std::stringstream stream;
diff --git a/src/libslic3r/Fill/Fill.cpp b/src/libslic3r/Fill/Fill.cpp
index 3c16527f07..d68bc7afb3 100644
--- a/src/libslic3r/Fill/Fill.cpp
+++ b/src/libslic3r/Fill/Fill.cpp
@@ -318,7 +318,7 @@ void export_group_fills_to_svg(const char *path, const std::vector
#endif
// friend to Layer
-void Layer::make_fills()
+void Layer::make_fills(FillAdaptive_Internal::Octree* adaptive_fill_octree, FillAdaptive_Internal::Octree* support_fill_octree)
{
for (LayerRegion *layerm : m_regions)
layerm->fills.clear();
@@ -345,6 +345,8 @@ void Layer::make_fills()
f->layer_id = this->id();
f->z = this->print_z;
f->angle = surface_fill.params.angle;
+ f->adapt_fill_octree = adaptive_fill_octree;
+ f->support_fill_octree = support_fill_octree;
// calculate flow spacing for infill pattern generation
bool using_internal_flow = ! surface_fill.surface.is_solid() && ! surface_fill.params.flow.bridge;
diff --git a/src/libslic3r/Fill/FillAdaptive.cpp b/src/libslic3r/Fill/FillAdaptive.cpp
new file mode 100644
index 0000000000..3b9212230d
--- /dev/null
+++ b/src/libslic3r/Fill/FillAdaptive.cpp
@@ -0,0 +1,520 @@
+#include "../ClipperUtils.hpp"
+#include "../ExPolygon.hpp"
+#include "../Surface.hpp"
+#include "../Geometry.hpp"
+#include "../AABBTreeIndirect.hpp"
+#include "../Layer.hpp"
+#include "../Print.hpp"
+#include "../ShortestPath.hpp"
+
+#include "FillAdaptive.hpp"
+
+namespace Slic3r {
+
+std::pair adaptive_fill_line_spacing(const PrintObject &print_object)
+{
+ // Output, spacing for icAdaptiveCubic and icSupportCubic
+ double adaptive_line_spacing = 0.;
+ double support_line_spacing = 0.;
+
+ enum class Tristate {
+ Yes,
+ No,
+ Maybe
+ };
+ struct RegionFillData {
+ Tristate has_adaptive_infill;
+ Tristate has_support_infill;
+ double density;
+ double extrusion_width;
+ };
+ std::vector region_fill_data;
+ region_fill_data.reserve(print_object.print()->regions().size());
+ bool build_octree = false;
+ for (const PrintRegion *region : print_object.print()->regions()) {
+ const PrintRegionConfig &config = region->config();
+ bool nonempty = config.fill_density > 0;
+ bool has_adaptive_infill = nonempty && config.fill_pattern == ipAdaptiveCubic;
+ bool has_support_infill = nonempty && config.fill_pattern == ipSupportCubic;
+ region_fill_data.push_back(RegionFillData({
+ has_adaptive_infill ? Tristate::Maybe : Tristate::No,
+ has_support_infill ? Tristate::Maybe : Tristate::No,
+ config.fill_density,
+ config.infill_extrusion_width
+ }));
+ build_octree |= has_adaptive_infill || has_support_infill;
+ }
+
+ if (build_octree) {
+ // Compute the average of above parameters over all layers
+ for (const Layer *layer : print_object.layers())
+ for (size_t region_id = 0; region_id < layer->regions().size(); ++ region_id) {
+ RegionFillData &rd = region_fill_data[region_id];
+ if (rd.has_adaptive_infill == Tristate::Maybe && ! layer->regions()[region_id]->fill_surfaces.empty())
+ rd.has_adaptive_infill = Tristate::Yes;
+ if (rd.has_support_infill == Tristate::Maybe && ! layer->regions()[region_id]->fill_surfaces.empty())
+ rd.has_support_infill = Tristate::Yes;
+ }
+
+ double adaptive_fill_density = 0.;
+ double adaptive_infill_extrusion_width = 0.;
+ int adaptive_cnt = 0;
+ double support_fill_density = 0.;
+ double support_infill_extrusion_width = 0.;
+ int support_cnt = 0;
+
+ for (const RegionFillData &rd : region_fill_data) {
+ if (rd.has_adaptive_infill == Tristate::Yes) {
+ adaptive_fill_density += rd.density;
+ adaptive_infill_extrusion_width += rd.extrusion_width;
+ ++ adaptive_cnt;
+ } else if (rd.has_support_infill == Tristate::Yes) {
+ support_fill_density += rd.density;
+ support_infill_extrusion_width += rd.extrusion_width;
+ ++ support_cnt;
+ }
+ }
+
+ auto to_line_spacing = [](int cnt, double density, double extrusion_width) {
+ if (cnt) {
+ density /= double(cnt);
+ extrusion_width /= double(cnt);
+ return extrusion_width / ((density / 100.0f) * 0.333333333f);
+ } else
+ return 0.;
+ };
+ adaptive_line_spacing = to_line_spacing(adaptive_cnt, adaptive_fill_density, adaptive_infill_extrusion_width);
+ support_line_spacing = to_line_spacing(support_cnt, support_fill_density, support_infill_extrusion_width);
+ }
+
+ return std::make_pair(adaptive_line_spacing, support_line_spacing);
+}
+
+void FillAdaptive::_fill_surface_single(const FillParams & params,
+ unsigned int thickness_layers,
+ const std::pair &direction,
+ ExPolygon & expolygon,
+ Polylines & polylines_out)
+{
+ if(this->adapt_fill_octree != nullptr)
+ this->generate_infill(params, thickness_layers, direction, expolygon, polylines_out, this->adapt_fill_octree);
+}
+
+void FillAdaptive::generate_infill(const FillParams & params,
+ unsigned int thickness_layers,
+ const std::pair &direction,
+ ExPolygon & expolygon,
+ Polylines & polylines_out,
+ FillAdaptive_Internal::Octree *octree)
+{
+ Vec3d rotation = Vec3d((5.0 * M_PI) / 4.0, Geometry::deg2rad(215.264), M_PI / 6.0);
+ Transform3d rotation_matrix = Geometry::assemble_transform(Vec3d::Zero(), rotation, Vec3d::Ones(), Vec3d::Ones());
+
+ // Store grouped lines by its direction (multiple of 120°)
+ std::vector infill_lines_dir(3);
+ this->generate_infill_lines(octree->root_cube.get(),
+ this->z, octree->origin, rotation_matrix,
+ infill_lines_dir, octree->cubes_properties,
+ int(octree->cubes_properties.size()) - 1);
+
+ Polylines all_polylines;
+ all_polylines.reserve(infill_lines_dir[0].size() * 3);
+ for (Lines &infill_lines : infill_lines_dir)
+ {
+ for (const Line &line : infill_lines)
+ {
+ all_polylines.emplace_back(line.a, line.b);
+ }
+ }
+
+ if (params.dont_connect)
+ {
+ // Crop all polylines
+ polylines_out = intersection_pl(all_polylines, to_polygons(expolygon));
+ }
+ else
+ {
+ // Crop all polylines
+ all_polylines = intersection_pl(all_polylines, to_polygons(expolygon));
+
+ Polylines boundary_polylines;
+ Polylines non_boundary_polylines;
+ for (const Polyline &polyline : all_polylines)
+ {
+ // connect_infill required all polylines to touch the boundary.
+ if(polyline.lines().size() == 1 && expolygon.has_boundary_point(polyline.lines().front().a) && expolygon.has_boundary_point(polyline.lines().front().b))
+ {
+ boundary_polylines.push_back(polyline);
+ }
+ else
+ {
+ non_boundary_polylines.push_back(polyline);
+ }
+ }
+
+ if(!boundary_polylines.empty())
+ {
+ boundary_polylines = chain_polylines(boundary_polylines);
+ FillAdaptive::connect_infill(std::move(boundary_polylines), expolygon, polylines_out, this->spacing, params);
+ }
+
+ polylines_out.insert(polylines_out.end(), non_boundary_polylines.begin(), non_boundary_polylines.end());
+ }
+
+#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
+ {
+ static int iRuna = 0;
+ BoundingBox bbox_svg = this->bounding_box;
+ {
+ ::Slic3r::SVG svg(debug_out_path("FillAdaptive-%d.svg", iRuna), bbox_svg);
+ for (const Polyline &polyline : polylines_out)
+ {
+ for (const Line &line : polyline.lines())
+ {
+ Point from = line.a;
+ Point to = line.b;
+ Point diff = to - from;
+
+ float shrink_length = scale_(0.4);
+ float line_slope = (float)diff.y() / diff.x();
+ float shrink_x = shrink_length / (float)std::sqrt(1.0 + (line_slope * line_slope));
+ float shrink_y = line_slope * shrink_x;
+
+ to.x() -= shrink_x;
+ to.y() -= shrink_y;
+ from.x() += shrink_x;
+ from.y() += shrink_y;
+
+ svg.draw(Line(from, to));
+ }
+ }
+ }
+
+ iRuna++;
+ }
+#endif /* SLIC3R_DEBUG */
+}
+
+void FillAdaptive::generate_infill_lines(
+ FillAdaptive_Internal::Cube *cube,
+ double z_position,
+ const Vec3d &origin,
+ const Transform3d &rotation_matrix,
+ std::vector &dir_lines_out,
+ const std::vector &cubes_properties,
+ int depth)
+{
+ using namespace FillAdaptive_Internal;
+
+ if(cube == nullptr)
+ {
+ return;
+ }
+
+ Vec3d cube_center_tranformed = rotation_matrix * cube->center;
+ double z_diff = std::abs(z_position - cube_center_tranformed.z());
+
+ if (z_diff > cubes_properties[depth].height / 2)
+ {
+ return;
+ }
+
+ if (z_diff < cubes_properties[depth].line_z_distance)
+ {
+ Point from(
+ scale_((cubes_properties[depth].diagonal_length / 2) * (cubes_properties[depth].line_z_distance - z_diff) / cubes_properties[depth].line_z_distance),
+ scale_(cubes_properties[depth].line_xy_distance - ((z_position - (cube_center_tranformed.z() - cubes_properties[depth].line_z_distance)) / sqrt(2))));
+ Point to(-from.x(), from.y());
+ // Relative to cube center
+
+ double rotation_angle = (2.0 * M_PI) / 3.0;
+ for (Lines &lines : dir_lines_out)
+ {
+ Vec3d offset = cube_center_tranformed - (rotation_matrix * origin);
+ Point from_abs(from), to_abs(to);
+
+ from_abs.x() += int(scale_(offset.x()));
+ from_abs.y() += int(scale_(offset.y()));
+ to_abs.x() += int(scale_(offset.x()));
+ to_abs.y() += int(scale_(offset.y()));
+
+// lines.emplace_back(from_abs, to_abs);
+ this->connect_lines(lines, Line(from_abs, to_abs));
+
+ from.rotate(rotation_angle);
+ to.rotate(rotation_angle);
+ }
+ }
+
+ for(const std::unique_ptr &child : cube->children)
+ {
+ if(child != nullptr)
+ {
+ generate_infill_lines(child.get(), z_position, origin, rotation_matrix, dir_lines_out, cubes_properties, depth - 1);
+ }
+ }
+}
+
+void FillAdaptive::connect_lines(Lines &lines, Line new_line)
+{
+ auto eps = int(scale_(0.10));
+ for (size_t i = 0; i < lines.size(); ++i)
+ {
+ if (std::abs(new_line.a.x() - lines[i].b.x()) < eps && std::abs(new_line.a.y() - lines[i].b.y()) < eps)
+ {
+ new_line.a = lines[i].a;
+ lines.erase(lines.begin() + i);
+ --i;
+ continue;
+ }
+
+ if (std::abs(new_line.b.x() - lines[i].a.x()) < eps && std::abs(new_line.b.y() - lines[i].a.y()) < eps)
+ {
+ new_line.b = lines[i].b;
+ lines.erase(lines.begin() + i);
+ --i;
+ continue;
+ }
+ }
+
+ lines.emplace_back(new_line.a, new_line.b);
+}
+
+std::unique_ptr FillAdaptive::build_octree(
+ TriangleMesh &triangle_mesh,
+ coordf_t line_spacing,
+ const Vec3d &cube_center)
+{
+ using namespace FillAdaptive_Internal;
+
+ if(line_spacing <= 0 || std::isnan(line_spacing))
+ {
+ return nullptr;
+ }
+
+ Vec3d bb_size = triangle_mesh.bounding_box().size();
+ // The furthest point from the center of the bottom of the mesh bounding box.
+ double furthest_point = std::sqrt(((bb_size.x() * bb_size.x()) / 4.0) +
+ ((bb_size.y() * bb_size.y()) / 4.0) +
+ (bb_size.z() * bb_size.z()));
+ double max_cube_edge_length = furthest_point * 2;
+
+ std::vector cubes_properties;
+ for (double edge_length = (line_spacing * 2); edge_length < (max_cube_edge_length * 2); edge_length *= 2)
+ {
+ CubeProperties props{};
+ props.edge_length = edge_length;
+ props.height = edge_length * sqrt(3);
+ props.diagonal_length = edge_length * sqrt(2);
+ props.line_z_distance = edge_length / sqrt(3);
+ props.line_xy_distance = edge_length / sqrt(6);
+ cubes_properties.push_back(props);
+ }
+
+ if (triangle_mesh.its.vertices.empty())
+ {
+ triangle_mesh.require_shared_vertices();
+ }
+
+ AABBTreeIndirect::Tree3f aabbTree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(
+ triangle_mesh.its.vertices, triangle_mesh.its.indices);
+ auto octree = std::make_unique(std::make_unique(cube_center), cube_center, cubes_properties);
+
+ FillAdaptive::expand_cube(octree->root_cube.get(), cubes_properties, aabbTree, triangle_mesh, int(cubes_properties.size()) - 1);
+
+ return octree;
+}
+
+void FillAdaptive::expand_cube(
+ FillAdaptive_Internal::Cube *cube,
+ const std::vector &cubes_properties,
+ const AABBTreeIndirect::Tree3f &distance_tree,
+ const TriangleMesh &triangle_mesh, int depth)
+{
+ using namespace FillAdaptive_Internal;
+
+ if (cube == nullptr || depth == 0)
+ {
+ return;
+ }
+
+ std::vector child_centers = {
+ Vec3d(-1, -1, -1), Vec3d( 1, -1, -1), Vec3d(-1, 1, -1), Vec3d( 1, 1, -1),
+ Vec3d(-1, -1, 1), Vec3d( 1, -1, 1), Vec3d(-1, 1, 1), Vec3d( 1, 1, 1)
+ };
+
+ double cube_radius_squared = (cubes_properties[depth].height * cubes_properties[depth].height) / 16;
+
+ for (size_t i = 0; i < 8; ++i)
+ {
+ const Vec3d &child_center = child_centers[i];
+ Vec3d child_center_transformed = cube->center + (child_center * (cubes_properties[depth].edge_length / 4));
+
+ if(AABBTreeIndirect::is_any_triangle_in_radius(triangle_mesh.its.vertices, triangle_mesh.its.indices,
+ distance_tree, child_center_transformed, cube_radius_squared))
+ {
+ cube->children[i] = std::make_unique(child_center_transformed);
+ FillAdaptive::expand_cube(cube->children[i].get(), cubes_properties, distance_tree, triangle_mesh, depth - 1);
+ }
+ }
+}
+
+void FillAdaptive_Internal::Octree::propagate_point(
+ Vec3d point,
+ FillAdaptive_Internal::Cube * current,
+ int depth,
+ const std::vector &cubes_properties)
+{
+ using namespace FillAdaptive_Internal;
+
+ if(depth <= 0)
+ {
+ return;
+ }
+
+ size_t octant_idx = Octree::find_octant(point, current->center);
+ Cube * child = current->children[octant_idx].get();
+
+ // Octant not exists, then create it
+ if(child == nullptr) {
+ std::vector child_centers = {
+ Vec3d(-1, -1, -1), Vec3d( 1, -1, -1), Vec3d(-1, 1, -1), Vec3d( 1, 1, -1),
+ Vec3d(-1, -1, 1), Vec3d( 1, -1, 1), Vec3d(-1, 1, 1), Vec3d( 1, 1, 1)
+ };
+
+ const Vec3d &child_center = child_centers[octant_idx];
+ Vec3d child_center_transformed = current->center + (child_center * (cubes_properties[depth].edge_length / 4));
+
+ current->children[octant_idx] = std::make_unique(child_center_transformed);
+ child = current->children[octant_idx].get();
+ }
+
+ Octree::propagate_point(point, child, (depth - 1), cubes_properties);
+}
+
+std::unique_ptr FillSupportCubic::build_octree(
+ TriangleMesh & triangle_mesh,
+ coordf_t line_spacing,
+ const Vec3d & cube_center,
+ const Transform3d &rotation_matrix)
+{
+ using namespace FillAdaptive_Internal;
+
+ if(line_spacing <= 0 || std::isnan(line_spacing))
+ {
+ return nullptr;
+ }
+
+ Vec3d bb_size = triangle_mesh.bounding_box().size();
+ // The furthest point from the center of the bottom of the mesh bounding box.
+ double furthest_point = std::sqrt(((bb_size.x() * bb_size.x()) / 4.0) +
+ ((bb_size.y() * bb_size.y()) / 4.0) +
+ (bb_size.z() * bb_size.z()));
+ double max_cube_edge_length = furthest_point * 2;
+
+ std::vector cubes_properties;
+ for (double edge_length = (line_spacing * 2); edge_length < (max_cube_edge_length * 2); edge_length *= 2)
+ {
+ CubeProperties props{};
+ props.edge_length = edge_length;
+ props.height = edge_length * sqrt(3);
+ props.diagonal_length = edge_length * sqrt(2);
+ props.line_z_distance = edge_length / sqrt(3);
+ props.line_xy_distance = edge_length / sqrt(6);
+ cubes_properties.push_back(props);
+ }
+
+ if (triangle_mesh.its.vertices.empty())
+ {
+ triangle_mesh.require_shared_vertices();
+ }
+
+ AABBTreeIndirect::Tree3f aabbTree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(
+ triangle_mesh.its.vertices, triangle_mesh.its.indices);
+
+ auto octree = std::make_unique(std::make_unique(cube_center), cube_center, cubes_properties);
+
+ double cube_edge_length = line_spacing / 2.0;
+ int max_depth = int(octree->cubes_properties.size()) - 1;
+ BoundingBoxf3 mesh_bb = triangle_mesh.bounding_box();
+ Vec3f vertical(0, 0, 1);
+
+ for (size_t facet_idx = 0; facet_idx < triangle_mesh.stl.facet_start.size(); ++facet_idx)
+ {
+ if(triangle_mesh.stl.facet_start[facet_idx].normal.dot(vertical) <= 0.707)
+ {
+ // The angle is smaller than PI/4, than infill don't to be there
+ continue;
+ }
+
+ stl_vertex v_1 = triangle_mesh.stl.facet_start[facet_idx].vertex[0];
+ stl_vertex v_2 = triangle_mesh.stl.facet_start[facet_idx].vertex[1];
+ stl_vertex v_3 = triangle_mesh.stl.facet_start[facet_idx].vertex[2];
+
+ std::vector triangle_vertices =
+ {Vec3d(v_1.x(), v_1.y(), v_1.z()),
+ Vec3d(v_2.x(), v_2.y(), v_2.z()),
+ Vec3d(v_3.x(), v_3.y(), v_3.z())};
+
+ BoundingBoxf3 triangle_bb(triangle_vertices);
+
+ Vec3d triangle_start_relative = triangle_bb.min - mesh_bb.min;
+ Vec3d triangle_end_relative = triangle_bb.max - mesh_bb.min;
+
+ Vec3crd triangle_start_idx = Vec3crd(
+ int(std::floor(triangle_start_relative.x() / cube_edge_length)),
+ int(std::floor(triangle_start_relative.y() / cube_edge_length)),
+ int(std::floor(triangle_start_relative.z() / cube_edge_length)));
+ Vec3crd triangle_end_idx = Vec3crd(
+ int(std::floor(triangle_end_relative.x() / cube_edge_length)),
+ int(std::floor(triangle_end_relative.y() / cube_edge_length)),
+ int(std::floor(triangle_end_relative.z() / cube_edge_length)));
+
+ for (int z = triangle_start_idx.z(); z <= triangle_end_idx.z(); ++z)
+ {
+ for (int y = triangle_start_idx.y(); y <= triangle_end_idx.y(); ++y)
+ {
+ for (int x = triangle_start_idx.x(); x <= triangle_end_idx.x(); ++x)
+ {
+ Vec3d cube_center_relative(x * cube_edge_length + (cube_edge_length / 2.0), y * cube_edge_length + (cube_edge_length / 2.0), z * cube_edge_length);
+ Vec3d cube_center_absolute = cube_center_relative + mesh_bb.min;
+
+ double cube_center_absolute_arr[3] = {cube_center_absolute.x(), cube_center_absolute.y(), cube_center_absolute.z()};
+ double distance = 0, cord_u = 0, cord_v = 0;
+
+ double dir[3] = {0.0, 0.0, 1.0};
+
+ double vert_0[3] = {triangle_vertices[0].x(),
+ triangle_vertices[0].y(),
+ triangle_vertices[0].z()};
+ double vert_1[3] = {triangle_vertices[1].x(),
+ triangle_vertices[1].y(),
+ triangle_vertices[1].z()};
+ double vert_2[3] = {triangle_vertices[2].x(),
+ triangle_vertices[2].y(),
+ triangle_vertices[2].z()};
+
+ if(intersect_triangle(cube_center_absolute_arr, dir, vert_0, vert_1, vert_2, &distance, &cord_u, &cord_v) && distance > 0 && distance <= cube_edge_length)
+ {
+ Vec3d cube_center_transformed(cube_center_absolute.x(), cube_center_absolute.y(), cube_center_absolute.z() + (cube_edge_length / 2.0));
+ Octree::propagate_point(rotation_matrix * cube_center_transformed, octree->root_cube.get(), max_depth, octree->cubes_properties);
+ }
+ }
+ }
+ }
+ }
+
+ return octree;
+}
+
+void FillSupportCubic::_fill_surface_single(const FillParams & params,
+ unsigned int thickness_layers,
+ const std::pair &direction,
+ ExPolygon & expolygon,
+ Polylines & polylines_out)
+{
+ if (this->support_fill_octree != nullptr)
+ this->generate_infill(params, thickness_layers, direction, expolygon, polylines_out, this->support_fill_octree);
+}
+
+} // namespace Slic3r
diff --git a/src/libslic3r/Fill/FillAdaptive.hpp b/src/libslic3r/Fill/FillAdaptive.hpp
new file mode 100644
index 0000000000..b24f206da2
--- /dev/null
+++ b/src/libslic3r/Fill/FillAdaptive.hpp
@@ -0,0 +1,139 @@
+#ifndef slic3r_FillAdaptive_hpp_
+#define slic3r_FillAdaptive_hpp_
+
+#include "../AABBTreeIndirect.hpp"
+
+#include "FillBase.hpp"
+
+namespace Slic3r {
+
+class PrintObject;
+class TriangleMesh;
+
+namespace FillAdaptive_Internal
+{
+ struct CubeProperties
+ {
+ double edge_length; // Lenght of edge of a cube
+ double height; // Height of rotated cube (standing on the corner)
+ double diagonal_length; // Length of diagonal of a cube a face
+ double line_z_distance; // Defines maximal distance from a center of a cube on Z axis on which lines will be created
+ double line_xy_distance;// Defines maximal distance from a center of a cube on X and Y axis on which lines will be created
+ };
+
+ struct Cube
+ {
+ Vec3d center;
+ std::unique_ptr children[8] = {};
+ Cube(const Vec3d ¢er) : center(center) {}
+ };
+
+ struct Octree
+ {
+ std::unique_ptr root_cube;
+ Vec3d origin;
+ std::vector cubes_properties;
+
+ Octree(std::unique_ptr rootCube, const Vec3d &origin, const std::vector &cubes_properties)
+ : root_cube(std::move(rootCube)), origin(origin), cubes_properties(cubes_properties) {}
+
+ inline static int find_octant(const Vec3d &i_cube, const Vec3d ¤t)
+ {
+ return (i_cube.z() > current.z()) * 4 + (i_cube.y() > current.y()) * 2 + (i_cube.x() > current.x());
+ }
+
+ static void propagate_point(
+ Vec3d point,
+ FillAdaptive_Internal::Cube *current_cube,
+ int depth,
+ const std::vector &cubes_properties);
+ };
+}; // namespace FillAdaptive_Internal
+
+//
+// Some of the algorithms used by class FillAdaptive were inspired by
+// Cura Engine's class SubDivCube
+// https://github.com/Ultimaker/CuraEngine/blob/master/src/infill/SubDivCube.h
+//
+class FillAdaptive : public Fill
+{
+public:
+ virtual ~FillAdaptive() {}
+
+protected:
+ virtual Fill* clone() const { return new FillAdaptive(*this); };
+ virtual void _fill_surface_single(
+ const FillParams ¶ms,
+ unsigned int thickness_layers,
+ const std::pair &direction,
+ ExPolygon &expolygon,
+ Polylines &polylines_out);
+
+ virtual bool no_sort() const { return true; }
+
+ void generate_infill_lines(
+ FillAdaptive_Internal::Cube *cube,
+ double z_position,
+ const Vec3d & origin,
+ const Transform3d & rotation_matrix,
+ std::vector & dir_lines_out,
+ const std::vector &cubes_properties,
+ int depth);
+
+ static void connect_lines(Lines &lines, Line new_line);
+
+ void generate_infill(const FillParams & params,
+ unsigned int thickness_layers,
+ const std::pair &direction,
+ ExPolygon & expolygon,
+ Polylines & polylines_out,
+ FillAdaptive_Internal::Octree *octree);
+
+public:
+ static std::unique_ptr build_octree(
+ TriangleMesh &triangle_mesh,
+ coordf_t line_spacing,
+ const Vec3d & cube_center);
+
+ static void expand_cube(
+ FillAdaptive_Internal::Cube *cube,
+ const std::vector &cubes_properties,
+ const AABBTreeIndirect::Tree3f &distance_tree,
+ const TriangleMesh & triangle_mesh,
+ int depth);
+};
+
+class FillSupportCubic : public FillAdaptive
+{
+public:
+ virtual ~FillSupportCubic() = default;
+
+protected:
+ virtual Fill* clone() const { return new FillSupportCubic(*this); };
+
+ virtual bool no_sort() const { return true; }
+
+ virtual void _fill_surface_single(
+ const FillParams ¶ms,
+ unsigned int thickness_layers,
+ const std::pair &direction,
+ ExPolygon &expolygon,
+ Polylines &polylines_out);
+
+public:
+ static std::unique_ptr build_octree(
+ TriangleMesh & triangle_mesh,
+ coordf_t line_spacing,
+ const Vec3d & cube_center,
+ const Transform3d &rotation_matrix);
+};
+
+// Calculate line spacing for
+// 1) adaptive cubic infill
+// 2) adaptive internal support cubic infill
+// Returns zero for a particular infill type if no such infill is to be generated.
+std::pair adaptive_fill_line_spacing(const PrintObject &print_object);
+
+} // namespace Slic3r
+
+#endif // slic3r_FillAdaptive_hpp_
diff --git a/src/libslic3r/Fill/FillBase.cpp b/src/libslic3r/Fill/FillBase.cpp
index c760218c01..077555d2ca 100644
--- a/src/libslic3r/Fill/FillBase.cpp
+++ b/src/libslic3r/Fill/FillBase.cpp
@@ -16,6 +16,7 @@
#include "FillRectilinear.hpp"
#include "FillRectilinear2.hpp"
#include "FillRectilinear3.hpp"
+#include "FillAdaptive.hpp"
namespace Slic3r {
@@ -37,7 +38,9 @@ Fill* Fill::new_from_type(const InfillPattern type)
case ipArchimedeanChords: return new FillArchimedeanChords();
case ipHilbertCurve: return new FillHilbertCurve();
case ipOctagramSpiral: return new FillOctagramSpiral();
- default: throw std::invalid_argument("unknown type");
+ case ipAdaptiveCubic: return new FillAdaptive();
+ case ipSupportCubic: return new FillSupportCubic();
+ default: throw Slic3r::InvalidArgument("unknown type");
}
}
diff --git a/src/libslic3r/Fill/FillBase.hpp b/src/libslic3r/Fill/FillBase.hpp
index 2e9b647354..77620e1181 100644
--- a/src/libslic3r/Fill/FillBase.hpp
+++ b/src/libslic3r/Fill/FillBase.hpp
@@ -11,6 +11,7 @@
#include "../libslic3r.h"
#include "../BoundingBox.hpp"
+#include "../Exception.hpp"
#include "../Utils.hpp"
namespace Slic3r {
@@ -19,9 +20,14 @@ class ExPolygon;
class Surface;
enum InfillPattern : int;
-class InfillFailedException : public std::runtime_error {
+namespace FillAdaptive_Internal {
+ struct Octree;
+};
+
+// Infill shall never fail, therefore the error is classified as RuntimeError, not SlicingError.
+class InfillFailedException : public Slic3r::RuntimeError {
public:
- InfillFailedException() : std::runtime_error("Infill failed") {}
+ InfillFailedException() : Slic3r::RuntimeError("Infill failed") {}
};
struct FillParams
@@ -69,6 +75,11 @@ public:
// In scaled coordinates. Bounding box of the 2D projection of the object.
BoundingBox bounding_box;
+ // Octree builds on mesh for usage in the adaptive cubic infill
+ FillAdaptive_Internal::Octree* adapt_fill_octree = nullptr;
+ // Octree builds on mesh for usage in the support cubic infill
+ FillAdaptive_Internal::Octree* support_fill_octree = nullptr;
+
public:
virtual ~Fill() {}
diff --git a/src/libslic3r/Flow.cpp b/src/libslic3r/Flow.cpp
index 1678be999c..e5dcf07310 100644
--- a/src/libslic3r/Flow.cpp
+++ b/src/libslic3r/Flow.cpp
@@ -53,7 +53,7 @@ static inline FlowRole opt_key_to_flow_role(const std::string &opt_key)
else if (opt_key == "support_material_extrusion_width")
return frSupportMaterial;
else
- throw std::runtime_error("opt_key_to_flow_role: invalid argument");
+ throw Slic3r::RuntimeError("opt_key_to_flow_role: invalid argument");
};
static inline void throw_on_missing_variable(const std::string &opt_key, const char *dependent_opt_key)
@@ -126,7 +126,7 @@ Flow Flow::new_from_config_width(FlowRole role, const ConfigOptionFloatOrPercent
{
// we need layer height unless it's a bridge
if (height <= 0 && bridge_flow_ratio == 0)
- throw std::invalid_argument("Invalid flow height supplied to new_from_config_width()");
+ throw Slic3r::InvalidArgument("Invalid flow height supplied to new_from_config_width()");
float w;
if (bridge_flow_ratio > 0) {
@@ -151,7 +151,7 @@ Flow Flow::new_from_spacing(float spacing, float nozzle_diameter, float height,
{
// we need layer height unless it's a bridge
if (height <= 0 && !bridge)
- throw std::invalid_argument("Invalid flow height supplied to new_from_spacing()");
+ throw Slic3r::InvalidArgument("Invalid flow height supplied to new_from_spacing()");
// Calculate width from spacing.
// For normal extrusons, extrusion width is wider than the spacing due to the rounding and squishing of the extrusions.
// For bridge extrusions, the extrusions are placed with a tiny BRIDGE_EXTRA_SPACING gaps between the threads.
diff --git a/src/libslic3r/Flow.hpp b/src/libslic3r/Flow.hpp
index 7d6e35873d..9e57ce9079 100644
--- a/src/libslic3r/Flow.hpp
+++ b/src/libslic3r/Flow.hpp
@@ -3,6 +3,7 @@
#include "libslic3r.h"
#include "Config.hpp"
+#include "Exception.hpp"
#include "ExtrusionEntity.hpp"
namespace Slic3r {
@@ -27,11 +28,11 @@ enum FlowRole {
frSupportMaterialInterface,
};
-class FlowError : public std::invalid_argument
+class FlowError : public Slic3r::InvalidArgument
{
public:
- FlowError(const std::string& what_arg) : invalid_argument(what_arg) {}
- FlowError(const char* what_arg) : invalid_argument(what_arg) {}
+ FlowError(const std::string& what_arg) : Slic3r::InvalidArgument(what_arg) {}
+ FlowError(const char* what_arg) : Slic3r::InvalidArgument(what_arg) {}
};
class FlowErrorNegativeSpacing : public FlowError
diff --git a/src/libslic3r/Format/3mf.cpp b/src/libslic3r/Format/3mf.cpp
index 657e9ec983..46a6c02af1 100644
--- a/src/libslic3r/Format/3mf.cpp
+++ b/src/libslic3r/Format/3mf.cpp
@@ -1,9 +1,11 @@
#include "../libslic3r.h"
+#include "../Exception.hpp"
#include "../Model.hpp"
#include "../Utils.hpp"
#include "../GCode.hpp"
#include "../Geometry.hpp"
#include "../GCode/ThumbnailData.hpp"
+#include "../Time.hpp"
#include "../I18N.hpp"
@@ -85,6 +87,8 @@ const char* OBJECTID_ATTR = "objectid";
const char* TRANSFORM_ATTR = "transform";
const char* PRINTABLE_ATTR = "printable";
const char* INSTANCESCOUNT_ATTR = "instances_count";
+const char* CUSTOM_SUPPORTS_ATTR = "slic3rpe:custom_supports";
+const char* CUSTOM_SEAM_ATTR = "slic3rpe:custom_seam";
const char* KEY_ATTR = "key";
const char* VALUE_ATTR = "value";
@@ -120,11 +124,11 @@ const char* INVALID_OBJECT_TYPES[] =
"other"
};
-class version_error : public std::runtime_error
+class version_error : public Slic3r::FileIOError
{
public:
- version_error(const std::string& what_arg) : std::runtime_error(what_arg) {}
- version_error(const char* what_arg) : std::runtime_error(what_arg) {}
+ version_error(const std::string& what_arg) : Slic3r::FileIOError(what_arg) {}
+ version_error(const char* what_arg) : Slic3r::FileIOError(what_arg) {}
};
const char* get_attribute_value_charptr(const char** attributes, unsigned int attributes_size, const char* attribute_key)
@@ -282,6 +286,8 @@ namespace Slic3r {
{
std::vector vertices;
std::vector triangles;
+ std::vector custom_supports;
+ std::vector custom_seam;
bool empty()
{
@@ -292,6 +298,8 @@ namespace Slic3r {
{
vertices.clear();
triangles.clear();
+ custom_supports.clear();
+ custom_seam.clear();
}
};
@@ -600,7 +608,7 @@ namespace Slic3r {
{
// ensure the zip archive is closed and rethrow the exception
close_zip_reader(&archive);
- throw std::runtime_error(e.what());
+ throw Slic3r::FileIOError(e.what());
}
}
}
@@ -773,7 +781,7 @@ namespace Slic3r {
{
char error_buf[1024];
::sprintf(error_buf, "Error (%s) while parsing '%s' at line %d", XML_ErrorString(XML_GetErrorCode(data->parser)), data->stat.m_filename, (int)XML_GetCurrentLineNumber(data->parser));
- throw std::runtime_error(error_buf);
+ throw Slic3r::FileIOError(error_buf);
}
return n;
@@ -782,7 +790,7 @@ namespace Slic3r {
catch (const version_error& e)
{
// rethrow the exception
- throw std::runtime_error(e.what());
+ throw Slic3r::FileIOError(e.what());
}
catch (std::exception& e)
{
@@ -1110,6 +1118,15 @@ namespace Slic3r {
float(std::atof(object_data_points[i+6].c_str())),
float(std::atof(object_data_points[i+7].c_str())));
}
+
+ // The holes are saved elevated above the mesh and deeper (bad idea indeed).
+ // This is retained for compatibility.
+ // Place the hole to the mesh and make it shallower to compensate.
+ // The offset is 1 mm above the mesh.
+ for (sla::DrainHole& hole : sla_drain_holes) {
+ hole.pos += hole.normal.normalized();
+ hole.height -= 1.f;
+ }
if (!sla_drain_holes.empty())
m_sla_drain_holes.insert(IdToSlaDrainHolesMap::value_type(object_id, sla_drain_holes));
@@ -1538,6 +1555,9 @@ namespace Slic3r {
m_curr_object.geometry.triangles.push_back((unsigned int)get_attribute_value_int(attributes, num_attributes, V1_ATTR));
m_curr_object.geometry.triangles.push_back((unsigned int)get_attribute_value_int(attributes, num_attributes, V2_ATTR));
m_curr_object.geometry.triangles.push_back((unsigned int)get_attribute_value_int(attributes, num_attributes, V3_ATTR));
+
+ m_curr_object.geometry.custom_supports.push_back(get_attribute_value_string(attributes, num_attributes, CUSTOM_SUPPORTS_ATTR));
+ m_curr_object.geometry.custom_seam.push_back(get_attribute_value_string(attributes, num_attributes, CUSTOM_SEAM_ATTR));
return true;
}
@@ -1871,6 +1891,18 @@ namespace Slic3r {
volume->source.transform = Slic3r::Geometry::Transformation(volume_matrix_to_object);
volume->calculate_convex_hull();
+ // recreate custom supports and seam from previously loaded attribute
+ for (unsigned i=0; im_supported_facets.set_triangle_from_string(i, geometry.custom_supports[index]);
+ if (! geometry.custom_seam[index].empty())
+ volume->m_seam_facets.set_triangle_from_string(i, geometry.custom_seam[index]);
+ }
+
+
// apply the remaining volume's metadata
for (const Metadata& metadata : volume_data.metadata)
{
@@ -1991,7 +2023,7 @@ namespace Slic3r {
bool _add_content_types_file_to_archive(mz_zip_archive& archive);
bool _add_thumbnail_file_to_archive(mz_zip_archive& archive, const ThumbnailData& thumbnail_data);
bool _add_relationships_file_to_archive(mz_zip_archive& archive);
- bool _add_model_file_to_archive(mz_zip_archive& archive, const Model& model, IdToObjectDataMap &objects_data);
+ bool _add_model_file_to_archive(const std::string& filename, mz_zip_archive& archive, const Model& model, IdToObjectDataMap& objects_data);
bool _add_object_to_model_stream(std::stringstream& stream, unsigned int& object_id, ModelObject& object, BuildItemsList& build_items, VolumeToOffsetsMap& volumes_offsets);
bool _add_mesh_to_object_stream(std::stringstream& stream, ModelObject& object, VolumeToOffsetsMap& volumes_offsets);
bool _add_build_to_model_stream(std::stringstream& stream, const BuildItemsList& build_items);
@@ -2054,7 +2086,7 @@ namespace Slic3r {
// Adds model file ("3D/3dmodel.model").
// This is the one and only file that contains all the geometry (vertices and triangles) of all ModelVolumes.
IdToObjectDataMap objects_data;
- if (!_add_model_file_to_archive(archive, model, objects_data))
+ if (!_add_model_file_to_archive(filename, archive, model, objects_data))
{
close_zip_writer(&archive);
boost::filesystem::remove(filename);
@@ -2203,7 +2235,7 @@ namespace Slic3r {
return true;
}
- bool _3MF_Exporter::_add_model_file_to_archive(mz_zip_archive& archive, const Model& model, IdToObjectDataMap &objects_data)
+ bool _3MF_Exporter::_add_model_file_to_archive(const std::string& filename, mz_zip_archive& archive, const Model& model, IdToObjectDataMap& objects_data)
{
std::stringstream stream;
// https://en.cppreference.com/w/cpp/types/numeric_limits/max_digits10
@@ -2214,6 +2246,19 @@ namespace Slic3r {
stream << "\n";
stream << "<" << MODEL_TAG << " unit=\"millimeter\" xml:lang=\"en-US\" xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\" xmlns:slic3rpe=\"http://schemas.slic3r.org/3mf/2017/06\">\n";
stream << " <" << METADATA_TAG << " name=\"" << SLIC3RPE_3MF_VERSION << "\">" << VERSION_3MF << "" << METADATA_TAG << ">\n";
+ std::string name = boost::filesystem::path(filename).stem().string();
+ stream << " <" << METADATA_TAG << " name=\"Title\">" << name << "" << METADATA_TAG << ">\n";
+ stream << " <" << METADATA_TAG << " name=\"Designer\">" << "" << METADATA_TAG << ">\n";
+ stream << " <" << METADATA_TAG << " name=\"Description\">" << name << "" << METADATA_TAG << ">\n";
+ stream << " <" << METADATA_TAG << " name=\"Copyright\">" << "" << METADATA_TAG << ">\n";
+ stream << " <" << METADATA_TAG << " name=\"LicenseTerms\">" << "" << METADATA_TAG << ">\n";
+ stream << " <" << METADATA_TAG << " name=\"Rating\">" << "" << METADATA_TAG << ">\n";
+ std::string date = Slic3r::Utils::utc_timestamp(Slic3r::Utils::get_current_time_utc());
+ // keep only the date part of the string
+ date = date.substr(0, 10);
+ stream << " <" << METADATA_TAG << " name=\"CreationDate\">" << date << "" << METADATA_TAG << ">\n";
+ stream << " <" << METADATA_TAG << " name=\"ModificationDate\">" << date << "" << METADATA_TAG << ">\n";
+ stream << " <" << METADATA_TAG << " name=\"Application\">" << SLIC3R_APP_KEY << "-" << SLIC3R_VERSION << "" << METADATA_TAG << ">\n";
stream << " <" << RESOURCES_TAG << ">\n";
// Instance transformations, indexed by the 3MF object ID (which is a linear serialization of all instances of all ModelObjects).
@@ -2316,9 +2361,9 @@ namespace Slic3r {
continue;
if (!volume->mesh().repaired)
- throw std::runtime_error("store_3mf() requires repair()");
+ throw Slic3r::FileIOError("store_3mf() requires repair()");
if (!volume->mesh().has_shared_vertices())
- throw std::runtime_error("store_3mf() requires shared vertices");
+ throw Slic3r::FileIOError("store_3mf() requires shared vertices");
volumes_offsets.insert(VolumeToOffsetsMap::value_type(volume, Offsets(vertices_count))).first;
@@ -2369,6 +2414,15 @@ namespace Slic3r {
{
stream << "v" << j + 1 << "=\"" << its.indices[i][j] + volume_it->second.first_vertex_id << "\" ";
}
+
+ std::string custom_supports_data_string = volume->m_supported_facets.get_triangle_as_string(i);
+ if (! custom_supports_data_string.empty())
+ stream << CUSTOM_SUPPORTS_ATTR << "=\"" << custom_supports_data_string << "\" ";
+
+ std::string custom_seam_data_string = volume->m_seam_facets.get_triangle_as_string(i);
+ if (! custom_seam_data_string.empty())
+ stream << CUSTOM_SEAM_ATTR << "=\"" << custom_seam_data_string << "\" ";
+
stream << "/>\n";
}
}
@@ -2559,7 +2613,18 @@ namespace Slic3r {
for (const ModelObject* object : model.objects)
{
++count;
- auto& drain_holes = object->sla_drain_holes;
+ sla::DrainHoles drain_holes = object->sla_drain_holes;
+
+ // The holes were placed 1mm above the mesh in the first implementation.
+ // This was a bad idea and the reference point was changed in 2.3 so
+ // to be on the mesh exactly. The elevated position is still saved
+ // in 3MFs for compatibility reasons.
+ for (sla::DrainHole& hole : drain_holes) {
+ hole.pos -= hole.normal.normalized();
+ hole.height += 1.f;
+ }
+
+
if (!drain_holes.empty())
{
out += string_printf(fmt, count);
diff --git a/src/libslic3r/Format/3mf.hpp b/src/libslic3r/Format/3mf.hpp
index 94a7027757..ccfd9356d8 100644
--- a/src/libslic3r/Format/3mf.hpp
+++ b/src/libslic3r/Format/3mf.hpp
@@ -35,6 +35,6 @@ namespace Slic3r {
// The model could be modified during the export process if meshes are not repaired or have no shared vertices
extern bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config, bool fullpath_sources, const ThumbnailData* thumbnail_data = nullptr);
-}; // namespace Slic3r
+} // namespace Slic3r
#endif /* slic3r_Format_3mf_hpp_ */
diff --git a/src/libslic3r/Format/AMF.cpp b/src/libslic3r/Format/AMF.cpp
index af7b9b1b60..1a706afa92 100644
--- a/src/libslic3r/Format/AMF.cpp
+++ b/src/libslic3r/Format/AMF.cpp
@@ -7,6 +7,7 @@
#include
#include "../libslic3r.h"
+#include "../Exception.hpp"
#include "../Model.hpp"
#include "../GCode.hpp"
#include "../PrintConfig.hpp"
@@ -923,7 +924,7 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi
{
char error_buf[1024];
::sprintf(error_buf, "Error (%s) while parsing '%s' at line %d", XML_ErrorString(XML_GetErrorCode(data->parser)), data->stat.m_filename, (int)XML_GetCurrentLineNumber(data->parser));
- throw std::runtime_error(error_buf);
+ throw Slic3r::FileIOError(error_buf);
}
return n;
@@ -948,9 +949,9 @@ bool extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_fi
if (check_version && (ctx.m_version > VERSION_AMF_COMPATIBLE))
{
// std::string msg = _(L("The selected amf file has been saved with a newer version of " + std::string(SLIC3R_APP_NAME) + " and is not compatible."));
- // throw std::runtime_error(msg.c_str());
+ // throw Slic3r::FileIOError(msg.c_str());
const std::string msg = (boost::format(_(L("The selected amf file has been saved with a newer version of %1% and is not compatible."))) % std::string(SLIC3R_APP_NAME)).str();
- throw std::runtime_error(msg);
+ throw Slic3r::FileIOError(msg);
}
return true;
@@ -994,7 +995,7 @@ bool load_amf_archive(const char* path, DynamicPrintConfig* config, Model* model
{
// ensure the zip archive is closed and rethrow the exception
close_zip_reader(&archive);
- throw std::runtime_error(e.what());
+ throw Slic3r::FileIOError(e.what());
}
break;
@@ -1147,9 +1148,9 @@ bool store_amf(const char* path, Model* model, const DynamicPrintConfig* config,
for (ModelVolume *volume : object->volumes) {
vertices_offsets.push_back(num_vertices);
if (! volume->mesh().repaired)
- throw std::runtime_error("store_amf() requires repair()");
+ throw Slic3r::FileIOError("store_amf() requires repair()");
if (! volume->mesh().has_shared_vertices())
- throw std::runtime_error("store_amf() requires shared vertices");
+ throw Slic3r::FileIOError("store_amf() requires shared vertices");
const indexed_triangle_set &its = volume->mesh().its;
const Transform3d& matrix = volume->get_matrix();
for (size_t i = 0; i < its.vertices.size(); ++i) {
diff --git a/src/libslic3r/Format/PRUS.cpp b/src/libslic3r/Format/PRUS.cpp
index d6f87197df..e2c38d9576 100644
--- a/src/libslic3r/Format/PRUS.cpp
+++ b/src/libslic3r/Format/PRUS.cpp
@@ -147,7 +147,7 @@ static void extract_model_from_archive(
}
}
if (! trafo_set)
- throw std::runtime_error(std::string("Archive ") + path + " does not contain a valid entry in scene.xml for " + name);
+ throw Slic3r::FileIOError(std::string("Archive ") + path + " does not contain a valid entry in scene.xml for " + name);
// Extract the STL.
StlHeader header;
@@ -266,7 +266,7 @@ static void extract_model_from_archive(
}
if (! mesh_valid)
- throw std::runtime_error(std::string("Archive ") + path + " does not contain a valid mesh for " + name);
+ throw Slic3r::FileIOError(std::string("Archive ") + path + " does not contain a valid mesh for " + name);
// Add this mesh to the model.
ModelVolume *volume = nullptr;
@@ -303,7 +303,7 @@ bool load_prus(const char *path, Model *model)
mz_bool res = MZ_FALSE;
try {
if (!open_zip_reader(&archive, path))
- throw std::runtime_error(std::string("Unable to init zip reader for ") + path);
+ throw Slic3r::FileIOError(std::string("Unable to init zip reader for ") + path);
std::vector scene_xml_data;
// For grouping multiple STLs into a single ModelObject for multi-material prints.
std::map group_to_model_object;
@@ -316,10 +316,10 @@ bool load_prus(const char *path, Model *model)
buffer.assign((size_t)stat.m_uncomp_size, 0);
res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, (char*)buffer.data(), (size_t)stat.m_uncomp_size, 0);
if (res == MZ_FALSE)
- std::runtime_error(std::string("Error while extracting a file from ") + path);
+ throw Slic3r::FileIOError(std::string("Error while extracting a file from ") + path);
if (strcmp(stat.m_filename, "scene.xml") == 0) {
if (! scene_xml_data.empty())
- throw std::runtime_error(std::string("Multiple scene.xml were found in the archive.") + path);
+ throw Slic3r::FileIOError(std::string("Multiple scene.xml were found in the archive.") + path);
scene_xml_data = std::move(buffer);
} else if (boost::iends_with(stat.m_filename, ".stl")) {
// May throw std::exception
diff --git a/src/libslic3r/Format/SL1.cpp b/src/libslic3r/Format/SL1.cpp
index ba5e89330b..274f84f002 100644
--- a/src/libslic3r/Format/SL1.cpp
+++ b/src/libslic3r/Format/SL1.cpp
@@ -8,8 +8,317 @@
#include "libslic3r/Zipper.hpp"
#include "libslic3r/SLAPrint.hpp"
+#include
+
+#include "libslic3r/Exception.hpp"
+#include "libslic3r/SlicesToTriangleMesh.hpp"
+#include "libslic3r/MarchingSquares.hpp"
+#include "libslic3r/ClipperUtils.hpp"
+#include "libslic3r/MTUtils.hpp"
+#include "libslic3r/PrintConfig.hpp"
+#include "libslic3r/SLA/RasterBase.hpp"
+#include "libslic3r/miniz_extension.hpp"
+#include "libslic3r/PNGRead.hpp"
+
+#include
+#include
+#include
+
+namespace marchsq {
+
+template<> struct _RasterTraits {
+ using Rst = Slic3r::png::ImageGreyscale;
+
+ // The type of pixel cell in the raster
+ using ValueType = uint8_t;
+
+ // Value at a given position
+ static uint8_t get(const Rst &rst, size_t row, size_t col)
+ {
+ return rst.get(row, col);
+ }
+
+ // Number of rows and cols of the raster
+ static size_t rows(const Rst &rst) { return rst.rows; }
+ static size_t cols(const Rst &rst) { return rst.cols; }
+};
+
+} // namespace marchsq
+
namespace Slic3r {
+namespace {
+
+struct PNGBuffer { std::vector buf; std::string fname; };
+struct ArchiveData {
+ boost::property_tree::ptree profile, config;
+ std::vector images;
+};
+
+static const constexpr char *CONFIG_FNAME = "config.ini";
+static const constexpr char *PROFILE_FNAME = "prusaslicer.ini";
+
+boost::property_tree::ptree read_ini(const mz_zip_archive_file_stat &entry,
+ MZ_Archive & zip)
+{
+ std::string buf(size_t(entry.m_uncomp_size), '\0');
+
+ if (!mz_zip_reader_extract_file_to_mem(&zip.arch, entry.m_filename,
+ buf.data(), buf.size(), 0))
+ throw Slic3r::FileIOError(zip.get_errorstr());
+
+ boost::property_tree::ptree tree;
+ std::stringstream ss(buf);
+ boost::property_tree::read_ini(ss, tree);
+ return tree;
+}
+
+PNGBuffer read_png(const mz_zip_archive_file_stat &entry,
+ MZ_Archive & zip,
+ const std::string & name)
+{
+ std::vector buf(entry.m_uncomp_size);
+
+ if (!mz_zip_reader_extract_file_to_mem(&zip.arch, entry.m_filename,
+ buf.data(), buf.size(), 0))
+ throw Slic3r::FileIOError(zip.get_errorstr());
+
+ return {std::move(buf), (name.empty() ? entry.m_filename : name)};
+}
+
+ArchiveData extract_sla_archive(const std::string &zipfname,
+ const std::string &exclude)
+{
+ ArchiveData arch;
+
+ // Little RAII
+ struct Arch: public MZ_Archive {
+ Arch(const std::string &fname) {
+ if (!open_zip_reader(&arch, fname))
+ throw Slic3r::FileIOError(get_errorstr());
+ }
+
+ ~Arch() { close_zip_reader(&arch); }
+ } zip (zipfname);
+
+ mz_uint num_entries = mz_zip_reader_get_num_files(&zip.arch);
+
+ for (mz_uint i = 0; i < num_entries; ++i)
+ {
+ mz_zip_archive_file_stat entry;
+
+ if (mz_zip_reader_file_stat(&zip.arch, i, &entry))
+ {
+ std::string name = entry.m_filename;
+ boost::algorithm::to_lower(name);
+
+ if (boost::algorithm::contains(name, exclude)) continue;
+
+ if (name == CONFIG_FNAME) arch.config = read_ini(entry, zip);
+ if (name == PROFILE_FNAME) arch.profile = read_ini(entry, zip);
+
+ if (boost::filesystem::path(name).extension().string() == ".png") {
+ auto it = std::lower_bound(
+ arch.images.begin(), arch.images.end(), PNGBuffer{{}, name},
+ [](const PNGBuffer &r1, const PNGBuffer &r2) {
+ return std::less()(r1.fname, r2.fname);
+ });
+
+ arch.images.insert(it, read_png(entry, zip, name));
+ }
+ }
+ }
+
+ return arch;
+}
+
+ExPolygons rings_to_expolygons(const std::vector &rings,
+ double px_w, double px_h)
+{
+ ExPolygons polys; polys.reserve(rings.size());
+
+ for (const marchsq::Ring &ring : rings) {
+ Polygon poly; Points &pts = poly.points;
+ pts.reserve(ring.size());
+
+ for (const marchsq::Coord &crd : ring)
+ pts.emplace_back(scaled(crd.c * px_w), scaled(crd.r * px_h));
+
+ polys.emplace_back(poly);
+ }
+
+ // reverse the raster transformations
+ return union_ex(polys);
+}
+
+template void foreach_vertex(ExPolygon &poly, Fn &&fn)
+{
+ for (auto &p : poly.contour.points) fn(p);
+ for (auto &h : poly.holes)
+ for (auto &p : h.points) fn(p);
+}
+
+void invert_raster_trafo(ExPolygons & expolys,
+ const sla::RasterBase::Trafo &trafo,
+ coord_t width,
+ coord_t height)
+{
+ if (trafo.flipXY) std::swap(height, width);
+
+ for (auto &expoly : expolys) {
+ if (trafo.mirror_y)
+ foreach_vertex(expoly, [height](Point &p) {p.y() = height - p.y(); });
+
+ if (trafo.mirror_x)
+ foreach_vertex(expoly, [width](Point &p) {p.x() = width - p.x(); });
+
+ expoly.translate(-trafo.center_x, -trafo.center_y);
+
+ if (trafo.flipXY)
+ foreach_vertex(expoly, [](Point &p) { std::swap(p.x(), p.y()); });
+
+ if ((trafo.mirror_x + trafo.mirror_y + trafo.flipXY) % 2) {
+ expoly.contour.reverse();
+ for (auto &h : expoly.holes) h.reverse();
+ }
+ }
+}
+
+struct RasterParams {
+ sla::RasterBase::Trafo trafo; // Raster transformations
+ coord_t width, height; // scaled raster dimensions (not resolution)
+ double px_h, px_w; // pixel dimesions
+ marchsq::Coord win; // marching squares window size
+};
+
+RasterParams get_raster_params(const DynamicPrintConfig &cfg)
+{
+ auto *opt_disp_cols = cfg.option("display_pixels_x");
+ auto *opt_disp_rows = cfg.option("display_pixels_y");
+ auto *opt_disp_w = cfg.option("display_width");
+ auto *opt_disp_h = cfg.option("display_height");
+ auto *opt_mirror_x = cfg.option("display_mirror_x");
+ auto *opt_mirror_y = cfg.option("display_mirror_y");
+ auto *opt_orient = cfg.option>("display_orientation");
+
+ if (!opt_disp_cols || !opt_disp_rows || !opt_disp_w || !opt_disp_h ||
+ !opt_mirror_x || !opt_mirror_y || !opt_orient)
+ throw Slic3r::FileIOError("Invalid SL1 file");
+
+ RasterParams rstp;
+
+ rstp.px_w = opt_disp_w->value / (opt_disp_cols->value - 1);
+ rstp.px_h = opt_disp_h->value / (opt_disp_rows->value - 1);
+
+ rstp.trafo = sla::RasterBase::Trafo{opt_orient->value == sladoLandscape ?
+ sla::RasterBase::roLandscape :
+ sla::RasterBase::roPortrait,
+ {opt_mirror_x->value, opt_mirror_y->value}};
+
+ rstp.height = scaled(opt_disp_h->value);
+ rstp.width = scaled(opt_disp_w->value);
+
+ return rstp;
+}
+
+struct SliceParams { double layerh = 0., initial_layerh = 0.; };
+
+SliceParams get_slice_params(const DynamicPrintConfig &cfg)
+{
+ auto *opt_layerh = cfg.option("layer_height");
+ auto *opt_init_layerh = cfg.option("initial_layer_height");
+
+ if (!opt_layerh || !opt_init_layerh)
+ throw Slic3r::FileIOError("Invalid SL1 file");
+
+ return SliceParams{opt_layerh->getFloat(), opt_init_layerh->getFloat()};
+}
+
+std::vector extract_slices_from_sla_archive(
+ ArchiveData & arch,
+ const RasterParams & rstp,
+ std::function progr)
+{
+ auto jobdir = arch.config.get("jobDir");
+ for (auto &c : jobdir) c = std::tolower(c);
+
+ std::vector slices(arch.images.size());
+
+ struct Status
+ {
+ double incr, val, prev;
+ bool stop = false;
+ tbb::spin_mutex mutex;
+ } st {100. / slices.size(), 0., 0.};
+
+ tbb::parallel_for(size_t(0), arch.images.size(),
+ [&arch, &slices, &st, &rstp, progr](size_t i) {
+ // Status indication guarded with the spinlock
+ {
+ std::lock_guard lck(st.mutex);
+ if (st.stop) return;
+
+ st.val += st.incr;
+ double curr = std::round(st.val);
+ if (curr > st.prev) {
+ st.prev = curr;
+ st.stop = !progr(int(curr));
+ }
+ }
+
+ png::ImageGreyscale img;
+ png::ReadBuf rb{arch.images[i].buf.data(), arch.images[i].buf.size()};
+ if (!png::decode_png(rb, img)) return;
+
+ auto rings = marchsq::execute(img, 128, rstp.win);
+ ExPolygons expolys = rings_to_expolygons(rings, rstp.px_w, rstp.px_h);
+
+ // Invert the raster transformations indicated in
+ // the profile metadata
+ invert_raster_trafo(expolys, rstp.trafo, rstp.width, rstp.height);
+
+ slices[i] = std::move(expolys);
+ });
+
+ if (st.stop) slices = {};
+
+ return slices;
+}
+
+} // namespace
+
+void import_sla_archive(const std::string &zipfname, DynamicPrintConfig &out)
+{
+ ArchiveData arch = extract_sla_archive(zipfname, "png");
+ out.load(arch.profile);
+}
+
+void import_sla_archive(
+ const std::string & zipfname,
+ Vec2i windowsize,
+ TriangleMesh & out,
+ DynamicPrintConfig & profile,
+ std::function progr)
+{
+ // Ensure minimum window size for marching squares
+ windowsize.x() = std::max(2, windowsize.x());
+ windowsize.y() = std::max(2, windowsize.y());
+
+ ArchiveData arch = extract_sla_archive(zipfname, "thumbnail");
+ profile.load(arch.profile);
+
+ RasterParams rstp = get_raster_params(profile);
+ rstp.win = {windowsize.y(), windowsize.x()};
+
+ SliceParams slicp = get_slice_params(profile);
+
+ std::vector slices =
+ extract_slices_from_sla_archive(arch, rstp, progr);
+
+ if (!slices.empty())
+ out = slices_to_triangle_mesh(slices, 0, slicp.layerh, slicp.initial_layerh);
+}
+
using ConfMap = std::map;
namespace {
@@ -126,9 +435,9 @@ uqptr SL1Archive::create_raster() const
return sla::create_raster_grayscale_aa(res, pxdim, gamma, tr);
}
-sla::EncodedRaster SL1Archive::encode_raster(const sla::RasterBase &rst) const
+sla::RasterEncoder SL1Archive::get_encoder() const
{
- return rst.encode(sla::PNGRasterEncoder());
+ return sla::PNGRasterEncoder{};
}
void SL1Archive::export_print(Zipper& zipper,
diff --git a/src/libslic3r/Format/SL1.hpp b/src/libslic3r/Format/SL1.hpp
index 1b9e95392b..ab731ff841 100644
--- a/src/libslic3r/Format/SL1.hpp
+++ b/src/libslic3r/Format/SL1.hpp
@@ -13,7 +13,7 @@ class SL1Archive: public SLAPrinter {
protected:
uqptr create_raster() const override;
- sla::EncodedRaster encode_raster(const sla::RasterBase &rst) const override;
+ sla::RasterEncoder get_encoder() const override;
public:
@@ -38,6 +38,24 @@ public:
}
};
+void import_sla_archive(const std::string &zipfname, DynamicPrintConfig &out);
+
+void import_sla_archive(
+ const std::string & zipfname,
+ Vec2i windowsize,
+ TriangleMesh & out,
+ DynamicPrintConfig & profile,
+ std::function progr = [](int) { return true; });
+
+inline void import_sla_archive(
+ const std::string & zipfname,
+ Vec2i windowsize,
+ TriangleMesh & out,
+ std::function progr = [](int) { return true; })
+{
+ DynamicPrintConfig profile;
+ import_sla_archive(zipfname, windowsize, out, profile, progr);
+}
} // namespace Slic3r::sla
diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp
index f863fd3ee8..88baa44772 100644
--- a/src/libslic3r/GCode.cpp
+++ b/src/libslic3r/GCode.cpp
@@ -1,6 +1,7 @@
#include "libslic3r.h"
#include "I18N.hpp"
#include "GCode.hpp"
+#include "Exception.hpp"
#include "ExtrusionEntity.hpp"
#include "EdgeGrid.hpp"
#include "Geometry.hpp"
@@ -48,606 +49,609 @@ using namespace std::literals::string_view_literals;
namespace Slic3r {
-//! macro used to mark string used at localization,
-//! return same string
+ //! macro used to mark string used at localization,
+ //! return same string
#define L(s) (s)
#define _(s) Slic3r::I18N::translate(s)
// Only add a newline in case the current G-code does not end with a newline.
-static inline void check_add_eol(std::string &gcode)
-{
- if (! gcode.empty() && gcode.back() != '\n')
- gcode += '\n';
-}
-
-
-// Return true if tch_prefix is found in custom_gcode
-static bool custom_gcode_changes_tool(const std::string& custom_gcode, const std::string& tch_prefix, unsigned next_extruder)
-{
- bool ok = false;
- size_t from_pos = 0;
- size_t pos = 0;
- while ((pos = custom_gcode.find(tch_prefix, from_pos)) != std::string::npos) {
- if (pos+1 == custom_gcode.size())
- break;
- from_pos = pos+1;
- // only whitespace is allowed before the command
- while (--pos < custom_gcode.size() && custom_gcode[pos] != '\n') {
- if (! std::isspace(custom_gcode[pos]))
- goto NEXT;
- }
- {
- // we should also check that the extruder changes to what was expected
- std::istringstream ss(custom_gcode.substr(from_pos, std::string::npos));
- unsigned num = 0;
- if (ss >> num)
- ok = (num == next_extruder);
- }
-NEXT: ;
+ static inline void check_add_eol(std::string& gcode)
+ {
+ if (!gcode.empty() && gcode.back() != '\n')
+ gcode += '\n';
}
- return ok;
-}
-void AvoidCrossingPerimeters::init_external_mp(const Print &print)
-{
- m_external_mp = Slic3r::make_unique(union_ex(this->collect_contours_all_layers(print.objects())));
-}
-// Plan a travel move while minimizing the number of perimeter crossings.
-// point is in unscaled coordinates, in the coordinate system of the current active object
-// (set by gcodegen.set_origin()).
-Polyline AvoidCrossingPerimeters::travel_to(const GCode &gcodegen, const Point &point)
-{
- // If use_external, then perform the path planning in the world coordinate system (correcting for the gcodegen offset).
- // Otherwise perform the path planning in the coordinate system of the active object.
- bool use_external = this->use_external_mp || this->use_external_mp_once;
- Point scaled_origin = use_external ? Point::new_scale(gcodegen.origin()(0), gcodegen.origin()(1)) : Point(0, 0);
- Polyline result = (use_external ? m_external_mp.get() : m_layer_mp.get())->
- shortest_path(gcodegen.last_pos() + scaled_origin, point + scaled_origin);
- if (use_external)
- result.translate(- scaled_origin);
- return result;
-}
-
-// Collect outer contours of all objects over all layers.
-// Discard objects only containing thin walls (offset would fail on an empty polygon).
-// Used by avoid crossing perimeters feature.
-Polygons AvoidCrossingPerimeters::collect_contours_all_layers(const PrintObjectPtrs& objects)
-{
- Polygons islands;
- for (const PrintObject *object : objects) {
- // Reducing all the object slices into the Z projection in a logarithimc fashion.
- // First reduce to half the number of layers.
- std::vector polygons_per_layer((object->layers().size() + 1) / 2);
- tbb::parallel_for(tbb::blocked_range(0, object->layers().size() / 2),
- [&object, &polygons_per_layer](const tbb::blocked_range &range) {
- for (size_t i = range.begin(); i < range.end(); ++ i) {
- const Layer* layer1 = object->layers()[i * 2];
- const Layer* layer2 = object->layers()[i * 2 + 1];
- Polygons polys;
- polys.reserve(layer1->lslices.size() + layer2->lslices.size());
- for (const ExPolygon &expoly : layer1->lslices)
- //FIXME no holes?
- polys.emplace_back(expoly.contour);
- for (const ExPolygon &expoly : layer2->lslices)
- //FIXME no holes?
- polys.emplace_back(expoly.contour);
- polygons_per_layer[i] = union_(polys);
- }
- });
- if (object->layers().size() & 1) {
- const Layer *layer = object->layers().back();
- Polygons polys;
- polys.reserve(layer->lslices.size());
- for (const ExPolygon &expoly : layer->lslices)
- //FIXME no holes?
- polys.emplace_back(expoly.contour);
- polygons_per_layer.back() = union_(polys);
- }
- // Now reduce down to a single layer.
- size_t cnt = polygons_per_layer.size();
- while (cnt > 1) {
- tbb::parallel_for(tbb::blocked_range(0, cnt / 2),
- [&polygons_per_layer](const tbb::blocked_range &range) {
- for (size_t i = range.begin(); i < range.end(); ++ i) {
- Polygons polys;
- polys.reserve(polygons_per_layer[i * 2].size() + polygons_per_layer[i * 2 + 1].size());
- polygons_append(polys, polygons_per_layer[i * 2]);
- polygons_append(polys, polygons_per_layer[i * 2 + 1]);
- polygons_per_layer[i * 2] = union_(polys);
- }
- });
- for (size_t i = 0; i < cnt / 2; ++ i)
- polygons_per_layer[i] = std::move(polygons_per_layer[i * 2]);
- if (cnt & 1)
- polygons_per_layer[cnt / 2] = std::move(polygons_per_layer[cnt - 1]);
- cnt = (cnt + 1) / 2;
- }
- // And collect copies of the objects.
- for (const PrintInstance &instance : object->instances()) {
- // All the layers were reduced to the 1st item of polygons_per_layer.
- size_t i = islands.size();
- polygons_append(islands, polygons_per_layer.front());
- for (; i < islands.size(); ++ i)
- islands[i].translate(instance.shift);
- }
- }
- return islands;
-}
-
-std::string OozePrevention::pre_toolchange(GCode &gcodegen)
-{
- std::string gcode;
-
- // move to the nearest standby point
- if (!this->standby_points.empty()) {
- // get current position in print coordinates
- Vec3d writer_pos = gcodegen.writer().get_position();
- Point pos = Point::new_scale(writer_pos(0), writer_pos(1));
-
- // find standby point
- Point standby_point;
- pos.nearest_point(this->standby_points, &standby_point);
-
- /* We don't call gcodegen.travel_to() because we don't need retraction (it was already
- triggered by the caller) nor avoid_crossing_perimeters and also because the coordinates
- of the destination point must not be transformed by origin nor current extruder offset. */
- gcode += gcodegen.writer().travel_to_xy(unscale(standby_point),
- "move to standby position");
- }
-
- if (gcodegen.config().standby_temperature_delta.value != 0) {
- // we assume that heating is always slower than cooling, so no need to block
- gcode += gcodegen.writer().set_temperature
- (this->_get_temp(gcodegen) + gcodegen.config().standby_temperature_delta.value, false, gcodegen.writer().extruder()->id());
- }
-
- return gcode;
-}
-
-std::string OozePrevention::post_toolchange(GCode &gcodegen)
-{
- return (gcodegen.config().standby_temperature_delta.value != 0) ?
- gcodegen.writer().set_temperature(this->_get_temp(gcodegen), true, gcodegen.writer().extruder()->id()) :
- std::string();
-}
-
-int
-OozePrevention::_get_temp(GCode &gcodegen)
-{
- return (gcodegen.layer() != NULL && gcodegen.layer()->id() == 0)
- ? gcodegen.config().first_layer_temperature.get_at(gcodegen.writer().extruder()->id())
- : gcodegen.config().temperature.get_at(gcodegen.writer().extruder()->id());
-}
-
-std::string Wipe::wipe(GCode &gcodegen, bool toolchange)
-{
- std::string gcode;
-
- /* Reduce feedrate a bit; travel speed is often too high to move on existing material.
- Too fast = ripping of existing material; too slow = short wipe path, thus more blob. */
- double wipe_speed = gcodegen.writer().config.travel_speed.value * 0.8;
-
- // get the retraction length
- double length = toolchange
- ? gcodegen.writer().extruder()->retract_length_toolchange()
- : gcodegen.writer().extruder()->retract_length();
- // Shorten the retraction length by the amount already retracted before wipe.
- length *= (1. - gcodegen.writer().extruder()->retract_before_wipe());
-
- if (length > 0) {
- /* Calculate how long we need to travel in order to consume the required
- amount of retraction. In other words, how far do we move in XY at wipe_speed
- for the time needed to consume retract_length at retract_speed? */
- double wipe_dist = scale_(length / gcodegen.writer().extruder()->retract_speed() * wipe_speed);
-
- /* Take the stored wipe path and replace first point with the current actual position
- (they might be different, for example, in case of loop clipping). */
- Polyline wipe_path;
- wipe_path.append(gcodegen.last_pos());
- wipe_path.append(
- this->path.points.begin() + 1,
- this->path.points.end()
- );
-
- wipe_path.clip_end(wipe_path.length() - wipe_dist);
-
- // subdivide the retraction in segments
- if (! wipe_path.empty()) {
- for (const Line &line : wipe_path.lines()) {
- double segment_length = line.length();
- /* Reduce retraction length a bit to avoid effective retraction speed to be greater than the configured one
- due to rounding (TODO: test and/or better math for this) */
- double dE = length * (segment_length / wipe_dist) * 0.95;
- //FIXME one shall not generate the unnecessary G1 Fxxx commands, here wipe_speed is a constant inside this cycle.
- // Is it here for the cooling markers? Or should it be outside of the cycle?
- gcode += gcodegen.writer().set_speed(wipe_speed*60, "", gcodegen.enable_cooling_markers() ? ";_WIPE" : "");
- gcode += gcodegen.writer().extrude_to_xy(
- gcodegen.point_to_gcode(line.b),
- -dE,
- "wipe and retract"
- );
+ // Return true if tch_prefix is found in custom_gcode
+ static bool custom_gcode_changes_tool(const std::string& custom_gcode, const std::string& tch_prefix, unsigned next_extruder)
+ {
+ bool ok = false;
+ size_t from_pos = 0;
+ size_t pos = 0;
+ while ((pos = custom_gcode.find(tch_prefix, from_pos)) != std::string::npos) {
+ if (pos + 1 == custom_gcode.size())
+ break;
+ from_pos = pos + 1;
+ // only whitespace is allowed before the command
+ while (--pos < custom_gcode.size() && custom_gcode[pos] != '\n') {
+ if (!std::isspace(custom_gcode[pos]))
+ goto NEXT;
}
- gcodegen.set_last_pos(wipe_path.points.back());
+ {
+ // we should also check that the extruder changes to what was expected
+ std::istringstream ss(custom_gcode.substr(from_pos, std::string::npos));
+ unsigned num = 0;
+ if (ss >> num)
+ ok = (num == next_extruder);
+ }
+ NEXT:;
}
-
- // prevent wiping again on same path
- this->reset_path();
- }
-
- return gcode;
-}
-
-static inline Point wipe_tower_point_to_object_point(GCode &gcodegen, const Vec2f &wipe_tower_pt)
-{
- return Point(scale_(wipe_tower_pt.x() - gcodegen.origin()(0)), scale_(wipe_tower_pt.y() - gcodegen.origin()(1)));
-}
-
-std::string WipeTowerIntegration::append_tcr(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, int new_extruder_id, double z) const
-{
- if (new_extruder_id != -1 && new_extruder_id != tcr.new_tool)
- throw std::invalid_argument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect.");
-
- std::string gcode;
-
- // Toolchangeresult.gcode assumes the wipe tower corner is at the origin (except for priming lines)
- // We want to rotate and shift all extrusions (gcode postprocessing) and starting and ending position
- float alpha = m_wipe_tower_rotation/180.f * float(M_PI);
- Vec2f start_pos = tcr.start_pos;
- Vec2f end_pos = tcr.end_pos;
- if (!tcr.priming) {
- start_pos = Eigen::Rotation2Df(alpha) * start_pos;
- start_pos += m_wipe_tower_pos;
- end_pos = Eigen::Rotation2Df(alpha) * end_pos;
- end_pos += m_wipe_tower_pos;
+ return ok;
}
- Vec2f wipe_tower_offset = tcr.priming ? Vec2f::Zero() : m_wipe_tower_pos;
- float wipe_tower_rotation = tcr.priming ? 0.f : alpha;
-
- std::string tcr_rotated_gcode = post_process_wipe_tower_moves(tcr, wipe_tower_offset, wipe_tower_rotation);
-
- if (!tcr.priming) {
- // Move over the wipe tower.
- // Retract for a tool change, using the toolchange retract value and setting the priming extra length.
- gcode += gcodegen.retract(true);
- gcodegen.m_avoid_crossing_perimeters.use_external_mp_once = true;
- gcode += gcodegen.travel_to(
- wipe_tower_point_to_object_point(gcodegen, start_pos),
- erMixed,
- "Travel to a Wipe Tower");
- gcode += gcodegen.unretract();
+ void AvoidCrossingPerimeters::init_external_mp(const Print& print)
+ {
+ m_external_mp = Slic3r::make_unique(union_ex(this->collect_contours_all_layers(print.objects())));
}
- double current_z = gcodegen.writer().get_position().z();
- if (z == -1.) // in case no specific z was provided, print at current_z pos
- z = current_z;
- if (! is_approx(z, current_z)) {
- gcode += gcodegen.writer().retract();
- gcode += gcodegen.writer().travel_to_z(z, "Travel down to the last wipe tower layer.");
- gcode += gcodegen.writer().unretract();
+ // Plan a travel move while minimizing the number of perimeter crossings.
+ // point is in unscaled coordinates, in the coordinate system of the current active object
+ // (set by gcodegen.set_origin()).
+ Polyline AvoidCrossingPerimeters::travel_to(const GCode& gcodegen, const Point& point)
+ {
+ // If use_external, then perform the path planning in the world coordinate system (correcting for the gcodegen offset).
+ // Otherwise perform the path planning in the coordinate system of the active object.
+ bool use_external = this->use_external_mp || this->use_external_mp_once;
+ Point scaled_origin = use_external ? Point::new_scale(gcodegen.origin()(0), gcodegen.origin()(1)) : Point(0, 0);
+ Polyline result = (use_external ? m_external_mp.get() : m_layer_mp.get())->
+ shortest_path(gcodegen.last_pos() + scaled_origin, point + scaled_origin);
+ if (use_external)
+ result.translate(-scaled_origin);
+ return result;
}
-
- // Process the end filament gcode.
- std::string end_filament_gcode_str;
- if (gcodegen.writer().extruder() != nullptr) {
- // Process the custom end_filament_gcode in case of single_extruder_multi_material.
- unsigned int old_extruder_id = gcodegen.writer().extruder()->id();
- const std::string &end_filament_gcode = gcodegen.config().end_filament_gcode.get_at(old_extruder_id);
- if (gcodegen.writer().extruder() != nullptr && ! end_filament_gcode.empty()) {
- end_filament_gcode_str = gcodegen.placeholder_parser_process("end_filament_gcode", end_filament_gcode, old_extruder_id);
- check_add_eol(end_filament_gcode_str);
+ // Collect outer contours of all objects over all layers.
+ // Discard objects only containing thin walls (offset would fail on an empty polygon).
+ // Used by avoid crossing perimeters feature.
+ Polygons AvoidCrossingPerimeters::collect_contours_all_layers(const PrintObjectPtrs& objects)
+ {
+ Polygons islands;
+ for (const PrintObject* object : objects) {
+ // Reducing all the object slices into the Z projection in a logarithimc fashion.
+ // First reduce to half the number of layers.
+ std::vector polygons_per_layer((object->layers().size() + 1) / 2);
+ tbb::parallel_for(tbb::blocked_range(0, object->layers().size() / 2),
+ [&object, &polygons_per_layer](const tbb::blocked_range& range) {
+ for (size_t i = range.begin(); i < range.end(); ++i) {
+ const Layer* layer1 = object->layers()[i * 2];
+ const Layer* layer2 = object->layers()[i * 2 + 1];
+ Polygons polys;
+ polys.reserve(layer1->lslices.size() + layer2->lslices.size());
+ for (const ExPolygon& expoly : layer1->lslices)
+ //FIXME no holes?
+ polys.emplace_back(expoly.contour);
+ for (const ExPolygon& expoly : layer2->lslices)
+ //FIXME no holes?
+ polys.emplace_back(expoly.contour);
+ polygons_per_layer[i] = union_(polys);
+ }
+ });
+ if (object->layers().size() & 1) {
+ const Layer* layer = object->layers().back();
+ Polygons polys;
+ polys.reserve(layer->lslices.size());
+ for (const ExPolygon& expoly : layer->lslices)
+ //FIXME no holes?
+ polys.emplace_back(expoly.contour);
+ polygons_per_layer.back() = union_(polys);
+ }
+ // Now reduce down to a single layer.
+ size_t cnt = polygons_per_layer.size();
+ while (cnt > 1) {
+ tbb::parallel_for(tbb::blocked_range(0, cnt / 2),
+ [&polygons_per_layer](const tbb::blocked_range& range) {
+ for (size_t i = range.begin(); i < range.end(); ++i) {
+ Polygons polys;
+ polys.reserve(polygons_per_layer[i * 2].size() + polygons_per_layer[i * 2 + 1].size());
+ polygons_append(polys, polygons_per_layer[i * 2]);
+ polygons_append(polys, polygons_per_layer[i * 2 + 1]);
+ polygons_per_layer[i * 2] = union_(polys);
+ }
+ });
+ for (size_t i = 0; i < cnt / 2; ++i)
+ polygons_per_layer[i] = std::move(polygons_per_layer[i * 2]);
+ if (cnt & 1)
+ polygons_per_layer[cnt / 2] = std::move(polygons_per_layer[cnt - 1]);
+ cnt = (cnt + 1) / 2;
+ }
+ // And collect copies of the objects.
+ for (const PrintInstance& instance : object->instances()) {
+ // All the layers were reduced to the 1st item of polygons_per_layer.
+ size_t i = islands.size();
+ polygons_append(islands, polygons_per_layer.front());
+ for (; i < islands.size(); ++i)
+ islands[i].translate(instance.shift);
+ }
}
+ return islands;
}
- // Process the custom toolchange_gcode. If it is empty, provide a simple Tn command to change the filament.
- // Otherwise, leave control to the user completely.
- std::string toolchange_gcode_str;
- if (true /*gcodegen.writer().extruder() != nullptr*/) {
- const std::string& toolchange_gcode = gcodegen.config().toolchange_gcode.value;
- if (!toolchange_gcode.empty()) {
+ std::string OozePrevention::pre_toolchange(GCode& gcodegen)
+ {
+ std::string gcode;
+
+ // move to the nearest standby point
+ if (!this->standby_points.empty()) {
+ // get current position in print coordinates
+ Vec3d writer_pos = gcodegen.writer().get_position();
+ Point pos = Point::new_scale(writer_pos(0), writer_pos(1));
+
+ // find standby point
+ Point standby_point;
+ pos.nearest_point(this->standby_points, &standby_point);
+
+ /* We don't call gcodegen.travel_to() because we don't need retraction (it was already
+ triggered by the caller) nor avoid_crossing_perimeters and also because the coordinates
+ of the destination point must not be transformed by origin nor current extruder offset. */
+ gcode += gcodegen.writer().travel_to_xy(unscale(standby_point),
+ "move to standby position");
+ }
+
+ if (gcodegen.config().standby_temperature_delta.value != 0) {
+ // we assume that heating is always slower than cooling, so no need to block
+ gcode += gcodegen.writer().set_temperature
+ (this->_get_temp(gcodegen) + gcodegen.config().standby_temperature_delta.value, false, gcodegen.writer().extruder()->id());
+ }
+
+ return gcode;
+ }
+
+ std::string OozePrevention::post_toolchange(GCode& gcodegen)
+ {
+ return (gcodegen.config().standby_temperature_delta.value != 0) ?
+ gcodegen.writer().set_temperature(this->_get_temp(gcodegen), true, gcodegen.writer().extruder()->id()) :
+ std::string();
+ }
+
+ int
+ OozePrevention::_get_temp(GCode& gcodegen)
+ {
+ return (gcodegen.layer() != NULL && gcodegen.layer()->id() == 0)
+ ? gcodegen.config().first_layer_temperature.get_at(gcodegen.writer().extruder()->id())
+ : gcodegen.config().temperature.get_at(gcodegen.writer().extruder()->id());
+ }
+
+ std::string Wipe::wipe(GCode& gcodegen, bool toolchange)
+ {
+ std::string gcode;
+
+ /* Reduce feedrate a bit; travel speed is often too high to move on existing material.
+ Too fast = ripping of existing material; too slow = short wipe path, thus more blob. */
+ double wipe_speed = gcodegen.writer().config.travel_speed.value * 0.8;
+
+ // get the retraction length
+ double length = toolchange
+ ? gcodegen.writer().extruder()->retract_length_toolchange()
+ : gcodegen.writer().extruder()->retract_length();
+ // Shorten the retraction length by the amount already retracted before wipe.
+ length *= (1. - gcodegen.writer().extruder()->retract_before_wipe());
+
+ if (length > 0) {
+ /* Calculate how long we need to travel in order to consume the required
+ amount of retraction. In other words, how far do we move in XY at wipe_speed
+ for the time needed to consume retract_length at retract_speed? */
+ double wipe_dist = scale_(length / gcodegen.writer().extruder()->retract_speed() * wipe_speed);
+
+ /* Take the stored wipe path and replace first point with the current actual position
+ (they might be different, for example, in case of loop clipping). */
+ Polyline wipe_path;
+ wipe_path.append(gcodegen.last_pos());
+ wipe_path.append(
+ this->path.points.begin() + 1,
+ this->path.points.end()
+ );
+
+ wipe_path.clip_end(wipe_path.length() - wipe_dist);
+
+ // subdivide the retraction in segments
+ if (!wipe_path.empty()) {
+ for (const Line& line : wipe_path.lines()) {
+ double segment_length = line.length();
+ /* Reduce retraction length a bit to avoid effective retraction speed to be greater than the configured one
+ due to rounding (TODO: test and/or better math for this) */
+ double dE = length * (segment_length / wipe_dist) * 0.95;
+ //FIXME one shall not generate the unnecessary G1 Fxxx commands, here wipe_speed is a constant inside this cycle.
+ // Is it here for the cooling markers? Or should it be outside of the cycle?
+ gcode += gcodegen.writer().set_speed(wipe_speed * 60, "", gcodegen.enable_cooling_markers() ? ";_WIPE" : "");
+ gcode += gcodegen.writer().extrude_to_xy(
+ gcodegen.point_to_gcode(line.b),
+ -dE,
+ "wipe and retract"
+ );
+ }
+ gcodegen.set_last_pos(wipe_path.points.back());
+ }
+
+ // prevent wiping again on same path
+ this->reset_path();
+ }
+
+ return gcode;
+ }
+
+ static inline Point wipe_tower_point_to_object_point(GCode& gcodegen, const Vec2f& wipe_tower_pt)
+ {
+ return Point(scale_(wipe_tower_pt.x() - gcodegen.origin()(0)), scale_(wipe_tower_pt.y() - gcodegen.origin()(1)));
+ }
+
+ std::string WipeTowerIntegration::append_tcr(GCode& gcodegen, const WipeTower::ToolChangeResult& tcr, int new_extruder_id, double z) const
+ {
+ if (new_extruder_id != -1 && new_extruder_id != tcr.new_tool)
+ throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect.");
+
+ std::string gcode;
+
+ // Toolchangeresult.gcode assumes the wipe tower corner is at the origin (except for priming lines)
+ // We want to rotate and shift all extrusions (gcode postprocessing) and starting and ending position
+ float alpha = m_wipe_tower_rotation / 180.f * float(M_PI);
+ Vec2f start_pos = tcr.start_pos;
+ Vec2f end_pos = tcr.end_pos;
+ if (!tcr.priming) {
+ start_pos = Eigen::Rotation2Df(alpha) * start_pos;
+ start_pos += m_wipe_tower_pos;
+ end_pos = Eigen::Rotation2Df(alpha) * end_pos;
+ end_pos += m_wipe_tower_pos;
+ }
+
+ Vec2f wipe_tower_offset = tcr.priming ? Vec2f::Zero() : m_wipe_tower_pos;
+ float wipe_tower_rotation = tcr.priming ? 0.f : alpha;
+
+ std::string tcr_rotated_gcode = post_process_wipe_tower_moves(tcr, wipe_tower_offset, wipe_tower_rotation);
+
+ if (!tcr.priming) {
+ // Move over the wipe tower.
+ // Retract for a tool change, using the toolchange retract value and setting the priming extra length.
+ gcode += gcodegen.retract(true);
+ gcodegen.m_avoid_crossing_perimeters.use_external_mp_once = true;
+ gcode += gcodegen.travel_to(
+ wipe_tower_point_to_object_point(gcodegen, start_pos),
+ erMixed,
+ "Travel to a Wipe Tower");
+ gcode += gcodegen.unretract();
+ }
+
+ double current_z = gcodegen.writer().get_position().z();
+ if (z == -1.) // in case no specific z was provided, print at current_z pos
+ z = current_z;
+ if (!is_approx(z, current_z)) {
+ gcode += gcodegen.writer().retract();
+ gcode += gcodegen.writer().travel_to_z(z, "Travel down to the last wipe tower layer.");
+ gcode += gcodegen.writer().unretract();
+ }
+
+
+ // Process the end filament gcode.
+ std::string end_filament_gcode_str;
+ if (gcodegen.writer().extruder() != nullptr) {
+ // Process the custom end_filament_gcode in case of single_extruder_multi_material.
+ unsigned int old_extruder_id = gcodegen.writer().extruder()->id();
+ const std::string& end_filament_gcode = gcodegen.config().end_filament_gcode.get_at(old_extruder_id);
+ if (gcodegen.writer().extruder() != nullptr && !end_filament_gcode.empty()) {
+ end_filament_gcode_str = gcodegen.placeholder_parser_process("end_filament_gcode", end_filament_gcode, old_extruder_id);
+ check_add_eol(end_filament_gcode_str);
+ }
+ }
+
+ // Process the custom toolchange_gcode. If it is empty, provide a simple Tn command to change the filament.
+ // Otherwise, leave control to the user completely.
+ std::string toolchange_gcode_str;
+ if (true /*gcodegen.writer().extruder() != nullptr*/) {
+ const std::string& toolchange_gcode = gcodegen.config().toolchange_gcode.value;
+ if (!toolchange_gcode.empty()) {
+ DynamicConfig config;
+ int previous_extruder_id = gcodegen.writer().extruder() ? (int)gcodegen.writer().extruder()->id() : -1;
+ config.set_key_value("previous_extruder", new ConfigOptionInt(previous_extruder_id));
+ config.set_key_value("next_extruder", new ConfigOptionInt((int)new_extruder_id));
+ config.set_key_value("layer_num", new ConfigOptionInt(gcodegen.m_layer_index));
+ config.set_key_value("layer_z", new ConfigOptionFloat(tcr.print_z));
+ toolchange_gcode_str = gcodegen.placeholder_parser_process("toolchange_gcode", toolchange_gcode, new_extruder_id, &config);
+ check_add_eol(toolchange_gcode_str);
+ }
+
+ std::string toolchange_command;
+ if (tcr.priming || (new_extruder_id >= 0 && gcodegen.writer().need_toolchange(new_extruder_id)))
+ toolchange_command = gcodegen.writer().toolchange(new_extruder_id);
+ if (!custom_gcode_changes_tool(toolchange_gcode_str, gcodegen.writer().toolchange_prefix(), new_extruder_id))
+ toolchange_gcode_str += toolchange_command;
+ else {
+ // We have informed the m_writer about the current extruder_id, we can ignore the generated G-code.
+ }
+ }
+
+ gcodegen.placeholder_parser().set("current_extruder", new_extruder_id);
+
+ // Process the start filament gcode.
+ std::string start_filament_gcode_str;
+ const std::string& start_filament_gcode = gcodegen.config().start_filament_gcode.get_at(new_extruder_id);
+ if (!start_filament_gcode.empty()) {
+ // Process the start_filament_gcode for the active filament only.
DynamicConfig config;
- int previous_extruder_id = gcodegen.writer().extruder() ? (int)gcodegen.writer().extruder()->id() : -1;
- config.set_key_value("previous_extruder", new ConfigOptionInt(previous_extruder_id));
- config.set_key_value("next_extruder", new ConfigOptionInt((int)new_extruder_id));
- config.set_key_value("layer_num", new ConfigOptionInt(gcodegen.m_layer_index));
- config.set_key_value("layer_z", new ConfigOptionFloat(tcr.print_z));
- toolchange_gcode_str = gcodegen.placeholder_parser_process("toolchange_gcode", toolchange_gcode, new_extruder_id, &config);
- check_add_eol(toolchange_gcode_str);
+ config.set_key_value("filament_extruder_id", new ConfigOptionInt(new_extruder_id));
+ start_filament_gcode_str = gcodegen.placeholder_parser_process("start_filament_gcode", start_filament_gcode, new_extruder_id, &config);
+ check_add_eol(start_filament_gcode_str);
}
- std::string toolchange_command;
- if (tcr.priming || (new_extruder_id >= 0 && gcodegen.writer().need_toolchange(new_extruder_id)))
- toolchange_command = gcodegen.writer().toolchange(new_extruder_id);
- if (! custom_gcode_changes_tool(toolchange_gcode_str, gcodegen.writer().toolchange_prefix(), new_extruder_id))
- toolchange_gcode_str += toolchange_command;
- else {
- // We have informed the m_writer about the current extruder_id, we can ignore the generated G-code.
- }
- }
-
- gcodegen.placeholder_parser().set("current_extruder", new_extruder_id);
-
- // Process the start filament gcode.
- std::string start_filament_gcode_str;
- const std::string &start_filament_gcode = gcodegen.config().start_filament_gcode.get_at(new_extruder_id);
- if (! start_filament_gcode.empty()) {
- // Process the start_filament_gcode for the active filament only.
+ // Insert the end filament, toolchange, and start filament gcode into the generated gcode.
DynamicConfig config;
- config.set_key_value("filament_extruder_id", new ConfigOptionInt(new_extruder_id));
- start_filament_gcode_str = gcodegen.placeholder_parser_process("start_filament_gcode", start_filament_gcode, new_extruder_id, &config);
- check_add_eol(start_filament_gcode_str);
+ config.set_key_value("end_filament_gcode", new ConfigOptionString(end_filament_gcode_str));
+ config.set_key_value("toolchange_gcode", new ConfigOptionString(toolchange_gcode_str));
+ config.set_key_value("start_filament_gcode", new ConfigOptionString(start_filament_gcode_str));
+ std::string tcr_gcode, tcr_escaped_gcode = gcodegen.placeholder_parser_process("tcr_rotated_gcode", tcr_rotated_gcode, new_extruder_id, &config);
+ unescape_string_cstyle(tcr_escaped_gcode, tcr_gcode);
+ gcode += tcr_gcode;
+ check_add_eol(toolchange_gcode_str);
+
+
+ // A phony move to the end position at the wipe tower.
+ gcodegen.writer().travel_to_xy(end_pos.cast());
+ gcodegen.set_last_pos(wipe_tower_point_to_object_point(gcodegen, end_pos));
+ if (!is_approx(z, current_z)) {
+ gcode += gcodegen.writer().retract();
+ gcode += gcodegen.writer().travel_to_z(current_z, "Travel back up to the topmost object layer.");
+ gcode += gcodegen.writer().unretract();
+ }
+
+ else {
+ // Prepare a future wipe.
+ gcodegen.m_wipe.path.points.clear();
+ if (new_extruder_id >= 0) {
+ // Start the wipe at the current position.
+ gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen, end_pos));
+ // Wipe end point: Wipe direction away from the closer tower edge to the further tower edge.
+ gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen,
+ Vec2f((std::abs(m_left - end_pos.x()) < std::abs(m_right - end_pos.x())) ? m_right : m_left,
+ end_pos.y())));
+ }
+ }
+
+ // Let the planner know we are traveling between objects.
+ gcodegen.m_avoid_crossing_perimeters.use_external_mp_once = true;
+ return gcode;
}
- // Insert the end filament, toolchange, and start filament gcode into the generated gcode.
- DynamicConfig config;
- config.set_key_value("end_filament_gcode", new ConfigOptionString(end_filament_gcode_str));
- config.set_key_value("toolchange_gcode", new ConfigOptionString(toolchange_gcode_str));
- config.set_key_value("start_filament_gcode", new ConfigOptionString(start_filament_gcode_str));
- std::string tcr_gcode, tcr_escaped_gcode = gcodegen.placeholder_parser_process("tcr_rotated_gcode", tcr_rotated_gcode, new_extruder_id, &config);
- unescape_string_cstyle(tcr_escaped_gcode, tcr_gcode);
- gcode += tcr_gcode;
- check_add_eol(toolchange_gcode_str);
+ // This function postprocesses gcode_original, rotates and moves all G1 extrusions and returns resulting gcode
+ // Starting position has to be supplied explicitely (otherwise it would fail in case first G1 command only contained one coordinate)
+ std::string WipeTowerIntegration::post_process_wipe_tower_moves(const WipeTower::ToolChangeResult& tcr, const Vec2f& translation, float angle) const
+ {
+ Vec2f extruder_offset = m_extruder_offsets[tcr.initial_tool].cast();
+ std::istringstream gcode_str(tcr.gcode);
+ std::string gcode_out;
+ std::string line;
+ Vec2f pos = tcr.start_pos;
+ Vec2f transformed_pos = pos;
+ Vec2f old_pos(-1000.1f, -1000.1f);
- // A phony move to the end position at the wipe tower.
- gcodegen.writer().travel_to_xy(end_pos.cast());
- gcodegen.set_last_pos(wipe_tower_point_to_object_point(gcodegen, end_pos));
- if (! is_approx(z, current_z)) {
- gcode += gcodegen.writer().retract();
- gcode += gcodegen.writer().travel_to_z(current_z, "Travel back up to the topmost object layer.");
- gcode += gcodegen.writer().unretract();
+ while (gcode_str) {
+ std::getline(gcode_str, line); // we read the gcode line by line
+
+ // All G1 commands should be translated and rotated. X and Y coords are
+ // only pushed to the output when they differ from last time.
+ // WT generator can override this by appending the never_skip_tag
+ if (line.find("G1 ") == 0) {
+ bool never_skip = false;
+ auto it = line.find(WipeTower::never_skip_tag());
+ if (it != std::string::npos) {
+ // remove the tag and remember we saw it
+ never_skip = true;
+ line.erase(it, it + WipeTower::never_skip_tag().size());
+ }
+ std::ostringstream line_out;
+ std::istringstream line_str(line);
+ line_str >> std::noskipws; // don't skip whitespace
+ char ch = 0;
+ while (line_str >> ch) {
+ if (ch == 'X' || ch == 'Y')
+ line_str >> (ch == 'X' ? pos.x() : pos.y());
+ else
+ line_out << ch;
+ }
+
+ transformed_pos = Eigen::Rotation2Df(angle) * pos + translation;
+
+ if (transformed_pos != old_pos || never_skip) {
+ line = line_out.str();
+ std::ostringstream oss;
+ oss << std::fixed << std::setprecision(3) << "G1 ";
+ if (transformed_pos.x() != old_pos.x() || never_skip)
+ oss << " X" << transformed_pos.x() - extruder_offset.x();
+ if (transformed_pos.y() != old_pos.y() || never_skip)
+ oss << " Y" << transformed_pos.y() - extruder_offset.y();
+ oss << " ";
+ line.replace(line.find("G1 "), 3, oss.str());
+ old_pos = transformed_pos;
+ }
+ }
+
+ gcode_out += line + "\n";
+
+ // If this was a toolchange command, we should change current extruder offset
+ if (line == "[toolchange_gcode]") {
+ extruder_offset = m_extruder_offsets[tcr.new_tool].cast();
+
+ // If the extruder offset changed, add an extra move so everything is continuous
+ if (extruder_offset != m_extruder_offsets[tcr.initial_tool].cast()) {
+ std::ostringstream oss;
+ oss << std::fixed << std::setprecision(3)
+ << "G1 X" << transformed_pos.x() - extruder_offset.x()
+ << " Y" << transformed_pos.y() - extruder_offset.y()
+ << "\n";
+ gcode_out += oss.str();
+ }
+ }
+ }
+ return gcode_out;
}
- else {
+
+ std::string WipeTowerIntegration::prime(GCode& gcodegen)
+ {
+ assert(m_layer_idx == 0);
+ std::string gcode;
+
+
+ // Disable linear advance for the wipe tower operations.
+ //gcode += (gcodegen.config().gcode_flavor == gcfRepRapSprinter ? std::string("M572 D0 S0\n") : std::string("M900 K0\n"));
+
+ for (const WipeTower::ToolChangeResult& tcr : m_priming) {
+ if (!tcr.extrusions.empty())
+ gcode += append_tcr(gcodegen, tcr, tcr.new_tool);
+
+
+ // Let the tool change be executed by the wipe tower class.
+ // Inform the G-code writer about the changes done behind its back.
+ //gcode += tcr.gcode;
+ // Let the m_writer know the current extruder_id, but ignore the generated G-code.
+ // unsigned int current_extruder_id = tcr.extrusions.back().tool;
+ // gcodegen.writer().toolchange(current_extruder_id);
+ // gcodegen.placeholder_parser().set("current_extruder", current_extruder_id);
+
+ }
+
+ // A phony move to the end position at the wipe tower.
+ /* gcodegen.writer().travel_to_xy(Vec2d(m_priming.back().end_pos.x, m_priming.back().end_pos.y));
+ gcodegen.set_last_pos(wipe_tower_point_to_object_point(gcodegen, m_priming.back().end_pos));
// Prepare a future wipe.
gcodegen.m_wipe.path.points.clear();
- if (new_extruder_id >= 0) {
- // Start the wipe at the current position.
- gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen, end_pos));
- // Wipe end point: Wipe direction away from the closer tower edge to the further tower edge.
- gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen,
- Vec2f((std::abs(m_left - end_pos.x()) < std::abs(m_right - end_pos.x())) ? m_right : m_left,
- end_pos.y())));
+ // Start the wipe at the current position.
+ gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen, m_priming.back().end_pos));
+ // Wipe end point: Wipe direction away from the closer tower edge to the further tower edge.
+ gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen,
+ WipeTower::xy((std::abs(m_left - m_priming.back().end_pos.x) < std::abs(m_right - m_priming.back().end_pos.x)) ? m_right : m_left,
+ m_priming.back().end_pos.y)));*/
+
+ return gcode;
+ }
+
+ std::string WipeTowerIntegration::tool_change(GCode& gcodegen, int extruder_id, bool finish_layer)
+ {
+ std::string gcode;
+ assert(m_layer_idx >= 0);
+ if (!m_brim_done || gcodegen.writer().need_toolchange(extruder_id) || finish_layer) {
+ if (m_layer_idx < (int)m_tool_changes.size()) {
+ if (!(size_t(m_tool_change_idx) < m_tool_changes[m_layer_idx].size()))
+ throw Slic3r::RuntimeError("Wipe tower generation failed, possibly due to empty first layer.");
+
+
+ // Calculate where the wipe tower layer will be printed. -1 means that print z will not change,
+ // resulting in a wipe tower with sparse layers.
+ double wipe_tower_z = -1;
+ bool ignore_sparse = false;
+ if (gcodegen.config().wipe_tower_no_sparse_layers.value) {
+ wipe_tower_z = m_last_wipe_tower_print_z;
+ ignore_sparse = (m_brim_done && m_tool_changes[m_layer_idx].size() == 1 && m_tool_changes[m_layer_idx].front().initial_tool == m_tool_changes[m_layer_idx].front().new_tool);
+ if (m_tool_change_idx == 0 && !ignore_sparse)
+ wipe_tower_z = m_last_wipe_tower_print_z + m_tool_changes[m_layer_idx].front().layer_height;
+ }
+
+ if (!ignore_sparse) {
+ gcode += append_tcr(gcodegen, m_tool_changes[m_layer_idx][m_tool_change_idx++], extruder_id, wipe_tower_z);
+ m_last_wipe_tower_print_z = wipe_tower_z;
+ }
+ }
+ m_brim_done = true;
}
+ return gcode;
}
- // Let the planner know we are traveling between objects.
- gcodegen.m_avoid_crossing_perimeters.use_external_mp_once = true;
- return gcode;
-}
-
-// This function postprocesses gcode_original, rotates and moves all G1 extrusions and returns resulting gcode
-// Starting position has to be supplied explicitely (otherwise it would fail in case first G1 command only contained one coordinate)
-std::string WipeTowerIntegration::post_process_wipe_tower_moves(const WipeTower::ToolChangeResult& tcr, const Vec2f& translation, float angle) const
-{
- Vec2f extruder_offset = m_extruder_offsets[tcr.initial_tool].cast();
-
- std::istringstream gcode_str(tcr.gcode);
- std::string gcode_out;
- std::string line;
- Vec2f pos = tcr.start_pos;
- Vec2f transformed_pos = pos;
- Vec2f old_pos(-1000.1f, -1000.1f);
-
- while (gcode_str) {
- std::getline(gcode_str, line); // we read the gcode line by line
-
- // All G1 commands should be translated and rotated. X and Y coords are
- // only pushed to the output when they differ from last time.
- // WT generator can override this by appending the never_skip_tag
- if (line.find("G1 ") == 0) {
- bool never_skip = false;
- auto it = line.find(WipeTower::never_skip_tag());
- if (it != std::string::npos) {
- // remove the tag and remember we saw it
- never_skip = true;
- line.erase(it, it+WipeTower::never_skip_tag().size());
- }
- std::ostringstream line_out;
- std::istringstream line_str(line);
- line_str >> std::noskipws; // don't skip whitespace
- char ch = 0;
- while (line_str >> ch) {
- if (ch == 'X' || ch =='Y')
- line_str >> (ch == 'X' ? pos.x() : pos.y());
- else
- line_out << ch;
- }
-
- transformed_pos = Eigen::Rotation2Df(angle) * pos + translation;
-
- if (transformed_pos != old_pos || never_skip) {
- line = line_out.str();
- std::ostringstream oss;
- oss << std::fixed << std::setprecision(3) << "G1 ";
- if (transformed_pos.x() != old_pos.x() || never_skip)
- oss << " X" << transformed_pos.x() - extruder_offset.x();
- if (transformed_pos.y() != old_pos.y() || never_skip)
- oss << " Y" << transformed_pos.y() - extruder_offset.y();
- oss << " ";
- line.replace(line.find("G1 "), 3, oss.str());
- old_pos = transformed_pos;
- }
- }
-
- gcode_out += line + "\n";
-
- // If this was a toolchange command, we should change current extruder offset
- if (line == "[toolchange_gcode]") {
- extruder_offset = m_extruder_offsets[tcr.new_tool].cast();
-
- // If the extruder offset changed, add an extra move so everything is continuous
- if (extruder_offset != m_extruder_offsets[tcr.initial_tool].cast()) {
- std::ostringstream oss;
- oss << std::fixed << std::setprecision(3)
- << "G1 X" << transformed_pos.x() - extruder_offset.x()
- << " Y" << transformed_pos.y() - extruder_offset.y()
- << "\n";
- gcode_out += oss.str();
- }
- }
- }
- return gcode_out;
-}
-
-
-std::string WipeTowerIntegration::prime(GCode &gcodegen)
-{
- assert(m_layer_idx == 0);
- std::string gcode;
-
-
- // Disable linear advance for the wipe tower operations.
- //gcode += (gcodegen.config().gcode_flavor == gcfRepRapSprinter ? std::string("M572 D0 S0\n") : std::string("M900 K0\n"));
-
- for (const WipeTower::ToolChangeResult& tcr : m_priming) {
- if (!tcr.extrusions.empty())
- gcode += append_tcr(gcodegen, tcr, tcr.new_tool);
-
-
- // Let the tool change be executed by the wipe tower class.
- // Inform the G-code writer about the changes done behind its back.
- //gcode += tcr.gcode;
- // Let the m_writer know the current extruder_id, but ignore the generated G-code.
- // unsigned int current_extruder_id = tcr.extrusions.back().tool;
- // gcodegen.writer().toolchange(current_extruder_id);
- // gcodegen.placeholder_parser().set("current_extruder", current_extruder_id);
-
+ // Print is finished. Now it remains to unload the filament safely with ramming over the wipe tower.
+ std::string WipeTowerIntegration::finalize(GCode& gcodegen)
+ {
+ std::string gcode;
+ if (std::abs(gcodegen.writer().get_position()(2) - m_final_purge.print_z) > EPSILON)
+ gcode += gcodegen.change_layer(m_final_purge.print_z);
+ gcode += append_tcr(gcodegen, m_final_purge, -1);
+ return gcode;
}
- // A phony move to the end position at the wipe tower.
- /* gcodegen.writer().travel_to_xy(Vec2d(m_priming.back().end_pos.x, m_priming.back().end_pos.y));
- gcodegen.set_last_pos(wipe_tower_point_to_object_point(gcodegen, m_priming.back().end_pos));
- // Prepare a future wipe.
- gcodegen.m_wipe.path.points.clear();
- // Start the wipe at the current position.
- gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen, m_priming.back().end_pos));
- // Wipe end point: Wipe direction away from the closer tower edge to the further tower edge.
- gcodegen.m_wipe.path.points.emplace_back(wipe_tower_point_to_object_point(gcodegen,
- WipeTower::xy((std::abs(m_left - m_priming.back().end_pos.x) < std::abs(m_right - m_priming.back().end_pos.x)) ? m_right : m_left,
- m_priming.back().end_pos.y)));*/
-
- return gcode;
-}
-
-std::string WipeTowerIntegration::tool_change(GCode &gcodegen, int extruder_id, bool finish_layer)
-{
- std::string gcode;
- assert(m_layer_idx >= 0);
- if (! m_brim_done || gcodegen.writer().need_toolchange(extruder_id) || finish_layer) {
- if (m_layer_idx < (int)m_tool_changes.size()) {
- if (! (size_t(m_tool_change_idx) < m_tool_changes[m_layer_idx].size()))
- throw std::runtime_error("Wipe tower generation failed, possibly due to empty first layer.");
-
-
- // Calculate where the wipe tower layer will be printed. -1 means that print z will not change,
- // resulting in a wipe tower with sparse layers.
- double wipe_tower_z = -1;
- bool ignore_sparse = false;
- if (gcodegen.config().wipe_tower_no_sparse_layers.value) {
- wipe_tower_z = m_last_wipe_tower_print_z;
- ignore_sparse = (m_brim_done && m_tool_changes[m_layer_idx].size() == 1 && m_tool_changes[m_layer_idx].front().initial_tool == m_tool_changes[m_layer_idx].front().new_tool);
- if (m_tool_change_idx == 0 && ! ignore_sparse)
- wipe_tower_z = m_last_wipe_tower_print_z + m_tool_changes[m_layer_idx].front().layer_height;
- }
-
- if (! ignore_sparse) {
- gcode += append_tcr(gcodegen, m_tool_changes[m_layer_idx][m_tool_change_idx++], extruder_id, wipe_tower_z);
- m_last_wipe_tower_print_z = wipe_tower_z;
- }
- }
- m_brim_done = true;
- }
- return gcode;
-}
-
-// Print is finished. Now it remains to unload the filament safely with ramming over the wipe tower.
-std::string WipeTowerIntegration::finalize(GCode &gcodegen)
-{
- std::string gcode;
- if (std::abs(gcodegen.writer().get_position()(2) - m_final_purge.print_z) > EPSILON)
- gcode += gcodegen.change_layer(m_final_purge.print_z);
- gcode += append_tcr(gcodegen, m_final_purge, -1);
- return gcode;
-}
+#if ENABLE_GCODE_VIEWER
+ const std::vector ColorPrintColors::Colors = { "#C0392B", "#E67E22", "#F1C40F", "#27AE60", "#1ABC9C", "#2980B9", "#9B59B6" };
+#endif // ENABLE_GCODE_VIEWER
#define EXTRUDER_CONFIG(OPT) m_config.OPT.get_at(m_writer.extruder()->id())
// Collect pairs of object_layer + support_layer sorted by print_z.
// object_layer & support_layer are considered to be on the same print_z, if they are not further than EPSILON.
-std::vector GCode::collect_layers_to_print(const PrintObject &object)
+std::vector GCode::collect_layers_to_print(const PrintObject& object)
{
std::vector layers_to_print;
layers_to_print.reserve(object.layers().size() + object.support_layers().size());
- // Calculate a minimum support layer height as a minimum over all extruders, but not smaller than 10um.
- // This is the same logic as in support generator.
- //FIXME should we use the printing extruders instead?
- double gap_over_supports = object.config().support_material_contact_distance;
- // FIXME should we test object.config().support_material_synchronize_layers ? Currently the support layers are synchronized with object layers iff soluble supports.
- assert(! object.config().support_material || gap_over_supports != 0. || object.config().support_material_synchronize_layers);
+ // Calculate a minimum support layer height as a minimum over all extruders, but not smaller than 10um.
+ // This is the same logic as in support generator.
+ //FIXME should we use the printing extruders instead?
+ double gap_over_supports = object.config().support_material_contact_distance;
+ // FIXME should we test object.config().support_material_synchronize_layers ? Currently the support layers are synchronized with object layers iff soluble supports.
+ assert(!object.config().support_material || gap_over_supports != 0. || object.config().support_material_synchronize_layers);
if (gap_over_supports != 0.) {
gap_over_supports = std::max(0., gap_over_supports);
- // Not a soluble support,
- double support_layer_height_min = 1000000.;
- for (auto lh : object.print()->config().min_layer_height.values)
- support_layer_height_min = std::min(support_layer_height_min, std::max(0.01, lh));
- gap_over_supports += support_layer_height_min;
+ // Not a soluble support,
+ double support_layer_height_min = 1000000.;
+ for (auto lh : object.print()->config().min_layer_height.values)
+ support_layer_height_min = std::min(support_layer_height_min, std::max(0.01, lh));
+ gap_over_supports += support_layer_height_min;
}
// Pair the object layers with the support layers by z.
- size_t idx_object_layer = 0;
+ size_t idx_object_layer = 0;
size_t idx_support_layer = 0;
const LayerToPrint* last_extrusion_layer = nullptr;
while (idx_object_layer < object.layers().size() || idx_support_layer < object.support_layers().size()) {
LayerToPrint layer_to_print;
- layer_to_print.object_layer = (idx_object_layer < object.layers().size()) ? object.layers()[idx_object_layer ++] : nullptr;
- layer_to_print.support_layer = (idx_support_layer < object.support_layers().size()) ? object.support_layers()[idx_support_layer ++] : nullptr;
+ layer_to_print.object_layer = (idx_object_layer < object.layers().size()) ? object.layers()[idx_object_layer++] : nullptr;
+ layer_to_print.support_layer = (idx_support_layer < object.support_layers().size()) ? object.support_layers()[idx_support_layer++] : nullptr;
if (layer_to_print.object_layer && layer_to_print.support_layer) {
if (layer_to_print.object_layer->print_z < layer_to_print.support_layer->print_z - EPSILON) {
layer_to_print.support_layer = nullptr;
- -- idx_support_layer;
- } else if (layer_to_print.support_layer->print_z < layer_to_print.object_layer->print_z - EPSILON) {
+ --idx_support_layer;
+ }
+ else if (layer_to_print.support_layer->print_z < layer_to_print.object_layer->print_z - EPSILON) {
layer_to_print.object_layer = nullptr;
- -- idx_object_layer;
+ --idx_object_layer;
}
}
layers_to_print.emplace_back(layer_to_print);
+ bool has_extrusions = (layer_to_print.object_layer && layer_to_print.object_layer->has_extrusions())
+ || (layer_to_print.support_layer && layer_to_print.support_layer->has_extrusions());
+
// Check that there are extrusions on the very first layer.
if (layers_to_print.size() == 1u) {
- if ((layer_to_print.object_layer && ! layer_to_print.object_layer->has_extrusions())
- || (layer_to_print.support_layer && ! layer_to_print.support_layer->has_extrusions()))
- throw std::runtime_error(_(L("There is an object with no extrusions on the first layer.")));
+ if (!has_extrusions)
+ throw Slic3r::RuntimeError(_(L("There is an object with no extrusions on the first layer.")));
}
// In case there are extrusions on this layer, check there is a layer to lay it on.
if ((layer_to_print.object_layer && layer_to_print.object_layer->has_extrusions())
- // Allow empty support layers, as the support generator may produce no extrusions for non-empty support regions.
- || (layer_to_print.support_layer /* && layer_to_print.support_layer->has_extrusions() */)) {
+ // Allow empty support layers, as the support generator may produce no extrusions for non-empty support regions.
+ || (layer_to_print.support_layer /* && layer_to_print.support_layer->has_extrusions() */)) {
double support_contact_z = (last_extrusion_layer && last_extrusion_layer->support_layer)
- ? gap_over_supports
- : 0.;
+ ? gap_over_supports
+ : 0.;
double maximal_print_z = (last_extrusion_layer ? last_extrusion_layer->print_z() : 0.)
- + layer_to_print.layer()->height
- + support_contact_z;
+ + layer_to_print.layer()->height
+ + support_contact_z;
// Negative support_contact_z is not taken into account, it can result in false positives in cases
// where previous layer has object extrusions too (https://github.com/prusa3d/PrusaSlicer/issues/2752)
- // Only check this layer in case it has some extrusions.
- bool has_extrusions = (layer_to_print.object_layer && layer_to_print.object_layer->has_extrusions())
- || (layer_to_print.support_layer && layer_to_print.support_layer->has_extrusions());
-
if (has_extrusions && layer_to_print.print_z() > maximal_print_z + 2. * EPSILON) {
const_cast(object.print())->active_step_add_warning(PrintStateBase::WarningLevel::CRITICAL,
_(L("Empty layers detected, the output would not be printable.")) + "\n\n" +
_(L("Object name")) + ": " + object.model_object()->name + "\n" + _(L("Print z")) + ": " +
std::to_string(layers_to_print.back().print_z()) + "\n\n" + _(L("This is "
- "usually caused by negligibly small extrusions or by a faulty model. Try to repair "
- "the model or change its orientation on the bed.")));
+ "usually caused by negligibly small extrusions or by a faulty model. Try to repair "
+ "the model or change its orientation on the bed.")));
}
// Remember last layer with extrusions.
@@ -662,7 +666,7 @@ std::vector GCode::collect_layers_to_print(const PrintObjec
// Prepare for non-sequential printing of multiple objects: Support resp. object layers with nearly identical print_z
// will be printed for all objects at once.
// Return a list of items.
-std::vector>> GCode::collect_layers_to_print(const Print &print)
+std::vector>> GCode::collect_layers_to_print(const Print& print)
{
struct OrderingItem {
coordf_t print_z;
@@ -677,30 +681,31 @@ std::vector>> GCode::collec
OrderingItem ordering_item;
ordering_item.object_idx = i;
ordering.reserve(ordering.size() + per_object[i].size());
- const LayerToPrint &front = per_object[i].front();
- for (const LayerToPrint <p : per_object[i]) {
- ordering_item.print_z = ltp.print_z();
+ const LayerToPrint& front = per_object[i].front();
+ for (const LayerToPrint& ltp : per_object[i]) {
+ ordering_item.print_z = ltp.print_z();
ordering_item.layer_idx = <p - &front;
ordering.emplace_back(ordering_item);
}
}
- std::sort(ordering.begin(), ordering.end(), [](const OrderingItem &oi1, const OrderingItem &oi2) { return oi1.print_z < oi2.print_z; });
+ std::sort(ordering.begin(), ordering.end(), [](const OrderingItem& oi1, const OrderingItem& oi2) { return oi1.print_z < oi2.print_z; });
std::vector>> layers_to_print;
+
// Merge numerically very close Z values.
for (size_t i = 0; i < ordering.size();) {
// Find the last layer with roughly the same print_z.
size_t j = i + 1;
coordf_t zmax = ordering[i].print_z + EPSILON;
- for (; j < ordering.size() && ordering[j].print_z <= zmax; ++ j) ;
+ for (; j < ordering.size() && ordering[j].print_z <= zmax; ++j);
// Merge into layers_to_print.
std::pair> merged;
// Assign an average print_z to the set of layers with nearly equal print_z.
- merged.first = 0.5 * (ordering[i].print_z + ordering[j-1].print_z);
+ merged.first = 0.5 * (ordering[i].print_z + ordering[j - 1].print_z);
merged.second.assign(print.objects().size(), LayerToPrint());
for (; i < j; ++i) {
- const OrderingItem &oi = ordering[i];
+ const OrderingItem& oi = ordering[i];
assert(merged.second[oi.object_idx].layer() == nullptr);
merged.second[oi.object_idx] = std::move(per_object[oi.object_idx][oi.layer_idx]);
}
@@ -710,7 +715,22 @@ std::vector>> GCode::collec
return layers_to_print;
}
+#if ENABLE_GCODE_VIEWER
+// free functions called by GCode::do_export()
+namespace DoExport {
+ static void update_print_estimated_times_stats(const GCodeProcessor& processor, PrintStatistics& print_statistics)
+ {
+ const GCodeProcessor::Result& result = processor.get_result();
+ print_statistics.estimated_normal_print_time = get_time_dhm(result.time_statistics.modes[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Normal)].time);
+ print_statistics.estimated_silent_print_time = processor.is_stealth_time_estimator_enabled() ?
+ get_time_dhm(result.time_statistics.modes[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].time) : "N/A";
+ }
+} // namespace DoExport
+
+void GCode::do_export(Print* print, const char* path, GCodeProcessor::Result* result, ThumbnailsGeneratorCallback thumbnail_cb)
+#else
void GCode::do_export(Print* print, const char* path, GCodePreviewData* preview_data, ThumbnailsGeneratorCallback thumbnail_cb)
+#endif // ENABLE_GCODE_VIEWER
{
PROFILE_CLEAR();
@@ -730,9 +750,11 @@ void GCode::do_export(Print* print, const char* path, GCodePreviewData* preview_
FILE *file = boost::nowide::fopen(path_tmp.c_str(), "wb");
if (file == nullptr)
- throw std::runtime_error(std::string("G-code export to ") + path + " failed.\nCannot open the file for writing.\n");
+ throw Slic3r::RuntimeError(std::string("G-code export to ") + path + " failed.\nCannot open the file for writing.\n");
+#if !ENABLE_GCODE_VIEWER
m_enable_analyzer = preview_data != nullptr;
+#endif // !ENABLE_GCODE_VIEWER
try {
m_placeholder_parser_failed_templates.clear();
@@ -741,7 +763,7 @@ void GCode::do_export(Print* print, const char* path, GCodePreviewData* preview_
if (ferror(file)) {
fclose(file);
boost::nowide::remove(path_tmp.c_str());
- throw std::runtime_error(std::string("G-code export to ") + path + " failed\nIs the disk full?\n");
+ throw Slic3r::RuntimeError(std::string("G-code export to ") + path + " failed\nIs the disk full?\n");
}
} catch (std::exception & /* ex */) {
// Rethrow on any exception. std::runtime_exception and CanceledException are expected to be thrown.
@@ -762,9 +784,17 @@ void GCode::do_export(Print* print, const char* path, GCodePreviewData* preview_
msg += " !!!!! Failed to process the custom G-code template ...\n";
msg += "and\n";
msg += " !!!!! End of an error report for the custom G-code template ...\n";
- throw std::runtime_error(msg);
+ throw Slic3r::RuntimeError(msg);
}
+#if ENABLE_GCODE_VIEWER
+ BOOST_LOG_TRIVIAL(debug) << "Start processing gcode, " << log_memory_info();
+ m_processor.process_file(path_tmp, [print]() { print->throw_if_canceled(); });
+ DoExport::update_print_estimated_times_stats(m_processor, print->m_print_statistics);
+ if (result != nullptr)
+ *result = std::move(m_processor.extract_result());
+ BOOST_LOG_TRIVIAL(debug) << "Finished processing gcode, " << log_memory_info();
+#else
GCodeTimeEstimator::PostProcessData normal_data = m_normal_time_estimator.get_post_process_data();
GCodeTimeEstimator::PostProcessData silent_data = m_silent_time_estimator.get_post_process_data();
@@ -773,8 +803,7 @@ void GCode::do_export(Print* print, const char* path, GCodePreviewData* preview_
BOOST_LOG_TRIVIAL(debug) << "Time estimator post processing" << log_memory_info();
GCodeTimeEstimator::post_process(path_tmp, 60.0f, remaining_times_enabled ? &normal_data : nullptr, (remaining_times_enabled && m_silent_time_estimator_enabled) ? &silent_data : nullptr);
- if (remaining_times_enabled)
- {
+ if (remaining_times_enabled) {
m_normal_time_estimator.reset();
if (m_silent_time_estimator_enabled)
m_silent_time_estimator.reset();
@@ -786,9 +815,10 @@ void GCode::do_export(Print* print, const char* path, GCodePreviewData* preview_
m_analyzer.calc_gcode_preview_data(*preview_data, [print]() { print->throw_if_canceled(); });
m_analyzer.reset();
}
+#endif // ENABLE_GCODE_VIEWER
if (rename_file(path_tmp, path))
- throw std::runtime_error(
+ throw Slic3r::RuntimeError(
std::string("Failed to rename the output G-code file from ") + path_tmp + " to " + path + '\n' +
"Is " + path_tmp + " locked?" + '\n');
@@ -802,7 +832,8 @@ void GCode::do_export(Print* print, const char* path, GCodePreviewData* preview_
// free functions called by GCode::_do_export()
namespace DoExport {
- static void init_time_estimators(const PrintConfig &config, GCodeTimeEstimator &normal_time_estimator, GCodeTimeEstimator &silent_time_estimator, bool &silent_time_estimator_enabled)
+#if !ENABLE_GCODE_VIEWER
+ static void init_time_estimators(const PrintConfig &config, GCodeTimeEstimator &normal_time_estimator, GCodeTimeEstimator &silent_time_estimator, bool &silent_time_estimator_enabled)
{
// resets time estimators
normal_time_estimator.reset();
@@ -874,8 +905,18 @@ namespace DoExport {
normal_time_estimator.set_filament_unload_times(config.filament_unload_time.values);
}
}
+#endif // !ENABLE_GCODE_VIEWER
- static void init_gcode_analyzer(const PrintConfig &config, GCodeAnalyzer &analyzer)
+#if ENABLE_GCODE_VIEWER
+ static void init_gcode_processor(const PrintConfig& config, GCodeProcessor& processor, bool& silent_time_estimator_enabled)
+ {
+ silent_time_estimator_enabled = (config.gcode_flavor == gcfMarlin) && config.silent_mode;
+ processor.reset();
+ processor.apply_config(config);
+ processor.enable_stealth_time_estimator(silent_time_estimator_enabled);
+ }
+#else
+ static void init_gcode_analyzer(const PrintConfig &config, GCodeAnalyzer &analyzer)
{
// resets analyzer
analyzer.reset();
@@ -899,7 +940,8 @@ namespace DoExport {
// tell analyzer about the gcode flavor
analyzer.set_gcode_flavor(config.gcode_flavor);
- }
+ }
+#endif // ENABLE_GCODE_VIEWER
static double autospeed_volumetric_limit(const Print &print)
{
@@ -1021,24 +1063,28 @@ namespace DoExport {
}
// Fill in print_statistics and return formatted string containing filament statistics to be inserted into G-code comment section.
- static std::string update_print_stats_and_format_filament_stats(
- const GCodeTimeEstimator &normal_time_estimator,
+ static std::string update_print_stats_and_format_filament_stats(
+#if !ENABLE_GCODE_VIEWER
+ const GCodeTimeEstimator &normal_time_estimator,
const GCodeTimeEstimator &silent_time_estimator,
const bool silent_time_estimator_enabled,
- const bool has_wipe_tower,
+#endif // !ENABLE_GCODE_VIEWER
+ const bool has_wipe_tower,
const WipeTowerData &wipe_tower_data,
const std::vector &extruders,
PrintStatistics &print_statistics)
- {
+ {
std::string filament_stats_string_out;
print_statistics.clear();
- print_statistics.estimated_normal_print_time = normal_time_estimator.get_time_dhm/*s*/();
- print_statistics.estimated_silent_print_time = silent_time_estimator_enabled ? silent_time_estimator.get_time_dhm/*s*/() : "N/A";
- print_statistics.estimated_normal_custom_gcode_print_times = normal_time_estimator.get_custom_gcode_times_dhm(true);
- if (silent_time_estimator_enabled)
- print_statistics.estimated_silent_custom_gcode_print_times = silent_time_estimator.get_custom_gcode_times_dhm(true);
- print_statistics.total_toolchanges = std::max(0, wipe_tower_data.number_of_toolchanges);
+#if !ENABLE_GCODE_VIEWER
+ print_statistics.estimated_normal_print_time = normal_time_estimator.get_time_dhm/*s*/();
+ print_statistics.estimated_silent_print_time = silent_time_estimator_enabled ? silent_time_estimator.get_time_dhm/*s*/() : "N/A";
+ print_statistics.estimated_normal_custom_gcode_print_times = normal_time_estimator.get_custom_gcode_times_dhm(true);
+ if (silent_time_estimator_enabled)
+ print_statistics.estimated_silent_custom_gcode_print_times = silent_time_estimator.get_custom_gcode_times_dhm(true);
+#endif // !ENABLE_GCODE_VIEWER
+ print_statistics.total_toolchanges = std::max(0, wipe_tower_data.number_of_toolchanges);
if (! extruders.empty()) {
std::pair out_filament_used_mm ("; filament used [mm] = ", 0);
std::pair out_filament_used_cm3("; filament used [cm3] = ", 0);
@@ -1128,15 +1174,29 @@ void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thu
{
PROFILE_FUNC();
- DoExport::init_time_estimators(print.config(),
- // modifies the following:
- m_normal_time_estimator, m_silent_time_estimator, m_silent_time_estimator_enabled);
+#if ENABLE_GCODE_VIEWER
+ // modifies m_silent_time_estimator_enabled
+ DoExport::init_gcode_processor(print.config(), m_processor, m_silent_time_estimator_enabled);
+#else
+ DoExport::init_time_estimators(print.config(),
+ // modifies the following:
+ m_normal_time_estimator, m_silent_time_estimator, m_silent_time_estimator_enabled);
DoExport::init_gcode_analyzer(print.config(), m_analyzer);
+#endif // ENABLE_GCODE_VIEWER
// resets analyzer's tracking data
+#if ENABLE_GCODE_VIEWER
+ m_last_height = 0.0f;
+ m_last_layer_z = 0.0f;
+#if ENABLE_GCODE_VIEWER_DATA_CHECKING
+ m_last_mm3_per_mm = 0.0;
+ m_last_width = 0.0f;
+#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
+#else
m_last_mm3_per_mm = GCodeAnalyzer::Default_mm3_per_mm;
m_last_width = GCodeAnalyzer::Default_Width;
m_last_height = GCodeAnalyzer::Default_Height;
+#endif // ENABLE_GCODE_VIEWER
// How many times will be change_layer() called?
// change_layer() in turn increments the progress bar status.
@@ -1227,12 +1287,16 @@ void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thu
print.throw_if_canceled();
// adds tags for time estimators
+#if ENABLE_GCODE_VIEWER
if (print.config().remaining_times.value)
- {
+ _writeln(file, GCodeProcessor::First_Line_M73_Placeholder_Tag);
+#else
+ if (print.config().remaining_times.value) {
_writeln(file, GCodeTimeEstimator::Normal_First_M73_Output_Placeholder_Tag);
if (m_silent_time_estimator_enabled)
_writeln(file, GCodeTimeEstimator::Silent_First_M73_Output_Placeholder_Tag);
}
+#endif // ENABLE_GCODE_VIEWER
// Prepare the helper object for replacing placeholders in custom G-code and output filename.
m_placeholder_parser = print.placeholder_parser();
@@ -1337,9 +1401,14 @@ void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thu
// Set extruder(s) temperature before and after start G-code.
this->_print_first_layer_extruder_temperatures(file, print, start_gcode, initial_extruder_id, false);
+#if ENABLE_GCODE_VIEWER
+ // adds tag for processor
+ _write_format(file, ";%s%s\n", GCodeProcessor::Extrusion_Role_Tag.c_str(), ExtrusionEntity::role_to_string(erCustom).c_str());
+#else
if (m_enable_analyzer)
// adds tag for analyzer
_write_format(file, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erCustom);
+#endif // ENABLE_GCODE_VIEWER
// Write the custom start G-code
_writeln(file, start_gcode);
@@ -1490,9 +1559,14 @@ void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thu
_write(file, this->retract());
_write(file, m_writer.set_fan(false));
+#if ENABLE_GCODE_VIEWER
+ // adds tag for processor
+ _write_format(file, ";%s%s\n", GCodeProcessor::Extrusion_Role_Tag.c_str(), ExtrusionEntity::role_to_string(erCustom).c_str());
+#else
if (m_enable_analyzer)
// adds tag for analyzer
_write_format(file, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erCustom);
+#endif // ENABLE_GCODE_VIEWER
// Process filament-specific gcode in extruder order.
{
@@ -1517,25 +1591,33 @@ void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thu
_write(file, m_writer.postamble());
// adds tags for time estimators
+#if ENABLE_GCODE_VIEWER
if (print.config().remaining_times.value)
- {
+ _writeln(file, GCodeProcessor::Last_Line_M73_Placeholder_Tag);
+#else
+ if (print.config().remaining_times.value) {
_writeln(file, GCodeTimeEstimator::Normal_Last_M73_Output_Placeholder_Tag);
if (m_silent_time_estimator_enabled)
_writeln(file, GCodeTimeEstimator::Silent_Last_M73_Output_Placeholder_Tag);
}
+#endif // ENABLE_GCODE_VIEWER
print.throw_if_canceled();
// calculates estimated printing time
+#if !ENABLE_GCODE_VIEWER
m_normal_time_estimator.calculate_time(false);
if (m_silent_time_estimator_enabled)
m_silent_time_estimator.calculate_time(false);
+#endif // !ENABLE_GCODE_VIEWER
// Get filament stats.
_write(file, DoExport::update_print_stats_and_format_filament_stats(
// Const inputs
- m_normal_time_estimator, m_silent_time_estimator, m_silent_time_estimator_enabled,
- has_wipe_tower, print.wipe_tower_data(),
+#if !ENABLE_GCODE_VIEWER
+ m_normal_time_estimator, m_silent_time_estimator, m_silent_time_estimator_enabled,
+#endif // !ENABLE_GCODE_VIEWER
+ has_wipe_tower, print.wipe_tower_data(),
m_writer.extruders(),
// Modifies
print.m_print_statistics));
@@ -1544,9 +1626,13 @@ void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thu
_write_format(file, "; total filament cost = %.1lf\n", print.m_print_statistics.total_cost);
if (print.m_print_statistics.total_toolchanges > 0)
_write_format(file, "; total toolchanges = %i\n", print.m_print_statistics.total_toolchanges);
+#if ENABLE_GCODE_VIEWER
+ _writeln(file, GCodeProcessor::Estimated_Printing_Time_Placeholder_Tag);
+#else
_write_format(file, "; estimated printing time (normal mode) = %s\n", m_normal_time_estimator.get_time_dhms().c_str());
if (m_silent_time_estimator_enabled)
_write_format(file, "; estimated printing time (silent mode) = %s\n", m_silent_time_estimator.get_time_dhms().c_str());
+#endif // ENABLE_GCODE_VIEWER
// Append full config.
_write(file, "\n");
@@ -1851,10 +1937,15 @@ namespace ProcessLayer
{
assert(m600_extruder_before_layer >= 0);
// Color Change or Tool Change as Color Change.
- // add tag for analyzer
- gcode += "; " + GCodeAnalyzer::Color_Change_Tag + ",T" + std::to_string(m600_extruder_before_layer) + "\n";
- // add tag for time estimator
- gcode += "; " + GCodeTimeEstimator::Color_Change_Tag + "\n";
+#if ENABLE_GCODE_VIEWER
+ // add tag for processor
+ gcode += "; " + GCodeProcessor::Color_Change_Tag + ",T" + std::to_string(m600_extruder_before_layer) + "\n";
+#else
+ // add tag for analyzer
+ gcode += "; " + GCodeAnalyzer::Color_Change_Tag + ",T" + std::to_string(m600_extruder_before_layer) + "\n";
+ // add tag for time estimator
+ gcode += "; " + GCodeTimeEstimator::Color_Change_Tag + "\n";
+#endif // ENABLE_GCODE_VIEWER
if (!single_extruder_printer && m600_extruder_before_layer >= 0 && first_extruder_id != (unsigned)m600_extruder_before_layer
// && !MMU1
@@ -1873,20 +1964,32 @@ namespace ProcessLayer
{
if (gcode_type == CustomGCode::PausePrint) // Pause print
{
- // add tag for analyzer
- gcode += "; " + GCodeAnalyzer::Pause_Print_Tag + "\n";
- //! FIXME_in_fw show message during print pause
+#if ENABLE_GCODE_VIEWER
+ // add tag for processor
+ gcode += "; " + GCodeProcessor::Pause_Print_Tag + "\n";
+#else
+ // add tag for analyzer
+ gcode += "; " + GCodeAnalyzer::Pause_Print_Tag + "\n";
+#endif // ENABLE_GCODE_VIEWER
+ //! FIXME_in_fw show message during print pause
if (!pause_print_msg.empty())
gcode += "M117 " + pause_print_msg + "\n";
- // add tag for time estimator
+#if !ENABLE_GCODE_VIEWER
+ // add tag for time estimator
gcode += "; " + GCodeTimeEstimator::Pause_Print_Tag + "\n";
+#endif // !ENABLE_GCODE_VIEWER
gcode += config.pause_print_gcode;
- }
+ }
else
{
- // add tag for analyzer
- gcode += "; " + GCodeAnalyzer::Custom_Code_Tag + "\n";
- // add tag for time estimator
+#if ENABLE_GCODE_VIEWER
+ // add tag for processor
+ gcode += "; " + GCodeProcessor::Custom_Code_Tag + "\n";
+#else
+ // add tag for analyzer
+ gcode += "; " + GCodeAnalyzer::Custom_Code_Tag + "\n";
+#endif // ENABLE_GCODE_VIEWER
+ // add tag for time estimator
//gcode += "; " + GCodeTimeEstimator::Custom_Code_Tag + "\n";
if (gcode_type == CustomGCode::Template) // Template Cistom Gcode
gcode += config.template_custom_gcode;
@@ -2029,6 +2132,22 @@ void GCode::process_layer(
std::string gcode;
+#if ENABLE_GCODE_VIEWER
+ // add tag for processor
+ gcode += "; " + GCodeProcessor::Layer_Change_Tag + "\n";
+ // export layer z
+ char buf[64];
+ sprintf(buf, ";Z:%g\n", print_z);
+ gcode += buf;
+ // export layer height
+ float height = first_layer ? static_cast(print_z) : static_cast(print_z) - m_last_layer_z;
+ sprintf(buf, ";%s%g\n", GCodeProcessor::Height_Tag.c_str(), height);
+ gcode += buf;
+ // update caches
+ m_last_layer_z = static_cast(print_z);
+ m_last_height = height;
+#endif // ENABLE_GCODE_VIEWER
+
// Set new layer - this will change Z and force a retraction if retract_layer_change is enabled.
if (! print.config().before_layer_gcode.value.empty()) {
DynamicConfig config;
@@ -2242,9 +2361,15 @@ void GCode::process_layer(
m_wipe_tower->tool_change(*this, extruder_id, extruder_id == layer_tools.extruders.back()) :
this->set_extruder(extruder_id, print_z);
+#if ENABLE_GCODE_VIEWER
+ // let analyzer tag generator aware of a role type change
+ if (layer_tools.has_wipe_tower && m_wipe_tower)
+ m_last_processor_extrusion_role = erWipeTower;
+#else
// let analyzer tag generator aware of a role type change
if (m_enable_analyzer && layer_tools.has_wipe_tower && m_wipe_tower)
m_last_analyzer_extrusion_role = erWipeTower;
+#endif // ENABLE_GCODE_VIEWER
if (auto loops_it = skirt_loops_per_extruder.find(extruder_id); loops_it != skirt_loops_per_extruder.end()) {
const std::pair loops = loops_it->second;
@@ -2348,11 +2473,13 @@ void GCode::process_layer(
if (m_cooling_buffer)
gcode = m_cooling_buffer->process_layer(gcode, layer.id());
+#if !ENABLE_GCODE_VIEWER
// add tag for analyzer
if (gcode.find(GCodeAnalyzer::Pause_Print_Tag) != gcode.npos)
gcode += "\n; " + GCodeAnalyzer::End_Pause_Print_Or_Custom_Code_Tag + "\n";
else if (gcode.find(GCodeAnalyzer::Custom_Code_Tag) != gcode.npos)
gcode += "\n; " + GCodeAnalyzer::End_Pause_Print_Or_Custom_Code_Tag + "\n";
+#endif // !ENABLE_GCODE_VIEWER
#ifdef HAS_PRESSURE_EQUALIZER
// Apply pressure equalization if enabled;
@@ -2363,12 +2490,17 @@ void GCode::process_layer(
#endif /* HAS_PRESSURE_EQUALIZER */
_write(file, gcode);
- BOOST_LOG_TRIVIAL(trace) << "Exported layer " << layer.id() << " print_z " << print_z <<
- ", time estimator memory: " <<
- format_memsize_MB(m_normal_time_estimator.memory_used() + (m_silent_time_estimator_enabled ? m_silent_time_estimator.memory_used() : 0)) <<
- ", analyzer memory: " <<
- format_memsize_MB(m_analyzer.memory_used()) <<
+#if ENABLE_GCODE_VIEWER
+ BOOST_LOG_TRIVIAL(trace) << "Exported layer " << layer.id() << " print_z " << print_z <<
log_memory_info();
+#else
+ BOOST_LOG_TRIVIAL(trace) << "Exported layer " << layer.id() << " print_z " << print_z <<
+ ", time estimator memory: " <<
+ format_memsize_MB(m_normal_time_estimator.memory_used() + (m_silent_time_estimator_enabled ? m_silent_time_estimator.memory_used() : 0)) <<
+ ", analyzer memory: " <<
+ format_memsize_MB(m_analyzer.memory_used()) <<
+ log_memory_info();
+#endif // ENABLE_GCODE_VIEWER
}
void GCode::apply_print_config(const PrintConfig &print_config)
@@ -2499,7 +2631,7 @@ plot(p2.subs(r,0.2).subs(z,1.), (x, -1, 3), adaptive=False, nb_of_points=400)
}
}
-static Points::iterator project_point_to_polygon_and_insert(Polygon &polygon, const Point &pt, double eps)
+static Points::const_iterator project_point_to_polygon_and_insert(Polygon &polygon, const Point &pt, double eps)
{
assert(polygon.points.size() >= 2);
if (polygon.points.size() <= 1)
@@ -2687,7 +2819,7 @@ std::string GCode::extrude_loop(ExtrusionLoop loop, std::string description, dou
// Insert a projection of last_pos into the polygon.
size_t last_pos_proj_idx;
{
- Points::iterator it = project_point_to_polygon_and_insert(polygon, last_pos, 0.1 * nozzle_r);
+ auto it = project_point_to_polygon_and_insert(polygon, last_pos, 0.1 * nozzle_r);
last_pos_proj_idx = it - polygon.points.begin();
}
@@ -2707,11 +2839,9 @@ std::string GCode::extrude_loop(ExtrusionLoop loop, std::string description, dou
if (was_clockwise)
ccwAngle = - ccwAngle;
float penalty = 0;
-// if (ccwAngle <- float(PI/3.))
if (ccwAngle <- float(0.6 * PI))
// Sharp reflex vertex. We love that, it hides the seam perfectly.
penalty = 0.f;
-// else if (ccwAngle > float(PI/3.))
else if (ccwAngle > float(0.6 * PI))
// Seams on sharp convex vertices are more visible than on reflex vertices.
penalty = penaltyConvexVertex;
@@ -2724,7 +2854,6 @@ std::string GCode::extrude_loop(ExtrusionLoop loop, std::string description, dou
penalty = penaltyConvexVertex + (penaltyFlatSurface - penaltyConvexVertex) * bspline_kernel(ccwAngle * float(PI * 2. / 3.));
}
// Give a negative penalty for points close to the last point or the prefered seam location.
- //float dist_to_last_pos_proj = last_pos_proj.distance_to(polygon.points[i]);
float dist_to_last_pos_proj = (i < last_pos_proj_idx) ?
std::min(lengths[last_pos_proj_idx] - lengths[i], lengths.back() - lengths[last_pos_proj_idx] + lengths[i]) :
std::min(lengths[i] - lengths[last_pos_proj_idx], lengths.back() - lengths[i] + lengths[last_pos_proj_idx]);
@@ -2744,14 +2873,10 @@ std::string GCode::extrude_loop(ExtrusionLoop loop, std::string description, dou
// Signed distance is positive outside the object, negative inside the object.
// The point is considered at an overhang, if it is more than nozzle radius
// outside of the lower layer contour.
- #ifdef NDEBUG // to suppress unused variable warning in release mode
- (*lower_layer_edge_grid)->signed_distance(p, search_r, dist);
- #else
- bool found = (*lower_layer_edge_grid)->signed_distance(p, search_r, dist);
- #endif
+ [[maybe_unused]] bool found = (*lower_layer_edge_grid)->signed_distance(p, search_r, dist);
// If the approximate Signed Distance Field was initialized over lower_layer_edge_grid,
// then the signed distnace shall always be known.
- assert(found);
+ assert(found);
penalties[i] += extrudate_overlap_penalty(float(nozzle_r), penaltyOverhangHalf, float(dist));
}
}
@@ -2759,7 +2884,6 @@ std::string GCode::extrude_loop(ExtrusionLoop loop, std::string description, dou
// Find a point with a minimum penalty.
size_t idx_min = std::min_element(penalties.begin(), penalties.end()) - penalties.begin();
- // if (seam_position == spAligned)
// For all (aligned, nearest, rear) seams:
{
// Very likely the weight of idx_min is very close to the weight of last_pos_proj_idx.
@@ -2918,7 +3042,7 @@ std::string GCode::extrude_entity(const ExtrusionEntity &entity, std::string des
else if (const ExtrusionLoop* loop = dynamic_cast(&entity))
return this->extrude_loop(*loop, description, speed, lower_layer_edge_grid);
else
- throw std::invalid_argument("Invalid argument supplied to extrude()");
+ throw Slic3r::InvalidArgument("Invalid argument supplied to extrude()");
return "";
}
@@ -3008,15 +3132,21 @@ std::string GCode::extrude_support(const ExtrusionEntityCollection &support_fill
void GCode::_write(FILE* file, const char *what)
{
if (what != nullptr) {
+#if ENABLE_GCODE_VIEWER
+ const char* gcode = what;
+#else
// apply analyzer, if enabled
const char* gcode = m_enable_analyzer ? m_analyzer.process_gcode(what).c_str() : what;
+#endif // !ENABLE_GCODE_VIEWER
// writes string to file
fwrite(gcode, 1, ::strlen(gcode), file);
+#if !ENABLE_GCODE_VIEWER
// updates time estimator and gcode lines vector
m_normal_time_estimator.add_gcode_block(gcode);
if (m_silent_time_estimator_enabled)
m_silent_time_estimator.add_gcode_block(gcode);
+#endif // !ENABLE_GCODE_VIEWER
}
}
@@ -3117,7 +3247,7 @@ std::string GCode::_extrude(const ExtrusionPath &path, std::string description,
} else if (path.role() == erGapFill) {
speed = m_config.get_abs_value("gap_fill_speed");
} else {
- throw std::invalid_argument("Invalid speed");
+ throw Slic3r::InvalidArgument("Invalid speed");
}
}
if (this->on_first_layer())
@@ -3155,42 +3285,71 @@ std::string GCode::_extrude(const ExtrusionPath &path, std::string description,
}
}
- // adds analyzer tags and updates analyzer's tracking data
- if (m_enable_analyzer)
- {
+ // adds processor tags and updates processor tracking data
+#if ENABLE_GCODE_VIEWER
+ // PrusaMultiMaterial::Writer may generate GCodeProcessor::Height_Tag lines without updating m_last_height
+ // so, if the last role was erWipeTower we force export of GCodeProcessor::Height_Tag lines
+ bool last_was_wipe_tower = (m_last_processor_extrusion_role == erWipeTower);
+#else
+ if (m_enable_analyzer) {
// PrusaMultiMaterial::Writer may generate GCodeAnalyzer::Height_Tag and GCodeAnalyzer::Width_Tag lines without updating m_last_height and m_last_width
// so, if the last role was erWipeTower we force export of GCodeAnalyzer::Height_Tag and GCodeAnalyzer::Width_Tag lines
bool last_was_wipe_tower = (m_last_analyzer_extrusion_role == erWipeTower);
+#endif // ENABLE_GCODE_VIEWER
char buf[64];
- if (path.role() != m_last_analyzer_extrusion_role)
- {
+#if ENABLE_GCODE_VIEWER
+ if (path.role() != m_last_processor_extrusion_role) {
+ m_last_processor_extrusion_role = path.role();
+ sprintf(buf, ";%s%s\n", GCodeProcessor::Extrusion_Role_Tag.c_str(), ExtrusionEntity::role_to_string(m_last_processor_extrusion_role).c_str());
+ gcode += buf;
+ }
+
+#if ENABLE_GCODE_VIEWER_DATA_CHECKING
+ if (last_was_wipe_tower || (m_last_mm3_per_mm != path.mm3_per_mm)) {
+ m_last_mm3_per_mm = path.mm3_per_mm;
+ sprintf(buf, ";%s%f\n", GCodeProcessor::Mm3_Per_Mm_Tag.c_str(), m_last_mm3_per_mm);
+ gcode += buf;
+ }
+
+ if (last_was_wipe_tower || m_last_width != path.width) {
+ m_last_width = path.width;
+ sprintf(buf, ";%s%g\n", GCodeProcessor::Width_Tag.c_str(), m_last_width);
+ gcode += buf;
+ }
+#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
+
+ if (last_was_wipe_tower || std::abs(m_last_height - path.height) > EPSILON) {
+ m_last_height = path.height;
+ sprintf(buf, ";%s%g\n", GCodeProcessor::Height_Tag.c_str(), m_last_height);
+ gcode += buf;
+ }
+#else
+ if (path.role() != m_last_analyzer_extrusion_role) {
m_last_analyzer_extrusion_role = path.role();
sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), int(m_last_analyzer_extrusion_role));
gcode += buf;
}
- if (last_was_wipe_tower || (m_last_mm3_per_mm != path.mm3_per_mm))
- {
+ if (last_was_wipe_tower || (m_last_mm3_per_mm != path.mm3_per_mm)) {
m_last_mm3_per_mm = path.mm3_per_mm;
sprintf(buf, ";%s%f\n", GCodeAnalyzer::Mm3_Per_Mm_Tag.c_str(), m_last_mm3_per_mm);
gcode += buf;
}
- if (last_was_wipe_tower || (m_last_width != path.width))
- {
+ if (last_was_wipe_tower || m_last_width != path.width) {
m_last_width = path.width;
sprintf(buf, ";%s%f\n", GCodeAnalyzer::Width_Tag.c_str(), m_last_width);
gcode += buf;
}
- if (last_was_wipe_tower || (m_last_height != path.height))
- {
+ if (last_was_wipe_tower || m_last_height != path.height) {
m_last_height = path.height;
sprintf(buf, ";%s%f\n", GCodeAnalyzer::Height_Tag.c_str(), m_last_height);
gcode += buf;
}
}
+#endif // ENABLE_GCODE_VIEWER
std::string comment;
if (m_enable_cooling_markers) {
@@ -3509,7 +3668,7 @@ void GCode::ObjectByExtruder::Island::Region::append(const Type type, const Extr
perimeters_or_infills_overrides = &infills_overrides;
break;
default:
- throw std::invalid_argument("Unknown parameter!");
+ throw Slic3r::InvalidArgument("Unknown parameter!");
}
// First we append the entities, there are eec->entities.size() of them:
diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp
index 8d47337832..8bae2ef43d 100644
--- a/src/libslic3r/GCode.hpp
+++ b/src/libslic3r/GCode.hpp
@@ -13,9 +13,13 @@
#include "GCode/SpiralVase.hpp"
#include "GCode/ToolOrdering.hpp"
#include "GCode/WipeTower.hpp"
-#include "GCodeTimeEstimator.hpp"
-#include "EdgeGrid.hpp"
+#if ENABLE_GCODE_VIEWER
+#include "GCode/GCodeProcessor.hpp"
+#else
#include "GCode/Analyzer.hpp"
+#include "GCodeTimeEstimator.hpp"
+#endif // ENABLE_GCODE_VIEWER
+#include "EdgeGrid.hpp"
#include "GCode/ThumbnailData.hpp"
#include
@@ -29,7 +33,9 @@ namespace Slic3r {
// Forward declarations.
class GCode;
+#if !ENABLE_GCODE_VIEWER
class GCodePreviewData;
+#endif // !ENABLE_GCODE_VIEWER
namespace { struct Item; }
struct PrintInstance;
@@ -138,6 +144,15 @@ private:
double m_last_wipe_tower_print_z = 0.f;
};
+#if ENABLE_GCODE_VIEWER
+class ColorPrintColors
+{
+ static const std::vector Colors;
+public:
+ static const std::vector& get() { return Colors; }
+};
+#endif // ENABLE_GCODE_VIEWER
+
class GCode {
public:
GCode() :
@@ -145,21 +160,33 @@ public:
m_enable_loop_clipping(true),
m_enable_cooling_markers(false),
m_enable_extrusion_role_markers(false),
+#if ENABLE_GCODE_VIEWER
+ m_last_processor_extrusion_role(erNone),
+#else
m_enable_analyzer(false),
m_last_analyzer_extrusion_role(erNone),
+#endif // ENABLE_GCODE_VIEWER
m_layer_count(0),
m_layer_index(-1),
m_layer(nullptr),
m_volumetric_speed(0),
m_last_pos_defined(false),
m_last_extrusion_role(erNone),
+#if ENABLE_GCODE_VIEWER_DATA_CHECKING
+ m_last_mm3_per_mm(0.0),
+ m_last_width(0.0f),
+#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
+#if !ENABLE_GCODE_VIEWER
m_last_mm3_per_mm(GCodeAnalyzer::Default_mm3_per_mm),
m_last_width(GCodeAnalyzer::Default_Width),
m_last_height(GCodeAnalyzer::Default_Height),
+#endif // !ENABLE_GCODE_VIEWER
m_brim_done(false),
m_second_layer_things_done(false),
+#if !ENABLE_GCODE_VIEWER
m_normal_time_estimator(GCodeTimeEstimator::Normal),
m_silent_time_estimator(GCodeTimeEstimator::Silent),
+#endif // !ENABLE_GCODE_VIEWER
m_silent_time_estimator_enabled(false),
m_last_obj_copy(nullptr, Point(std::numeric_limits::max(), std::numeric_limits::max()))
{}
@@ -167,7 +194,11 @@ public:
// throws std::runtime_exception on error,
// throws CanceledException through print->throw_if_canceled().
+#if ENABLE_GCODE_VIEWER
+ void do_export(Print* print, const char* path, GCodeProcessor::Result* result = nullptr, ThumbnailsGeneratorCallback thumbnail_cb = nullptr);
+#else
void do_export(Print* print, const char* path, GCodePreviewData* preview_data = nullptr, ThumbnailsGeneratorCallback thumbnail_cb = nullptr);
+#endif // ENABLE_GCODE_VIEWER
// Exported for the helper classes (OozePrevention, Wipe) and for the Perl binding for unit tests.
const Vec2d& origin() const { return m_origin; }
@@ -327,11 +358,16 @@ private:
// Markers for the Pressure Equalizer to recognize the extrusion type.
// The Pressure Equalizer removes the markers from the final G-code.
bool m_enable_extrusion_role_markers;
+#if ENABLE_GCODE_VIEWER
+ // Keeps track of the last extrusion role passed to the processor
+ ExtrusionRole m_last_processor_extrusion_role;
+#else
// Enableds the G-code Analyzer.
// Extended markers will be added during G-code generation.
// The G-code Analyzer will remove these comments from the final G-code.
bool m_enable_analyzer;
ExtrusionRole m_last_analyzer_extrusion_role;
+#endif // ENABLE_GCODE_VIEWER
// How many times will change_layer() be called?
// change_layer() will update the progress bar.
unsigned int m_layer_count;
@@ -344,10 +380,20 @@ private:
double m_volumetric_speed;
// Support for the extrusion role markers. Which marker is active?
ExtrusionRole m_last_extrusion_role;
+#if ENABLE_GCODE_VIEWER
+ // Support for G-Code Processor
+ float m_last_height{ 0.0f };
+ float m_last_layer_z{ 0.0f };
+#if ENABLE_GCODE_VIEWER_DATA_CHECKING
+ double m_last_mm3_per_mm;
+ float m_last_width{ 0.0f };
+#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
+#else
// Support for G-Code Analyzer
double m_last_mm3_per_mm;
float m_last_width;
float m_last_height;
+#endif // ENABLE_GCODE_VIEWER
Point m_last_pos;
bool m_last_pos_defined;
@@ -368,13 +414,20 @@ private:
// Index of a last object copy extruded.
std::pair m_last_obj_copy;
+#if !ENABLE_GCODE_VIEWER
// Time estimators
GCodeTimeEstimator m_normal_time_estimator;
GCodeTimeEstimator m_silent_time_estimator;
+#endif // !ENABLE_GCODE_VIEWER
bool m_silent_time_estimator_enabled;
+#if ENABLE_GCODE_VIEWER
+ // Processor
+ GCodeProcessor m_processor;
+#else
// Analyzer
GCodeAnalyzer m_analyzer;
+#endif // ENABLE_GCODE_VIEWER
// Write a string into a file.
void _write(FILE* file, const std::string& what) { this->_write(file, what.c_str()); }
diff --git a/src/libslic3r/GCode/Analyzer.cpp b/src/libslic3r/GCode/Analyzer.cpp
index 73c20f1b58..d022b37983 100644
--- a/src/libslic3r/GCode/Analyzer.cpp
+++ b/src/libslic3r/GCode/Analyzer.cpp
@@ -12,6 +12,8 @@
#include "Analyzer.hpp"
#include "PreviewData.hpp"
+#if !ENABLE_GCODE_VIEWER
+
static const std::string AXIS_STR = "XYZE";
static const float MMMIN_TO_MMSEC = 1.0f / 60.0f;
static const float INCHES_TO_MM = 25.4f;
@@ -350,7 +352,7 @@ void GCodeAnalyzer::_processG1(const GCodeReader::GCodeLine& line)
if (delta_pos[E] < 0.0f)
{
if ((delta_pos[X] != 0.0f) || (delta_pos[Y] != 0.0f) || (delta_pos[Z] != 0.0f))
- type = GCodeMove::Move;
+ type = GCodeMove::Move;
else
type = GCodeMove::Retract;
}
@@ -651,7 +653,7 @@ bool GCodeAnalyzer::_process_tags(const GCodeReader::GCodeLine& line)
return true;
}
- // color change tag
+ // pause print tag
pos = comment.find(Pause_Print_Tag);
if (pos != comment.npos)
{
@@ -659,7 +661,7 @@ bool GCodeAnalyzer::_process_tags(const GCodeReader::GCodeLine& line)
return true;
}
- // color change tag
+ // custom code tag
pos = comment.find(Custom_Code_Tag);
if (pos != comment.npos)
{
@@ -667,7 +669,7 @@ bool GCodeAnalyzer::_process_tags(const GCodeReader::GCodeLine& line)
return true;
}
- // color change tag
+ // end pause print or custom code tag
pos = comment.find(End_Pause_Print_Or_Custom_Code_Tag);
if (pos != comment.npos)
{
@@ -1191,3 +1193,5 @@ size_t GCodeAnalyzer::memory_used() const
}
} // namespace Slic3r
+
+#endif // !ENABLE_GCODE_VIEWER
diff --git a/src/libslic3r/GCode/Analyzer.hpp b/src/libslic3r/GCode/Analyzer.hpp
index 4ac383fea6..37d9072592 100644
--- a/src/libslic3r/GCode/Analyzer.hpp
+++ b/src/libslic3r/GCode/Analyzer.hpp
@@ -1,6 +1,8 @@
#ifndef slic3r_GCode_Analyzer_hpp_
#define slic3r_GCode_Analyzer_hpp_
+#if !ENABLE_GCODE_VIEWER
+
#include "../libslic3r.h"
#include "../PrintConfig.hpp"
#include "../ExtrusionEntity.hpp"
@@ -302,4 +304,6 @@ private:
} // namespace Slic3r
+#endif // !ENABLE_GCODE_VIEWER
+
#endif /* slic3r_GCode_Analyzer_hpp_ */
diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp
new file mode 100644
index 0000000000..0a5617559d
--- /dev/null
+++ b/src/libslic3r/GCode/GCodeProcessor.cpp
@@ -0,0 +1,2181 @@
+#include "libslic3r/libslic3r.h"
+#include "libslic3r/Utils.hpp"
+#include "libslic3r/Print.hpp"
+#include "GCodeProcessor.hpp"
+
+#include
+#include
+#include
+
+#include
+#include
+
+#if ENABLE_GCODE_VIEWER
+#include
+
+static const float INCHES_TO_MM = 25.4f;
+static const float MMMIN_TO_MMSEC = 1.0f / 60.0f;
+
+static const float DEFAULT_ACCELERATION = 1500.0f; // Prusa Firmware 1_75mm_MK2
+
+namespace Slic3r {
+
+const std::string GCodeProcessor::Extrusion_Role_Tag = "TYPE:";
+const std::string GCodeProcessor::Height_Tag = "HEIGHT:";
+const std::string GCodeProcessor::Layer_Change_Tag = "LAYER_CHANGE";
+const std::string GCodeProcessor::Color_Change_Tag = "COLOR_CHANGE";
+const std::string GCodeProcessor::Pause_Print_Tag = "PAUSE_PRINT";
+const std::string GCodeProcessor::Custom_Code_Tag = "CUSTOM_GCODE";
+
+const std::string GCodeProcessor::First_Line_M73_Placeholder_Tag = "; _GP_FIRST_LINE_M73_PLACEHOLDER";
+const std::string GCodeProcessor::Last_Line_M73_Placeholder_Tag = "; _GP_LAST_LINE_M73_PLACEHOLDER";
+const std::string GCodeProcessor::Estimated_Printing_Time_Placeholder_Tag = "; _GP_ESTIMATED_PRINTING_TIME_PLACEHOLDER";
+
+#if ENABLE_GCODE_VIEWER_DATA_CHECKING
+const std::string GCodeProcessor::Width_Tag = "WIDTH:";
+const std::string GCodeProcessor::Mm3_Per_Mm_Tag = "MM3_PER_MM:";
+#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
+
+static bool is_valid_extrusion_role(int value)
+{
+ return (static_cast(erNone) <= value) && (value <= static_cast(erMixed));
+}
+
+static void set_option_value(ConfigOptionFloats& option, size_t id, float value)
+{
+ if (id < option.values.size())
+ option.values[id] = static_cast(value);
+};
+
+static float get_option_value(const ConfigOptionFloats& option, size_t id)
+{
+ return option.values.empty() ? 0.0f :
+ ((id < option.values.size()) ? static_cast(option.values[id]) : static_cast(option.values.back()));
+}
+
+static float estimated_acceleration_distance(float initial_rate, float target_rate, float acceleration)
+{
+ return (acceleration == 0.0f) ? 0.0f : (sqr(target_rate) - sqr(initial_rate)) / (2.0f * acceleration);
+}
+
+static float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance)
+{
+ return (acceleration == 0.0f) ? 0.0f : (2.0f * acceleration * distance - sqr(initial_rate) + sqr(final_rate)) / (4.0f * acceleration);
+}
+
+static float speed_from_distance(float initial_feedrate, float distance, float acceleration)
+{
+ // to avoid invalid negative numbers due to numerical errors
+ float value = std::max(0.0f, sqr(initial_feedrate) + 2.0f * acceleration * distance);
+ return ::sqrt(value);
+}
+
+// Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the
+// acceleration within the allotted distance.
+static float max_allowable_speed(float acceleration, float target_velocity, float distance)
+{
+ // to avoid invalid negative numbers due to numerical errors
+ float value = std::max(0.0f, sqr(target_velocity) - 2.0f * acceleration * distance);
+ return std::sqrt(value);
+}
+
+static float acceleration_time_from_distance(float initial_feedrate, float distance, float acceleration)
+{
+ return (acceleration != 0.0f) ? (speed_from_distance(initial_feedrate, distance, acceleration) - initial_feedrate) / acceleration : 0.0f;
+}
+
+void GCodeProcessor::CachedPosition::reset()
+{
+ std::fill(position.begin(), position.end(), FLT_MAX);
+ feedrate = FLT_MAX;
+}
+
+void GCodeProcessor::CpColor::reset()
+{
+ counter = 0;
+ current = 0;
+}
+
+float GCodeProcessor::Trapezoid::acceleration_time(float entry_feedrate, float acceleration) const
+{
+ return acceleration_time_from_distance(entry_feedrate, accelerate_until, acceleration);
+}
+
+float GCodeProcessor::Trapezoid::cruise_time() const
+{
+ return (cruise_feedrate != 0.0f) ? cruise_distance() / cruise_feedrate : 0.0f;
+}
+
+float GCodeProcessor::Trapezoid::deceleration_time(float distance, float acceleration) const
+{
+ return acceleration_time_from_distance(cruise_feedrate, (distance - decelerate_after), -acceleration);
+}
+
+float GCodeProcessor::Trapezoid::cruise_distance() const
+{
+ return decelerate_after - accelerate_until;
+}
+
+void GCodeProcessor::TimeBlock::calculate_trapezoid()
+{
+ trapezoid.cruise_feedrate = feedrate_profile.cruise;
+
+ float accelerate_distance = std::max(0.0f, estimated_acceleration_distance(feedrate_profile.entry, feedrate_profile.cruise, acceleration));
+ float decelerate_distance = std::max(0.0f, estimated_acceleration_distance(feedrate_profile.cruise, feedrate_profile.exit, -acceleration));
+ float cruise_distance = distance - accelerate_distance - decelerate_distance;
+
+ // Not enough space to reach the nominal feedrate.
+ // This means no cruising, and we'll have to use intersection_distance() to calculate when to abort acceleration
+ // and start braking in order to reach the exit_feedrate exactly at the end of this block.
+ if (cruise_distance < 0.0f) {
+ accelerate_distance = std::clamp(intersection_distance(feedrate_profile.entry, feedrate_profile.exit, acceleration, distance), 0.0f, distance);
+ cruise_distance = 0.0f;
+ trapezoid.cruise_feedrate = speed_from_distance(feedrate_profile.entry, accelerate_distance, acceleration);
+ }
+
+ trapezoid.accelerate_until = accelerate_distance;
+ trapezoid.decelerate_after = accelerate_distance + cruise_distance;
+}
+
+float GCodeProcessor::TimeBlock::time() const
+{
+ return trapezoid.acceleration_time(feedrate_profile.entry, acceleration)
+ + trapezoid.cruise_time()
+ + trapezoid.deceleration_time(distance, acceleration);
+}
+
+void GCodeProcessor::TimeMachine::State::reset()
+{
+ feedrate = 0.0f;
+ safe_feedrate = 0.0f;
+ axis_feedrate = { 0.0f, 0.0f, 0.0f, 0.0f };
+ abs_axis_feedrate = { 0.0f, 0.0f, 0.0f, 0.0f };
+}
+
+void GCodeProcessor::TimeMachine::CustomGCodeTime::reset()
+{
+ needed = false;
+ cache = 0.0f;
+ times = std::vector>();
+}
+
+void GCodeProcessor::TimeMachine::reset()
+{
+ enabled = false;
+ acceleration = 0.0f;
+ max_acceleration = 0.0f;
+ extrude_factor_override_percentage = 1.0f;
+ time = 0.0f;
+ curr.reset();
+ prev.reset();
+ gcode_time.reset();
+ blocks = std::vector();
+ g1_times_cache = std::vector