Compare commits

..
Author SHA1 Message Date
Valerii Bokhan 60b4a61854 Fix: Show indexed coFloatsOrPercents options in unsaved changes dialog (#15472) 2026-09-17 10:56:17 -03:00
Ian Bassi 7065fa9eae Fix extruder clearance help link anchor (#15738) 2026-09-17 09:54:42 -03:00
Ian Bassi 59e40a2c2e Print unsupported walls last (#15411) 2026-09-17 09:14:20 -03:00
Ian Bassi 82e91bd472 Port wipe tower BBS improvements (#15485) 2026-09-17 09:08:50 -03:00
packerlschupfer ca668a3bc9 CLI: --inspect-paint — dump per-facet paint state as JSON (#14608)
* CLI: --inspect-paint — dump per-facet paint state as JSON

Reads the per-facet enforcer/blocker/extruder/fuzzy-skin state stored
on every ModelVolume (supported_facets / seam_facets /
mmu_segmentation_facets / fuzzy_skin_facets) and emits a structured
JSON summary to stdout. Machine-readable alternative to opening the
paint gizmos.

Per (object, volume, layer, state): facet count, surface area in
mm², and mesh-local bounding box. Empty layers collapse to
{"empty": true}. Summary at the top level rolls up totals.

One correctness detail worth calling out: FacetsAnnotation::
get_facets_strict returns an indexed_triangle_set whose `vertices`
array is the whole source mesh — only `indices` are filtered to the
painted triangles. A naive bounding_box(its) would report the whole
mesh's bbox even when only a few facets are painted. The helper
its_referenced_bbox() walks only the vertices actually indexed by
the painted triangles, so `bbox` correctly localizes the painted
region.

Rationale: every paint-driven workflow — GUI-painted .3mf verified
in CI, AI agents planning support enforcers, MMU color layout checks
— needs to know what's already painted on a model. Today that's a
GUI-only read. --inspect-paint closes that loop for scripted callers.

New file src/slic3r/Utils/PaintCLI.{hpp,cpp} (~215 lines). Depends
only on Model, TriangleMesh, TriangleSelector, FacetsAnnotation, and
nlohmann::json — all already in tree. No new dependencies, no
signature changes, no behavior change when the flag is absent.

Registered as an action (parallel to --info) so it satisfies the
"needs an action" check and bypasses the GUI fallback; control falls
through the normal post-action path to a clean exit 0.

Verification:
  unpainted STL:     every layer {"empty": true}, summary zero
  GUI-painted .3mf:  enforcer count / area / bbox match painter
  clean JSON:        parseable via jq

* CLI --inspect-paint: exit after printing, reject conflicting actions

- Finish like the end of CLI::run once the JSON is written, as the
  tooltip says. The callback manager is Linux-only, so its use is
  guarded.
- Reject actions that would otherwise be skipped without notice
  (--slice, --export-3mf, ...) before loading. Load-time options such as
  --uptodate are still accepted.
- Replace invalid UTF-8 in object names and paths instead of throwing.
- Report every input file as sources; inputs are merged into one model
  before actions run.

* CLI --inspect-paint: reject a run without input

Without an input file or --load-assemble-list there is nothing to
inspect, and the run printed nothing and exited 0. Reject it up front
with CLI_INVALID_PARAMS, next to the other invalid-parameter checks.
2026-09-17 12:01:49 +08:00
Kris Austin 6b0e190e64 ci: key the Windows compiler cache on the MSVC toolset version (#15729) 2026-09-16 18:30:18 -03:00
Kris Austin 8effa27f4a build: build the dependencies with clang-cl under the Visual Studio generator (#15673)
The deps superbuild passes the Visual Studio generator and platform to
every sub-build but not the toolset, so build_win.bat -d -l without -x
compiled every dependency with cl even though the superbuild had been
configured with -T ClangCL; CMake replaces the forwarded
CMAKE_<LANG>_COMPILER with whatever the toolset ran. The recipes that
adapt to clang-cl then disagreed with what had been built, and
wxInspector told FindwxWidgets to look in lib/clang_x64_lib while the
cl-built wxWidgets had installed into lib/vc_x64_lib:

  Could NOT find wxWidgets (missing: wxWidgets_LIBRARIES
  wxWidgets_INCLUDE_DIRS core base aui propgrid)

Forward CMAKE_GENERATOR_TOOLSET as well, so the dependencies compile
with clang-cl under MSBuild the way they already do under Ninja. Four
of them need more than that:

- OpenSSL always builds with cl, and MSBuild runs its nmake steps in
  the project's toolset environment, where ClangCL puts clang's include
  directory first and cl trips over clang's stdint.h. The project gets
  the default toolset.
- Boost.Container's dlmalloc needs -Wno-incompatible-pointer-types
  under clang. boost_container links as C++, and the Visual Studio
  generator writes only the link language's flags into the project, so
  its C file never saw CMAKE_C_FLAGS. Under that generator the option
  goes through the C++ flags as well, with the defaults kept.
- Draco's tools and NLopt's testopt compile sources their own static
  library also contains. MSBuild lists libraries before objects and
  lld-link resolves archive members as each input arrives, so the
  library's copy is pulled in before the executable's own object and
  the link fails on duplicate symbols; link.exe defers the search and
  Ninja lists the objects first. Nothing uses those executables, so
  they get /FORCE:MULTIPLE there.

The Ninja path is unchanged: the generated configure commands of all
29 dependencies are identical before and after. OCCT's arm64 override
to cl still applies under Ninja but not under the Visual Studio
generator, where the toolset wins; that combination never built and is
left for a follow-up.
2026-09-16 14:28:50 -03:00
Ian BassiandRodrigo Faselli 72774e5398 Toolchange Cyclic Order (#14868)
* Toolchange Cyclic Order

* Apply cyclic order to first layer

* Unit test

* Copilot fixes

---------

Co-authored-by: Rodrigo Faselli <162915171+RF47@users.noreply.github.com>
2026-09-16 12:19:03 -03:00
121 changed files with 2766 additions and 3529 deletions
+9
View File
@@ -85,6 +85,15 @@ jobs:
shell: bash shell: bash
run: | run: |
leg="${{ runner.os }}-${{ inputs.arch || 'amd64' }}${{ runner.os == 'Windows' && format('-{0}', inputs.compiler) || '' }}" leg="${{ runner.os }}-${{ inputs.arch || 'amd64' }}${{ runner.os == 'Windows' && format('-{0}', inputs.compiler) || '' }}"
# clang-cl refuses a precompiled header from another cl.exe build and ccache
# does not hash that build, so each one gets its own cache. The build number
# is read from cl.exe itself; the toolset directory keeps its name across patches.
if [ "${{ runner.os }}" = Windows ]; then
vswhere='/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe'
toolset=$(tr -d '\r\n' < "$("$vswhere" -latest -products '*' -find 'VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt' | tr -d '\r')")
cl=$("$vswhere" -latest -products '*' -find 'VC\Tools\MSVC\'"$toolset"'\**\cl.exe' | tr -d '\r' | head -1)
leg="$leg-vc$("$cl" 2>&1 | grep -o -E 'Version [0-9.]+' | cut -d' ' -f2)"
fi
echo "CCACHE_LEG=$leg" >> "$GITHUB_ENV" echo "CCACHE_LEG=$leg" >> "$GITHUB_ENV"
echo "CCACHE_ENTRY=ccache-$leg-${{ github.run_id }}-${{ github.run_attempt }}" >> "$GITHUB_ENV" echo "CCACHE_ENTRY=ccache-$leg-${{ github.run_id }}-${{ github.run_attempt }}" >> "$GITHUB_ENV"
+1 -42
View File
@@ -821,37 +821,6 @@ find_package(OpenSSL REQUIRED)
find_package(CURL REQUIRED) find_package(CURL REQUIRED)
find_package(Freetype REQUIRED) find_package(Freetype REQUIRED)
if (SLIC3R_GUI)
# LibDataChannel's installed export references its bundled dependencies,
# but does not install their CMake targets. Recreate those targets from
# the same dependency prefix before loading the LibDataChannel config.
if (NOT TARGET Usrsctp::usrsctp)
find_library(_ORCA_USRSCTP_LIBRARY NAMES usrsctp
PATHS "${CMAKE_PREFIX_PATH}/lib" NO_DEFAULT_PATH)
if (_ORCA_USRSCTP_LIBRARY)
add_library(Usrsctp::usrsctp UNKNOWN IMPORTED GLOBAL)
set_target_properties(Usrsctp::usrsctp PROPERTIES
IMPORTED_LOCATION "${_ORCA_USRSCTP_LIBRARY}"
IMPORTED_LINK_INTERFACE_LANGUAGES C
INTERFACE_LINK_LIBRARIES "Threads::Threads")
endif()
endif()
if (NOT TARGET LibJuice::LibJuice)
find_library(_ORCA_LIBJUICE_LIBRARY NAMES juice
PATHS "${CMAKE_PREFIX_PATH}/lib" NO_DEFAULT_PATH)
if (_ORCA_LIBJUICE_LIBRARY)
add_library(LibJuice::LibJuice UNKNOWN IMPORTED GLOBAL)
set_target_properties(LibJuice::LibJuice PROPERTIES
IMPORTED_LOCATION "${_ORCA_LIBJUICE_LIBRARY}"
IMPORTED_LINK_INTERFACE_LANGUAGES C
INTERFACE_LINK_LIBRARIES "Threads::Threads")
endif()
endif()
find_package(LibDataChannel CONFIG REQUIRED)
endif()
add_library(libcurl INTERFACE) add_library(libcurl INTERFACE)
target_link_libraries(libcurl INTERFACE CURL::libcurl) target_link_libraries(libcurl INTERFACE CURL::libcurl)
@@ -1134,7 +1103,6 @@ function(orcaslicer_copy_dlls target config postfix output_dlls)
${CMAKE_PREFIX_PATH}/bin/occt/TKXDESTEP.dll ${CMAKE_PREFIX_PATH}/bin/occt/TKXDESTEP.dll
${CMAKE_PREFIX_PATH}/bin/occt/TKXSBase.dll ${CMAKE_PREFIX_PATH}/bin/occt/TKXSBase.dll
${CMAKE_PREFIX_PATH}/bin/freetype.dll ${CMAKE_PREFIX_PATH}/bin/freetype.dll
${CMAKE_PREFIX_PATH}/bin/avformat-61.dll
${CMAKE_PREFIX_PATH}/bin/avcodec-61.dll ${CMAKE_PREFIX_PATH}/bin/avcodec-61.dll
${CMAKE_PREFIX_PATH}/bin/swresample-5.dll ${CMAKE_PREFIX_PATH}/bin/swresample-5.dll
${CMAKE_PREFIX_PATH}/bin/swscale-8.dll ${CMAKE_PREFIX_PATH}/bin/swscale-8.dll
@@ -1174,7 +1142,6 @@ function(orcaslicer_copy_dlls target config postfix output_dlls)
${_out_dir}/TKXSBase.dll ${_out_dir}/TKXSBase.dll
${_out_dir}/freetype.dll ${_out_dir}/freetype.dll
${_out_dir}/avformat-61.dll
${_out_dir}/avcodec-61.dll ${_out_dir}/avcodec-61.dll
${_out_dir}/swresample-5.dll ${_out_dir}/swresample-5.dll
${_out_dir}/swscale-8.dll ${_out_dir}/swscale-8.dll
@@ -1197,10 +1164,7 @@ function(orcaslicer_copy_sos target config postfix output_sos)
set(_out_dir "${CMAKE_CURRENT_BINARY_DIR}") set(_out_dir "${CMAKE_CURRENT_BINARY_DIR}")
endif () endif ()
file(COPY ${CMAKE_PREFIX_PATH}/lib/libavformat.so file(COPY ${CMAKE_PREFIX_PATH}/lib/libavcodec.so
${CMAKE_PREFIX_PATH}/lib/libavformat.so.61
${CMAKE_PREFIX_PATH}/lib/libavformat.so.61.1.100
${CMAKE_PREFIX_PATH}/lib/libavcodec.so
${CMAKE_PREFIX_PATH}/lib/libavcodec.so.61 ${CMAKE_PREFIX_PATH}/lib/libavcodec.so.61
${CMAKE_PREFIX_PATH}/lib/libavcodec.so.61.3.100 ${CMAKE_PREFIX_PATH}/lib/libavcodec.so.61.3.100
${CMAKE_PREFIX_PATH}/lib/libavutil.so ${CMAKE_PREFIX_PATH}/lib/libavutil.so
@@ -1215,9 +1179,6 @@ function(orcaslicer_copy_sos target config postfix output_sos)
DESTINATION ${_out_dir}) DESTINATION ${_out_dir})
set(${output_sos} set(${output_sos}
${_out_dir}/libavformat.so
${_out_dir}/libavformat.so.61
${_out_dir}/libavformat.so.61.1.100
${_out_dir}/libavcodec.so ${_out_dir}/libavcodec.so
${_out_dir}/libavcodec.so.61 ${_out_dir}/libavcodec.so.61
${_out_dir}/libavcodec.so.61.3.100 ${_out_dir}/libavcodec.so.61.3.100
@@ -1347,8 +1308,6 @@ endif ()
if (CMAKE_SYSTEM_NAME STREQUAL "Linux") if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(LIBRARY_FILES set(LIBRARY_FILES
${LIBDIR_BIN}/libavformat.so.61
${LIBDIR_BIN}/libavformat.so.61.1.100
${LIBDIR_BIN}/libavcodec.so.61 ${LIBDIR_BIN}/libavcodec.so.61
${LIBDIR_BIN}/libavcodec.so.61.3.100 ${LIBDIR_BIN}/libavcodec.so.61.3.100
${LIBDIR_BIN}/libavutil.so.59 ${LIBDIR_BIN}/libavutil.so.59
+8
View File
@@ -27,8 +27,15 @@ endif ()
# Boost.Container's bundled dlmalloc passes int* where the Win32 Interlocked API # Boost.Container's bundled dlmalloc passes int* where the Win32 Interlocked API
# takes volatile long*; cl compiles that with a warning, clang errors out. # takes volatile long*; cl compiles that with a warning, clang errors out.
set(_boost_c_flags_line "") set(_boost_c_flags_line "")
set(_boost_cxx_flags_line "")
if (MSVC AND CMAKE_C_COMPILER_ID STREQUAL "Clang") if (MSVC AND CMAKE_C_COMPILER_ID STREQUAL "Clang")
set(_boost_c_flags_line "-DCMAKE_C_FLAGS:STRING=-Wno-incompatible-pointer-types") set(_boost_c_flags_line "-DCMAKE_C_FLAGS:STRING=-Wno-incompatible-pointer-types")
# The Visual Studio generator applies only the link language's flags to a
# project, and boost_container links as C++, so its C file never sees
# CMAKE_C_FLAGS. The C++ flags reach every file; keep CMake's defaults.
if (CMAKE_GENERATOR MATCHES "Visual Studio")
set(_boost_cxx_flags_line "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} -Wno-incompatible-pointer-types")
endif ()
endif () endif ()
orcaslicer_add_cmake_project(Boost orcaslicer_add_cmake_project(Boost
@@ -46,6 +53,7 @@ orcaslicer_add_cmake_project(Boost
"${_context_arch_line}" "${_context_arch_line}"
"${_context_impl_line}" "${_context_impl_line}"
"${_boost_c_flags_line}" "${_boost_c_flags_line}"
"${_boost_cxx_flags_line}"
) )
set(DEP_Boost_DEPENDS ZLIB) set(DEP_Boost_DEPENDS ZLIB)
+9 -7
View File
@@ -184,6 +184,11 @@ function(orcaslicer_add_cmake_project projectname)
if (_dep_msvc_gen) if (_dep_msvc_gen)
set(_gen CMAKE_GENERATOR "${DEP_MSVC_GEN}" CMAKE_GENERATOR_PLATFORM "${DEP_PLATFORM}") set(_gen CMAKE_GENERATOR "${DEP_MSVC_GEN}" CMAKE_GENERATOR_PLATFORM "${DEP_PLATFORM}")
# The toolset picks the compiler here, not the CMAKE_<LANG>_COMPILER
# forwarded below, so without it a clang-cl superbuild builds with cl.
if (CMAKE_GENERATOR_TOOLSET)
list(APPEND _gen CMAKE_GENERATOR_TOOLSET "${CMAKE_GENERATOR_TOOLSET}")
endif ()
else() else()
set(_gen "") set(_gen "")
endif() endif()
@@ -375,6 +380,10 @@ include(libnoise/libnoise.cmake)
include(Draco/Draco.cmake) include(Draco/Draco.cmake)
include(FFMPEG/FFMPEG.cmake)
include(Assimp/Assimp.cmake)
# I *think* 1.1 is used for *just* md5 hashing? # I *think* 1.1 is used for *just* md5 hashing?
# 3.1 has everything in the right place, but the md5 funcs used are deprecated # 3.1 has everything in the right place, but the md5 funcs used are deprecated
# a grep across the repo shows it is used for other things # a grep across the repo shows it is used for other things
@@ -385,12 +394,6 @@ if(NOT OPENSSL_FOUND)
set(OPENSSL_PKG dep_OpenSSL) set(OPENSSL_PKG dep_OpenSSL)
endif() endif()
include(FFMPEG/FFMPEG.cmake)
include(Assimp/Assimp.cmake)
include(DataChannel/DataChannel.cmake)
set(DATACHANNEL_PKG dep_DataChannel)
# we don't want to load a "wrong" openssl when loading curl # we don't want to load a "wrong" openssl when loading curl
# so, just don't even bother # so, just don't even bother
# ...i think this is how it works? change if wrong # ...i think this is how it works? change if wrong
@@ -463,7 +466,6 @@ set(_dep_list
dep_wxInspector dep_wxInspector
dep_FFMPEG dep_FFMPEG
dep_Assimp dep_Assimp
${DATACHANNEL_PKG}
) )
if (MSVC) if (MSVC)
-20
View File
@@ -1,20 +0,0 @@
# libdatachannel is the native ICE/DTLS/SCTP implementation used by the
# GUI WebRTC camera controller. Keep the source revision fixed: the signaling
# protocol is evolving independently of this transport dependency.
orcaslicer_add_cmake_project(DataChannel
DEPENDS ${OPENSSL_PKG}
CMAKE_ARGS
-DNO_EXAMPLES=ON
-DNO_TESTS=ON
-DNO_WEBSOCKET=ON
-DNO_MEDIA=ON
-DUSE_NICE=OFF
-DUSE_SYSTEM_JUICE=OFF
-DUSE_SYSTEM_USRSCTP=OFF
-DOPENSSL_ROOT_DIR:PATH=${DESTDIR}
-DOPENSSL_USE_STATIC_LIBS=ON
GIT_REPOSITORY https://github.com/paullouisageneau/libdatachannel.git
GIT_TAG v0.22.2
GIT_SHALLOW ON
GIT_SUBMODULES_RECURSE ON
)
+3
View File
@@ -7,4 +7,7 @@ orcaslicer_add_cmake_project(Draco
${_options} ${_options}
URL https://github.com/google/draco/archive/refs/tags/1.5.7.zip URL https://github.com/google/draco/archive/refs/tags/1.5.7.zip
URL_HASH SHA256=27b72ba2d5ff3d0a9814ad40d4cb88f8dc89a35491c0866d952473f8f9416b77 URL_HASH SHA256=27b72ba2d5ff3d0a9814ad40d4cb88f8dc89a35491c0866d952473f8f9416b77
CMAKE_ARGS
# The encoder and decoder tools duplicate draco.lib; see deps-windows.cmake.
"${DEP_LLD_FORCE_MULTIPLE}"
) )
+3 -19
View File
@@ -1,16 +1,5 @@
set(_conf_cmd ./configure) set(_conf_cmd ./configure)
set(_ffmpeg_depends)
set(_ffmpeg_configure_command ${_conf_cmd})
if (TARGET dep_OpenSSL)
set(_ffmpeg_depends DEPENDS dep_OpenSSL)
set(_ffmpeg_configure_command
${CMAKE_COMMAND} -E env
"PKG_CONFIG_PATH=${DESTDIR}/lib/pkgconfig:$ENV{PKG_CONFIG_PATH}"
${_conf_cmd}
)
endif()
if (MSVC) if (MSVC)
set(_source_dir "${CMAKE_BINARY_DIR}/dep_FFMPEG-prefix/src/dep_FFMPEG") set(_source_dir "${CMAKE_BINARY_DIR}/dep_FFMPEG-prefix/src/dep_FFMPEG")
@@ -20,7 +9,6 @@ if (MSVC)
set(PREBUILD_HASH_x64 "e65916020ddb9ef84b2666dfbcbfc9b1d67f69d15b4a66db53754637bf2d498c") set(PREBUILD_HASH_x64 "e65916020ddb9ef84b2666dfbcbfc9b1d67f69d15b4a66db53754637bf2d498c")
ExternalProject_Add(dep_FFMPEG ExternalProject_Add(dep_FFMPEG
${_ffmpeg_depends}
URL ${PREBUILD_URL_${DEPS_ARCH}} URL ${PREBUILD_URL_${DEPS_ARCH}}
URL_HASH SHA256=${PREBUILD_HASH_${DEPS_ARCH}} URL_HASH SHA256=${PREBUILD_HASH_${DEPS_ARCH}}
DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/FFMPEG DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/FFMPEG
@@ -33,8 +21,6 @@ if (MSVC)
) )
else () else ()
set(_openssl_cmd --enable-openssl)
if (APPLE) if (APPLE)
set(_minos_cmd set(_minos_cmd
"--extra-cflags=-mmacosx-version-min=${DEP_OSX_TARGET}" "--extra-cflags=-mmacosx-version-min=${DEP_OSX_TARGET}"
@@ -66,11 +52,10 @@ else ()
endif() endif()
ExternalProject_Add(dep_FFMPEG ExternalProject_Add(dep_FFMPEG
${_ffmpeg_depends}
URL https://github.com/FFmpeg/FFmpeg/archive/refs/tags/n7.0.3.tar.gz URL https://github.com/FFmpeg/FFmpeg/archive/refs/tags/n7.0.3.tar.gz
URL_HASH SHA256=DEEDCABE339165214A3637DF4C86A507AEF0D793CF8774FF68735F4737E8DDBC URL_HASH SHA256=DEEDCABE339165214A3637DF4C86A507AEF0D793CF8774FF68735F4737E8DDBC
DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/FFMPEG DOWNLOAD_DIR ${DEP_DOWNLOAD_DIR}/FFMPEG
CONFIGURE_COMMAND ${_ffmpeg_configure_command} CONFIGURE_COMMAND ${_conf_cmd}
${_cross_cmd} ${_cross_cmd}
${_pic_cmd} ${_pic_cmd}
${_arch_cmd} ${_arch_cmd}
@@ -78,21 +63,20 @@ else ()
"--prefix=${DESTDIR}" "--prefix=${DESTDIR}"
${_link_cmd} ${_link_cmd}
${_minos_cmd} ${_minos_cmd}
${_openssl_cmd}
--disable-doc --disable-doc
--enable-small --enable-small
--disable-outdevs --disable-outdevs
--disable-filters --disable-filters
--enable-filter=*null*,afade,*fifo,*format,*resample,aeval,allrgb,allyuv,atempo,pan,*bars,color,*key,crop,draw*,eq*,framerate,*_qsv,*_vaapi,*v4l2*,hw*,scale,volume,test* --enable-filter=*null*,afade,*fifo,*format,*resample,aeval,allrgb,allyuv,atempo,pan,*bars,color,*key,crop,draw*,eq*,framerate,*_qsv,*_vaapi,*v4l2*,hw*,scale,volume,test*
--disable-protocols --disable-protocols
--enable-protocol=file,fd,pipe,http,https,rtp,tcp,udp --enable-protocol=file,fd,pipe,rtp,udp
--disable-muxers --disable-muxers
--enable-muxer=rtp --enable-muxer=rtp
--disable-encoders --disable-encoders
--disable-decoders --disable-decoders
--enable-decoder=*aac*,h264*,mp3*,mjpeg,rv* --enable-decoder=*aac*,h264*,mp3*,mjpeg,rv*
--disable-demuxers --disable-demuxers
--enable-demuxer=h264,mp3,mov,mpjpeg,rtsp,sdp --enable-demuxer=h264,mp3,mov
--disable-zlib --disable-zlib
--disable-avdevice --disable-avdevice
BUILD_IN_SOURCE ON BUILD_IN_SOURCE ON
+2
View File
@@ -8,6 +8,8 @@ orcaslicer_add_cmake_project(NLopt
-DNLOPT_GUILE:BOOL=OFF -DNLOPT_GUILE:BOOL=OFF
-DNLOPT_SWIG:BOOL=OFF -DNLOPT_SWIG:BOOL=OFF
-DNLOPT_TESTS:BOOL=OFF -DNLOPT_TESTS:BOOL=OFF
# testopt is built regardless of NLOPT_TESTS; see deps-windows.cmake.
"${DEP_LLD_FORCE_MULTIPLE}"
) )
if (MSVC) if (MSVC)
+6
View File
@@ -80,6 +80,12 @@ ExternalProject_Add(dep_OpenSSL
INSTALL_COMMAND ${_install_cmd} INSTALL_COMMAND ${_install_cmd}
) )
if (CMAKE_GENERATOR MATCHES "Visual Studio")
# OpenSSL builds with cl, but MSBuild runs nmake in this project's toolset
# environment, and ClangCL's puts clang's headers first. Use the default.
set_target_properties(dep_OpenSSL PROPERTIES VS_PLATFORM_TOOLSET "$(DefaultPlatformToolset)")
endif ()
ExternalProject_Add_Step(dep_OpenSSL install_cmake_files ExternalProject_Add_Step(dep_OpenSSL install_cmake_files
DEPENDEES install DEPENDEES install
+9
View File
@@ -42,6 +42,15 @@ else ()
message(FATAL_ERROR "Unsupported OS architecture: ${DEPS_ARCH}") message(FATAL_ERROR "Unsupported OS architecture: ${DEPS_ARCH}")
endif () endif ()
# Draco's tools and NLopt's testopt compile sources that are also in their
# static library. MSBuild passes the library before the objects and lld-link
# resolves as it goes, so the library's copy wins and the object then reads as
# a duplicate. Nothing uses those executables, so let lld keep the first one.
set(DEP_LLD_FORCE_MULTIPLE "")
if (CMAKE_GENERATOR MATCHES "Visual Studio" AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(DEP_LLD_FORCE_MULTIPLE "-DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS} /FORCE:MULTIPLE")
endif ()
if (${DEP_DEBUG}) if (${DEP_DEBUG})
set(DEP_BOOST_DEBUG "debug") set(DEP_BOOST_DEBUG "debug")
else () else ()
+1 -3
View File
@@ -575,7 +575,7 @@ function CapabilityCanRun(plugin, capability) {
} }
function IsPluginChecked(plugin) { function IsPluginChecked(plugin) {
return plugin.is_loaded; return GetStatus(plugin) === "Activated";
} }
function HasMixedCapabilityState(plugin) { function HasMixedCapabilityState(plugin) {
@@ -1347,8 +1347,6 @@ function StatusDescription(plugin) {
return "This plugin is still loading."; return "This plugin is still loading.";
case "Error": case "Error":
return "This plugin is blocked until its error is fixed."; return "This plugin is blocked until its error is fixed.";
case "RuntimeError":
return "This plugin is loaded but a capability reported an error.";
case "Inactive": case "Inactive":
default: default:
return "This plugin is inactive. Activate it to install or load it."; return "This plugin is inactive. Activate it to install or load it.";
@@ -424,11 +424,6 @@ body.pane-resizing {
font-weight: 600; font-weight: 600;
} }
.status-cell.status-runtimeerror {
color: var(--plugin-status-warn);
font-weight: 600;
}
.status-cell.status-loading { .status-cell.status-loading {
color: var(--plugin-status-warn); color: var(--plugin-status-warn);
font-weight: 600; font-weight: 600;
@@ -685,11 +680,6 @@ body.pane-resizing {
color: var(--plugin-status-danger); color: var(--plugin-status-danger);
} }
.detail-status-chip.status-runtimeerror {
background: var(--plugin-status-warn-bg);
color: var(--plugin-status-warn);
}
.detail-status-chip.status-loading { .detail-status-chip.status-loading {
background: var(--plugin-status-warn-bg); background: var(--plugin-status-warn-bg);
color: var(--plugin-status-warn); color: var(--plugin-status-warn);
@@ -325,13 +325,6 @@ modules:
sha256: deedcabe339165214a3637df4c86a507aef0d793cf8774ff68735f4737e8ddbc sha256: deedcabe339165214a3637df4c86a507aef0d793cf8774ff68735f4737e8ddbc
dest: external-packages/FFMPEG dest: external-packages/FFMPEG
# libdatachannel v0.22.2
- type: git
url: https://github.com/paullouisageneau/libdatachannel.git
tag: v0.22.2
commit: b3390b4e01e97071dd054684870c4bb5221794bf
dest: deps/build_flatpak/dep_DataChannel-prefix/src/dep_DataChannel
# --------------------------------------------------------------- # ---------------------------------------------------------------
# Fallback archives for deps normally provided by the GNOME SDK. # Fallback archives for deps normally provided by the GNOME SDK.
# These are only used if find_package() fails to locate them. # These are only used if find_package() fails to locate them.
+48
View File
@@ -87,6 +87,7 @@ using namespace nlohmann;
#include "dev-utils/BaseException.h" #include "dev-utils/BaseException.h"
#endif #endif
#include "slic3r/Utils/MeshInspect.hpp" #include "slic3r/Utils/MeshInspect.hpp"
#include "slic3r/Utils/PaintCLI.hpp"
#include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/PartPlate.hpp"
#include "slic3r/GUI/BitmapCache.hpp" #include "slic3r/GUI/BitmapCache.hpp"
#include "slic3r/GUI/OpenGLManager.hpp" #include "slic3r/GUI/OpenGLManager.hpp"
@@ -1443,6 +1444,29 @@ int CLI::run(int argc, char **argv)
} }
} }
// --inspect-paint prints its JSON and exits, so any action that does work of its
// own (slicing, exporting) would be skipped without notice. Reject those up front;
// only options that merely tune how the input is loaded may come along.
if (std::find(m_actions.begin(), m_actions.end(), "inspect_paint") != m_actions.end()) {
static const std::set<std::string> inspect_compatible = { "inspect_paint", "uptodate", "load_defaultfila", "min_save",
"mtcpp", "mstpp", "no_check", "normative_check", "pipe" };
for (const std::string &action : m_actions) {
if (inspect_compatible.count(action) == 0) {
std::string flag = action;
std::replace(flag.begin(), flag.end(), '_', '-');
boost::nowide::cerr << "--inspect-paint cannot be combined with --" << flag << std::endl;
record_exit_reson(outfile_dir, CLI_INVALID_PARAMS, 0, cli_errors[CLI_INVALID_PARAMS], sliced_info);
flush_and_exit(CLI_INVALID_PARAMS);
}
}
// Without input there is nothing to inspect; fail rather than print nothing and exit 0.
if (m_input_files.empty() && m_config.opt_string("load_assemble_list").empty()) {
boost::nowide::cerr << "--inspect-paint needs an input file or --load-assemble-list" << std::endl;
record_exit_reson(outfile_dir, CLI_INVALID_PARAMS, 0, cli_errors[CLI_INVALID_PARAMS], sliced_info);
flush_and_exit(CLI_INVALID_PARAMS);
}
}
// --export-settings - writes its JSON to stdout, so reject every action or transform that may write there // --export-settings - writes its JSON to stdout, so reject every action or transform that may write there
// too (--info, --help, --orient, slicing and exporting). The allowed ones do nothing when nothing is // too (--info, --help, --orient, slicing and exporting). The allowed ones do nothing when nothing is
// sliced or exported. // sliced or exported.
@@ -6100,6 +6124,30 @@ int CLI::run(int argc, char **argv)
cli_status_callback(slicing_status); cli_status_callback(slicing_status);
} }
g_cli_callback_mgr.stop(); g_cli_callback_mgr.stop();
#endif
for (Model &m : m_models)
m.remove_backup_path_if_exist();
record_exit_reson(outfile_dir, CLI_SUCCESS, plate_to_slice, cli_errors[CLI_SUCCESS], sliced_info);
boost::nowide::cerr.flush();
return CLI_SUCCESS;
} else if (opt_key == "inspect_paint") {
// --inspect-paint — read the per-facet enforcer/blocker/extruder/
// fuzzy state from the loaded model and emit a JSON summary.
// Machine-readable alternative to opening the paint gizmos.
for (Model &model : m_models) {
model.add_default_instances();
Slic3r::PaintCLI::inspect_to_json(model, m_input_files, boost::nowide::cout);
}
boost::nowide::cout.flush();
// The tooltip promises "then exit"; conflicting actions were rejected before
// loading. Finish like the end of run(). flush_and_exit() is not usable here:
// it prints "found error ..." to stdout, which would corrupt the JSON.
#if defined(__linux__) || defined(__LINUX__)
if (g_cli_callback_mgr.is_started()) {
PrintBase::SlicingStatus slicing_status{100, "All done, Success"};
cli_status_callback(slicing_status);
}
g_cli_callback_mgr.stop();
#endif #endif
for (Model &m : m_models) for (Model &m : m_models)
m.remove_backup_path_if_exist(); m.remove_backup_path_if_exist();
+4
View File
@@ -454,6 +454,10 @@ class ExtrusionLoop : public ExtrusionEntity
{ {
public: public:
ExtrusionPaths paths; ExtrusionPaths paths;
// ORCA: Set on a loop extruded entirely in mid air and out of reach of the layer below: it has
// nothing to lean on until this layer is bridged, so the G-code writer holds it back until the
// infill is down. See defer_unsupported_loops() in PerimeterGenerator.cpp.
bool print_after_infill = false;
ExtrusionLoop(ExtrusionLoopRole role = elrDefault) : m_loop_role(role) {} ExtrusionLoop(ExtrusionLoopRole role = elrDefault) : m_loop_role(role) {}
ExtrusionLoop(const ExtrusionPaths &paths, ExtrusionLoopRole role = elrDefault) : paths(paths), m_loop_role(role) {} ExtrusionLoop(const ExtrusionPaths &paths, ExtrusionLoopRole role = elrDefault) : paths(paths), m_loop_role(role) {}
+62 -19
View File
@@ -1028,11 +1028,21 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
double current_z = gcodegen.writer().get_position().z(); double current_z = gcodegen.writer().get_position().z();
if (z == -1.) // in case no specific z was provided, print at current_z pos if (z == -1.) // in case no specific z was provided, print at current_z pos
z = current_z; z = current_z;
if (!is_approx(z, current_z)) { // Orca: wipe_tower_no_sparse_layers crash guard. With sparse layers skipped the tower is
// compacted far below the object, so descending to it is only safe once the nozzle is parked
// over the tower - which is what the is_finish_first travel above does. Otherwise the nozzle
// is still over the model and this descent would drive it into the print, so defer it to the
// re-descents below, which run after the travel to the tower.
const bool defer_compacted_descend = m_sparse_layers_skipped
&& !tcr.priming && !tcr.is_finish_first && (current_z - z) > EPSILON;
if (!is_approx(z, current_z) && !defer_compacted_descend) {
gcode += gcodegen.writer().retract(); gcode += gcodegen.writer().retract();
gcode += gcodegen.writer().travel_to_z(z, "Travel down to the last wipe tower layer."); gcode += gcodegen.writer().travel_to_z(z, "Travel down to the last wipe tower layer.");
gcode += gcodegen.writer().unretract(); gcode += gcodegen.writer().unretract();
} }
// Tower compacted below the object, so any extrusion emitted without an explicit z has to be
// pulled back down to it first.
const bool compacted_below_object = m_sparse_layers_skipped && z >= 0. && (tcr.print_z - z) > EPSILON;
// Process the end filament gcode. // Process the end filament gcode.
bool add_change_filament_624 = false; bool add_change_filament_624 = false;
@@ -1085,11 +1095,23 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
std::string nozzle_change_gcode_trans; std::string nozzle_change_gcode_trans;
if (is_nozzle_change) { if (is_nozzle_change) {
// move to start_pos before nozzle change // move to start_pos before nozzle change
// Orca: travel_to() lifts to the object layer height to clear the print. That lift is
// needed when arriving from the model, but is a wasted full-height Z bounce when the
// nozzle already sits on the compacted tower, so travel at the compacted z instead.
const bool compact_intower_nc_travel = compacted_below_object
&& (tcr.print_z - gcodegen.writer().get_position().z()) > EPSILON;
std::string start_pos_str; std::string start_pos_str;
start_pos_str = gcodegen.travel_to(wipe_tower_point_to_object_point(gcodegen, transform_wt_pt(tcr.nozzle_change_result.start_pos) + plate_origin_2d), erMixed, start_pos_str = gcodegen.travel_to(wipe_tower_point_to_object_point(gcodegen, transform_wt_pt(tcr.nozzle_change_result.start_pos) + plate_origin_2d), erMixed,
"Move to nozzle change start pos"); "Move to nozzle change start pos", compact_intower_nc_travel ? z : DBL_MAX);
check_add_eol(start_pos_str); check_add_eol(start_pos_str);
nozzle_change_gcode_trans += start_pos_str; nozzle_change_gcode_trans += start_pos_str;
// The nozzle-change wipe below carries no explicit z, so it would extrude at the object
// layer height and float above the compacted tower. Descend unless the travel stayed down.
if (!compact_intower_nc_travel && compacted_below_object) {
std::string nc_z_descend = gcodegen.writer().travel_to_z(z, "Descend to compacted wipe tower z (no sparse layers)");
check_add_eol(nc_z_descend);
nozzle_change_gcode_trans += nc_z_descend;
}
nozzle_change_gcode_trans += gcodegen.unretract(); nozzle_change_gcode_trans += gcodegen.unretract();
nozzle_change_gcode_trans += transform_gcode(tcr.nozzle_change_result.gcode, tcr.nozzle_change_result.start_pos, wipe_tower_offset, wipe_tower_rotation); nozzle_change_gcode_trans += transform_gcode(tcr.nozzle_change_result.gcode, tcr.nozzle_change_result.start_pos, wipe_tower_offset, wipe_tower_rotation);
gcodegen.set_last_pos(wipe_tower_point_to_object_point(gcodegen, transform_wt_pt(tcr.nozzle_change_result.end_pos) + plate_origin_2d)); gcodegen.set_last_pos(wipe_tower_point_to_object_point(gcodegen, transform_wt_pt(tcr.nozzle_change_result.end_pos) + plate_origin_2d));
@@ -1428,6 +1450,15 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
start_filament_gcode_str = start_filament_gcode_str + wipe_next_start_point_str + toolchange_unretract_str; start_filament_gcode_str = start_filament_gcode_str + wipe_next_start_point_str + toolchange_unretract_str;
// Orca: the custom change_filament_gcode lifts to the object layer height and the unretract
// de-hops back to it, so every tower extrusion emitted after it (purge moves, and the wall
// when it prints after the toolchange) would float above the compacted tower. Descend first.
if (compacted_below_object) {
std::string z_descend = gcodegen.writer().travel_to_z(z, "Descend to compacted wipe tower z (no sparse layers)");
check_add_eol(z_descend);
start_filament_gcode_str += z_descend;
}
// Insert the end filament, toolchange, and start filament gcode into the generated gcode. // Insert the end filament, toolchange, and start filament gcode into the generated gcode.
DynamicConfig config; DynamicConfig config;
config.set_key_value("filament_end_gcode", new ConfigOptionString(end_filament_gcode_str)); config.set_key_value("filament_end_gcode", new ConfigOptionString(end_filament_gcode_str));
@@ -1915,11 +1946,9 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
// resulting in a wipe tower with sparse layers. // resulting in a wipe tower with sparse layers.
double wipe_tower_z = -1; double wipe_tower_z = -1;
bool ignore_sparse = false; bool ignore_sparse = false;
if (gcodegen.config().wipe_tower_no_sparse_layers.value) { if (m_sparse_layers_skipped) {
wipe_tower_z = m_last_wipe_tower_print_z; wipe_tower_z = m_last_wipe_tower_print_z;
ignore_sparse = (m_tool_changes[m_layer_idx].size() == 1 && ignore_sparse = wipe_tower_layer_is_sparse(m_tool_changes[m_layer_idx]) && m_layer_idx != 0;
m_tool_changes[m_layer_idx].front().initial_tool == m_tool_changes[m_layer_idx].front().new_tool &&
m_layer_idx != 0);
if (m_tool_change_idx == 0 && !ignore_sparse) 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; wipe_tower_z = m_last_wipe_tower_print_z + m_tool_changes[m_layer_idx].front().layer_height;
} }
@@ -1935,12 +1964,9 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
// resulting in a wipe tower with sparse layers. // resulting in a wipe tower with sparse layers.
double wipe_tower_z = -1; double wipe_tower_z = -1;
bool ignore_sparse = false; bool ignore_sparse = false;
if (gcodegen.config().wipe_tower_no_sparse_layers.value) { if (m_sparse_layers_skipped) {
wipe_tower_z = m_last_wipe_tower_print_z; ignore_sparse = wipe_tower_layer_is_sparse(m_tool_changes[m_layer_idx]);
ignore_sparse = (m_tool_changes[m_layer_idx].size() == 1 && wipe_tower_z = m_compacted_tower_z[m_layer_idx];
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 ((m_enable_timelapse_print || m_enable_wrapping_detection) && m_is_first_print) { if ((m_enable_timelapse_print || m_enable_wrapping_detection) && m_is_first_print) {
@@ -1953,10 +1979,8 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
if (!(size_t(m_tool_change_idx) < m_tool_changes[m_layer_idx].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."); throw Slic3r::RuntimeError("Wipe tower generation failed, possibly due to empty first layer.");
if (!ignore_sparse) { if (!ignore_sparse)
gcode += append_tcr(gcodegen, m_tool_changes[m_layer_idx][m_tool_change_idx++], extruder_id, wipe_tower_z); 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;
}
} }
} }
@@ -1970,9 +1994,8 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
return true; return true;
bool ignore_sparse = false; bool ignore_sparse = false;
if (gcodegen.config().wipe_tower_no_sparse_layers.value) { if (m_sparse_layers_skipped)
ignore_sparse = (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); ignore_sparse = wipe_tower_layer_is_sparse(m_tool_changes[m_layer_idx]);
}
if ((m_enable_timelapse_print || m_enable_wrapping_detection) && m_is_first_print) { if ((m_enable_timelapse_print || m_enable_wrapping_detection) && m_is_first_print) {
return false; return false;
@@ -6580,6 +6603,8 @@ LayerResult GCode::process_layer(
} }
// Then print infill // Then print infill
gcode += this->extrude_infill(print, by_region_specific, false); gcode += this->extrude_infill(print, by_region_specific, false);
// Then the walls left hanging in mid air, now that the infill can anchor them
gcode += this->extrude_perimeters(print, by_region_specific, first_layer, false, true);
// Then print perimeters of regions that has is_infill_first == true // Then print perimeters of regions that has is_infill_first == true
gcode += this->extrude_perimeters(print, by_region_specific, first_layer, true); gcode += this->extrude_perimeters(print, by_region_specific, first_layer, true);
} }
@@ -6875,6 +6900,7 @@ LayerResult GCode::process_layer(
has_insert_timelapse_gcode = true; has_insert_timelapse_gcode = true;
} }
gcode += this->extrude_infill(print, by_region_specific, false); gcode += this->extrude_infill(print, by_region_specific, false);
gcode += this->extrude_perimeters(print, by_region_specific, first_layer, false, true);
gcode += this->extrude_perimeters(print, by_region_specific, first_layer, true); gcode += this->extrude_perimeters(print, by_region_specific, first_layer, true);
// ironing // ironing
gcode += this->extrude_infill(print, by_region_specific, true); gcode += this->extrude_infill(print, by_region_specific, true);
@@ -7615,7 +7641,7 @@ std::string GCode::extrude_path(const ExtrusionPath& path, const std::string& de
} }
// Extrude perimeters: Decide where to put seams (hide or align seams). // Extrude perimeters: Decide where to put seams (hide or align seams).
std::string GCode::extrude_perimeters(const Print &print, const std::vector<ObjectByExtruder::Island::Region> &by_region, bool is_first_layer, bool is_infill_first) std::string GCode::extrude_perimeters(const Print &print, const std::vector<ObjectByExtruder::Island::Region> &by_region, bool is_first_layer, bool is_infill_first, bool unsupported_loops_only)
{ {
std::string gcode; std::string gcode;
for (const ObjectByExtruder::Island::Region &region : by_region) for (const ObjectByExtruder::Island::Region &region : by_region)
@@ -7634,7 +7660,24 @@ std::string GCode::extrude_perimeters(const Print &print, const std::vector<Obje
m_config.wipe_inward_distance.value > 0. && m_config.wipe_inward_distance.value > 0. &&
scale_(FILAMENT_CONFIG(wipe_distance)) > SCALED_EPSILON) scale_(FILAMENT_CONFIG(wipe_distance)) > SCALED_EPSILON)
wipe_support.emplace(); wipe_support.emplace();
// ORCA: loops flagged as extruded in mid air, out of reach of the layer below, are held back
// for a second pass after the infill that anchors them. Infill already precedes infill first walls.
const bool defer_unsupported = !is_infill_first;
auto waits_for_infill = [](const ExtrusionEntity *ee) {
return ee->is_loop() && static_cast<const ExtrusionLoop *>(ee)->print_after_infill;
};
// The deferred pass runs after the infill, so the loops the first pass emitted are
// already down and belong in the prefix an inward wipe may land on.
if (wipe_support && defer_unsupported && unsupported_loops_only)
for (const ExtrusionEntity* ee : region.perimeters)
if (!waits_for_infill(ee))
wipe_support->append(*ee);
for (const ExtrusionEntity* ee : region.perimeters) { for (const ExtrusionEntity* ee : region.perimeters) {
if (defer_unsupported && waits_for_infill(ee) != unsupported_loops_only)
continue;
gcode += this->extrude_entity(*ee, "perimeter", -1., region.perimeters, gcode += this->extrude_entity(*ee, "perimeter", -1., region.perimeters,
wipe_support ? &*wipe_support : nullptr); wipe_support ? &*wipe_support : nullptr);
if (wipe_support) if (wipe_support)
+12 -2
View File
@@ -106,8 +106,13 @@ public:
m_enable_wrapping_detection(print_config.enable_wrapping_detection && (print_config.wrapping_exclude_area.values.size() > 2) && (slice_used_filaments.size() <= 1)), m_enable_wrapping_detection(print_config.enable_wrapping_detection && (print_config.wrapping_exclude_area.values.size() > 2) && (slice_used_filaments.size() <= 1)),
m_is_first_print(true), m_is_first_print(true),
m_print_config(&print_config), m_print_config(&print_config),
m_last_wipe_tower_print_z(print_config.z_offset.value) m_last_wipe_tower_print_z(print_config.z_offset.value),
m_sparse_layers_skipped(wipe_tower_sparse_layers_skipped(print_config))
{ {
// Precomputed rather than accumulated while emitting, so that the clearance validator and
// the emitter cannot disagree about where the compacted tower sits on any given layer.
if (m_sparse_layers_skipped)
m_compacted_tower_z = compute_compacted_wipe_tower_z(tool_changes, float(print_config.z_offset.value));
// initialize with the extruder offset of master extruder id // initialize with the extruder offset of master extruder id
m_extruder_offsets.resize(print_config.filament_map.size(), print_config.extruder_offset.get_at(print_config.master_extruder_id.value - 1)); m_extruder_offsets.resize(print_config.filament_map.size(), print_config.extruder_offset.get_at(print_config.master_extruder_id.value - 1));
const auto& filament_map = print_config.filament_map.values; // 1 based idx const auto& filament_map = print_config.filament_map.values; // 1 based idx
@@ -167,6 +172,11 @@ private:
float m_wipe_tower_depth; float m_wipe_tower_depth;
BoundingBoxf m_wipe_tower_bbx; BoundingBoxf m_wipe_tower_bbx;
Vec2f m_rib_offset{Vec2f(0, 0)}; Vec2f m_rib_offset{Vec2f(0, 0)};
// wipe_tower_no_sparse_layers, as answered by the shared compaction rule rather than by the raw
// option: smooth timelapse and wrapping detection keep a tower on every layer regardless.
const bool m_sparse_layers_skipped;
// Print z of the compacted tower per planned layer. Empty when the tower is not compacted.
std::vector<float> m_compacted_tower_z;
}; };
class ColorPrintColors class ColorPrintColors
@@ -524,7 +534,7 @@ private:
// For sequential print, the instance of the object to be printing has to be defined. // For sequential print, the instance of the object to be printing has to be defined.
const size_t single_object_instance_idx); const size_t single_object_instance_idx);
std::string extrude_perimeters(const Print& print, const std::vector<ObjectByExtruder::Island::Region>& by_region, bool is_first_layer, bool is_infill_first); std::string extrude_perimeters(const Print& print, const std::vector<ObjectByExtruder::Island::Region>& by_region, bool is_first_layer, bool is_infill_first, bool unsupported_loops_only = false);
std::string extrude_infill(const Print& print, const std::vector<ObjectByExtruder::Island::Region>& by_region, bool ironing); std::string extrude_infill(const Print& print, const std::vector<ObjectByExtruder::Island::Region>& by_region, bool ironing);
std::string extrude_support(const ExtrusionEntityCollection& support_fills, const ExtrusionRole support_extrusion_role); std::string extrude_support(const ExtrusionEntityCollection& support_fills, const ExtrusionRole support_extrusion_role);
+60 -5
View File
@@ -2735,6 +2735,28 @@ void ToolOrdering::enforce_mixed_component_order()
} }
} }
// Declared in ToolOrdering.hpp (exposed for unit testing).
std::vector<unsigned int> parse_cyclic_order(const std::string& str, unsigned int number_of_extruders)
{
std::vector<unsigned int> order;
for (const std::string& token : split_string(str, ',')) {
try {
size_t pos = 0;
int filament = std::stoi(token, &pos); // stoi skips leading whitespace by itself
// stoi stops at the first non-digit, so "2x" would parse as 2. Require the whole token to be
// consumed (bar trailing whitespace) to drop it like any other garbage.
if (token.find_first_not_of(" \t\r\n", pos) != std::string::npos)
continue;
if (filament >= 1 && (unsigned int)filament <= number_of_extruders
&& std::find(order.begin(), order.end(), (unsigned int)(filament - 1)) == order.end())
order.emplace_back((unsigned int)(filament - 1));
} catch (const std::exception&) {
// Not a number, ignore it.
}
}
return order;
}
void ToolOrdering::reorder_extruders_for_minimum_flush_volume(bool reorder_first_layer) void ToolOrdering::reorder_extruders_for_minimum_flush_volume(bool reorder_first_layer)
{ {
const PrintConfig* print_config = m_print_config_ptr; const PrintConfig* print_config = m_print_config_ptr;
@@ -2832,11 +2854,41 @@ void ToolOrdering::reorder_extruders_for_minimum_flush_volume(bool reorder_first
const bool use_cyclic_ordering = const bool use_cyclic_ordering =
(print_config->toolchange_ordering == ToolChangeOrderingType::Cyclic); (print_config->toolchange_ordering == ToolChangeOrderingType::Cyclic);
// By default the first layer keeps its adhesion-optimized order (and any custom first layer
// sequence); the cyclic sequence is only forced onto it when the user opts in.
const bool cyclic_first_layer = use_cyclic_ordering && print_config->toolchange_cyclic_first_layer.value;
// Optional user defined cyclic sequence, given as 1-based filament numbers ("3,2,1,4"). Filaments
// missing from it keep their ascending order after the listed ones, so a partial or bogus entry
// still yields the default cyclic order.
const std::vector<unsigned int> cyclic_order =
use_cyclic_ordering ? parse_cyclic_order(print_config->toolchange_cyclic_order.value, number_of_extruders)
: std::vector<unsigned int>();
// Reorder a layer's filaments (0-based) for cyclic ordering: ascending by default, or following the
// user defined sequence when one was given. Filaments absent from the sequence keep ascending order
// after the listed ones.
auto apply_cyclic_order = [&cyclic_order](std::vector<unsigned int>& filaments) {
std::sort(filaments.begin(), filaments.end());
if (!cyclic_order.empty())
std::stable_sort(filaments.begin(), filaments.end(), [&cyclic_order](unsigned int lhs, unsigned int rhs) {
auto rank = [&cyclic_order](unsigned int filament) {
return size_t(std::find(cyclic_order.begin(), cyclic_order.end(), filament) - cyclic_order.begin());
};
return rank(lhs) < rank(rhs);
});
};
// other_layers_seq: the layer_idx and extruder_idx are base on 1 // other_layers_seq: the layer_idx and extruder_idx are base on 1
auto get_custom_seq = [&other_layers_seqs, &reorder_first_layer, &first_layer_filaments, &layer_filaments, use_cyclic_ordering](int layer_idx, std::vector<int>& out_seq) -> bool { auto get_custom_seq = [&other_layers_seqs, &reorder_first_layer, &first_layer_filaments, &layer_filaments, use_cyclic_ordering, cyclic_first_layer, &apply_cyclic_order](int layer_idx, std::vector<int>& out_seq) -> bool {
if (!reorder_first_layer && layer_idx == 0) { if (!reorder_first_layer && layer_idx == 0) {
out_seq.resize(first_layer_filaments.size()); // The first layer tool order is already decided (adhesion-optimized, plus any custom first
std::transform(first_layer_filaments.begin(), first_layer_filaments.end(), out_seq.begin(), [](auto item) {return item + 1; }); // layer sequence). Only override it with the cyclic sequence when the user opted in.
std::vector<unsigned int> ordered = first_layer_filaments;
if (cyclic_first_layer)
apply_cyclic_order(ordered);
out_seq.resize(ordered.size());
std::transform(ordered.begin(), ordered.end(), out_seq.begin(), [](auto item) {return int(item) + 1; });
return true; return true;
} }
for (size_t idx = other_layers_seqs.size() - 1; idx != size_t(-1); --idx) { for (size_t idx = other_layers_seqs.size() - 1; idx != size_t(-1); --idx) {
@@ -2847,9 +2899,12 @@ void ToolOrdering::reorder_extruders_for_minimum_flush_volume(bool reorder_first
} }
} }
if (use_cyclic_ordering && layer_idx >= 0 && size_t(layer_idx) < layer_filaments.size()) { // Skip the first layer here (layer_idx == 0 only reaches this point on the reorder_first_layer
// path) unless the user asked for cyclic order on it, so it keeps the default flush ordering.
if (use_cyclic_ordering && layer_idx >= 0 && (layer_idx != 0 || cyclic_first_layer)
&& size_t(layer_idx) < layer_filaments.size()) {
std::vector<unsigned int> ordered = layer_filaments[size_t(layer_idx)]; std::vector<unsigned int> ordered = layer_filaments[size_t(layer_idx)];
std::sort(ordered.begin(), ordered.end()); apply_cyclic_order(ordered);
out_seq.resize(ordered.size()); out_seq.resize(ordered.size());
std::transform(ordered.begin(), ordered.end(), out_seq.begin(), [](auto item) { return int(item) + 1; }); std::transform(ordered.begin(), ordered.end(), out_seq.begin(), [](auto item) { return int(item) + 1; });
return true; return true;
+5
View File
@@ -417,6 +417,11 @@ private:
int most_used_extruder; int most_used_extruder;
}; };
// Parse the user defined cyclic toolchange sequence ("3,2 , 1 , 4") into 0-based filament indices.
// Out-of-range entries, duplicates and non-numeric tokens are dropped, so a partially valid string
// still orders the filaments it does name. Exposed for unit testing.
std::vector<unsigned int> parse_cyclic_order(const std::string& str, unsigned int number_of_extruders);
} // namespace SLic3r } // namespace SLic3r
#endif /* slic3r_ToolOrdering_hpp_ */ #endif /* slic3r_ToolOrdering_hpp_ */
+31 -7
View File
@@ -25,6 +25,30 @@ static constexpr int arc_fit_size = 20;
enum class LimitFlow { None, LimitPrintFlow, LimitRammingFlow, LimitRammingFlowNC};//nc:nozzle change enum class LimitFlow { None, LimitPrintFlow, LimitRammingFlow, LimitRammingFlowNC};//nc:nozzle change
static const std::map<float, float> nozzle_diameter_to_nozzle_change_width{{0.2f, 0.5f}, {0.4f, 1.0f}, {0.6f, 1.2f}, {0.8f, 1.4f}}; static const std::map<float, float> nozzle_diameter_to_nozzle_change_width{{0.2f, 0.5f}, {0.4f, 1.0f}, {0.6f, 1.2f}, {0.8f, 1.4f}};
bool wipe_tower_sparse_layers_skipped(const PrintConfig &config)
{
return config.wipe_tower_no_sparse_layers.value && config.timelapse_type.value != TimelapseType::tlSmooth &&
! config.enable_wrapping_detection.value;
}
bool wipe_tower_layer_is_sparse(const std::vector<WipeTower::ToolChangeResult> &layer_tool_changes)
{
return layer_tool_changes.size() == 1 && layer_tool_changes.front().initial_tool == layer_tool_changes.front().new_tool;
}
std::vector<float> compute_compacted_wipe_tower_z(const std::vector<std::vector<WipeTower::ToolChangeResult>> &tool_changes,
float base_z)
{
std::vector<float> tower_z(tool_changes.size(), base_z);
float last = base_z;
for (size_t i = 0; i < tool_changes.size(); ++i) {
if (! tool_changes[i].empty() && ! wipe_tower_layer_is_sparse(tool_changes[i]))
last += tool_changes[i].front().layer_height;
tower_z[i] = last;
}
return tower_z;
}
inline float align_round(float value, float base) inline float align_round(float value, float base)
{ {
return std::round(value / base) * base; return std::round(value / base) * base;
@@ -1879,7 +1903,7 @@ WipeTower::WipeTower(const PrintConfig& config, int plate_idx, Vec3d plate_origi
m_z_pos(0.f), m_z_pos(0.f),
//m_bridging(float(config.wipe_tower_bridging)), //m_bridging(float(config.wipe_tower_bridging)),
m_bridging(10.f), m_bridging(10.f),
m_no_sparse_layers(config.wipe_tower_no_sparse_layers), m_sparse_layers_skipped(wipe_tower_sparse_layers_skipped(config)),
m_gcode_flavor(config.gcode_flavor), m_gcode_flavor(config.gcode_flavor),
m_travel_speed(config.travel_speed.get_at(get_extruder_index(config, (unsigned int)initial_tool))), m_travel_speed(config.travel_speed.get_at(get_extruder_index(config, (unsigned int)initial_tool))),
m_current_tool(initial_tool), m_current_tool(initial_tool),
@@ -2977,7 +3001,7 @@ WipeTower::ToolChangeResult WipeTower::finish_layer(bool extrude_perimeter, bool
// Ask our writer about how much material was consumed. // Ask our writer about how much material was consumed.
// Skip this in case the layer is sparse and config option to not print sparse layers is enabled. // Skip this in case the layer is sparse and config option to not print sparse layers is enabled.
if (! m_no_sparse_layers || toolchanges_on_layer) if (! m_sparse_layers_skipped || toolchanges_on_layer)
if (m_current_tool < m_used_filament_length.size()) if (m_current_tool < m_used_filament_length.size())
m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length(); m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length();
@@ -3021,7 +3045,7 @@ void WipeTower::plan_toolchange(float z_par, float layer_height_par, unsigned in
if (m_plan.empty() || m_plan.back().z + WT_EPSILON < z_par) // if we moved to a new layer, we'll add it to m_plan first if (m_plan.empty() || m_plan.back().z + WT_EPSILON < z_par) // if we moved to a new layer, we'll add it to m_plan first
m_plan.push_back(WipeTowerInfo(z_par, layer_height_par)); m_plan.push_back(WipeTowerInfo(z_par, layer_height_par));
if (m_first_layer_idx == size_t(-1) && (! m_no_sparse_layers || old_tool != new_tool)) if (m_first_layer_idx == size_t(-1) && (! m_sparse_layers_skipped || old_tool != new_tool))
m_first_layer_idx = m_plan.size() - 1; m_first_layer_idx = m_plan.size() - 1;
if (old_tool == new_tool) // new layer without toolchanges - we are done if (old_tool == new_tool) // new layer without toolchanges - we are done
@@ -3874,7 +3898,7 @@ WipeTower::ToolChangeResult WipeTower::finish_layer_new(bool extrude_perimeter,
// Ask our writer about how much material was consumed. // Ask our writer about how much material was consumed.
// Skip this in case the layer is sparse and config option to not print sparse layers is enabled. // Skip this in case the layer is sparse and config option to not print sparse layers is enabled.
if (!m_no_sparse_layers || toolchanges_on_layer) if (!m_sparse_layers_skipped || toolchanges_on_layer)
if (m_current_tool < m_used_filament_length.size()) if (m_current_tool < m_used_filament_length.size())
m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length(); m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length();
@@ -3984,7 +4008,7 @@ WipeTower::ToolChangeResult WipeTower::finish_block(const WipeTowerBlock &block,
// Ask our writer about how much material was consumed. // Ask our writer about how much material was consumed.
// Skip this in case the layer is sparse and config option to not print sparse layers is enabled. // Skip this in case the layer is sparse and config option to not print sparse layers is enabled.
if (!m_no_sparse_layers || toolchanges_on_layer) if (!m_sparse_layers_skipped || toolchanges_on_layer)
if (filament_id < m_used_filament_length.size()) if (filament_id < m_used_filament_length.size())
m_used_filament_length[filament_id] += writer.get_and_reset_used_filament_length(); m_used_filament_length[filament_id] += writer.get_and_reset_used_filament_length();
@@ -4101,7 +4125,7 @@ WipeTower::ToolChangeResult WipeTower::finish_block_solid(const WipeTowerBlock &
// Ask our writer about how much material was consumed. // Ask our writer about how much material was consumed.
// Skip this in case the layer is sparse and config option to not print sparse layers is enabled. // Skip this in case the layer is sparse and config option to not print sparse layers is enabled.
if (!m_no_sparse_layers || toolchanges_on_layer) if (!m_sparse_layers_skipped || toolchanges_on_layer)
if (filament_id < m_used_filament_length.size()) if (filament_id < m_used_filament_length.size())
m_used_filament_length[filament_id] += writer.get_and_reset_used_filament_length(); m_used_filament_length[filament_id] += writer.get_and_reset_used_filament_length();
@@ -5155,7 +5179,7 @@ WipeTower::ToolChangeResult WipeTower::only_generate_out_wall(bool is_new_mode)
// Ask our writer about how much material was consumed. // Ask our writer about how much material was consumed.
// Skip this in case the layer is sparse and config option to not print sparse layers is enabled. // Skip this in case the layer is sparse and config option to not print sparse layers is enabled.
if (!m_no_sparse_layers || toolchanges_on_layer) if (!m_sparse_layers_skipped || toolchanges_on_layer)
if (m_current_tool < m_used_filament_length.size()) m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length(); if (m_current_tool < m_used_filament_length.size()) m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length();
return construct_tcr(writer, false, old_tool, true, false, 0.f, false); return construct_tcr(writer, false, old_tool, true, false, 0.f, false);
+19 -1
View File
@@ -521,7 +521,7 @@ private:
//float m_parking_pos_retraction = 0.f; //float m_parking_pos_retraction = 0.f;
//float m_extra_loading_move = 0.f; //float m_extra_loading_move = 0.f;
float m_bridging = 0.f; float m_bridging = 0.f;
bool m_no_sparse_layers = false; bool m_sparse_layers_skipped = false;
// BBS: remove useless config // BBS: remove useless config
//bool m_set_extruder_trimpot = false; //bool m_set_extruder_trimpot = false;
bool m_adhesion = true; bool m_adhesion = true;
@@ -680,6 +680,24 @@ private:
}; };
// Compaction rule for wipe_tower_no_sparse_layers. Shared by the G-code emitter and by the
// clearance validator so that both agree on where the compacted tower actually sits; a drift
// between the two would either let a real nozzle collision through or reject a safe plate.
// Whether sparse layers are really skipped, i.e. whether the tower is compacted at all. Smooth
// timelapse and wrapping detection put a tower on every layer, so no layer is ever dropped and the
// tower keeps following the object even though the option is on. Tower planning, G-code emission and
// the clearance validator all ask this single question, so none of them can compact on its own.
bool wipe_tower_sparse_layers_skipped(const PrintConfig &config);
// A planned layer prints no tower at all when its only toolchange keeps the same filament.
bool wipe_tower_layer_is_sparse(const std::vector<WipeTower::ToolChangeResult> &layer_tool_changes);
// Print z the compacted tower reaches on every planned layer. Sparse layers carry over the
// previous value, so the tower falls one layer height behind the object for each of them. base_z is
// the z the tower starts from, which Orca offsets by z_offset.
std::vector<float> compute_compacted_wipe_tower_z(const std::vector<std::vector<WipeTower::ToolChangeResult>> &tool_changes,
float base_z = 0.f);
} // namespace Slic3r } // namespace Slic3r
+7 -7
View File
@@ -1032,7 +1032,7 @@ WipeTower2::WipeTower2(const PrintConfig& config, const PrintRegionConfig& defau
m_y_shift(0.f), m_y_shift(0.f),
m_z_pos(0.f), m_z_pos(0.f),
m_bridging(float(config.wipe_tower_bridging)), m_bridging(float(config.wipe_tower_bridging)),
m_no_sparse_layers(config.wipe_tower_no_sparse_layers), m_sparse_layers_skipped(wipe_tower_sparse_layers_skipped(config)),
m_gcode_flavor(config.gcode_flavor), m_gcode_flavor(config.gcode_flavor),
m_travel_speed(config.travel_speed.get_at(get_extruder_index(config, (unsigned int)initial_tool))), m_travel_speed(config.travel_speed.get_at(get_extruder_index(config, (unsigned int)initial_tool))),
m_infill_speed(default_region_config.sparse_infill_speed.get_at(get_extruder_index(config, (unsigned int)initial_tool))), m_infill_speed(default_region_config.sparse_infill_speed.get_at(get_extruder_index(config, (unsigned int)initial_tool))),
@@ -1730,7 +1730,7 @@ void WipeTower2::toolchange_Change(
} else if (m_wall_type == (int)wtwCone) { } else if (m_wall_type == (int)wtwCone) {
const double support_scale = get_wipe_tower_cone_base(m_wipe_tower_width, m_wipe_tower_height, m_wipe_tower_depth, const double support_scale = get_wipe_tower_cone_base(m_wipe_tower_width, m_wipe_tower_height, m_wipe_tower_depth,
m_wipe_tower_cone_angle).second; m_wipe_tower_cone_angle).second;
const double z = m_no_sparse_layers ? (m_current_height + m_layer_info->height) : m_layer_info->z; const double z = m_sparse_layers_skipped ? (m_current_height + m_layer_info->height) : m_layer_info->z;
const double r = std::tan(Geometry::deg2rad(m_wipe_tower_cone_angle / 2.f)) * (m_wipe_tower_height - z); const double r = std::tan(Geometry::deg2rad(m_wipe_tower_cone_angle / 2.f)) * (m_wipe_tower_height - z);
const double w = m_layer_info->depth + m_perimeter_width; const double w = m_layer_info->depth + m_perimeter_width;
if (r > 0.5 * w + 0.01) { // same guard as generate_support_cone_wall if (r > 0.5 * w + 0.01) { // same guard as generate_support_cone_wall
@@ -1872,7 +1872,7 @@ void WipeTower2::toolchange_Wipe(
// All the calculations in all other places take the spacing into account for all the layers. // All the calculations in all other places take the spacing into account for all the layers.
// If spare layers are excluded->if 1 or less toolchange has been done, it must be sill the first layer, too.So slow down. // If spare layers are excluded->if 1 or less toolchange has been done, it must be sill the first layer, too.So slow down.
const float target_speed = is_first_layer() || (m_num_tool_changes <= 1 && m_no_sparse_layers) ? m_first_layer_speed * 60.f : std::min(m_wipe_tower_max_purge_speed * 60.f, m_infill_speed * 60.f); const float target_speed = is_first_layer() || (m_num_tool_changes <= 1 && m_sparse_layers_skipped) ? m_first_layer_speed * 60.f : std::min(m_wipe_tower_max_purge_speed * 60.f, m_infill_speed * 60.f);
float wipe_speed = 0.33f * target_speed; float wipe_speed = 0.33f * target_speed;
// if there is less than 2.5*line_width to the edge, advance straightaway (there is likely a blob anyway) // if there is less than 2.5*line_width to the edge, advance straightaway (there is likely a blob anyway)
@@ -1970,7 +1970,7 @@ WipeTower::ToolChangeResult WipeTower2::finish_layer()
// Slow down on the 1st layer. // Slow down on the 1st layer.
// If spare layers are excluded -> if 1 or less toolchange has been done, it must be still the first layer, too. So slow down. // If spare layers are excluded -> if 1 or less toolchange has been done, it must be still the first layer, too. So slow down.
bool first_layer = is_first_layer() || (m_num_tool_changes <= 1 && m_no_sparse_layers); bool first_layer = is_first_layer() || (m_num_tool_changes <= 1 && m_sparse_layers_skipped);
float feedrate = first_layer ? m_first_layer_speed * 60.f : std::min(m_wipe_tower_max_purge_speed * 60.f, m_infill_speed * 60.f); float feedrate = first_layer ? m_first_layer_speed * 60.f : std::min(m_wipe_tower_max_purge_speed * 60.f, m_infill_speed * 60.f);
if (m_enable_tower_interface_features && m_prev_layer_had_interface) if (m_enable_tower_interface_features && m_prev_layer_had_interface)
feedrate = std::min(feedrate, 20.f * 60.f); feedrate = std::min(feedrate, 20.f * 60.f);
@@ -2103,7 +2103,7 @@ WipeTower::ToolChangeResult WipeTower2::finish_layer()
// Ask our writer about how much material was consumed. // Ask our writer about how much material was consumed.
// Skip this in case the layer is sparse and config option to not print sparse layers is enabled. // Skip this in case the layer is sparse and config option to not print sparse layers is enabled.
if (! m_no_sparse_layers || toolchanges_on_layer || first_layer) { if (! m_sparse_layers_skipped || toolchanges_on_layer || first_layer) {
if (m_current_tool < m_used_filament_length.size()) if (m_current_tool < m_used_filament_length.size())
m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length(); m_used_filament_length[m_current_tool] += writer.get_and_reset_used_filament_length();
m_current_height += m_layer_info->height; m_current_height += m_layer_info->height;
@@ -2226,7 +2226,7 @@ void WipeTower2::plan_toolchange(float z_par, float layer_height_par, unsigned i
if (m_plan.empty() || m_plan.back().z + WT_EPSILON < z_par) // if we moved to a new layer, we'll add it to m_plan first if (m_plan.empty() || m_plan.back().z + WT_EPSILON < z_par) // if we moved to a new layer, we'll add it to m_plan first
m_plan.push_back(WipeTowerInfo(z_par, layer_height_par)); m_plan.push_back(WipeTowerInfo(z_par, layer_height_par));
if (m_first_layer_idx == size_t(-1) && (! m_no_sparse_layers || old_tool != new_tool || m_plan.size() == 1)) if (m_first_layer_idx == size_t(-1) && (! m_sparse_layers_skipped || old_tool != new_tool || m_plan.size() == 1))
m_first_layer_idx = m_plan.size() - 1; m_first_layer_idx = m_plan.size() - 1;
if (old_tool == new_tool) // new layer without toolchanges - we are done if (old_tool == new_tool) // new layer without toolchanges - we are done
@@ -2652,7 +2652,7 @@ Polygon WipeTower2::generate_support_cone_wall(
const auto [R, support_scale] = get_wipe_tower_cone_base(m_wipe_tower_width, m_wipe_tower_height, m_wipe_tower_depth, const auto [R, support_scale] = get_wipe_tower_cone_base(m_wipe_tower_width, m_wipe_tower_height, m_wipe_tower_depth,
m_wipe_tower_cone_angle); m_wipe_tower_cone_angle);
double z = m_no_sparse_layers ? double z = m_sparse_layers_skipped ?
(m_current_height + m_layer_info->height) : (m_current_height + m_layer_info->height) :
m_layer_info->z; // the former should actually work in both cases, but let's stay on the safe side (the 2.6.0 is close) m_layer_info->z; // the former should actually work in both cases, but let's stay on the safe side (the 2.6.0 is close)
+1 -1
View File
@@ -267,7 +267,7 @@ private:
float m_parking_pos_retraction = 0.f; float m_parking_pos_retraction = 0.f;
float m_extra_loading_move = 0.f; float m_extra_loading_move = 0.f;
float m_bridging = 0.f; float m_bridging = 0.f;
bool m_no_sparse_layers = false; bool m_sparse_layers_skipped = false;
bool m_set_extruder_trimpot = false; bool m_set_extruder_trimpot = false;
bool m_adhesion = true; bool m_adhesion = true;
GCodeFlavor m_gcode_flavor; GCodeFlavor m_gcode_flavor;
+1
View File
@@ -153,6 +153,7 @@ bool Layer::is_perimeter_compatible(const Print& print, const PrintRegion& a, co
&& config.gap_infill_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.gap_infill_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) && config.gap_infill_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.gap_infill_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id))
&& config.filter_out_gap_fill.value == other_config.filter_out_gap_fill.value && config.filter_out_gap_fill.value == other_config.filter_out_gap_fill.value
&& config.detect_overhang_wall == other_config.detect_overhang_wall && config.detect_overhang_wall == other_config.detect_overhang_wall
&& config.unsupported_wall_last == other_config.unsupported_wall_last
&& config.overhang_reverse == other_config.overhang_reverse && config.overhang_reverse == other_config.overhang_reverse
&& config.overhang_reverse_threshold == other_config.overhang_reverse_threshold && config.overhang_reverse_threshold == other_config.overhang_reverse_threshold
&& config.wall_direction == other_config.wall_direction && config.wall_direction == other_config.wall_direction
+71
View File
@@ -550,6 +550,7 @@ static ExtrusionEntityCollection traverse_extrusions(const PerimeterGenerator& p
if (!paths.empty()) { if (!paths.empty()) {
if (extrusion->is_closed) { if (extrusion->is_closed) {
ExtrusionLoop extrusion_loop(std::move(paths), pg_extrusion.is_contour ? elrDefault : elrHole); ExtrusionLoop extrusion_loop(std::move(paths), pg_extrusion.is_contour ? elrDefault : elrHole);
extrusion_loop.inset_idx = extrusion->inset_idx;
if ((perimeter_generator.config->wall_direction == WallDirection::CounterClockwise) == if ((perimeter_generator.config->wall_direction == WallDirection::CounterClockwise) ==
(pg_extrusion.is_contour || pg_extrusions.size() == 2)) (pg_extrusion.is_contour || pg_extrusions.size() == 2))
extrusion_loop.make_counter_clockwise(); extrusion_loop.make_counter_clockwise();
@@ -1318,6 +1319,73 @@ static void reorient_perimeters(ExtrusionEntityCollection &entities, bool steep_
} }
} }
// A loop made of nothing but overhang paths lies entirely off the lower layer.
static bool is_unsupported_loop(const ExtrusionEntity *entity)
{
if (!entity->is_loop())
return false;
const ExtrusionPaths &paths = static_cast<const ExtrusionLoop *>(entity)->paths;
return !paths.empty() && std::all_of(paths.begin(), paths.end(),
[](const ExtrusionPath &path) { return path.role() == erOverhangPerimeter; });
}
// ORCA: A wall loop with nothing under it has nothing to lean on, so whatever the configured wall
// sequence it is extruded after the loops that anchor it, innermost first. A loop that runs alongside
// an anchored one belongs to the same wall stack and keeps its place ahead of the infill, which needs
// it as an anchor; one that touches nothing has only that infill to rest on, so it is flagged for the
// G-code writer to hold it back until the infill is down.
static void defer_unsupported_loops(const PerimeterGenerator &perimeter_generator, ExtrusionEntityCollection &entities)
{
if (!perimeter_generator.config->unsupported_wall_last)
return;
ExtrusionEntitiesPtr &src = entities.entities;
auto first_deferred = std::stable_partition(src.begin(), src.end(),
[](const ExtrusionEntity *entity) { return !is_unsupported_loop(entity); });
if (first_deferred == src.end())
return;
std::stable_sort(first_deferred, src.end(),
[](const ExtrusionEntity *lhs, const ExtrusionEntity *rhs) { return lhs->inset_idx > rhs->inset_idx; });
auto collect_lines = [](const ExtrusionEntity *entity, Lines &out) {
Polylines polylines;
entity->collect_polylines(polylines);
append(out, to_lines(polylines));
};
Lines anchored;
for (auto it = src.begin(); it != first_deferred; ++it)
collect_lines(*it, anchored);
std::vector<ExtrusionLoop *> unattached;
for (auto it = first_deferred; it != src.end(); ++it)
unattached.emplace_back(static_cast<ExtrusionLoop *>(*it));
// A loop leaning on a loop that is itself anchored is anchored as well, so spread outwards from
// the anchored loops until no unsupported loop is left touching what was reached.
const double touch_distance = 1.5 * std::max(perimeter_generator.ext_perimeter_flow.scaled_spacing(),
perimeter_generator.perimeter_flow.scaled_spacing());
while (!anchored.empty()) {
AABBTreeLines::LinesDistancer<Line> distancer{std::move(anchored)};
anchored.clear();
for (ExtrusionLoop *&loop : unattached) {
if (loop == nullptr)
continue;
const Points points = loop->as_polyline().points;
if (std::any_of(points.begin(), points.end(),
[&distancer, touch_distance](const Point &point) { return distancer.distance_from_lines<false>(point) < touch_distance; })) {
collect_lines(loop, anchored);
loop = nullptr;
}
}
}
for (ExtrusionLoop *loop : unattached)
if (loop != nullptr)
loop->print_after_infill = true;
}
void PerimeterGenerator::process_classic() void PerimeterGenerator::process_classic()
{ {
group_region_by_fuzzify(*this); group_region_by_fuzzify(*this);
@@ -1804,6 +1872,8 @@ void PerimeterGenerator::process_classic()
} }
} }
defer_unsupported_loops(*this, entities);
// append perimeters for this slice as a collection // append perimeters for this slice as a collection
if (! entities.empty()) if (! entities.empty())
this->loops->append(entities); this->loops->append(entities);
@@ -2742,6 +2812,7 @@ void PerimeterGenerator::process_arachne()
reorient_perimeters(extrusion_coll, steep_overhang_contour, steep_overhang_hole, reorient_perimeters(extrusion_coll, steep_overhang_contour, steep_overhang_hole,
this->config->overhang_reverse_internal_only); this->config->overhang_reverse_internal_only);
} }
defer_unsupported_loops(*this, extrusion_coll);
this->loops->append(extrusion_coll); this->loops->append(extrusion_coll);
} }
+4 -1
View File
@@ -1058,6 +1058,7 @@ static std::vector<std::string> s_Preset_print_options{
"reduce_crossing_wall", "reduce_crossing_wall",
"detect_thin_wall", "detect_thin_wall",
"detect_overhang_wall", "detect_overhang_wall",
"unsupported_wall_last",
"overhang_reverse", "overhang_reverse",
"overhang_reverse_threshold", "overhang_reverse_threshold",
"overhang_reverse_internal_only", "overhang_reverse_internal_only",
@@ -1320,6 +1321,8 @@ static std::vector<std::string> s_Preset_print_options{
"wipe_tower_extra_flow", "wipe_tower_extra_flow",
"single_extruder_multi_material_priming", "single_extruder_multi_material_priming",
"toolchange_ordering", "toolchange_ordering",
"toolchange_cyclic_order",
"toolchange_cyclic_first_layer",
"wipe_tower_rotation_angle", "wipe_tower_rotation_angle",
"tree_support_branch_distance_organic", "tree_support_branch_distance_organic",
"tree_support_branch_diameter_organic", "tree_support_branch_diameter_organic",
@@ -1445,7 +1448,7 @@ static std::vector<std::string> s_Preset_printer_options {
"gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs",
"single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode", "single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode",
"printer_model", "printer_variant", "printer_extruder_id", "printer_extruder_variant", "extruder_variant_list", "default_nozzle_volume_type", "printer_model", "printer_variant", "printer_extruder_id", "printer_extruder_variant", "extruder_variant_list", "default_nozzle_volume_type",
"printable_height", "extruder_printable_height", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", "printable_height", "extruder_printable_height", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", "extruder_clearance_dist_to_rod",
"nozzle_height", "master_extruder_id", "nozzle_height", "master_extruder_id",
"default_print_profile", "inherits", "default_print_profile", "inherits",
"silent_mode", "silent_mode",
+1
View File
@@ -3824,6 +3824,7 @@ unsigned int PresetBundle::sync_ams_list(std::vector<std::pair<DynamicPrintConfi
ConfigOptionStrings *filament_color_type = project_config.option<ConfigOptionStrings>("filament_colour_type"); ConfigOptionStrings *filament_color_type = project_config.option<ConfigOptionStrings>("filament_colour_type");
ConfigOptionInts * filament_map = project_config.option<ConfigOptionInts>("filament_map"); ConfigOptionInts * filament_map = project_config.option<ConfigOptionInts>("filament_map");
ConfigOptionInts * filament_volume_map = project_config.option<ConfigOptionInts>("filament_volume_map"); ConfigOptionInts * filament_volume_map = project_config.option<ConfigOptionInts>("filament_volume_map");
// Snapshot and temporarily strip mixed filament slots so AMS sync operates on physical // Snapshot and temporarily strip mixed filament slots so AMS sync operates on physical
// filaments only. A mixed slot is virtual and has no tray to sync against; leaving it in // filaments only. A mixed slot is virtual and has no tray to sync against; leaving it in
// would let AMS mapping overwrite it and would break the physical-first slot ordering the // would let AMS mapping overwrite it and would break the physical-first slot ordering the
+389
View File
@@ -360,6 +360,8 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n
|| opt_key == "other_layers_print_sequence" || opt_key == "other_layers_print_sequence"
|| opt_key == "other_layers_print_sequence_nums" || opt_key == "other_layers_print_sequence_nums"
|| opt_key == "toolchange_ordering" || opt_key == "toolchange_ordering"
|| opt_key == "toolchange_cyclic_order"
|| opt_key == "toolchange_cyclic_first_layer"
|| opt_key == "extruder_ams_count" || opt_key == "extruder_ams_count"
|| opt_key == "extruder_nozzle_stats" || opt_key == "extruder_nozzle_stats"
|| opt_key == "filament_map_mode" || opt_key == "filament_map_mode"
@@ -964,6 +966,377 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print
return single_object_exception; return single_object_exception;
} }
// ---------------------------------------------------------------------------------------------
// Clearance rule for a prime tower compacted by wipe_tower_no_sparse_layers.
// Ported from BambuStudio and adapted to Orca's printer config: Orca has no
// prime_tower_lift_height (z_hop alone bounds the spiral), spells the toolhead radius
// extruder_clearance_radius, and derives the spiral slope from the per-filament travel_slope instead
// of one global constant.
// ---------------------------------------------------------------------------------------------
double compacted_tower_footprint_padding(const PrintConfig &config, double brim_width)
{
// The brim is deposited material like any other and reaches past the wall on the first layer, so
// the sweeping rod has to clear it too.
//
// On top of it, two effects make a nominal outline fall short of the printed tower on its low
// corner even though it overshoots by millimetres on the high one: WipeTower re-centres the tower
// by rib_offset once its first-layer wall is known, and the precise check hulls extrusion centre
// lines, so the deposited material reaches half a line width further still. Allowing a line width
// per side covers both, which is what keeps an estimated footprint enclosing the real one and the
// pre-slice check stricter than the precise one.
return std::max(0., brim_width) + 2. * config.nozzle_diameter.get_at(0);
}
Polygons compacted_wipe_tower_rings(const CompactedTowerZone &zone, bool any_body_tier)
{
Polygons rings = zone.grown_nozzle;
if (any_body_tier)
append(rings, zone.grown_body);
return rings;
}
CompactedTowerZone compacted_wipe_tower_zone(const PrintConfig &config, const Polygon &tower_footprint)
{
CompactedTowerZone zone;
if (tower_footprint.points.empty())
return zone;
// Spiral Z-hop at wipe-tower entry (the G3 Z I J that GCodeWriter emits for a SpiralLift) starts on
// the tower outline at a low Z. The spiral centre sits one radius away from the start point, so the
// circle reaches 2 * radius beyond the outline. radius = lift / (2*pi*atan(travel_slope)) is the
// same formula GCodeWriter uses; both are per filament, so take the widest any filament can make.
double spiral_reach = 0.;
for (size_t i = 0; i < config.z_hop.size(); ++i) {
const double lift = std::min(double(config.z_hop.get_at(i)), 5.);
if (lift < EPSILON)
continue;
const double slope = i < config.travel_slope.size() ? double(config.travel_slope.get_at(i)) : 0.;
if (slope < EPSILON)
continue;
spiral_reach = std::max(spiral_reach, 2. * lift / (2. * PI * std::atan(slope)));
}
// Working footprint = outline grown by the spiral envelope. All later clearance tests use this, so
// a travel that leaves the deposited wall at low Z is still treated as part of the tower.
zone.hull = tower_footprint;
if (spiral_reach > EPSILON) {
const Polygons grown = offset(tower_footprint, float(scale_(spiral_reach)), jtRound, scale_(0.1));
if (! grown.empty())
zone.hull = Geometry::convex_hull(grown);
}
// The rod sweeps the whole X axis, so its keep-out band is the tower's Y span widened by half
// the nozzle-to-rod offset per side (the instance carries the other half). Orca's sequential
// check has no such margin, having had no option to read it from until now.
zone.bbox_rod = zone.hull.bounding_box();
zone.bbox_rod.offset(scale_(config.extruder_clearance_dist_to_rod.value * 0.5));
// Horizontal clearance, mirroring the sequential print check down to how the distance is split:
// there each of the two object hulls grows by half of extruder_clearance_radius, so the two
// outlines touch exactly when the objects are the full radius apart. Splitting it the same way
// here (half on the tower, half on the instance in compacted_wipe_tower_clearance) states the
// same criterion, and it is what lets the plater draw both outlines: they meet at the instant the
// check trips, instead of one of them being already buried inside the other. The smaller
// MAX_OUTER_NOZZLE_DIAMETER tier is the bare nozzle cone, the only part narrow enough to sit
// beside an object rising less than nozzle_height. The 0.2 mm shaved off is the same rounding
// slack the sequential check applies, 0.1 mm per side. Both rings are built here; which one a
// given object is measured against depends on its own height and is decided in
// compacted_wipe_tower_clearance().
zone.body_radius = config.extruder_clearance_radius.value;
zone.grown_body = offset(zone.hull, float(scale_(compacted_tower_half_clearance(zone.body_radius))), jtRound, scale_(0.1));
zone.grown_nozzle = offset(zone.hull, float(scale_(compacted_tower_half_clearance(MAX_OUTER_NOZZLE_DIAMETER))), jtRound, scale_(0.1));
return zone;
}
CompactedTowerClearance compacted_wipe_tower_clearance(const PrintConfig &config, const CompactedTowerZone &zone,
const Polygon &inst_hull, double object_rise)
{
BoundingBox inst_bbox = inst_hull.bounding_box();
inst_bbox.offset(scale_(config.extruder_clearance_dist_to_rod.value * 0.5));
// Only the Y span matters for the rod: it spans the whole X axis, so an object sharing the tower's
// Y band passes under it however far apart the two are in X.
const bool overlaps_in_y = std::min(inst_bbox.max.y(), zone.bbox_rod.max.y()) - std::max(inst_bbox.min.y(), zone.bbox_rod.min.y()) > 0;
CompactedTowerClearance result;
result.far_clearance = overlaps_in_y ? config.extruder_clearance_height_to_rod.value : config.extruder_clearance_height_to_lid.value;
// The rod and the lid are the only obstacles once the object stands far enough away. Closer than
// the toolhead radius it is the head body itself that hits the object, and it does so as soon as
// the object rises past the nozzle cone, which is far below the rod.
// The instance carries the other half of each clearance, the tower rings already hold the first
// half; see compacted_wipe_tower_zone(). Both halves are needed for the verdict to mean
// "a full radius apart", and drawing what is tested is what keeps the plater honest.
//
// Which tier applies is a property of this object alone: the head body sits above the nozzle cone,
// so it cannot reach an object that stays below nozzle_height however close it stands, and however
// tall the rest of the plate is.
const bool object_is_short = object_rise <= double(config.nozzle_height.value) + EPSILON;
result.body_clearance = object_is_short ? double(MAX_OUTER_NOZZLE_DIAMETER) : zone.body_radius;
const Polygons inst_near_nozzle = offset(inst_hull, float(scale_(compacted_tower_half_clearance(MAX_OUTER_NOZZLE_DIAMETER))), jtRound, scale_(0.1));
const bool near_nozzle = ! intersection(zone.grown_nozzle, inst_near_nozzle).empty();
result.near_body = false;
if (! object_is_short) {
const Polygons inst_near_body = offset(inst_hull, float(scale_(compacted_tower_half_clearance(zone.body_radius))), jtRound, scale_(0.1));
result.near_body = ! intersection(zone.grown_body, inst_near_body).empty();
}
result.allowed_rise = result.far_clearance;
if (near_nozzle)
result.allowed_rise = 0.;
else if (result.near_body)
result.allowed_rise = std::min(result.far_clearance, double(config.nozzle_height.value));
return result;
}
Polygon compacted_wipe_tower_offender_outline(const Polygon &inst_hull, double body_clearance)
{
// Exactly the half-clearance the check grew this instance by, so the halo drawn around an object is
// the very outline that was tested against the tower ring of the same tier. Passing the clearance
// the object was actually judged on keeps a short object from being drawn with the wide ring it is
// not subject to.
const Polygons grown = offset(inst_hull, float(scale_(compacted_tower_half_clearance(body_clearance))), jtRound, scale_(0.1));
return grown.empty() ? inst_hull : grown.front();
}
// Shared user-facing message for every compacted-tower clearance failure. Height-limit and too-close
// are the same class of layout violation under "No sparse layers", so they share one wording.
static std::string compacted_wipe_tower_clearance_error()
{
return L("The relative position of the model and the prime tower does not meet the requirements of the \"No sparse layers\" feature. Please adjust their relative positions, lower the model height, or turn off \"No sparse layers\".");
}
// Convex hull of one print instance in bed coordinates, the same outline both compacted tower checks
// compare against the tower.
static Polygon compacted_tower_print_instance_hull(const PrintObject &object, const PrintInstance &instance)
{
Points pts;
for (const ModelVolume *v : object.model_object()->volumes) {
if (! v->is_model_part())
continue;
Polygon hull = v->get_convex_hull_2d(Geometry::assemble_transform(Vec3d::Zero(), instance.model_instance->get_rotation(),
instance.model_instance->get_scaling_factor(), instance.model_instance->get_mirror()));
hull.translate(instance.shift - object.center_offset());
append(pts, hull.points);
}
return pts.empty() ? Polygon() : Geometry::convex_hull(pts);
}
// Footprint the compacted prime tower is expected to occupy on the plate, in bed coordinates.
// Before psWipeTower has run there is no tower geometry at all, so this falls back to the same
// estimate the plater builds its preview box from. Answering while the user is still arranging the
// plate is the whole point of the pre-slice check, and an estimate is all that can be had then.
static Polygon estimated_wipe_tower_footprint(const Print &print)
{
const PrintConfig &config = print.config();
const size_t filaments_cnt = print.extruders().size();
if (filaments_cnt == 0)
return Polygon();
const WipeTowerData &wtd = print.wipe_tower_data(filaments_cnt);
double width, depth, brim;
Vec2d local_min;
if (wtd.bbx.size().x() > EPSILON && wtd.bbx.size().y() > EPSILON) {
// The tower has already been generated once, so use its real box (brim included) instead of
// re-estimating. Same frame first_layer_wipe_tower_corners() works in.
width = wtd.bbx.size().x();
depth = wtd.bbx.size().y();
local_min = wtd.bbx.min + wtd.rib_offset.cast<double>();
brim = 0.;
} else {
depth = wtd.depth;
if (depth < EPSILON)
return Polygon();
// PartPlate::estimate_wipe_tower_size() squares the rib tower off and the preview box the user
// drags around is built from that, so match it here rather than keeping the nominal width.
width = config.wipe_tower_wall_type.value == WipeTowerWallType::wtwRib ? depth : double(config.prime_tower_width.value);
local_min = Vec2d::Zero();
brim = double(wtd.brim_width);
}
const double padding = compacted_tower_footprint_padding(config, brim);
local_min -= Vec2d(padding, padding);
width += 2. * padding;
depth += 2. * padding;
const Eigen::Rotation2Dd rot(Geometry::deg2rad(config.wipe_tower_rotation_angle.value));
const Vec2d translate(config.wipe_tower_x.get_at(print.get_plate_index()) + print.get_plate_origin()(0),
config.wipe_tower_y.get_at(print.get_plate_index()) + print.get_plate_origin()(1));
Polygon footprint;
for (const Vec2d &corner : { local_min,
Vec2d(local_min.x() + width, local_min.y()),
Vec2d(local_min.x() + width, local_min.y() + depth),
Vec2d(local_min.x(), local_min.y() + depth) }) {
const Vec2d p = rot * corner + translate;
footprint.points.emplace_back(scale_(p.x()), scale_(p.y()));
}
return footprint;
}
// Pre-slice counterpart of validate_compacted_wipe_tower_clearance(). It applies the very same
// clearance rule, but to an estimated tower footprint instead of the real tool-change extrusions,
// which is what lets it run from Print::validate() before anything has been sliced. Reporting through
// polygons / height_polygons rather than by throwing is what puts the collision area and the height
// limit plane on the plater, exactly the way sequential printing does it.
StringObjectException Print::compacted_wipe_tower_clearance_valid(const Print &print, Polygons *polygons, std::vector<std::pair<Polygon, float>> *height_polygons)
{
const PrintConfig &config = print.config();
if (! wipe_tower_sparse_layers_skipped(config) || config.print_sequence != PrintSequence::ByLayer || ! print.has_wipe_tower())
return {};
const CompactedTowerZone zone = compacted_wipe_tower_zone(config, estimated_wipe_tower_footprint(print));
if (zone.empty())
return {};
StringObjectException exception;
Polygons offenders;
bool body_tier_used = false;
for (const PrintObject *object : print.objects()) {
const double object_top = unscaled<double>(object->max_z());
for (const PrintInstance &instance : object->instances()) {
const Polygon inst_hull = compacted_tower_print_instance_hull(*object, instance);
if (inst_hull.points.empty())
continue;
const CompactedTowerClearance clearance = compacted_wipe_tower_clearance(config, zone, inst_hull, object_top);
body_tier_used = body_tier_used || compacted_tower_body_tier(clearance);
// Every tier the precise check applies is applied here too, otherwise an object standing
// within the toolhead radius would pass here and then be rejected mid-slice, which is the
// one outcome this check exists to prevent. The compacted tower base is unknown before
// slicing, so the rise is measured from the plate rather than from the tower top; that
// overstates it by the tower's own height and makes this check err strict, never lax.
if (object_top <= clearance.allowed_rise + EPSILON)
continue;
// Height-limit and too-close cases share one user-facing message: both mean the layout
// violates the "No sparse layers" clearance rule, and the remedies are the same.
const std::string msg = compacted_wipe_tower_clearance_error();
if (exception.string.empty()) {
exception.string = msg;
exception.object = instance.model_instance;
} else {
// Same wording for every offender; keep a single copy and drop the object pointer.
exception.object = nullptr;
}
const Polygon outline = compacted_wipe_tower_offender_outline(inst_hull, clearance.body_clearance);
offenders.emplace_back(outline);
if (height_polygons)
height_polygons->emplace_back(outline, float(clearance.allowed_rise));
}
}
// Draw the tower's keep-out ring alongside the offending objects, so the collision area reads as
// "this object reaches into the space the toolhead needs around the tower" rather than as a lone
// highlighted object. Emitted only on a real collision; the plater discards polygons otherwise.
// Only the rings some object on this plate is actually measured against are drawn, so that a ring
// and an object outline touching always means that object is over its limit.
if (polygons && ! offenders.empty()) {
append(*polygons, compacted_wipe_tower_rings(zone, body_tier_used));
append(*polygons, offenders);
}
return exception;
}
// With wipe_tower_no_sparse_layers the tower only grows on layers that carry a real toolchange,
// so it ends up far below the object and the nozzle has to descend to it. While the nozzle sits
// down on the compacted tower the rod is at tower_z + extruder_clearance_height_to_rod, and it
// sweeps the tower's Y band across the whole X axis. Anything already printed above that line and
// sharing the band gets hit. Nearer than the toolhead radius the head body hits the object well before
// the rod does, which is the horizontal half of the same problem. The spiral Z-hop that opens a wipe-
// tower travel also leaves the extrusion outline at a low Z, so the footprint used here is the
// deposited hull grown by the spiral circle's maximum reach. This mirrors both clearance checks of
// sequential printing, except that the tower is revisited over and over, so every object is compared
// against it.
void Print::validate_compacted_wipe_tower_clearance() const
{
// Nothing to check when the tower is not compacted: it then follows the object as usual and the
// regular by-layer clearance check already covers it. Asking wipe_tower_sparse_layers_skipped()
// rather than the raw option keeps this from rejecting plates whose tower is in fact full height.
if (! wipe_tower_sparse_layers_skipped(m_config) || m_config.print_sequence != PrintSequence::ByLayer)
return;
const std::vector<std::vector<WipeTower::ToolChangeResult>> &tool_changes = m_wipe_tower_data.tool_changes;
if (tool_changes.empty() || m_objects.empty())
return;
// Same accumulation the G-code emitter runs, so validation and output cannot disagree.
const std::vector<float> tower_z = compute_compacted_wipe_tower_z(tool_changes, float(m_config.z_offset.value));
// Wipe tower footprint: build it from the ACTUAL tool-change extrusions rather than the nominal
// width x depth rectangle returned by first_layer_wipe_tower_corners(). With a rib wall the printed
// wall bulges past the nominal box and the first-layer brim reaches even further; the nominal box
// (m_wipe_tower_data.bbx) undercounts that outermost extent by several millimetres, which is
// exactly the extent that decides how close the sweeping rod comes to a neighbouring object. The
// extrusion end-points are stored in the wipe-tower local frame, so we map them to the bed frame
// with the same transform the G-code emitter applies. The two emitters differ in where rib_offset
// enters: WipeTowerIntegration::append_tcr() (type 1) rotates the point and then adds the offset,
// append_tcr2() (type 2) adds it before rotating. On a rotated rib-wall tower the two land several
// millimetres apart, which is exactly the margin this check measures, so follow the emitter in use.
const Eigen::Rotation2Dd wt_rot(Geometry::deg2rad(m_config.wipe_tower_rotation_angle.value));
const Vec2d wt_translate(m_config.wipe_tower_x.get_at(m_plate_index) + m_origin(0),
m_config.wipe_tower_y.get_at(m_plate_index) + m_origin(1));
const Vec2d rib_off = m_wipe_tower_data.rib_offset.cast<double>();
const bool rib_off_rotates = this->wipe_tower_type() == WipeTowerType::Type2;
auto to_bed = [&wt_rot, &wt_translate, &rib_off, rib_off_rotates](const Vec2d &pt) {
return rib_off_rotates ? Vec2d(wt_rot * (pt + rib_off) + wt_translate) : Vec2d(wt_rot * pt + wt_translate + rib_off);
};
Points tower_pts;
for (const std::vector<WipeTower::ToolChangeResult> &layer : tool_changes) {
if (layer.empty() || wipe_tower_layer_is_sparse(layer))
continue;
for (const WipeTower::ToolChangeResult &tcr : layer)
for (size_t i = 0; i < tcr.extrusions.size(); ++i) {
// A zero width marks a travel end-point. Keep it only when it opens a real extrusion, so
// the hull covers the deposited material and nothing else; travels reach a bit further out
// than the walls do.
const WipeTower::Extrusion &e = tcr.extrusions[i];
if (e.width == 0.f && (i + 1 == tcr.extrusions.size() || tcr.extrusions[i + 1].width == 0.f))
continue;
const Vec2d p = to_bed(Vec2d(e.pos.x(), e.pos.y()));
tower_pts.emplace_back(scale_(p.x()), scale_(p.y()));
}
}
if (tower_pts.empty())
return;
const CompactedTowerZone zone = compacted_wipe_tower_zone(m_config, Geometry::convex_hull(tower_pts));
if (zone.empty())
return;
for (const PrintObject *object : m_objects) {
const double object_top = unscaled<double>(object->max_z());
for (const PrintInstance &instance : object->instances()) {
const Polygon inst_hull = compacted_tower_print_instance_hull(*object, instance);
if (inst_hull.points.empty())
continue;
// Report the worst layer rather than the first offending one, it is the one that explains the
// collision best. The rise has to be known before the clearance: it is what selects the
// horizontal tier, the nozzle cone being out of the head body's reach.
double max_rise = 0.;
for (size_t i = 0; i < tool_changes.size(); ++i) {
if (tool_changes[i].empty() || wipe_tower_layer_is_sparse(tool_changes[i]))
continue;
// Nothing above the current layer exists yet, so a tall object only counts up to it.
const double rise = std::min(object_top, double(tool_changes[i].front().print_z)) - tower_z[i];
if (rise > max_rise)
max_rise = rise;
}
const CompactedTowerClearance clearance = compacted_wipe_tower_clearance(m_config, zone, inst_hull, max_rise);
if (max_rise <= clearance.allowed_rise + EPSILON)
continue;
// Same wording as compacted_wipe_tower_clearance_valid(): height-limit and too-close
// share one message, since both are layout violations of "No sparse layers".
throw Slic3r::SlicingError(compacted_wipe_tower_clearance_error());
}
}
}
//BBS //BBS
static StringObjectException layered_print_cleareance_valid(const Print &print, StringObjectException *warning) static StringObjectException layered_print_cleareance_valid(const Print &print, StringObjectException *warning)
{ {
@@ -1408,6 +1781,16 @@ StringObjectException Print::validate(std::vector<StringObjectException> *warnin
} }
if (!layer_warning.string.empty()) if (!layer_warning.string.empty())
add_warning(layer_warning); add_warning(layer_warning);
// Orca: a compacted prime tower drags the nozzle back down to the plate on every toolchange, so
// tall objects collide with it much like they do in sequential printing. Checking it here rather
// than only during slicing is what lets the plater show the collision area and the height limit
// while the plate is still being arranged.
ret = compacted_wipe_tower_clearance_valid(*this, collison_polygons, height_polygons);
if (!ret.string.empty()) {
ret.type = STRING_EXCEPT_OBJECT_COLLISION_IN_LAYER_PRINT;
return ret;
}
} }
if (m_config.enable_prime_tower) { if (m_config.enable_prime_tower) {
@@ -2620,6 +3003,12 @@ void Print::process(long long *time_cost_with_cache, bool use_cache)
if (this->has_wipe_tower()) { if (this->has_wipe_tower()) {
m_fake_wipe_tower.set_pos({ m_config.wipe_tower_x.get_at(m_plate_index), m_config.wipe_tower_y.get_at(m_plate_index) }); m_fake_wipe_tower.set_pos({ m_config.wipe_tower_x.get_at(m_plate_index), m_config.wipe_tower_y.get_at(m_plate_index) });
// Validated on every process() run rather than only when the wipe tower step is (re)generated.
// Moving the tower changes only wipe_tower_x/y, which invalidates psSkirtBrim but not psWipeTower,
// so a validate call living inside _make_wipe_tower would be skipped and keep using the stale
// position, missing a fresh collision. The tower geometry (tool_changes) is stored in the local
// frame and is position independent, so re-checking here with the current position is correct.
this->validate_compacted_wipe_tower_clearance();
} }
if (this->set_started(psSkirtBrim)) { if (this->set_started(psSkirtBrim)) {
+87
View File
@@ -1160,6 +1160,8 @@ public:
//BBS //BBS
static StringObjectException sequential_print_clearance_valid(const Print &print, Polygons *polygons = nullptr, std::vector<std::pair<Polygon, float>>* height_polygons = nullptr); static StringObjectException sequential_print_clearance_valid(const Print &print, Polygons *polygons = nullptr, std::vector<std::pair<Polygon, float>>* height_polygons = nullptr);
// Orca: pre-slice clearance check for a prime tower compacted by "No sparse layers".
static StringObjectException compacted_wipe_tower_clearance_valid(const Print &print, Polygons *polygons = nullptr, std::vector<std::pair<Polygon, float>>* height_polygons = nullptr);
ConflictResultOpt get_conflict_result() const { return m_conflict_result; } ConflictResultOpt get_conflict_result() const { return m_conflict_result; }
// Return 4 wipe tower corners in the world coordinates (shifted and rotated), including the wipe tower brim. // Return 4 wipe tower corners in the world coordinates (shifted and rotated), including the wipe tower brim.
@@ -1174,6 +1176,8 @@ public:
void set_calib_params(const Calib_Params& params); void set_calib_params(const Calib_Params& params);
const Calib_Params& calib_params() const { return m_calib_params; } const Calib_Params& calib_params() const { return m_calib_params; }
Vec2d translate_to_print_space(const Vec2d &point) const; Vec2d translate_to_print_space(const Vec2d &point) const;
// Orca: precise counterpart of compacted_wipe_tower_clearance_valid(), run once the tower exists.
void validate_compacted_wipe_tower_clearance() const;
float get_wipe_tower_depth() const { return m_wipe_tower_data.depth; } float get_wipe_tower_depth() const { return m_wipe_tower_data.depth; }
BoundingBoxf get_wipe_tower_bbx() const { return m_wipe_tower_data.bbx; } BoundingBoxf get_wipe_tower_bbx() const { return m_wipe_tower_data.bbx; }
Vec2f get_rib_offset() const { return m_wipe_tower_data.rib_offset; } Vec2f get_rib_offset() const { return m_wipe_tower_data.rib_offset; }
@@ -1394,6 +1398,89 @@ public:
}; };
// ---------------------------------------------------------------------------------------------
// Clearance rule for a prime tower compacted by wipe_tower_no_sparse_layers. Shared by the precise
// check that runs on the real extrusions, the pre-slice estimate that feeds the plater with collision
// polygons, and the plater's own live preview while the user drags the tower or an object around.
// Keeping the rule in one place is what stops those three from drifting apart and reporting different
// things for the same plate.
// ---------------------------------------------------------------------------------------------
// Half of a clearance distance, the share each of the two outlines carries. Sequential printing splits
// extruder_clearance_radius between the two object hulls this way; the tower checks split their
// clearances between the tower ring and the instance hull for the same reason, so that the two
// outlines the plater draws touch precisely when the check trips. The 0.2 mm comes off first: it is
// the rounding slack the sequential check applies, 0.1 mm per side.
inline double compacted_tower_half_clearance(double clearance) { return 0.5 * (clearance - 0.2); }
// Keep-out geometry a compacted tower projects onto the plate, derived from its bare footprint.
struct CompactedTowerZone
{
// Footprint the checks work on: the raw outline grown by the spiral Z-hop envelope.
Polygon hull;
// hull grown by half the toolhead radius; an object whose own half-grown hull reaches into it is
// hit by the head body. This is also the ring the plater draws.
Polygons grown_body;
// hull grown by half the bare nozzle cone radius, the innermost tier.
Polygons grown_nozzle;
// hull bounding box, the Y band the rod sweeps.
BoundingBox bbox_rod;
// Full body clearance, of which grown_body carries half. Which of the two tiers applies is decided
// per object rather than here; see compacted_wipe_tower_clearance().
double body_radius { 0. };
bool empty() const { return hull.points.empty(); }
};
// Per-side padding a bare wipe tower outline needs before the clearance checks may treat it as the
// tower's footprint. Callers whose outline already carries the first-layer brim pass zero for it.
// Shared by the pre-slice estimate and the plater's live preview: both start from an outline that
// falls short of the printed tower in the same two ways, and padding them by different amounts is
// exactly how the preview and the validation behind it would end up disagreeing.
double compacted_tower_footprint_padding(const PrintConfig &config, double brim_width);
// Grow a bare tower footprint (bed frame, scaled) into its keep-out zone.
CompactedTowerZone compacted_wipe_tower_zone(const PrintConfig &config, const Polygon &tower_footprint);
// How far an object may rise above the compacted tower base before the toolhead hits it.
struct CompactedTowerClearance
{
// Height the object may reach above the tower base. Zero means it may not rise at all.
double allowed_rise;
// Clearance that applies once the object stands clear of the toolhead in XY, i.e. rod or lid.
double far_clearance;
// The object sits within the toolhead radius, so the head body limits it rather than the rod.
bool near_body;
// Horizontal clearance this particular object has to keep from the tower: the full toolhead
// radius once it rises past the nozzle cone, the bare cone while it stays below. It is what the
// error message quotes and what the plater grows the object outline by.
double body_clearance;
};
// object_rise is the height above the tower base that the caller is going to compare against
// allowed_rise. It also selects the horizontal tier, so the two cannot disagree.
CompactedTowerClearance compacted_wipe_tower_clearance(const PrintConfig &config, const CompactedTowerZone &zone,
const Polygon &inst_hull, double object_rise);
// This object was judged on a tier reaching past the bare nozzle cone, so the wide ring is the one its
// outline has to be drawn against.
inline bool compacted_tower_body_tier(const CompactedTowerClearance &clearance)
{
return clearance.body_clearance > double(MAX_OUTER_NOZZLE_DIAMETER);
}
// Keep-out rings to draw around the tower. The nozzle one always applies; the wide body one is drawn
// only when some object on the plate is actually measured against it, otherwise it would show a
// keep-out zone no object can violate.
Polygons compacted_wipe_tower_rings(const CompactedTowerZone &zone, bool any_body_tier);
// Outline to hand the plater for an offending object: the instance hull grown by the same half
// clearance the check grew it by, which is CompactedTowerClearance::body_clearance for that object.
// Sequential printing reports its hulls the same way, and it doubles as the fix for the bare hull
// being unusable on screen, where drawn flat it hides under the object and drawn at the height limit
// it ends up buried inside the mesh.
Polygon compacted_wipe_tower_offender_outline(const Polygon &inst_hull, double body_clearance);
} /* slic3r_Print_hpp_ */ } /* slic3r_Print_hpp_ */
#endif #endif
+65 -2
View File
@@ -2549,6 +2549,16 @@ void PrintConfigDef::init_fff_params()
def->enum_labels.push_back("5"); def->enum_labels.push_back("5");
def->mode = comAdvanced; def->mode = comAdvanced;
// Orca: already carried by the BBL/Qidi/Geeetech/Eryone machine profiles, which inherited it from
// the BambuStudio import; without a definition here it was parsed as an unknown key and dropped.
def = this->add("extruder_clearance_dist_to_rod", coFloat);
def->label = L("Distance to rod");
def->tooltip = L("Horizontal distance of the nozzle tip to the rod's farther edge. Used for collision avoidance in by-object printing.");
def->sidetext = L("mm"); // millimeters, CIS languages need translation
def->min = 0;
def->mode = comAdvanced;
def->set_default_value(new ConfigOptionFloat(40));
def = this->add("extruder_clearance_height_to_rod", coFloat); def = this->add("extruder_clearance_height_to_rod", coFloat);
def->label = L("Height to rod"); def->label = L("Height to rod");
def->tooltip = L("Distance from the nozzle tip to the lower rod. Used for collision avoidance in by-object printing."); def->tooltip = L("Distance from the nozzle tip to the lower rod. Used for collision avoidance in by-object printing.");
@@ -5537,6 +5547,16 @@ void PrintConfigDef::init_fff_params()
def->mode = comAdvanced; def->mode = comAdvanced;
def->set_default_value(new ConfigOptionBool(true)); def->set_default_value(new ConfigOptionBool(true));
def = this->add("unsupported_wall_last", coBool);
def->label = L("Print unsupported walls last");
def->category = L("Quality");
def->tooltip = L("Wall loops that lie entirely in mid air are printed once something can hold them:\n"
"they are extruded after the other walls of their island, innermost first, whatever the wall order is.\n"
"A loop that only the bridges of this layer can anchor waits until those bridges are printed, while a loop running "
"alongside a supported wall keeps its place before the infill, which needs it as an anchor.");
def->mode = comAdvanced;
def->set_default_value(new ConfigOptionBool(false));
def = this->add("outer_wall_filament_id", coInt); def = this->add("outer_wall_filament_id", coInt);
def->gui_type = ConfigOptionDef::GUIType::i_enum_open; def->gui_type = ConfigOptionDef::GUIType::i_enum_open;
def->label = L("Outer walls"); def->label = L("Outer walls");
@@ -6673,8 +6693,10 @@ void PrintConfigDef::init_fff_params()
def = this->add("wipe_tower_no_sparse_layers", coBool); def = this->add("wipe_tower_no_sparse_layers", coBool);
def->label = L("No sparse layers (beta)"); def->label = L("No sparse layers (beta)");
def->tooltip = L("If enabled, the wipe tower will not be printed on layers with no tool changes. " def->tooltip = L("If enabled, the wipe tower will not be printed on layers with no tool changes. "
"On layers with a tool change, extruder will travel downward to print the wipe tower. " "On layers with a tool change, extruder will travel downward to print the wipe tower, "
"User is responsible for ensuring there is no collision with the print."); "so the tower ends up below the model and the toolhead has to reach down to it. "
"Layouts where that would collide with an already printed object are rejected. "
"Has no effect with smooth timelapse or clumping detection, which need a tower on every layer.");
def->mode = comAdvanced; def->mode = comAdvanced;
def->set_default_value(new ConfigOptionBool(false)); def->set_default_value(new ConfigOptionBool(false));
@@ -6700,6 +6722,34 @@ void PrintConfigDef::init_fff_params()
def->enum_labels.emplace_back(L("Cyclic")); def->enum_labels.emplace_back(L("Cyclic"));
def->set_default_value(new ConfigOptionEnum<ToolChangeOrderingType>(ToolChangeOrderingType::Default)); def->set_default_value(new ConfigOptionEnum<ToolChangeOrderingType>(ToolChangeOrderingType::Default));
def = this->add("toolchange_cyclic_order", coString);
def->label = L("Cyclic order");
def->category = L("Advanced");
def->tooltip = L(
"Custom filament sequence used by the cyclic toolchange ordering, as filament numbers separated by commas (e.g. \"3,2,1,4\").\n"
"Each layer prints its filaments following this sequence; filaments not listed are printed last, in ascending order.\n"
"Leave empty to cycle through the filaments in ascending order."
);
def->mode = comExpert;
def->set_default_value(new ConfigOptionString(""));
def = this->add("toolchange_cyclic_first_layer", coBool);
def->label = L("Apply cyclic order to first layer");
def->category = L("Advanced");
def->tooltip = L(
"Applies the cyclic toolchange order to the first layer as well.\n"
"By default this is disabled, because the first layer is instead ordered for the best bed "
"adhesion: filaments that print small, fragile first-layer features are printed last, so the "
"following tool changes and travel moves are less likely to knock those weakly anchored parts "
"loose. This first-layer order also honors a custom first layer filament sequence when one is set. "
"The cyclic order's benefit (extra tool changes give each layer more time to cool) does not apply "
"to the first layer, which is printed slowly and hot for adhesion.\n"
"Enable this only if you need the exact same tool sequence on every layer, including the first, at "
"the cost of that adhesion optimization."
);
def->mode = comExpert;
def->set_default_value(new ConfigOptionBool(false));
def = this->add("slice_closing_radius", coFloat); def = this->add("slice_closing_radius", coFloat);
def->label = L("Slice gap closing radius"); def->label = L("Slice gap closing radius");
def->category = L("Quality"); def->category = L("Quality");
@@ -11963,6 +12013,19 @@ CLIActionsConfigDef::CLIActionsConfigDef()
"the --ground-* options choose from. Machine-readable alternative to --info."); "the --ground-* options choose from. Machine-readable alternative to --info.");
def->set_default_value(new ConfigOptionBool(false)); def->set_default_value(new ConfigOptionBool(false));
// --inspect-paint \u2014 dump the per-facet enforcer/blocker/extruder/fuzzy
// paint state stored on the loaded model (supports, seam, MMU color,
// fuzzy-skin) as JSON. Read-only; lets CI / scripted / AI tooling
// reason about existing paint on a .3mf without loading the GUI.
def = this->add("inspect_paint", coBool);
def->label = L("Inspect paint (JSON to stdout)");
def->tooltip = L("Print a structured JSON summary of every painted layer "
"(supports, seam, MMU color, fuzzy-skin) already stored on "
"the loaded model \u2014 per-state facet count, surface area, "
"and mesh-local bounding box \u2014 then exit. Machine-readable "
"alternative to opening the paint gizmos in the GUI.");
def->set_default_value(new ConfigOptionBool(false));
def = this->add("export_settings", coString); def = this->add("export_settings", coString);
def->label = L("Export Settings"); def->label = L("Export Settings");
def->tooltip = L("This exports settings to a file. Use - to write them to stdout."); def->tooltip = L("This exports settings to a file. Use - to write them to stdout.");
+4
View File
@@ -1353,6 +1353,7 @@ PRINT_CONFIG_CLASS_DEFINE(
((ConfigOptionFloatsNullable, filament_ironing_speed)) ((ConfigOptionFloatsNullable, filament_ironing_speed))
// Detect bridging perimeters // Detect bridging perimeters
((ConfigOptionBool, detect_overhang_wall)) ((ConfigOptionBool, detect_overhang_wall))
((ConfigOptionBool, unsupported_wall_last))
((ConfigOptionInt, outer_wall_filament_id)) ((ConfigOptionInt, outer_wall_filament_id))
((ConfigOptionInt, inner_wall_filament_id)) ((ConfigOptionInt, inner_wall_filament_id))
((ConfigOptionFloatOrPercent, inner_wall_line_width)) ((ConfigOptionFloatOrPercent, inner_wall_line_width))
@@ -1627,6 +1628,8 @@ PRINT_CONFIG_CLASS_DEFINE(
((ConfigOptionBool, manual_filament_change)) ((ConfigOptionBool, manual_filament_change))
((ConfigOptionBool, single_extruder_multi_material_priming)) ((ConfigOptionBool, single_extruder_multi_material_priming))
((ConfigOptionEnum<ToolChangeOrderingType>, toolchange_ordering)) ((ConfigOptionEnum<ToolChangeOrderingType>, toolchange_ordering))
((ConfigOptionString, toolchange_cyclic_order))
((ConfigOptionBool, toolchange_cyclic_first_layer))
((ConfigOptionBool, wipe_tower_no_sparse_layers)) ((ConfigOptionBool, wipe_tower_no_sparse_layers))
((ConfigOptionString, change_filament_gcode)) ((ConfigOptionString, change_filament_gcode))
((ConfigOptionString, change_extrusion_role_gcode)) ((ConfigOptionString, change_extrusion_role_gcode))
@@ -1788,6 +1791,7 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE(
((ConfigOptionBools, slow_down_for_layer_cooling)) ((ConfigOptionBools, slow_down_for_layer_cooling))
((ConfigOptionInts, close_fan_the_first_x_layers)) ((ConfigOptionInts, close_fan_the_first_x_layers))
((ConfigOptionEnum<DraftShield>, draft_shield)) ((ConfigOptionEnum<DraftShield>, draft_shield))
((ConfigOptionFloat, extruder_clearance_dist_to_rod))//BBS
((ConfigOptionFloat, extruder_clearance_height_to_rod))//BBs ((ConfigOptionFloat, extruder_clearance_height_to_rod))//BBs
((ConfigOptionFloat, extruder_clearance_height_to_lid))//BBS ((ConfigOptionFloat, extruder_clearance_height_to_lid))//BBS
((ConfigOptionFloat, extruder_clearance_radius)) ((ConfigOptionFloat, extruder_clearance_radius))
+1
View File
@@ -1501,6 +1501,7 @@ bool PrintObject::invalidate_state_by_config_options(
|| opt_key == "fuzzy_skin_octaves" || opt_key == "fuzzy_skin_octaves"
|| opt_key == "fuzzy_skin_persistence" || opt_key == "fuzzy_skin_persistence"
|| opt_key == "detect_overhang_wall" || opt_key == "detect_overhang_wall"
|| opt_key == "unsupported_wall_last"
|| opt_key == "overhang_reverse" || opt_key == "overhang_reverse"
|| opt_key == "overhang_reverse_internal_only" || opt_key == "overhang_reverse_internal_only"
|| opt_key == "overhang_reverse_threshold" || opt_key == "overhang_reverse_threshold"
+8 -15
View File
@@ -226,7 +226,6 @@ set(SLIC3R_GUI_SOURCES
GUI/GLToolbar.hpp GUI/GLToolbar.hpp
GUI/ImageDPIFrame.cpp GUI/ImageDPIFrame.cpp
GUI/ImageDPIFrame.hpp GUI/ImageDPIFrame.hpp
GUI/IMediaController.hpp
GUI/GUI_App.cpp GUI/GUI_App.cpp
GUI/GUI_App.hpp GUI/GUI_App.hpp
GUI/GUI_AuxiliaryList.cpp GUI/GUI_AuxiliaryList.cpp
@@ -348,8 +347,6 @@ set(SLIC3R_GUI_SOURCES
GUI/MediaFilePanel.h GUI/MediaFilePanel.h
GUI/MediaPlayCtrl.cpp GUI/MediaPlayCtrl.cpp
GUI/MediaPlayCtrl.h GUI/MediaPlayCtrl.h
GUI/WebRtcMediaController.cpp
GUI/WebRtcMediaController.hpp
GUI/MeshUtils.cpp GUI/MeshUtils.cpp
GUI/MeshUtils.hpp GUI/MeshUtils.hpp
GUI/ModelMall.cpp GUI/ModelMall.cpp
@@ -539,8 +536,6 @@ set(SLIC3R_GUI_SOURCES
GUI/WebUserLoginDialog.hpp GUI/WebUserLoginDialog.hpp
GUI/WebViewDialog.cpp GUI/WebViewDialog.cpp
GUI/WebViewDialog.hpp GUI/WebViewDialog.hpp
GUI/WebMediaController.hpp
GUI/WebMediaController.cpp
GUI/Widgets/AMSControl.cpp GUI/Widgets/AMSControl.cpp
GUI/Widgets/AMSControl.hpp GUI/Widgets/AMSControl.hpp
GUI/Widgets/AMSItem.cpp GUI/Widgets/AMSItem.cpp
@@ -687,6 +682,8 @@ set(SLIC3R_GUI_SOURCES
Utils/Bonjour.hpp Utils/Bonjour.hpp
Utils/MeshInspect.cpp Utils/MeshInspect.cpp
Utils/MeshInspect.hpp Utils/MeshInspect.hpp
Utils/PaintCLI.cpp
Utils/PaintCLI.hpp
Utils/CalibUtils.cpp Utils/CalibUtils.cpp
Utils/CalibUtils.hpp Utils/CalibUtils.hpp
Utils/ColorSpaceConvert.cpp Utils/ColorSpaceConvert.cpp
@@ -733,7 +730,6 @@ set(SLIC3R_GUI_SOURCES
Utils/NetworkAgentFactory.cpp Utils/NetworkAgentFactory.cpp
Utils/ICloudServiceAgent.hpp Utils/ICloudServiceAgent.hpp
Utils/IPrinterAgent.hpp Utils/IPrinterAgent.hpp
Utils/ICameraSignalingChannel.hpp
Utils/OrcaCloudServiceAgent.cpp Utils/OrcaCloudServiceAgent.cpp
Utils/OrcaCloudServiceAgent.hpp Utils/OrcaCloudServiceAgent.hpp
Utils/OrcaPrinterAgent.cpp Utils/OrcaPrinterAgent.cpp
@@ -878,7 +874,7 @@ else()
set(_opengl_link_lib OpenGL::GL) set(_opengl_link_lib OpenGL::GL)
endif() endif()
target_link_libraries(libslic3r_gui libslic3r cereal::cereal imgui imguizmo minilzo libvgcode md4c-html glad ${_opengl_link_lib} hidapi mdns ${wxWidgets_LIBRARIES} glfw libcurl OpenSSL::SSL OpenSSL::Crypto LibDataChannel::LibDataChannel noise::noise pybind11::embed) target_link_libraries(libslic3r_gui libslic3r cereal::cereal imgui imguizmo minilzo libvgcode md4c-html glad ${_opengl_link_lib} hidapi mdns ${wxWidgets_LIBRARIES} glfw libcurl OpenSSL::SSL OpenSSL::Crypto noise::noise pybind11::embed)
if (CMAKE_SYSTEM_NAME STREQUAL "Linux") if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
# Linux finds wxWidgets in module mode, whose include dirs and definitions # Linux finds wxWidgets in module mode, whose include dirs and definitions
@@ -935,32 +931,29 @@ endif ()
if (APPLE) if (APPLE)
# Static FFmpeg from the deps install: nothing to bundle into the .app, # Static FFmpeg from the deps install: nothing to bundle into the .app,
# no rpath/install_name handling. Order matters: avformat -> avcodec -> swscale -> avutil. # no rpath/install_name handling. Order matters: avcodec -> swscale -> avutil.
find_library(LIBAVFORMAT_LIBRARY NAMES libavformat.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBAVCODEC_LIBRARY NAMES libavcodec.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH) find_library(LIBAVCODEC_LIBRARY NAMES libavcodec.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBSWSCALE_LIBRARY NAMES libswscale.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH) find_library(LIBSWSCALE_LIBRARY NAMES libswscale.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBAVUTIL_LIBRARY NAMES libavutil.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH) find_library(LIBAVUTIL_LIBRARY NAMES libavutil.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
if (NOT LIBAVFORMAT_LIBRARY OR NOT LIBAVCODEC_LIBRARY OR NOT LIBSWSCALE_LIBRARY OR NOT LIBAVUTIL_LIBRARY) if (NOT LIBAVCODEC_LIBRARY OR NOT LIBSWSCALE_LIBRARY OR NOT LIBAVUTIL_LIBRARY)
message(FATAL_ERROR "Static FFmpeg (libavformat.a/libavcodec.a/libswscale.a/libavutil.a) not found under ${CMAKE_PREFIX_PATH}/lib. Rebuild the deps — FFMPEG builds static-only on macOS.") message(FATAL_ERROR "Static FFmpeg (libavcodec.a/libswscale.a/libavutil.a) not found under ${CMAKE_PREFIX_PATH}/lib. Rebuild the deps — FFMPEG builds static-only on macOS.")
endif () endif ()
target_link_libraries(libslic3r_gui ${LIBAVFORMAT_LIBRARY} ${LIBAVCODEC_LIBRARY} ${LIBSWSCALE_LIBRARY} ${LIBAVUTIL_LIBRARY}) target_link_libraries(libslic3r_gui ${LIBAVCODEC_LIBRARY} ${LIBSWSCALE_LIBRARY} ${LIBAVUTIL_LIBRARY})
target_include_directories(libslic3r_gui SYSTEM PRIVATE ${CMAKE_PREFIX_PATH}/include) target_include_directories(libslic3r_gui SYSTEM PRIVATE ${CMAKE_PREFIX_PATH}/include)
elseif (WIN32) elseif (WIN32)
# Prebuilt shared FFmpeg from the deps install. Windows has no pkg-config, # Prebuilt shared FFmpeg from the deps install. Windows has no pkg-config,
# so resolve the import libraries out of the deps prefix directly; the DLLs # so resolve the import libraries out of the deps prefix directly; the DLLs
# are copied next to the executable by the top level CMakeLists. # are copied next to the executable by the top level CMakeLists.
find_library(LIBAVFORMAT_LIBRARY NAMES avformat PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBAVCODEC_LIBRARY NAMES avcodec PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH) find_library(LIBAVCODEC_LIBRARY NAMES avcodec PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBSWSCALE_LIBRARY NAMES swscale PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH) find_library(LIBSWSCALE_LIBRARY NAMES swscale PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBAVUTIL_LIBRARY NAMES avutil PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH) find_library(LIBAVUTIL_LIBRARY NAMES avutil PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
if (NOT LIBAVCODEC_LIBRARY OR NOT LIBSWSCALE_LIBRARY OR NOT LIBAVUTIL_LIBRARY) if (NOT LIBAVCODEC_LIBRARY OR NOT LIBSWSCALE_LIBRARY OR NOT LIBAVUTIL_LIBRARY)
message(FATAL_ERROR "FFmpeg (avcodec/swscale/avutil) not found under ${CMAKE_PREFIX_PATH}/lib. Rebuild the deps.") message(FATAL_ERROR "FFmpeg (avcodec/swscale/avutil) not found under ${CMAKE_PREFIX_PATH}/lib. Rebuild the deps.")
endif () endif ()
target_link_libraries(libslic3r_gui ${LIBAVFORMAT_LIBRARY} ${LIBAVCODEC_LIBRARY} ${LIBSWSCALE_LIBRARY} ${LIBAVUTIL_LIBRARY}) target_link_libraries(libslic3r_gui ${LIBAVCODEC_LIBRARY} ${LIBSWSCALE_LIBRARY} ${LIBAVUTIL_LIBRARY})
target_include_directories(libslic3r_gui SYSTEM PRIVATE ${CMAKE_PREFIX_PATH}/include) target_include_directories(libslic3r_gui SYSTEM PRIVATE ${CMAKE_PREFIX_PATH}/include)
else () else ()
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
libavformat
libavcodec libavcodec
libswscale libswscale
libavutil libavutil
-27
View File
@@ -45,25 +45,6 @@ int AVVideoDecoder::open(Bambu_StreamInfo const &info)
return 0; return 0;
} }
int AVVideoDecoder::open(AVCodecParameters const &parameters)
{
if (avcodec_parameters_to_context(codec_ctx_, &parameters) < 0)
return -1;
auto codec = avcodec_find_decoder(codec_ctx_->codec_id);
if (codec == nullptr) {
fprintf(stderr, "AVVideoDecoder: unsupported codec!\n");
return -1;
}
if (avcodec_open2(codec_ctx_, codec, nullptr) < 0) {
fprintf(stderr, "AVVideoDecoder: could not open codec\n");
return -1;
}
frame_ = av_frame_alloc();
return frame_ == nullptr ? -1 : 0;
}
int AVVideoDecoder::decode(const Bambu_Sample &sample) int AVVideoDecoder::decode(const Bambu_Sample &sample)
{ {
int ret = -1; int ret = -1;
@@ -90,14 +71,6 @@ int AVVideoDecoder::decode(const Bambu_Sample &sample)
return ret; return ret;
} }
int AVVideoDecoder::decode(const AVPacket &packet)
{
int ret = avcodec_send_packet(codec_ctx_, &packet);
if (ret == 0)
got_frame_ = avcodec_receive_frame(codec_ctx_, frame_) == 0;
return ret;
}
int AVVideoDecoder::flush() int AVVideoDecoder::flush()
{ {
int ret = avcodec_send_packet(codec_ctx_, nullptr); int ret = avcodec_send_packet(codec_ctx_, nullptr);
-10
View File
@@ -23,10 +23,8 @@ public:
public: public:
int open(Bambu_StreamInfo const &info); int open(Bambu_StreamInfo const &info);
int open(AVCodecParameters const &parameters);
int decode(Bambu_Sample const &sample); int decode(Bambu_Sample const &sample);
int decode(AVPacket const &packet);
int flush(); int flush();
@@ -36,14 +34,6 @@ public:
bool toWxBitmap(wxBitmap &bitmap, wxSize const & size); bool toWxBitmap(wxBitmap &bitmap, wxSize const & size);
// Native size of the most recently decoded frame, or an unspecified size if
// nothing has decoded yet. Lets a caller learn the video dimensions when the
// container/probe could not report them up front.
wxSize decoded_frame_size() const
{
return got_frame_ && frame_ ? wxSize{frame_->width, frame_->height} : wxSize{};
}
private: private:
AVCodecContext *codec_ctx_ = nullptr; AVCodecContext *codec_ctx_ = nullptr;
AVFrame * frame_ = nullptr; AVFrame * frame_ = nullptr;
+1 -1
View File
@@ -328,7 +328,7 @@ void SelectMObjectPopup::update_user_devices()
} }
m_bind_machine_list.clear(); m_bind_machine_list.clear();
m_bind_machine_list = dev->get_my_machine_list(dev->get_current_printer_agent_id()); m_bind_machine_list = dev->get_my_machine_list();
//sort list //sort list
std::vector<std::pair<std::string, MachineObject*>> user_machine_list; std::vector<std::pair<std::string, MachineObject*>> user_machine_list;
+12 -3
View File
@@ -8,7 +8,6 @@
#include "libslic3r/Print.hpp" #include "libslic3r/Print.hpp"
#include "DeviceCore/DevConfig.h" #include "DeviceCore/DevConfig.h"
#include "DeviceCore/DevConfigUtil.h"
#include "DeviceCore/DevExtruderSystem.h" #include "DeviceCore/DevExtruderSystem.h"
#include "DeviceCore/DevFilaBlackList.h" #include "DeviceCore/DevFilaBlackList.h"
#include "DeviceCore/DevFilaSystem.h" #include "DeviceCore/DevFilaSystem.h"
@@ -1648,8 +1647,18 @@ bool CalibrationPresetPage::is_blocking_printing()
if (obj_ == nullptr) return true; if (obj_ == nullptr) return true;
PresetBundle* preset_bundle = wxGetApp().preset_bundle; PresetBundle* preset_bundle = wxGetApp().preset_bundle;
const auto source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle); auto source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle);
return !DevPrinterConfigUtil::is_printer_model_compatible(source_model, *obj_); auto target_model = obj_->printer_type;
if (source_model != target_model) {
std::vector<std::string> compatible_machine = obj_->get_compatible_machine();
vector<std::string>::iterator it = find(compatible_machine.begin(), compatible_machine.end(), source_model);
if (it == compatible_machine.end()) {
return true;
}
}
return false;
} }
bool CalibrationPresetPage::is_nozzle_info_synced() const bool CalibrationPresetPage::is_nozzle_info_synced() const
+61 -1
View File
@@ -28,6 +28,7 @@ wxEND_EVENT_TABLE()
wxDEFINE_EVENT(EVT_VCAMERA_SWITCH, wxMouseEvent); wxDEFINE_EVENT(EVT_VCAMERA_SWITCH, wxMouseEvent);
wxDEFINE_EVENT(EVT_SDCARD_ABSENT_HINT, wxCommandEvent); wxDEFINE_EVENT(EVT_SDCARD_ABSENT_HINT, wxCommandEvent);
wxDEFINE_EVENT(EVT_CAM_SOURCE_CHANGE, wxCommandEvent);
#define CAMERAPOPUP_CLICK_INTERVAL 20 #define CAMERAPOPUP_CLICK_INTERVAL 20
@@ -81,7 +82,7 @@ CameraPopup::CameraPopup(wxWindow *parent)
top_sizer->Add(m_text_liveview_retry, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT | wxALL, FromDIP(5)); top_sizer->Add(m_text_liveview_retry, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT | wxALL, FromDIP(5));
top_sizer->Add(m_switch_liveview_retry, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, FromDIP(5)); top_sizer->Add(m_switch_liveview_retry, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, FromDIP(5));
m_switch_liveview_retry->Bind(wxEVT_TOGGLEBUTTON, [](wxCommandEvent &e) { m_switch_liveview_retry->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent &e) {
wxGetApp().app_config->set("liveview", "auto_retry", e.IsChecked()); wxGetApp().app_config->set("liveview", "auto_retry", e.IsChecked());
e.Skip(); e.Skip();
}); });
@@ -101,6 +102,34 @@ CameraPopup::CameraPopup(wxWindow *parent)
top_sizer->Add(0, 0, wxALL, 0); top_sizer->Add(0, 0, wxALL, 0);
} }
// Orca: custom IP camera source — lets the user point Live Video at any camera URL (Orca feature; not in the reference)
m_custom_camera_input_confirm = new Button(m_panel, _L("Enable"));
m_custom_camera_input_confirm->SetBackgroundColor(wxColour(38, 166, 154));
m_custom_camera_input_confirm->SetBorderColor(wxColour(38, 166, 154));
m_custom_camera_input_confirm->SetTextColor(wxColour(0xFFFFFE));
m_custom_camera_input_confirm->SetFont(Label::Body_14);
m_custom_camera_input_confirm->SetMinSize(wxSize(FromDIP(90), FromDIP(30)));
m_custom_camera_input_confirm->SetPosition(wxDefaultPosition);
m_custom_camera_input_confirm->SetCornerRadius(FromDIP(12));
m_custom_camera_input = new TextInput(m_panel, wxEmptyString, wxEmptyString, wxEmptyString, wxDefaultPosition, wxDefaultSize);
m_custom_camera_input->GetTextCtrl()->SetHint(_L("Hostname or IP"));
m_custom_camera_input->GetTextCtrl()->SetFont(Label::Body_14);
m_custom_camera_hint = new wxStaticText(m_panel, wxID_ANY, _L("Custom camera source"));
m_custom_camera_hint->Wrap(-1);
m_custom_camera_hint->SetFont(Label::Head_14);
m_custom_camera_hint->SetForegroundColour(TEXT_COL);
m_custom_camera_input_confirm->Bind(wxEVT_BUTTON, &CameraPopup::on_camera_source_changed, this);
if (!wxGetApp().app_config->get("camera", "custom_source").empty()) {
m_custom_camera_input->GetTextCtrl()->SetValue(wxGetApp().app_config->get("camera", "custom_source"));
set_custom_cam_button_state(wxGetApp().app_config->get("camera", "enable_custom_source") == "true");
}
top_sizer->Add(m_custom_camera_hint, 0, wxALIGN_CENTER_VERTICAL | wxALIGN_LEFT | wxALL, FromDIP(5));
top_sizer->Add(0, 0, wxALL, 0);
top_sizer->Add(m_custom_camera_input, 2, wxALIGN_CENTER_VERTICAL | wxEXPAND | wxALL, FromDIP(5));
top_sizer->Add(m_custom_camera_input_confirm, 1, wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT | wxALL, FromDIP(5));
main_sizer->Add(top_sizer, 0, wxALL, FromDIP(10)); main_sizer->Add(top_sizer, 0, wxALL, FromDIP(10));
auto url = wxString(L"https://www.orcaslicer.com/wiki/"); // Orca: neutral wiki link (vendor URL removed) auto url = wxString(L"https://www.orcaslicer.com/wiki/"); // Orca: neutral wiki link (vendor URL removed)
@@ -155,6 +184,37 @@ void CameraPopup::sdcard_absent_hint()
GetEventHandler()->ProcessEvent(evt); GetEventHandler()->ProcessEvent(evt);
} }
void CameraPopup::on_camera_source_changed(wxCommandEvent &event)
{
if (m_obj && !m_custom_camera_input->GetTextCtrl()->IsEmpty()) {
handle_camera_source_change();
}
}
void CameraPopup::handle_camera_source_change()
{
m_custom_camera_enabled = !m_custom_camera_enabled;
set_custom_cam_button_state(m_custom_camera_enabled);
wxGetApp().app_config->set("camera", "custom_source", m_custom_camera_input->GetTextCtrl()->GetValue().ToStdString());
wxGetApp().app_config->set("camera", "enable_custom_source", m_custom_camera_enabled);
wxCommandEvent evt(EVT_CAM_SOURCE_CHANGE);
evt.SetEventObject(this);
GetEventHandler()->ProcessEvent(evt);
}
void CameraPopup::set_custom_cam_button_state(bool state)
{
m_custom_camera_enabled = state;
auto stateColour = state ? wxColour(170, 0, 0) : wxColour(38, 166, 154);
auto stateText = state ? "Disable" : "Enable";
m_custom_camera_input_confirm->SetBackgroundColor(stateColour);
m_custom_camera_input_confirm->SetBorderColor(stateColour);
m_custom_camera_input_confirm->SetLabel(_L(stateText));
}
void CameraPopup::on_switch_recording(wxCommandEvent& event) void CameraPopup::on_switch_recording(wxCommandEvent& event)
{ {
if (!m_obj) return; if (!m_obj) return;
+9 -4
View File
@@ -15,12 +15,14 @@
#include "Widgets/SwitchButton.hpp" #include "Widgets/SwitchButton.hpp"
#include "Widgets/RadioBox.hpp" #include "Widgets/RadioBox.hpp"
#include "Widgets/PopupWindow.hpp" #include "Widgets/PopupWindow.hpp"
#include "Widgets/TextInput.hpp"
namespace Slic3r { namespace Slic3r {
namespace GUI { namespace GUI {
wxDECLARE_EVENT(EVT_VCAMERA_SWITCH, wxMouseEvent); wxDECLARE_EVENT(EVT_VCAMERA_SWITCH, wxMouseEvent);
wxDECLARE_EVENT(EVT_SDCARD_ABSENT_HINT, wxCommandEvent); wxDECLARE_EVENT(EVT_SDCARD_ABSENT_HINT, wxCommandEvent);
wxDECLARE_EVENT(EVT_CAM_SOURCE_CHANGE, wxCommandEvent);
class CameraPopup : public PopupWindow class CameraPopup : public PopupWindow
{ {
@@ -51,6 +53,9 @@ protected:
void on_switch_recording(wxCommandEvent& event); void on_switch_recording(wxCommandEvent& event);
void on_set_resolution(); void on_set_resolution();
void sdcard_absent_hint(); void sdcard_absent_hint();
void on_camera_source_changed(wxCommandEvent& event);
void handle_camera_source_change();
void set_custom_cam_button_state(bool state);
wxWindow * create_item_radiobox(wxString title, wxWindow *parent, wxString tooltip, int padding_left); wxWindow * create_item_radiobox(wxString title, wxWindow *parent, wxString tooltip, int padding_left);
void select_curr_radiobox(int btn_idx); void select_curr_radiobox(int btn_idx);
@@ -71,10 +76,10 @@ private:
wxStaticText* m_text_liveview_retry; wxStaticText* m_text_liveview_retry;
SwitchButton* m_switch_liveview_retry; SwitchButton* m_switch_liveview_retry;
#endif //BBL_RELEASE_TO_PUBLIC #endif //BBL_RELEASE_TO_PUBLIC
// wxStaticText* m_custom_camera_hint; wxStaticText* m_custom_camera_hint;
// TextInput* m_custom_camera_input; TextInput* m_custom_camera_input;
// Button* m_custom_camera_input_confirm; Button* m_custom_camera_input_confirm;
// bool m_custom_camera_enabled{ false }; bool m_custom_camera_enabled{ false };
wxStaticText* m_text_resolution; wxStaticText* m_text_resolution;
wxWindow* m_resolution_options[RESOLUTION_OPTIONS_NUM]; wxWindow* m_resolution_options[RESOLUTION_OPTIONS_NUM];
wxScrolledWindow *m_panel; wxScrolledWindow *m_panel;
+9 -2
View File
@@ -1041,10 +1041,12 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
for (auto el : {"wipe_tower_rotation_angle", "wipe_tower_cone_angle", for (auto el : {"wipe_tower_rotation_angle", "wipe_tower_cone_angle",
"wipe_tower_extra_spacing", "wipe_tower_max_purge_speed", "wipe_tower_extra_spacing", "wipe_tower_max_purge_speed",
"wipe_tower_bridging", "wipe_tower_extra_flow", "wipe_tower_bridging", "wipe_tower_extra_flow"})
"wipe_tower_no_sparse_layers"})
toggle_line(el, have_prime_tower && supports_wipe_tower_2); toggle_line(el, have_prime_tower && supports_wipe_tower_2);
// Orca: both tower generators skip sparse layers, so this is not a wipe tower 2 exclusive.
toggle_line("wipe_tower_no_sparse_layers", have_prime_tower);
WipeTowerWallType wipe_tower_wall_type = config->opt_enum<WipeTowerWallType>("wipe_tower_wall_type"); WipeTowerWallType wipe_tower_wall_type = config->opt_enum<WipeTowerWallType>("wipe_tower_wall_type");
bool have_rib_wall = (wipe_tower_wall_type == WipeTowerWallType::wtwRib)&&have_prime_tower; bool have_rib_wall = (wipe_tower_wall_type == WipeTowerWallType::wtwRib)&&have_prime_tower;
toggle_line("wipe_tower_cone_angle", have_prime_tower && supports_wipe_tower_2 && wipe_tower_wall_type == WipeTowerWallType::wtwCone); toggle_line("wipe_tower_cone_angle", have_prime_tower && supports_wipe_tower_2 && wipe_tower_wall_type == WipeTowerWallType::wtwCone);
@@ -1055,6 +1057,10 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
toggle_line("single_extruder_multi_material_priming", !bSEMM && have_prime_tower && supports_wipe_tower_2); toggle_line("single_extruder_multi_material_priming", !bSEMM && have_prime_tower && supports_wipe_tower_2);
bool use_cyclic_ordering = config->opt_enum<ToolChangeOrderingType>("toolchange_ordering") == ToolChangeOrderingType::Cyclic;
toggle_line("toolchange_cyclic_order", use_cyclic_ordering);
toggle_line("toolchange_cyclic_first_layer", use_cyclic_ordering);
toggle_line("prime_volume",have_prime_tower && (!purge_in_primetower || !bSEMM)); toggle_line("prime_volume",have_prime_tower && (!purge_in_primetower || !bSEMM));
for (auto el : {"flush_into_infill", "flush_into_support", "flush_into_objects"}) for (auto el : {"flush_into_infill", "flush_into_support", "flush_into_objects"})
@@ -1128,6 +1134,7 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
bool has_detect_overhang_wall = config->opt_bool("detect_overhang_wall"); bool has_detect_overhang_wall = config->opt_bool("detect_overhang_wall");
bool has_overhang_reverse = config->opt_bool("overhang_reverse"); bool has_overhang_reverse = config->opt_bool("overhang_reverse");
bool allow_overhang_reverse = !has_spiral_vase; bool allow_overhang_reverse = !has_spiral_vase;
toggle_line("unsupported_wall_last", has_detect_overhang_wall);
toggle_line("overhang_reverse", allow_overhang_reverse); toggle_line("overhang_reverse", allow_overhang_reverse);
toggle_line("overhang_reverse_internal_only", allow_overhang_reverse && has_overhang_reverse); toggle_line("overhang_reverse_internal_only", allow_overhang_reverse && has_overhang_reverse);
bool has_overhang_reverse_internal_only = config->opt_bool("overhang_reverse_internal_only"); bool has_overhang_reverse_internal_only = config->opt_bool("overhang_reverse_internal_only");
+11
View File
@@ -188,6 +188,17 @@ wxString get_string_value(const std::string& opt_key, const DynamicPrintConfig&
out = double_to_string(opt->value) + (opt->percent ? "%" : ""); out = double_to_string(opt->value) + (opt->percent ? "%" : "");
return out; return out;
} }
case coFloatsOrPercents: {
const auto* values = static_cast<const ConfigOptionVector<FloatOrPercent>*>(option);
// Orca: Preset comparison may request the entire vector instead of an indexed entry.
if (orig_opt_idx < 0)
return from_u8(option->serialize());
if (opt_idx < values->size()) {
const FloatOrPercent& value = values->get_at(opt_idx);
return double_to_string(value.value) + (value.percent ? "%" : "");
}
return _L("Undefined");
}
case coEnum: { case coEnum: {
return get_string_from_enum(pure_key, config, return get_string_from_enum(pure_key, config,
pure_key == "top_surface_pattern" || pure_key == "top_surface_pattern" ||
+1 -3
View File
@@ -35,9 +35,7 @@ ConnectPrinterDialog::ConnectPrinterDialog(wxWindow *parent, wxWindowID id, cons
sizer_connect = new wxBoxSizer(wxHORIZONTAL); sizer_connect = new wxBoxSizer(wxHORIZONTAL);
m_textCtrl_code = new TextInput(this, wxEmptyString); m_textCtrl_code = new TextInput(this, wxEmptyString);
// OrcaSonar uses a 12-character base32 access code. Keep this field long m_textCtrl_code->GetTextCtrl()->SetMaxLength(10);
// enough for it while retaining the existing validation for LAN codes.
m_textCtrl_code->GetTextCtrl()->SetMaxLength(12);
m_textCtrl_code->SetFont(Label::Body_14); m_textCtrl_code->SetFont(Label::Body_14);
m_textCtrl_code->SetCornerRadius(FromDIP(5)); m_textCtrl_code->SetCornerRadius(FromDIP(5));
m_textCtrl_code->SetSize(wxSize(FromDIP(330), FromDIP(40))); m_textCtrl_code->SetSize(wxSize(FromDIP(330), FromDIP(40)));
@@ -1,7 +1,5 @@
#include "DevConfigUtil.h" #include "DevConfigUtil.h"
#include "slic3r/GUI/DeviceManager.hpp"
#include <wx/dir.h> #include <wx/dir.h>
#include <boost/filesystem/operations.hpp> #include <boost/filesystem/operations.hpp>
#include "../I18N.hpp" #include "../I18N.hpp"
@@ -43,19 +41,6 @@ static void _toolhead_translation_markers()
std::string DevPrinterConfigUtil::m_resource_file_path = ""; std::string DevPrinterConfigUtil::m_resource_file_path = "";
bool DevPrinterConfigUtil::is_printer_model_compatible(const std::string& source_model, MachineObject& machine)
{
const std::string& target_model = machine.printer_type;
if (is_optional_printer_model_id(source_model) || is_optional_printer_model_id(target_model))
return true;
if (source_model == target_model)
return true;
const auto compatible_machine = machine.get_compatible_machine();
return std::find(compatible_machine.begin(), compatible_machine.end(), source_model) != compatible_machine.end();
}
std::map<std::string, std::string> DevPrinterConfigUtil::get_all_model_id_with_name() std::map<std::string, std::string> DevPrinterConfigUtil::get_all_model_id_with_name()
{ {
@@ -25,8 +25,6 @@
namespace Slic3r namespace Slic3r
{ {
class MachineObject;
/// Toolhead component type (extruder / nozzle / hotend) /// Toolhead component type (extruder / nozzle / hotend)
enum class ToolHeadComponent { enum class ToolHeadComponent {
Extruder, Extruder,
@@ -61,10 +59,6 @@ public:
/*printer*/ /*printer*/
// info // info
static std::map<std::string, std::string> get_all_model_id_with_name(); static std::map<std::string, std::string> get_all_model_id_with_name();
// A printer agent may not know the physical model. Keep that case optional so
// model compatibility checks do not turn missing identity into a hard error.
static bool is_printer_model_compatible(const std::string& source_model, MachineObject& machine);
static bool is_optional_printer_model_id(const std::string& model_id) { return model_id.empty(); }
static std::string get_printer_type(const std::string& type_str) { return get_value_from_config<std::string>(type_str, "printer_type"); } static std::string get_printer_type(const std::string& type_str) { return get_value_from_config<std::string>(type_str, "printer_type"); }
static std::string get_printer_display_name(const std::string& type_str) { return get_value_from_config<std::string>(type_str, "display_name"); } static std::string get_printer_display_name(const std::string& type_str) { return get_value_from_config<std::string>(type_str, "display_name"); }
static std::string get_printer_series_str(std::string type_str) { return get_value_from_config<std::string>(type_str, "printer_series"); } static std::string get_printer_series_str(std::string type_str) { return get_value_from_config<std::string>(type_str, "printer_series"); }
+3 -3
View File
@@ -762,9 +762,9 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS
{ {
curr_tray->remain = -1; curr_tray->remain = -1;
} }
// The tray objects are reused across status updates. Reset this if (tray_it->contains("tray_slot_placeholder")) {
// state when a previously empty slot receives a filament again. curr_tray->is_slot_placeholder = true;
curr_tray->is_slot_placeholder = tray_it->contains("tray_slot_placeholder"); }
int ams_id_int = 0; int ams_id_int = 0;
int tray_id_int = 0; int tray_id_int = 0;
try try
+24 -89
View File
@@ -3,7 +3,6 @@
#include <exception> #include <exception>
#include "DevManager.h" #include "DevManager.h"
#include "CloudProvider.hpp"
#include "DevUtil.h" #include "DevUtil.h"
// TODO: remove this include // TODO: remove this include
@@ -15,8 +14,6 @@
#include "libslic3r/Time.hpp" #include "libslic3r/Time.hpp"
#include "IPrinterAgent.hpp"
using namespace nlohmann; using namespace nlohmann;
namespace { namespace {
@@ -267,10 +264,6 @@ namespace Slic3r
/* update userMachineList info */ /* update userMachineList info */
auto it = userMachineList.find(dev_id); auto it = userMachineList.find(dev_id);
if (it != userMachineList.end()) { if (it != userMachineList.end()) {
// A reused entry may have been created while another printer agent was active.
// The response was obtained through the current agent, so move ownership with
// the entry; otherwise agent-scoped lists hide it after a preset switch.
it->second->printer_agent_id = get_current_printer_agent_id();
if (it->second->get_dev_ip() != dev_ip || if (it->second->get_dev_ip() != dev_ip ||
it->second->bind_state != bind_state || it->second->bind_state != bind_state ||
it->second->bind_sec_link != sec_link || it->second->bind_sec_link != sec_link ||
@@ -301,9 +294,6 @@ namespace Slic3r
// update properties // update properties
/* ip changed */ /* ip changed */
obj = it->second; obj = it->second;
// A reused LAN entry may have been discovered while another printer agent was
// active. The current discovery message establishes ownership for this agent.
obj->printer_agent_id = get_current_printer_agent_id();
if (obj->get_dev_ip().compare(dev_ip) != 0) { if (obj->get_dev_ip().compare(dev_ip) != 0) {
if ( connection_name.empty() ) { if ( connection_name.empty() ) {
@@ -415,9 +405,6 @@ namespace Slic3r
auto it = localMachineList.find(machine.dev_id); auto it = localMachineList.find(machine.dev_id);
if (it != localMachineList.end()) { if (it != localMachineList.end()) {
obj = it->second; obj = it->second;
// insert_local_device is called by the active agent, so a reused entry must follow
// that agent as well; otherwise the agent-scoped printer list hides it.
obj->printer_agent_id = get_current_printer_agent_id();
} else { } else {
obj = new MachineObject(this, m_agent, machine.dev_name, machine.dev_id, machine.dev_ip); obj = new MachineObject(this, m_agent, machine.dev_name, machine.dev_id, machine.dev_ip);
obj->printer_agent_id = get_current_printer_agent_id(); obj->printer_agent_id = get_current_printer_agent_id();
@@ -510,7 +497,7 @@ namespace Slic3r
MachineObject* DeviceManager::get_my_machine(std::string dev_id) MachineObject* DeviceManager::get_my_machine(std::string dev_id)
{ {
auto list = get_my_machine_list(get_current_printer_agent_id()); auto list = get_my_machine_list();
auto it = list.find(dev_id); auto it = list.find(dev_id);
if (it != list.end()) if (it != list.end())
{ {
@@ -547,15 +534,25 @@ namespace Slic3r
OnSelectedMachineChanged(previous_selected_machine, selected_machine); OnSelectedMachineChanged(previous_selected_machine, selected_machine);
} }
void DeviceManager::clear_other_devices() void DeviceManager::clear_other_devices(const std::string& target_agent_id)
{ {
// Device entries are now scoped by printer_agent_id when they are presented. Keep // why: on agent swap, keep "My Devices" but drop the transient "Other Devices"
// agent-owned discoveries across a switch so agents without automatic discovery (and // Those belong to the previous agent's network scan; the new agent's start_discovery re-populates its own.
// plugins whose devices have not received an access code yet) do not lose their list. //
// Entries without an owner are legacy/unscoped and cannot safely be shown. // Also drop "My Devices" stamped by a different agent than the one we're swapping to
// (target_agent_id, passed by the caller since the live agent hasn't been repointed yet
// at this point): otherwise a device first discovered under agent A survives every swap
// with a stale printer_agent_id, stays hidden from every agent's filtered list, and only
// gets re-tagged if something happens to delete and re-create it (e.g. account logout).
// Dropping it here instead lets the new agent's start_discovery re-insert and re-stamp it
// like any other fresh device.
const auto my = get_my_machine_list();
for (auto it = localMachineList.begin(); it != localMachineList.end();) for (auto it = localMachineList.begin(); it != localMachineList.end();)
{ {
if (!it->second || it->second->printer_agent_id.empty()) const bool is_my_device = my.find(it->first) != my.end();
const bool agent_mismatch = !target_agent_id.empty() && it->second &&
it->second->printer_agent_id != target_agent_id;
if (!is_my_device || agent_mismatch)
{ {
delete it->second; delete it->second;
it = localMachineList.erase(it); it = localMachineList.erase(it);
@@ -571,22 +568,8 @@ namespace Slic3r
{ {
BOOST_LOG_TRIVIAL(info) << "set_selected_machine=" << dev_id BOOST_LOG_TRIVIAL(info) << "set_selected_machine=" << dev_id
<< " cur_selected=" << selected_machine; << " cur_selected=" << selected_machine;
auto my_machine_list = get_my_machine_list(get_current_printer_agent_id()); auto my_machine_list = get_my_machine_list();
auto it = my_machine_list.find(dev_id); auto it = my_machine_list.find(dev_id);
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: set_selected_machine lookup dev_id=" << dev_id
<< " found=" << (it != my_machine_list.end())
<< " my_machine_count=" << my_machine_list.size()
<< " current_agent=" << get_current_printer_agent_id()
<< " provider=" << GUI::wxGetApp().get_printer_cloud_provider();
if (it != my_machine_list.end() && it->second) {
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: target machine dev_id=" << it->second->get_dev_id()
<< " printer_agent_id=" << it->second->printer_agent_id
<< " connection_type=" << it->second->connection_type()
<< " dev_connection_type=" << it->second->dev_connection_type;
} else if (!dev_id.empty()) {
BOOST_LOG_TRIVIAL(warning) << "Orca diagnostic: target machine was not found in the current agent's machine list";
return false;
}
// disconnect last if dev_id difference from previous one // disconnect last if dev_id difference from previous one
auto last_selected = my_machine_list.find(selected_machine); auto last_selected = my_machine_list.find(selected_machine);
@@ -597,9 +580,7 @@ namespace Slic3r
m_agent->disconnect_printer(); m_agent->disconnect_printer();
} }
else if (last_selected->second->connection_type() == "cloud") { else if (last_selected->second->connection_type() == "cloud") {
const int result = m_agent->set_user_selected_machine(""); m_agent->set_user_selected_machine("");
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: cleared previous cloud selection dev_id="
<< selected_machine << " result=" << result;
} }
} }
@@ -651,9 +632,7 @@ namespace Slic3r
{ {
// diff dev_id, cloud => set_user_selected_machine(new) // diff dev_id, cloud => set_user_selected_machine(new)
BOOST_LOG_TRIVIAL(info) << "set_selected_machine: select new cloud machine, dev_id =" << dev_id; BOOST_LOG_TRIVIAL(info) << "set_selected_machine: select new cloud machine, dev_id =" << dev_id;
const int result = m_agent->set_user_selected_machine(dev_id); m_agent->set_user_selected_machine(dev_id);
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: set new cloud selection dev_id="
<< dev_id << " result=" << result;
it->second->reset(); it->second->reset();
} }
else else
@@ -681,8 +660,6 @@ namespace Slic3r
selected_machine = dev_id; selected_machine = dev_id;
record_user_last_machine(selected_machine); record_user_last_machine(selected_machine);
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: DeviceManager selection complete selected_machine="
<< selected_machine;
return true; return true;
} }
@@ -713,9 +690,7 @@ namespace Slic3r
dev_list.push_back(it->first); dev_list.push_back(it->first);
BOOST_LOG_TRIVIAL(trace) << "add_user_subscribe: " << it->first; BOOST_LOG_TRIVIAL(trace) << "add_user_subscribe: " << it->first;
} }
const int result = m_agent->add_subscribe(dev_list); m_agent->add_subscribe(dev_list);
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: add_user_subscribe count=" << dev_list.size()
<< " result=" << result;
} }
@@ -728,9 +703,7 @@ namespace Slic3r
dev_list.push_back(it->first); dev_list.push_back(it->first);
BOOST_LOG_TRIVIAL(trace) << "del_user_subscribe: " << it->first; BOOST_LOG_TRIVIAL(trace) << "del_user_subscribe: " << it->first;
} }
const int result = m_agent->del_subscribe(dev_list); m_agent->del_subscribe(dev_list);
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: del_user_subscribe count=" << dev_list.size()
<< " result=" << result;
} }
void DeviceManager::subscribe_device_list(std::vector<std::string> dev_list) void DeviceManager::subscribe_device_list(std::vector<std::string> dev_list)
@@ -849,23 +822,7 @@ namespace Slic3r
try try
{ {
json j = json::parse(body); json j = json::parse(body);
const std::string provider = GUI::wxGetApp().get_printer_cloud_provider();
const bool has_request_context = j.contains("provider") && j.contains("agent_id") && j.contains("generation");
const std::string provider = j.contains("provider") ? j["provider"].get<std::string>()
: GUI::wxGetApp().get_printer_cloud_provider();
const std::string agent_id = j.contains("agent_id") ? j["agent_id"].get<std::string>()
: get_current_printer_agent_id();
const std::uint64_t generation = j.value("generation", std::uint64_t(0));
if (has_request_context &&
(provider != GUI::wxGetApp().get_printer_cloud_provider() ||
agent_id != get_current_printer_agent_id() ||
generation != (m_agent ? m_agent->get_user_machine_list_generation() : 0))) {
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": ignoring stale response provider="
<< provider << " agent_id=" << agent_id
<< " generation=" << generation;
return;
}
#if !BBL_RELEASE_TO_PUBLIC #if !BBL_RELEASE_TO_PUBLIC
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": " << j; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": " << j;
@@ -888,14 +845,11 @@ namespace Slic3r
/* update field */ /* update field */
obj = iter->second; obj = iter->second;
obj->set_dev_id(dev_id); obj->set_dev_id(dev_id);
// A device can be rediscovered by a different agent after a preset
// switch while retaining the same MachineObject instance.
obj->printer_agent_id = agent_id;
} }
else else
{ {
obj = new MachineObject(this, m_agent, "", "", ""); obj = new MachineObject(this, m_agent, "", "", "");
obj->printer_agent_id = agent_id; obj->printer_agent_id = get_current_printer_agent_id();
if (m_agent) if (m_agent)
{ {
obj->set_bind_status(m_agent->get_user_name(provider)); obj->set_bind_status(m_agent->get_user_name(provider));
@@ -910,12 +864,6 @@ namespace Slic3r
if (!obj) continue; if (!obj) continue;
// Orca cloud printers are only ever delivered through this REST
// account list; tag them so DeviceManager's cloud/lan branches
// (subscribe + deselect in set_selected_machine) treat them right.
if (provider == ORCA_CLOUD_PROVIDER)
obj->dev_connection_type = "cloud";
if (!elem["dev_id"].is_null()) if (!elem["dev_id"].is_null())
obj->set_dev_id(elem["dev_id"].get<std::string>()); obj->set_dev_id(elem["dev_id"].get<std::string>());
if (!elem["dev_name"].is_null()) if (!elem["dev_name"].is_null())
@@ -947,12 +895,6 @@ namespace Slic3r
acc_code.erase(std::remove(acc_code.begin(), acc_code.end(), '\n'), acc_code.end()); acc_code.erase(std::remove(acc_code.begin(), acc_code.end(), '\n'), acc_code.end());
obj->set_access_code(acc_code); obj->set_access_code(acc_code);
} }
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: parsed cloud machine dev_id=" << dev_id
<< " name=" << obj->get_dev_name()
<< " agent_id=" << obj->printer_agent_id
<< " connection_type=" << obj->connection_type()
<< " online=" << obj->m_is_online;
} }
//remove MachineObject from userMachineList //remove MachineObject from userMachineList
@@ -968,9 +910,6 @@ namespace Slic3r
iterat++; iterat++;
} }
} }
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: parse_user_print_info complete provider=" << provider
<< " parsed_count=" << new_list.size()
<< " stored_count=" << userMachineList.size();
} }
} }
catch (std::exception& e) catch (std::exception& e)
@@ -987,14 +926,10 @@ namespace Slic3r
unsigned int http_code; unsigned int http_code;
std::string body; std::string body;
int result = m_agent->get_user_print_info(&http_code, &body, provider); int result = m_agent->get_user_print_info(&http_code, &body, provider);
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: get_user_print_info provider=" << provider
<< " result=" << result << " http_code=" << http_code
<< " body_bytes=" << body.size();
if (result == 0) if (result == 0)
{ {
// parse_user_print_info and on_machine_alive (SSDP for discovery) both mutate the same userMachineList map. // parse_user_print_info and on_machine_alive (SSDP for discovery) both mutate the same userMachineList map.
// on_machine_alive mutates the map on the UI thread, do the same for parse_user_print_info. // on_machine_alive mutates the map on the UI thread, do the same for parse_user_print_info.
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: queueing parse_user_print_info on UI thread";
Slic3r::GUI::wxGetApp().CallAfter([this, body]() { parse_user_print_info(body); }); Slic3r::GUI::wxGetApp().CallAfter([this, body]() { parse_user_print_info(body); });
} }
} }
+4 -3
View File
@@ -74,9 +74,10 @@ public:
void erase_user_machine(std::string dev_id) { userMachineList.erase(dev_id); } void erase_user_machine(std::string dev_id) { userMachineList.erase(dev_id); }
void clean_user_info(bool keep_local_selection = false); void clean_user_info(bool keep_local_selection = false);
// Retain agent-owned LAN discoveries across a switch; the active-agent list filter keeps // target_agent_id: id of the agent being swapped to (empty = no agent-mismatch check,
// entries from other agents hidden while allowing them to reappear when switched back. // just the original "drop Other Devices" behavior). Pass the incoming agent's id, not the
void clear_other_devices(); // live one - this runs before the live agent is repointed.
void clear_other_devices(const std::string& target_agent_id = "");
void load_last_machine(); void load_last_machine();
void update_user_machine_list_info(const std::string& provider); void update_user_machine_list_info(const std::string& provider);
+83 -165
View File
@@ -53,7 +53,6 @@
#include "DeviceCore/DevStatus.h" #include "DeviceCore/DevStatus.h"
#include "DeviceCore/DevUpgrade.h" #include "DeviceCore/DevUpgrade.h"
#include "IPrinterAgent.hpp"
#define CALI_DEBUG #define CALI_DEBUG
#define MINUTE_30 1800000 //ms #define MINUTE_30 1800000 //ms
@@ -374,22 +373,8 @@ NozzleVolumeType convert_to_nozzle_type(const std::string &str)
wxString MachineObject::get_printer_type_display_str() const wxString MachineObject::get_printer_type_display_str() const
{ {
std::string display_name = DevPrinterConfigUtil::get_printer_display_name(printer_type); std::string display_name = DevPrinterConfigUtil::get_printer_display_name(printer_type);
// Bambu printers use m_resource_file_path + "/printers/" + type_str + ".json", which is a semantic that only works for their profiles.
// For any other profile, we can simply consult preset bundle if the model_id exists.
if (display_name.empty()) {
for (const auto& [vendor_id, vendor] : GUI::wxGetApp().preset_bundle->vendors) {
for (const auto& model : vendor.models) {
if (printer_type == model.model_id)
display_name = model.name;
}
}
}
if (!display_name.empty()) if (!display_name.empty())
return display_name; return display_name;
else if (printer_type == "orcasonar")
return "OrcaSonar Printer";
else else
return _L("Unknown"); return _L("Unknown");
} }
@@ -1356,6 +1341,7 @@ int MachineObject::command_get_access_code() {
return this->publish_json(j); return this->publish_json(j);
} }
int MachineObject::command_request_push_all(bool request_now) int MachineObject::command_request_push_all(bool request_now)
{ {
auto curr_time = std::chrono::system_clock::now(); auto curr_time = std::chrono::system_clock::now();
@@ -1487,17 +1473,26 @@ int MachineObject::command_upgrade_module(std::string url, std::string module_ty
int MachineObject::command_xyz_abs() int MachineObject::command_xyz_abs()
{ {
return command_with_dialog(m_agent->command_xyz_abs(get_dev_id(), MachineObject::m_sequence_id++, is_lan_mode_printer())); return this->publish_gcode("G90 \n");
} }
int MachineObject::command_auto_leveling() int MachineObject::command_auto_leveling()
{ {
return command_with_dialog(m_agent->command_auto_leveling(get_dev_id(), MachineObject::m_sequence_id++, is_lan_mode_printer())); return this->publish_gcode("G29 \n");
} }
int MachineObject::command_go_home() int MachineObject::command_go_home()
{ {
return command_with_dialog(m_agent->command_go_home(get_dev_id(), this->is_in_printing(), m_support_mqtt_homing, MachineObject::m_sequence_id++, is_lan_mode_printer())); if (m_support_mqtt_homing)
{
json j;
j["print"]["command"] = "back_to_center";
j["print"]["sequence_id"] = std::to_string(MachineObject::m_sequence_id++);
return this->publish_json(j);
}
// gcode command
return this->is_in_printing() ? this->publish_gcode("G28 X\n") : this->publish_gcode("G28 \n");
} }
int MachineObject::command_task_partskip(std::vector<int> part_ids) int MachineObject::command_task_partskip(std::vector<int> part_ids)
@@ -1619,12 +1614,23 @@ int MachineObject::command_stop_buzzer()
int MachineObject::command_set_bed(int temp) int MachineObject::command_set_bed(int temp)
{ {
return command_with_dialog(m_agent->command_set_bed(get_dev_id(), temp, m_support_mqtt_bet_ctrl, MachineObject::m_sequence_id++, is_lan_mode_printer())); if (m_support_mqtt_bet_ctrl)
{
json j;
j["print"]["command"] = "set_bed_temp";
j["print"]["temp"] = temp;
j["print"]["sequence_id"] = std::to_string(MachineObject::m_sequence_id++);
return this->publish_json(j);
}
std::string gcode_str = (boost::format("M140 S%1%\n") % temp).str();
return this->publish_gcode(gcode_str);
} }
int MachineObject::command_set_nozzle(int temp) int MachineObject::command_set_nozzle(int temp)
{ {
return command_with_dialog(m_agent->command_set_nozzle(get_dev_id(), temp, MachineObject::m_sequence_id++, is_lan_mode_printer())); std::string gcode_str = (boost::format("M104 S%1%\n") % temp).str();
return this->publish_gcode(gcode_str);
} }
int MachineObject::command_set_nozzle_new(int nozzle_id, int temp) int MachineObject::command_set_nozzle_new(int nozzle_id, int temp)
@@ -1729,7 +1735,9 @@ int MachineObject::command_ams_user_settings(bool start_read_opt, bool tray_read
int MachineObject::command_ams_calibrate(int ams_id) int MachineObject::command_ams_calibrate(int ams_id)
{ {
return command_with_dialog(m_agent->command_ams_calibrate(get_dev_id(), ams_id, MachineObject::m_sequence_id++, is_lan_mode_printer())); std::string gcode_cmd = (boost::format("M620 C%1% \n") % ams_id).str();
BOOST_LOG_TRIVIAL(trace) << "ams_debug: gcode_cmd" << gcode_cmd;
return this->publish_gcode(gcode_cmd);
} }
int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::string filament_id, std::string setting_id, std::string tray_color, std::string tray_type, int nozzle_temp_min, int nozzle_temp_max) int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::string filament_id, std::string setting_id, std::string tray_color, std::string tray_type, int nozzle_temp_min, int nozzle_temp_max)
@@ -1767,7 +1775,9 @@ int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::s
int MachineObject::command_ams_refresh_rfid(std::string tray_id) int MachineObject::command_ams_refresh_rfid(std::string tray_id)
{ {
return command_with_dialog(m_agent->command_ams_refresh_rfid(get_dev_id(), tray_id, MachineObject::m_sequence_id++, is_lan_mode_printer())); std::string gcode_cmd = (boost::format("M620 R%1% \n") % tray_id).str();
BOOST_LOG_TRIVIAL(trace) << "ams_debug: gcode_cmd" << gcode_cmd;
return this->publish_gcode(gcode_cmd);
} }
int MachineObject::command_ams_refresh_rfid2(int ams_id, int slot_id) int MachineObject::command_ams_refresh_rfid2(int ams_id, int slot_id)
@@ -1780,16 +1790,12 @@ int MachineObject::command_ams_refresh_rfid2(int ams_id, int slot_id)
return this->publish_json(j); return this->publish_json(j);
} }
int MachineObject::command_start_camera()
{
if (!m_agent) return -1;
return m_agent->command_start_camera(get_dev_id());
}
int MachineObject::command_ams_select_tray(std::string tray_id) int MachineObject::command_ams_select_tray(std::string tray_id)
{ {
return command_with_dialog(m_agent->command_ams_select_tray(get_dev_id(), tray_id, MachineObject::m_sequence_id++, is_lan_mode_printer())); std::string gcode_cmd = (boost::format("M620 P%1% \n") % tray_id).str();
BOOST_LOG_TRIVIAL(trace) << "ams_debug: gcode_cmd" << gcode_cmd;
return this->publish_gcode(gcode_cmd);
} }
int MachineObject::command_ams_control(std::string action) int MachineObject::command_ams_control(std::string action)
@@ -1948,9 +1954,47 @@ int MachineObject::command_ams_air_print_detect(bool air_print_detect)
int MachineObject::command_axis_control(std::string axis, double unit, double input_val, int speed) int MachineObject::command_axis_control(std::string axis, double unit, double input_val, int speed)
{ {
return command_with_dialog(m_agent->command_axis_control(get_dev_id(), axis, unit, input_val, speed, is_core_xy(), if (m_support_mqtt_axis_control)
m_support_mqtt_axis_control, MachineObject::m_sequence_id++, {
is_lan_mode_printer())); int dir = input_val > 0 ? 1 : -1;
// i3-arch printers move the bed for Y/Z, so the on-screen direction is
// reversed — same negation the g-code fallback below applies.
if (!is_core_xy() && (axis.compare("Y") == 0 || axis.compare("Z") == 0)) {
dir = -dir;
}
json j;
j["print"]["command"] = "xyz_ctrl";
j["print"]["axis"] = axis;
j["print"]["dir"] = dir;
j["print"]["mode"] = (std::abs(input_val) >= 10) ? 1 : 0;
j["print"]["sequence_id"] = std::to_string(MachineObject::m_sequence_id++);
return this->publish_json(j);
}
double value = input_val;
if (!is_core_xy()) {
if ( axis.compare("Y") == 0
|| axis.compare("Z") == 0) {
value = -1.0 * input_val;
}
}
char cmd[256];
if (axis.compare("X") == 0
|| axis.compare("Y") == 0
|| axis.compare("Z") == 0) {
sprintf(cmd, "M211 S \nM211 X1 Y1 Z1\nM1002 push_ref_mode\nG91 \nG1 %s%0.1f F%d\nM1002 pop_ref_mode\nM211 R\n", axis.c_str(), value * unit, speed);
}
else if (axis.compare("E") == 0) {
sprintf(cmd, "M83 \nG0 %s%0.1f F%d\n", axis.c_str(), value * unit, speed);
}
else {
return -1;
}
return this->publish_gcode(cmd);
} }
int MachineObject::command_extruder_control(int nozzle_id, double val) int MachineObject::command_extruder_control(int nozzle_id, double val)
@@ -2575,12 +2619,7 @@ void MachineObject::reset()
vt_slot.erase(vt_slot.begin() + 1); vt_slot.erase(vt_slot.begin() + 1);
} }
} }
// why: reset reuses MachineObject, so release its lazy subtask subtask_ = nullptr;
// before dropping the pointer to prevent reconnect leaks.
if (subtask_) {
delete subtask_;
subtask_ = nullptr;
}
has_extra_flow_type = false; has_extra_flow_type = false;
m_partskip_ids.clear(); m_partskip_ids.clear();
} }
@@ -2590,24 +2629,10 @@ void MachineObject::set_print_state(std::string status)
print_status = status; print_status = status;
} }
// why: printer agents can report progress without BBL cloud task identity.
void MachineObject::update_print_progress(const json& value)
{
if (value.is_string())
mc_print_percent = stoi(value.get<std::string>());
else if (value.is_number_integer())
mc_print_percent = value.get<int>();
else
return;
if (BBLSubTask* curr_task = get_subtask())
curr_task->task_progress = mc_print_percent;
}
int MachineObject::connect(bool use_openssl) int MachineObject::connect(bool use_openssl)
{ {
if (get_dev_ip().empty()) return -1; if (get_dev_ip().empty()) return -1;
std::string username = m_agent ? m_agent->default_lan_username() : std::string(); std::string username = "bblp";
std::string password = get_access_code(); std::string password = get_access_code();
if (m_agent) { if (m_agent) {
@@ -2717,14 +2742,6 @@ int MachineObject::publish_json(const json& json_item, int qos, int flag)
BOOST_LOG_TRIVIAL(error) << "publish_json: " << json_item.dump() << " code: " << rtn; BOOST_LOG_TRIVIAL(error) << "publish_json: " << json_item.dump() << " code: " << rtn;
} }
// why: the agent is the only thing that knows what it can translate, so it reports
// not-supported in its return value and this - the single funnel every command_* builder
// passes through - is the one place that turns it into something the user sees. No list of
// unsupported commands is needed anywhere: an agent that has no case for a command says so.
if (rtn == ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED || rtn == ORCA_NETWORK_ERR_CAP_NOT_AVAILABLE) {
show_unsupported_dlg(rtn);
}
return rtn; return rtn;
} }
@@ -3029,13 +3046,6 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_
} }
} catch (...) {} } catch (...) {}
try {
if (j.contains("info"))
parse_new_info2(j["info"]);
} catch (...) {
BOOST_LOG_TRIVIAL(error) << "parse_json: failed to parse OrcaSonar capability info";
}
try { try {
if (auto ptr = m_fila_system->GetAmsFirmwareSwitch().lock()) { if (auto ptr = m_fila_system->GetAmsFirmwareSwitch().lock()) {
ptr->ParseFirmwareSwitch(j); ptr->ParseFirmwareSwitch(j);
@@ -3288,7 +3298,10 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_
print_type = jj["print_type"].get<std::string>(); print_type = jj["print_type"].get<std::string>();
} }
if (jj.contains("mc_percent")) { if (jj.contains("mc_percent")) {
update_print_progress(jj["mc_percent"]); if (jj["mc_percent"].is_string())
mc_print_percent = stoi(j["print"]["mc_percent"].get<std::string>());
else if (jj["mc_percent"].is_number_integer())
mc_print_percent = j["print"]["mc_percent"].get<int>();
} }
if (jj.contains("mc_print_sub_stage")) { if (jj.contains("mc_print_sub_stage")) {
if (jj["mc_print_sub_stage"].is_number_integer()) if (jj["mc_print_sub_stage"].is_number_integer())
@@ -3458,9 +3471,6 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_
this->task_id_ = jj["task_id"].get<std::string>(); this->task_id_ = jj["task_id"].get<std::string>();
} }
if (jj.contains("thumbnail_url") && jj["thumbnail_url"].is_string())
m_agent_thumbnail_url = jj["thumbnail_url"].get<std::string>();
if (jj.contains("job_attr")) { if (jj.contains("job_attr")) {
int jobAttr = jj["job_attr"].get<int>(); int jobAttr = jj["job_attr"].get<int>();
jobState_ = get_flag_bits(jobAttr, 4, 4); jobState_ = get_flag_bits(jobAttr, 4, 4);
@@ -3506,6 +3516,7 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_
update_slice_info(jj["project_id"].get<std::string>(), jj["profile_id"].get<std::string>(), jj["subtask_id"].get<std::string>(), plate_index); update_slice_info(jj["project_id"].get<std::string>(), jj["profile_id"].get<std::string>(), jj["subtask_id"].get<std::string>(), plate_index);
BBLSubTask* curr_task = get_subtask(); BBLSubTask* curr_task = get_subtask();
if (curr_task) { if (curr_task) {
curr_task->task_progress = mc_print_percent;
curr_task->printing_status = print_status; curr_task->printing_status = print_status;
curr_task->task_id = jj["subtask_id"].get<std::string>(); curr_task->task_id = jj["subtask_id"].get<std::string>();
} }
@@ -3808,7 +3819,6 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_
has_ipcam = true; has_ipcam = true;
} else { } else {
has_ipcam = false; has_ipcam = false;
webcam_stream_url.clear();
} }
} }
if (ipcam.contains("resolution")) { if (ipcam.contains("resolution")) {
@@ -3843,9 +3853,6 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_
liveview_local = local_rtsp_url.empty() ? LVL_None : local_rtsp_url == "disable" liveview_local = local_rtsp_url.empty() ? LVL_None : local_rtsp_url == "disable"
? LVL_Disable : boost::algorithm::starts_with(local_rtsp_url, "rtsps") ? LVL_Rtsps : LVL_Rtsp; ? LVL_Disable : boost::algorithm::starts_with(local_rtsp_url, "rtsps") ? LVL_Rtsps : LVL_Rtsp;
} }
if (ipcam.contains("stream_url") && ipcam["stream_url"].is_string()) {
webcam_stream_url = ipcam["stream_url"].get<std::string>();
}
if (ipcam.contains("tutk_server")) { if (ipcam.contains("tutk_server")) {
tutk_state = ipcam["tutk_server"].get<std::string>(); tutk_state = ipcam["tutk_server"].get<std::string>();
} }
@@ -5425,86 +5432,6 @@ void MachineObject::parse_new_info(json print)
} }
} }
void MachineObject::parse_new_info2(const json& info)
{
if (!info.is_object() || info.value("command", "") != "get_capabilities")
return;
const auto capabilities_it = info.find("capabilities");
if (capabilities_it == info.end() || !capabilities_it->is_object())
return;
const auto flags_it = capabilities_it->find("flags");
if (flags_it == capabilities_it->end() || !flags_it->is_object())
return;
const json& flags = *flags_it;
BOOST_LOG_TRIVIAL(info) << "parse_new_info2: OrcaSonar capability flags=" << flags.dump();
auto parse_bool = [&flags](const char* name, bool& target) {
const auto it = flags.find(name);
if (it != flags.end() && it->is_boolean())
target = it->get<bool>();
};
parse_bool("support_send_to_sd", is_support_send_to_sdcard);
parse_bool("support_filament_backup", is_support_filament_backup);
parse_bool("support_update_remain", is_support_update_remain);
parse_bool("support_auto_recovery_step_loss", is_support_auto_recovery_step_loss);
parse_bool("support_ams_humidity", is_support_ams_humidity);
parse_bool("support_prompt_sound", is_support_prompt_sound);
parse_bool("support_filament_tangle_detect", is_support_filament_tangle_detect);
parse_bool("support_1080dpi", is_support_1080dpi);
parse_bool("support_cloud_print_only", is_support_cloud_print_only);
parse_bool("support_command_ams_switch", is_support_command_ams_switch);
parse_bool("support_mqtt_alive", is_support_mqtt_alive);
parse_bool("support_motor_noise_cali", is_support_motor_noise_cali);
parse_bool("support_timelapse", is_support_timelapse);
parse_bool("support_user_preset", is_support_user_preset);
parse_bool("support_refresh_nozzle", is_support_refresh_nozzle);
parse_bool("support_flow_calibration", is_support_flow_calibration);
parse_bool("support_build_plate_marker_detect", is_support_build_plate_marker_detect);
parse_bool("support_nozzle_blob_detect", is_support_nozzle_blob_detection);
if (!m_manager->IsMultiMachineEnabled() && !is_support_agora)
parse_bool("support_tunnel_mqtt", is_support_tunnel_mqtt);
const auto bed_leveling_it = flags.find("support_bed_leveling");
if (bed_leveling_it != flags.end() && bed_leveling_it->is_number_integer())
is_support_bed_leveling = bed_leveling_it->get<int>();
auto copy_bool = [&flags](json& target, const char* name) {
const auto it = flags.find(name);
if (it != flags.end() && it->is_boolean())
target[name] = *it;
};
// The capability manifest uses an object for this range, while the legacy
// DeviceCore parser consumes a boolean plus a two-element range array.
json device_config;
copy_bool(device_config, "support_chamber");
copy_bool(device_config, "support_first_layer_inspect");
copy_bool(device_config, "support_ai_monitoring");
copy_bool(device_config, "support_lidar_calibration");
const auto chamber_edit_it = flags.find("support_chamber_temp_edit");
if (chamber_edit_it != flags.end() && chamber_edit_it->is_boolean()) {
device_config["support_chamber_temp_edit"] = *chamber_edit_it;
} else if (chamber_edit_it != flags.end() && chamber_edit_it->is_object()) {
const auto min_it = chamber_edit_it->find("min");
const auto max_it = chamber_edit_it->find("max");
if (min_it != chamber_edit_it->end() && max_it != chamber_edit_it->end() && min_it->is_number() && max_it->is_number()) {
device_config["support_chamber_temp_edit"] = true;
device_config["support_chamber_temp_edit_range"] = {*min_it, *max_it};
}
}
json fan_config;
copy_bool(fan_config, "support_aux_fan");
copy_bool(fan_config, "support_chamber_fan");
m_config->ParseConfig(device_config);
m_fan->ParseV2_0(fan_config);
}
static bool is_hex_digit(char c) { static bool is_hex_digit(char c) {
return std::isxdigit(static_cast<unsigned char>(c)) != 0; return std::isxdigit(static_cast<unsigned char>(c)) != 0;
} }
@@ -6010,15 +5937,6 @@ bool MachineObject::HasAms() const
return m_fila_system->HasAms(); return m_fila_system->HasAms();
} }
int MachineObject::command_with_dialog(int cmd_result)
{
if (!m_agent)
return -1;
if (cmd_result == ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED || cmd_result == ORCA_NETWORK_ERR_CAP_NOT_AVAILABLE)
show_unsupported_dlg(cmd_result);
return cmd_result;
}
void change_the_opacity(wxColour& colour) void change_the_opacity(wxColour& colour)
{ {
if (colour.Alpha() == 255) { if (colour.Alpha() == 255) {
+26 -13
View File
@@ -18,7 +18,6 @@
#include "boost/bimap/bimap.hpp" #include "boost/bimap/bimap.hpp"
#include "libslic3r/calib.hpp" #include "libslic3r/calib.hpp"
#include "libslic3r/Utils.hpp" #include "libslic3r/Utils.hpp"
#include "slic3r/Utils/PrinterNetworkTypes.hpp"
#include "DeviceCore/DevDefs.h" #include "DeviceCore/DevDefs.h"
#include "DeviceCore/DevConfigUtil.h" #include "DeviceCore/DevConfigUtil.h"
@@ -101,6 +100,7 @@ struct DevPrintTaskRatingInfo;
// given nozzle diameter (mm), bucketed per nozzle size to mirror the printer firmware. // given nozzle diameter (mm), bucketed per nozzle size to mirror the printer firmware.
bool is_stringing_prone_filament(const std::string& filament_id, float nozzle_diameter); bool is_stringing_prone_filament(const std::string& filament_id, float nozzle_diameter);
class MachineObject class MachineObject
{ {
private: private:
@@ -307,7 +307,7 @@ public:
bool ams_support_virtual_tray { true }; bool ams_support_virtual_tray { true };
time_t ams_user_setting_start = 0; time_t ams_user_setting_start = 0;
time_t ams_switch_filament_start = 0; time_t ams_switch_filament_start = 0;
AmsStatusMain ams_status_main = AmsStatusMain::AMS_STATUS_MAIN_IDLE; AmsStatusMain ams_status_main;
int ams_status_sub; int ams_status_sub;
int ams_version = 0; int ams_version = 0;
@@ -547,12 +547,30 @@ public:
bool xcam_first_layer_inspector { false }; bool xcam_first_layer_inspector { false };
time_t xcam_first_layer_hold_start = 0; time_t xcam_first_layer_hold_start = 0;
std::string local_rtsp_url; std::string local_rtsp_url;
std::string webcam_stream_url;
std::string tutk_state; std::string tutk_state;
LiveviewLocal liveview_local{ LiveviewLocal::LVL_None }; enum LiveviewLocal {
LiveviewRemote liveview_remote{ LiveviewRemote::LVR_None}; LVL_None,
FileLocal file_local{ FileLocal::FL_None }; LVL_Disable,
FileRemote file_remote{ FileRemote::FR_None }; LVL_Local,
LVL_Rtsps,
LVL_Rtsp
} liveview_local{ LVL_None };
enum LiveviewRemote {
LVR_None,
LVR_Tutk,
LVR_Agora,
LVR_TutkAgora
} liveview_remote{ LVR_None };
enum FileLocal {
FL_None,
FL_Local
} file_local{ FL_None };
enum FileRemote {
FR_None,
FR_Tutk,
FR_Agora,
FR_TutkAgora
} file_remote{ FR_None };
enum PlateMakerDectect : int enum PlateMakerDectect : int
{ {
@@ -690,8 +708,6 @@ public:
std::string subtask_id_; std::string subtask_id_;
std::string job_id_; std::string job_id_;
std::string last_subtask_id_; std::string last_subtask_id_;
// note: printer-agent-supplied thumbnail url, empty when the agent supplies none.
std::string m_agent_thumbnail_url;
BBLSliceInfo* slice_info {nullptr}; BBLSliceInfo* slice_info {nullptr};
boost::thread* get_slice_info_thread { nullptr }; boost::thread* get_slice_info_thread { nullptr };
boost::thread* get_model_task_thread { nullptr }; boost::thread* get_model_task_thread { nullptr };
@@ -749,7 +765,6 @@ public:
int command_set_printer_nozzle(std::string nozzle_type, float diameter); int command_set_printer_nozzle(std::string nozzle_type, float diameter);
int command_set_printer_nozzle2(int id, std::string nozzle_type, float diameter); int command_set_printer_nozzle2(int id, std::string nozzle_type, float diameter);
int command_get_access_code(); int command_get_access_code();
int command_start_camera();
int command_ack_proceed(json& proceed); int command_ack_proceed(json& proceed);
int command_purification_disable(); int command_purification_disable();
int command_dont_remind_next_time(json& mqtt_guard_json); int command_dont_remind_next_time(json& mqtt_guard_json);
@@ -879,7 +894,6 @@ public:
static bool is_in_printing_status(std::string status); static bool is_in_printing_status(std::string status);
void set_print_state(std::string status); void set_print_state(std::string status);
void update_print_progress(const json& value);
bool is_connected(); bool is_connected();
bool is_connecting(); bool is_connecting();
@@ -947,7 +961,6 @@ public:
/*for parse new info*/ /*for parse new info*/
bool check_enable_np(const json& print) const; bool check_enable_np(const json& print) const;
void parse_new_info(json print); void parse_new_info(json print);
void parse_new_info2(const json& info);
int get_flag_bits(std::string str, int start, int count = 1) const; int get_flag_bits(std::string str, int start, int count = 1) const;
uint32_t get_flag_bits_no_border(std::string str, int start_idx, int count = 1) const; uint32_t get_flag_bits_no_border(std::string str, int start_idx, int count = 1) const;
int get_flag_bits(int num, int start, int count = 1, int base = 10) const; int get_flag_bits(int num, int start, int count = 1, int base = 10) const;
@@ -976,7 +989,7 @@ public:
void command_set_save_remote_print_file_to_storage(bool save); void command_set_save_remote_print_file_to_storage(bool save);
private: private:
int command_with_dialog(int cmd_result);
/* xcam door open check*/ /* xcam door open check*/
bool is_support_door_open_check = false; bool is_support_door_open_check = false;
DoorOpenCheckState xcam_door_open_check = DoorOpenCheckState::DOOR_OPEN_CHECK_DISABLE; DoorOpenCheckState xcam_door_open_check = DoorOpenCheckState::DOOR_OPEN_CHECK_DISABLE;
+104 -2
View File
@@ -4316,6 +4316,9 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt)
if (can_sequential_clearance_show_in_gizmo()) if (can_sequential_clearance_show_in_gizmo())
update_sequential_clearance(); update_sequential_clearance();
} else { } else {
// Orca: by-layer counterpart, for a prime tower compacted by "No sparse layers".
if (current_printer_technology() == ptFFF && can_sequential_clearance_show_in_gizmo())
update_compacted_wipe_tower_clearance();
if (c == GLGizmosManager::EType::Move || if (c == GLGizmosManager::EType::Move ||
c == GLGizmosManager::EType::Scale || c == GLGizmosManager::EType::Scale ||
c == GLGizmosManager::EType::Rotate) c == GLGizmosManager::EType::Rotate)
@@ -4549,8 +4552,12 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt)
TransformationType trafo_type; TransformationType trafo_type;
trafo_type.set_relative(); trafo_type.set_relative();
m_selection.translate(cur_pos - m_mouse.drag.start_position_3D, trafo_type); m_selection.translate(cur_pos - m_mouse.drag.start_position_3D, trafo_type);
if (current_printer_technology() == ptFFF && (fff_print()->config().print_sequence == PrintSequence::ByObject)) if (current_printer_technology() == ptFFF) {
update_sequential_clearance(); if (fff_print()->config().print_sequence == PrintSequence::ByObject)
update_sequential_clearance();
else
update_compacted_wipe_tower_clearance();
}
// BBS // BBS
//wxGetApp().obj_manipul()->set_dirty(); //wxGetApp().obj_manipul()->set_dirty();
m_dirty = true; m_dirty = true;
@@ -5614,6 +5621,101 @@ bool GLCanvas3D::can_sequential_clearance_show_in_gizmo() {
return false; return false;
} }
// Live preview of the compacted prime tower clearance, the by-layer counterpart of
// update_sequential_clearance(). Called while the user drags a volume / gizmo; idle visibility
// matches sequential print (hidden when valid, filled when Print::validate reports a collision).
// Print::compacted_wipe_tower_clearance_valid() answers the same question authoritatively, but it
// reads the tower position from the config, which only catches up once do_move() writes it back on
// mouse release. Recomputing from the volumes here is what makes the keep-out zone follow the tower
// while it is still under the cursor.
void GLCanvas3D::update_compacted_wipe_tower_clearance()
{
if (current_printer_technology() != ptFFF)
return;
const Print *print = fff_print();
if (print == nullptr)
return;
const PrintConfig &config = print->config();
if (config.print_sequence != PrintSequence::ByLayer || ! wipe_tower_sparse_layers_skipped(config) || ! print->has_wipe_tower())
return;
PartPlateList &plate_list = wxGetApp().plater()->get_partplate_list();
PartPlate *plate = plate_list.get_curr_plate();
if (plate == nullptr)
return;
const int plate_id = plate_list.get_curr_plate_index();
// Once the tower has been generated the scene shows its real mesh with the brim merged in,
// otherwise it is a bare estimated cube with no brim at all. Only the latter needs the brim added
// here, and the width comes from WipeTowerData, the same source the preview box is sized from, so
// the zone cannot be padded against a brim the preview was not built with.
const bool preview_carries_brim = print->is_step_done(psWipeTower) && print->wipe_tower_data().wipe_tower_mesh_data.has_value();
const double brim = preview_carries_brim ? 0. : double(print->wipe_tower_data(print->extruders().size()).brim_width);
const double padding = compacted_tower_footprint_padding(config, brim);
// Tower footprint straight from the volume the user sees, so that dragging either the tower or an
// object updates the zone on the very next frame.
Polygon tower_footprint;
for (const GLVolume *v : m_volumes.volumes) {
if (! v->is_wipe_tower || v->object_idx() - 1000 != plate_id)
continue;
const BoundingBoxf3 bbox = v->transformed_convex_hull_bounding_box();
tower_footprint = Polygon({ Point(scale_(bbox.min.x() - padding), scale_(bbox.min.y() - padding)),
Point(scale_(bbox.max.x() + padding), scale_(bbox.min.y() - padding)),
Point(scale_(bbox.max.x() + padding), scale_(bbox.max.y() + padding)),
Point(scale_(bbox.min.x() - padding), scale_(bbox.max.y() + padding)) });
break;
}
const CompactedTowerZone zone = compacted_wipe_tower_zone(config, tower_footprint);
if (zone.empty()) {
reset_sequential_print_clearance();
return;
}
// While dragging, outline every on-plate instance next to the tower ring, the way sequential print
// outlines every object. Both carry half of the clearance, so the two outlines meeting is precisely
// the moment that object goes over its limit - which is what makes the pair worth drawing at all.
// The tier is per object, so a short object gets the narrow nozzle outline rather than the wide
// body one it is not subject to; without that, a 3 mm object parked beside the tower would be drawn
// deep inside the keep-out ring while passing the check. Only the instances that already exceed
// allowed_rise also get a height limit plane.
Polygons outlines;
std::vector<std::pair<Polygon, float>> height_polygons;
bool body_tier_used = false;
const BoundingBox plate_bb = plate->get_bounding_box_crd();
for (const ModelObject *model_object : m_model->objects) {
for (size_t i = 0; i < model_object->instances.size(); ++i) {
Geometry::Transformation trafo(model_object->instances[i]->get_transformation());
const Vec3d offset = trafo.get_offset();
trafo.set_offset(Vec3d(offset.x(), offset.y(), 0.0));
const Polygon inst_hull = model_object->convex_hull_2d(trafo.get_matrix());
if (inst_hull.points.empty() || ! plate_bb.overlap(inst_hull.bounding_box()))
continue;
// Same tiers and the same rise measured from the plate as
// Print::compacted_wipe_tower_clearance_valid(), so that the preview and the validation
// that follows it never contradict each other.
const double object_top = model_object->get_instance_max_z(i);
const CompactedTowerClearance clearance = compacted_wipe_tower_clearance(config, zone, inst_hull, object_top);
body_tier_used = body_tier_used || compacted_tower_body_tier(clearance);
const Polygon outline = compacted_wipe_tower_offender_outline(inst_hull, clearance.body_clearance);
outlines.emplace_back(outline);
if (object_top <= clearance.allowed_rise + EPSILON)
continue;
height_polygons.emplace_back(outline, float(clearance.allowed_rise));
}
}
Polygons polygons = compacted_wipe_tower_rings(zone, body_tier_used);
append(polygons, outlines);
set_sequential_print_clearance_visible(true);
set_sequential_print_clearance_render_fill(false);
set_sequential_print_clearance_polygons(polygons, height_polygons);
}
void GLCanvas3D::update_sequential_clearance() void GLCanvas3D::update_sequential_clearance()
{ {
if (current_printer_technology() != ptFFF || (fff_print()->config().print_sequence == PrintSequence::ByLayer)) if (current_printer_technology() != ptFFF || (fff_print()->config().print_sequence == PrintSequence::ByLayer))
+2
View File
@@ -1191,6 +1191,8 @@ public:
bool can_sequential_clearance_show_in_gizmo(); bool can_sequential_clearance_show_in_gizmo();
void update_sequential_clearance(); void update_sequential_clearance();
// Orca: by-layer counterpart, for a prime tower compacted by "No sparse layers".
void update_compacted_wipe_tower_clearance();
const Print* fff_print() const; const Print* fff_print() const;
const SLAPrint* sla_print() const; const SLAPrint* sla_print() const;
+35 -20
View File
@@ -3,7 +3,6 @@
#include "libslic3r/Technologies.hpp" #include "libslic3r/Technologies.hpp"
#include "libslic3r/Platform.hpp" #include "libslic3r/Platform.hpp"
#include "GUI_App.hpp" #include "GUI_App.hpp"
#include "DeviceCore/DevConfigUtil.h"
#include "BindDialog.hpp" #include "BindDialog.hpp"
#include "DeviceManager.hpp" #include "DeviceManager.hpp"
#include "HMS.hpp" #include "HMS.hpp"
@@ -24,6 +23,7 @@
#include <boost/locale/encoding_utf.hpp> #include <boost/locale/encoding_utf.hpp>
#include <boost/log/detail/native_typeof.hpp> #include <boost/log/detail/native_typeof.hpp>
#include <libslic3r/Config.hpp> #include <libslic3r/Config.hpp>
#include <mutex>
#include <slic3r/plugin/PythonPluginInterface.hpp> #include <slic3r/plugin/PythonPluginInterface.hpp>
#include <wx/event.h> #include <wx/event.h>
@@ -40,11 +40,9 @@
#include <iterator> #include <iterator>
#include <exception> #include <exception>
#include <cstdlib> #include <cstdlib>
#include <mutex>
#include <regex> #include <regex>
#include <thread> #include <thread>
#include <string_view> #include <string_view>
#include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <boost/format.hpp> #include <boost/format.hpp>
@@ -89,6 +87,7 @@
#include "libslic3r/Thread.hpp" #include "libslic3r/Thread.hpp"
#include "libslic3r/miniz_extension.hpp" #include "libslic3r/miniz_extension.hpp"
#include "libslic3r/Utils.hpp" #include "libslic3r/Utils.hpp"
#include "libslic3r/Color.hpp"
#include "slic3r/plugin/PluginManager.hpp" #include "slic3r/plugin/PluginManager.hpp"
#include "slic3r/plugin/host/PluginHostUi.hpp" #include "slic3r/plugin/host/PluginHostUi.hpp"
#include "slic3r/plugin/PythonInterpreter.hpp" #include "slic3r/plugin/PythonInterpreter.hpp"
@@ -108,18 +107,19 @@
#include "../Utils/PrintHost.hpp" #include "../Utils/PrintHost.hpp"
#include "../Utils/Process.hpp" #include "../Utils/Process.hpp"
#include "../Utils/wxInspectorPlugins/Registration.hpp" #include "../Utils/wxInspectorPlugins/Registration.hpp"
#include "../Utils/MacDarkMode.hpp"
#include "../Utils/Http.hpp" #include "../Utils/Http.hpp"
#include "../Utils/InstanceID.hpp" #include "../Utils/InstanceID.hpp"
#include "../Utils/UndoRedo.hpp" #include "../Utils/UndoRedo.hpp"
#include "slic3r/Config/Snapshot.hpp" #include "slic3r/Config/Snapshot.hpp"
#include "Preferences.hpp" #include "Preferences.hpp"
#include "Tab.hpp" #include "Tab.hpp"
#include "SysInfoDialog.hpp"
#include "UpdateDialogs.hpp" #include "UpdateDialogs.hpp"
#include "Mouse3DController.hpp" #include "Mouse3DController.hpp"
#include "RemovableDriveManager.hpp" #include "RemovableDriveManager.hpp"
#include "InstanceCheck.hpp" #include "InstanceCheck.hpp"
#ifdef __APPLE__ #ifdef __APPLE__
#include "../Utils/MacDarkMode.hpp"
#include "DeepLinkHandlerMac.h" #include "DeepLinkHandlerMac.h"
#endif #endif
#include "NotificationManager.hpp" #include "NotificationManager.hpp"
@@ -128,6 +128,8 @@
#include "PrintHostDialogs.hpp" #include "PrintHostDialogs.hpp"
#include "NetworkPluginDialog.hpp" #include "NetworkPluginDialog.hpp"
#include "DesktopIntegrationDialog.hpp" #include "DesktopIntegrationDialog.hpp"
#include "SendSystemInfoDialog.hpp"
#include "ParamsDialog.hpp"
#include "KBShortcutsDialog.hpp" #include "KBShortcutsDialog.hpp"
#include "DownloadProgressDialog.hpp" #include "DownloadProgressDialog.hpp"
#include "TroubleshootDialog.hpp" #include "TroubleshootDialog.hpp"
@@ -138,6 +140,7 @@
#include "Widgets/ProgressDialog.hpp" #include "Widgets/ProgressDialog.hpp"
//BBS: DailyTip and UserGuide Dialog //BBS: DailyTip and UserGuide Dialog
#include "WebDownPluginDlg.hpp"
#include "WebGuideDialog.hpp" #include "WebGuideDialog.hpp"
#include "ReleaseNote.hpp" #include "ReleaseNote.hpp"
#include "PrivacyUpdateDialog.hpp" #include "PrivacyUpdateDialog.hpp"
@@ -2382,8 +2385,14 @@ bool GUI_App::is_blocking_printing(MachineObject *obj_)
{ {
DeviceManager *dev = Slic3r::GUI::wxGetApp().getDeviceManager(); DeviceManager *dev = Slic3r::GUI::wxGetApp().getDeviceManager();
if (!dev) return true; if (!dev) return true;
std::string target_model;
if (obj_ == nullptr) { if (obj_ == nullptr) {
obj_ = dev->get_selected_machine(); obj_ = dev->get_selected_machine();
if (obj_) {
target_model = obj_->printer_type;
}
} else {
target_model = obj_->printer_type;
} }
if (!obj_) if (!obj_)
@@ -2394,7 +2403,14 @@ bool GUI_App::is_blocking_printing(MachineObject *obj_)
PresetBundle *preset_bundle = wxGetApp().preset_bundle; PresetBundle *preset_bundle = wxGetApp().preset_bundle;
std::string source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle); std::string source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle);
return !DevPrinterConfigUtil::is_printer_model_compatible(source_model, *obj_); if (source_model != target_model) {
std::vector<std::string> compatible_machine = obj_->get_compatible_machine();
vector<std::string>::iterator it = find(compatible_machine.begin(), compatible_machine.end(), source_model);
if (it == compatible_machine.end()) {
return true;
}
}
return false;
} }
// If formatted for github, plaintext with OpenGL extensions enclosed into <details>. // If formatted for github, plaintext with OpenGL extensions enclosed into <details>.
@@ -3945,16 +3961,20 @@ void GUI_App::set_live_printer_agent(std::shared_ptr<IPrinterAgent> agent)
m_agent->set_user_selected_machine(""); m_agent->set_user_selected_machine("");
// note: belt-and-suspenders (precedent: DeviceManagerRefresher::on_timer) // note: belt-and-suspenders (precedent: DeviceManagerRefresher::on_timer)
dev->OnSelectedMachineLost(); // why: clear stale sidebar sync-status / AMS dev->OnSelectedMachineLost(); // why: clear stale sidebar sync-status / AMS
// why: retain agent-owned LAN discoveries so agents without automatic discovery (for // why: drop stale LAN discoveries; keep My Devices, but only those belonging to the
// example the Moonraker-based Qidi/Snapmaker agents) can reuse them after a switch. // agent we're about to swap to, so a device stamped by the outgoing agent doesn't
dev->clear_other_devices(); // linger hidden - the new agent's start_discovery re-inserts and re-stamps it fresh.
// agent is null when clearing the live agent entirely (e.g. plugin unload); there's no
// target to filter against then, so fall back to the original "keep all My Devices"
// behavior rather than guessing.
dev->clear_other_devices(agent ? agent->get_agent_info().id : std::string());
} }
m_agent->set_printer_agent(agent); m_agent->set_printer_agent(agent);
sidebar().update_all_preset_comboboxes(); sidebar().update_all_preset_comboboxes();
} }
std::string GUI_App::resolve_printer_agent_id(const std::string& stored_id) const std::string GUI_App::resolve_printer_agent_id(const std::string& stored_id)
{ {
if (!stored_id.empty()) if (!stored_id.empty())
return stored_id; return stored_id;
@@ -3990,7 +4010,6 @@ void GUI_App::switch_printer_agent()
std::string log_dir = data_dir(); std::string log_dir = data_dir();
std::string cloud_agent_id = agent_info.id == BBL_PRINTER_AGENT_ID ? BBL_CLOUD_PROVIDER : ORCA_CLOUD_PROVIDER; std::string cloud_agent_id = agent_info.id == BBL_PRINTER_AGENT_ID ? BBL_CLOUD_PROVIDER : ORCA_CLOUD_PROVIDER;
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " " << agent_info.id;
std::shared_ptr<ICloudServiceAgent> cloud_agent = m_agent->get_cloud_agent(cloud_agent_id); std::shared_ptr<ICloudServiceAgent> cloud_agent = m_agent->get_cloud_agent(cloud_agent_id);
// Create new printer agent via registry // Create new printer agent via registry
@@ -4004,10 +4023,8 @@ void GUI_App::switch_printer_agent()
return; return;
} }
// Compare the registered IDs, not only the implementation pointer. Different registry IDs // The factory caches agents per ID, so an identical pointer means the agent type is unchanged.
// may intentionally be backed by the same implementation object (especially for plugins). if (m_agent->get_printer_agent() == new_printer_agent) {
const auto current_printer_agent = m_agent->get_printer_agent();
if (current_printer_agent && current_printer_agent->get_agent_info().id == effective_agent_id) {
// Orca: the agent type is unchanged (e.g. switching between two Moonraker/Klipper // Orca: the agent type is unchanged (e.g. switching between two Moonraker/Klipper
// printer presets), so the selected machine and the agent's cached device_info still // printer presets), so the selected machine and the agent's cached device_info still
// point at the previously active printer preset. Re-select the machine when the new // point at the previously active printer preset. Re-select the machine when the new
@@ -4966,16 +4983,14 @@ bool GUI_App::is_user_login(const std::string& provider/* = ORCA_CLOUD_PROVIDER*
return false; return false;
} }
std::string GUI_App::get_printer_cloud_provider() const const std::string& GUI_App::get_printer_cloud_provider() const
{ {
const std::string agent_id = resolve_printer_agent_id( // Orca todo: this need to be revisted. currently it is mainly used for device manager and related clausses and only bambu machines use them.
preset_bundle ? preset_bundle->printers.get_edited_preset().config.opt_string("printer_agent") //
: std::string()); return BBL_CLOUD_PROVIDER;
return agent_id == BBL_PRINTER_AGENT_ID ? BBL_CLOUD_PROVIDER : ORCA_CLOUD_PROVIDER;
} }
bool GUI_App::check_login(const std::string& provider/* = ORCA_CLOUD_PROVIDER*/) bool GUI_App::check_login(const std::string& provider/* = ORCA_CLOUD_PROVIDER*/)
{ {
bool result = false; bool result = false;
+5 -2
View File
@@ -23,6 +23,9 @@
#include <wx/snglinst.h> #include <wx/snglinst.h>
#include <wx/msgdlg.h> #include <wx/msgdlg.h>
#include <mutex>
#include <stack>
//#define BBL_HAS_FIRST_PAGE 1 //#define BBL_HAS_FIRST_PAGE 1
#define STUDIO_INACTIVE_TIMEOUT 15*60*1000 #define STUDIO_INACTIVE_TIMEOUT 15*60*1000
#define LOG_FILES_MAX_NUM 30 #define LOG_FILES_MAX_NUM 30
@@ -366,7 +369,7 @@ public:
// Reconcile the live printer agent with the stored preset selection. // Reconcile the live printer agent with the stored preset selection.
void switch_printer_agent(); void switch_printer_agent();
std::string resolve_printer_agent_id(const std::string& stored_id) const; std::string resolve_printer_agent_id(const std::string& stored_id);
// ORCA TODO: in the future, bbl presets should specify "bbl" printer agent id // ORCA TODO: in the future, bbl presets should specify "bbl" printer agent id
// then, all resolve and canonical would just be ORCA<->"" // then, all resolve and canonical would just be ORCA<->""
std::string canonical_printer_agent_id(const std::string& picked_id); std::string canonical_printer_agent_id(const std::string& picked_id);
@@ -492,7 +495,7 @@ public:
bool check_login(const std::string& provider = ORCA_CLOUD_PROVIDER); bool check_login(const std::string& provider = ORCA_CLOUD_PROVIDER);
void get_login_info(const std::string& provider = ORCA_CLOUD_PROVIDER); void get_login_info(const std::string& provider = ORCA_CLOUD_PROVIDER);
bool is_user_login(const std::string& provider = ORCA_CLOUD_PROVIDER); bool is_user_login(const std::string& provider = ORCA_CLOUD_PROVIDER);
std::string get_printer_cloud_provider() const; const std::string& get_printer_cloud_provider() const;
void request_user_login(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER); void request_user_login(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER);
void request_user_handle(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER); void request_user_handle(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER);
-46
View File
@@ -1,46 +0,0 @@
#pragma once
#include <wx/mediactrl.h>
#include <wx/uri.h>
#include <memory>
#include <slic3r/Utils/IPrinterAgent.hpp>
namespace Slic3r { namespace GUI {
class IMediaController
{
public:
virtual ~IMediaController() = default;
virtual void Load(wxURI url) = 0;
// The default keeps existing media controllers unaware of camera-specific modes.
virtual void Load(wxURI url, CameraStreamMode mode)
{
(void) mode;
Load(url);
}
virtual void Play() = 0;
virtual void Stop() = 0;
virtual wxMediaState GetState() { return wxMediaState{}; }
virtual int GetLastError() const { return {}; };
virtual wxSize GetVideoSize() const { return {}; };
virtual void StartSession(std::unique_ptr<ICameraSignalingChannel> channel)
{
(void) channel;
}
virtual void StopSession() {}
private:
};
}} // namespace Slic3r::GUI
+1 -2
View File
@@ -14,7 +14,6 @@
#include "slic3r/Utils/FileTransferUtils.hpp" #include "slic3r/Utils/FileTransferUtils.hpp"
#include "slic3r/Utils/BBLNetworkPlugin.hpp" #include "slic3r/Utils/BBLNetworkPlugin.hpp"
#include "NetworkAgent.hpp"
namespace Slic3r { namespace Slic3r {
namespace GUI { namespace GUI {
@@ -204,7 +203,7 @@ void PrintJob::process(Ctl &ctl)
params.dev_ip = m_dev_ip; params.dev_ip = m_dev_ip;
params.use_ssl_for_ftp = m_local_use_ssl_for_ftp; params.use_ssl_for_ftp = m_local_use_ssl_for_ftp;
params.use_ssl_for_mqtt = m_local_use_ssl; params.use_ssl_for_mqtt = m_local_use_ssl;
params.username = m_agent->default_lan_username(); params.username = "bblp";
params.password = m_access_code; params.password = m_access_code;
// check access code and ip address // check access code and ip address
+2 -2
View File
@@ -126,7 +126,7 @@ void SendJob::process(Ctl &ctl)
if (m_is_check_mode) { if (m_is_check_mode) {
PrintParams verify_params; PrintParams verify_params;
verify_params.dev_ip = m_dev_ip; verify_params.dev_ip = m_dev_ip;
verify_params.username = agent->default_lan_username(); verify_params.username = "bblp";
verify_params.password = m_access_code; verify_params.password = m_access_code;
verify_params.use_ssl_for_ftp = m_local_use_ssl_for_ftp; verify_params.use_ssl_for_ftp = m_local_use_ssl_for_ftp;
verify_params.use_ssl_for_mqtt = m_local_use_ssl; verify_params.use_ssl_for_mqtt = m_local_use_ssl;
@@ -211,7 +211,7 @@ void SendJob::process(Ctl &ctl)
// local print access // local print access
params.dev_ip = m_dev_ip; params.dev_ip = m_dev_ip;
params.username = agent->default_lan_username(); params.username = "bblp";
params.password = m_access_code; params.password = m_access_code;
params.use_ssl_for_ftp = m_local_use_ssl_for_ftp; params.use_ssl_for_ftp = m_local_use_ssl_for_ftp;
params.use_ssl_for_mqtt = m_local_use_ssl; params.use_ssl_for_mqtt = m_local_use_ssl;
+1 -1
View File
@@ -4311,7 +4311,7 @@ void MainFrame::load_printer_url()
if (auto *device_manager = wxGetApp().getDeviceManager()) { if (auto *device_manager = wxGetApp().getDeviceManager()) {
auto *machine = device_manager->get_selected_machine(); auto *machine = device_manager->get_selected_machine();
if (!machine) { if (!machine) {
auto machines = device_manager->get_my_machine_list(device_manager->get_current_printer_agent_id()); auto machines = device_manager->get_my_machine_list();
if (machines.size() == 1) if (machines.size() == 1)
machine = machines.begin()->second; machine = machines.begin()->second;
} }
+18 -263
View File
@@ -7,7 +7,6 @@
#include "DeviceManager.hpp" #include "DeviceManager.hpp"
#include "DeviceCore/DevConfigUtil.h" #include "DeviceCore/DevConfigUtil.h"
#include "slic3r/Utils/NetworkAgent.hpp" #include "slic3r/Utils/NetworkAgent.hpp"
#include "slic3r/Utils/NetworkAgentFactory.hpp"
#include "libslic3r/Thread.hpp" #include "libslic3r/Thread.hpp"
#include "libslic3r/AppConfig.hpp" #include "libslic3r/AppConfig.hpp"
#include "I18N.hpp" #include "I18N.hpp"
@@ -16,14 +15,11 @@
#include "slic3r/Utils/BBLNetworkPlugin.hpp" #include "slic3r/Utils/BBLNetworkPlugin.hpp"
#include <algorithm>
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
#include <boost/log/trivial.hpp> #include <boost/log/trivial.hpp>
#include <boost/nowide/cstdio.hpp> #include <boost/nowide/cstdio.hpp>
#include <boost/nowide/fstream.hpp> #include <boost/nowide/fstream.hpp>
#include <boost/nowide/utf8_codecvt.hpp> #include <boost/nowide/utf8_codecvt.hpp>
#include <slic3r/GUI/DeviceManager.hpp>
#undef pid_t #undef pid_t
#include <boost/process.hpp> #include <boost/process.hpp>
#ifdef __WIN32__ #ifdef __WIN32__
@@ -143,11 +139,6 @@ MediaPlayCtrl::MediaPlayCtrl(wxWindow *parent, wxMediaCtrl3 *media_ctrl, const w
MediaPlayCtrl::~MediaPlayCtrl() MediaPlayCtrl::~MediaPlayCtrl()
{ {
m_webrtc_stopping = true;
if (m_webrtc_ctrl)
m_webrtc_ctrl->StopSession();
m_media_ctrl->EndExternalStream();
m_webrtc_stopping = false;
{ {
boost::unique_lock lock(m_mutex); boost::unique_lock lock(m_mutex);
m_tasks.push_back("<exit>"); m_tasks.push_back("<exit>");
@@ -160,77 +151,8 @@ MediaPlayCtrl::~MediaPlayCtrl()
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": " << this; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": " << this;
} }
void MediaPlayCtrl::SetWebMediaController(IMediaController *ctrl)
{
m_web_ctrl = ctrl;
}
CameraStreamMode MediaPlayCtrl::current_mode() const
{
auto agent = wxGetApp().getAgent();
return agent ? agent->get_camera_stream_mode() : CameraStreamMode::none;
}
void MediaPlayCtrl::SetMachineObject(MachineObject* obj) void MediaPlayCtrl::SetMachineObject(MachineObject* obj)
{ {
const CameraStreamMode mode = current_mode();
if (mode != m_last_mode) {
if (m_last_state != MEDIASTATE_IDLE) {
m_failed_code = 0; // a mode switch is not a stream failure - don't arm back-off
Stop(" ");
}
m_last_mode = mode;
}
switch (mode) {
case CameraStreamMode::http:
case CameraStreamMode::https:
case CameraStreamMode::http_snapshot:
case CameraStreamMode::rtsp: {
std::string machine = obj ? obj->get_dev_id() : "";
auto agent = wxGetApp().getAgent();
std::string url = agent ? agent->get_local_camera_stream_url() : "";
m_camera_exists = !url.empty();
Enable(obj && m_camera_exists);
bool changed = machine != m_machine || url != m_agent_camera_url;
m_machine = machine;
m_agent_camera_url = url;
m_url = from_u8(url);
if (!changed) {
return;
}
// A genuine machine/URL switch: not a failure, so drop any pending
// failure back-off before (re)starting on the new target.
m_web_user_stopped = false;
m_failed_code = 0;
m_failed_retry = 0;
m_next_retry = wxDateTime();
if (m_last_state != MEDIASTATE_IDLE)
Stop(" ");
return;
}
case CameraStreamMode::webrtc: {
std::string machine = obj ? obj->get_dev_id() : "";
m_camera_exists = obj != nullptr;
Enable(obj != nullptr);
const bool changed = machine != m_machine;
BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::SetMachineObject webrtc: changed=" << changed
<< " last_state=" << m_last_state << " web_user_stopped=" << m_web_user_stopped;
m_machine = machine;
m_url.clear();
m_agent_camera_url.clear();
if (!changed) {
return;
}
m_web_user_stopped = false;
if (m_last_state != MEDIASTATE_IDLE)
Stop(" ");
return;
}
default:
break;
}
std::string machine = obj ? obj->get_dev_id() : ""; std::string machine = obj ? obj->get_dev_id() : "";
if (obj) { if (obj) {
m_camera_exists = obj->has_ipcam; m_camera_exists = obj->has_ipcam;
@@ -245,12 +167,12 @@ void MediaPlayCtrl::SetMachineObject(MachineObject* obj)
if (DevPrinterConfigUtil::get_printer_series_str(obj->printer_type) == "series_o" && BBLNetworkPlugin::instance().use_legacy_network()) { if (DevPrinterConfigUtil::get_printer_series_str(obj->printer_type) == "series_o" && BBLNetworkPlugin::instance().use_legacy_network()) {
// Legacy plugin cannot support remote play for H2D, force using local mode // Legacy plugin cannot support remote play for H2D, force using local mode
m_remote_proto = LiveviewRemote::LVR_None; m_remote_proto = MachineObject::LVR_None;
} }
} else { } else {
m_camera_exists = false; m_camera_exists = false;
m_lan_mode = false; m_lan_mode = false;
m_lan_proto = LiveviewLocal::LVL_None; m_lan_proto = MachineObject::LVL_None;
m_lan_ip.clear(); m_lan_ip.clear();
m_lan_passwd.clear(); m_lan_passwd.clear();
m_dev_ver.clear(); m_dev_ver.clear();
@@ -260,6 +182,8 @@ void MediaPlayCtrl::SetMachineObject(MachineObject* obj)
} }
Enable(obj && obj->is_info_ready() && obj->m_push_count > 0); Enable(obj && obj->is_info_ready() && obj->m_push_count > 0);
if (machine == m_machine) { if (machine == m_machine) {
if (m_last_state == MEDIASTATE_IDLE && IsEnabled())
Play();
return; return;
} }
m_machine = machine; m_machine = machine;
@@ -330,90 +254,6 @@ void refresh_agora_url(char const* device, char const* dev_ver, char const* chan
void MediaPlayCtrl::Play() void MediaPlayCtrl::Play()
{ {
switch (current_mode()) {
case CameraStreamMode::http_snapshot:
if (!m_next_retry.IsValid() || wxDateTime::Now() < m_next_retry)
return;
if (!IsShownOnScreen()) return;
if (m_last_state != MEDIASTATE_IDLE) return;
if (m_machine.empty() || !IsEnabled() || !m_camera_exists || m_url.IsEmpty() || !m_web_ctrl) {
Stop(_L("Please confirm if the printer is connected."));
return;
}
m_button_play->SetIcon("media_stop");
m_web_ctrl->Load(wxURI(m_url), current_mode());
m_web_ctrl->Play();
m_last_state = wxMEDIASTATE_PLAYING;
SetStatus(_L("Playing..."), false);
return;
case CameraStreamMode::http:
case CameraStreamMode::https:
case CameraStreamMode::rtsp:
if (m_next_retry.IsValid() && wxDateTime::Now() < m_next_retry)
return;
if (!IsShownOnScreen()) return;
if (m_last_state != MEDIASTATE_IDLE) return;
m_failed_code = 0;
if (m_machine.empty() || !IsEnabled() || !m_camera_exists || m_url.IsEmpty()) {
Stop(_L("Please confirm if the printer is connected."));
return;
}
m_button_play->SetIcon("media_stop");
load();
return;
case CameraStreamMode::webrtc: {
BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::Play webrtc: last_state=" << m_last_state
<< " next_retry_valid=" << m_next_retry.IsValid()
<< " next_retry_future=" << (m_next_retry.IsValid() && wxDateTime::Now() < m_next_retry)
<< " failed_retry=" << m_failed_retry << " shown=" << IsShownOnScreen();
if (m_webrtc_ctrl && m_webrtc_ctrl->is_active()) {
BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::Play webrtc: session already active, ignoring";
return;
}
if (m_next_retry.IsValid() && wxDateTime::Now() < m_next_retry)
return;
if (!IsShownOnScreen() || m_last_state != MEDIASTATE_IDLE)
return;
m_failed_code = 0;
if (m_machine.empty() || !IsEnabled() || !m_camera_exists) {
Stop(_L("Please confirm if the printer is connected."));
return;
}
auto agent = wxGetApp().getAgent();
auto channel = agent ? agent->create_camera_signaling_channel(m_machine) : nullptr;
if (!channel) {
Stop(_L("Sign in to OrcaCloud to view the camera."));
return;
}
if (!m_webrtc_ctrl) {
m_webrtc_ctrl = std::make_unique<WebRtcMediaController>(
[this](const wxImage& image, wxSize size) { m_media_ctrl->SetExternalFrame(image, size); },
[this, token = std::weak_ptr<int>(m_token)](WebRtcMediaController::Status status) {
if (token.expired())
return;
CallAfter([this, status] { on_webrtc_status(status); });
});
}
m_button_play->SetIcon("media_stop");
m_media_ctrl->BeginExternalStream();
m_last_state = MEDIASTATE_INITIALIZING;
SetStatus(_L("Initializing..."), false);
m_webrtc_stopping = false;
m_webrtc_ctrl->StartSession(std::move(channel));
m_webrtc_epoch = m_webrtc_ctrl->epoch();
return;
}
default: // assumed to be CameraStreamMode::none
if (NetworkAgent* agent = wxGetApp().getAgent()) {
if (auto printer_agent = agent->get_printer_agent()) {
if (printer_agent->get_agent_info().id != BBL_PRINTER_AGENT_ID) {
return;
}
}
}
break;
}
if (!m_next_retry.IsValid() || wxDateTime::Now() < m_next_retry) if (!m_next_retry.IsValid() || wxDateTime::Now() < m_next_retry)
return; return;
if (!IsShownOnScreen()) if (!IsShownOnScreen())
@@ -443,14 +283,14 @@ void MediaPlayCtrl::Play()
BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::Play: " << m_lan_proto << m_remote_proto << m_disable_lan; BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::Play: " << m_lan_proto << m_remote_proto << m_disable_lan;
NetworkAgent *agent = wxGetApp().getAgent(); NetworkAgent *agent = wxGetApp().getAgent();
std::string agent_version = agent ? agent->get_version() : ""; std::string agent_version = agent ? agent->get_version() : "";
if (m_lan_proto > LiveviewLocal::LVL_Disable && (m_lan_mode || !m_remote_proto) && !m_disable_lan && !m_lan_ip.empty()) { if (m_lan_proto > MachineObject::LVL_Disable && (m_lan_mode || !m_remote_proto) && !m_disable_lan && !m_lan_ip.empty()) {
m_disable_lan = m_remote_proto && !m_lan_mode; // try remote next time m_disable_lan = m_remote_proto && !m_lan_mode; // try remote next time
std::string url; std::string url;
if (m_lan_proto == LiveviewLocal::LVL_Local) if (m_lan_proto == MachineObject::LVL_Local)
url = "bambu:///local/" + m_lan_ip + ".?port=6000&user=" + m_lan_user + "&passwd=" + m_lan_passwd; url = "bambu:///local/" + m_lan_ip + ".?port=6000&user=" + m_lan_user + "&passwd=" + m_lan_passwd;
else if (m_lan_proto == LiveviewLocal::LVL_Rtsps) else if (m_lan_proto == MachineObject::LVL_Rtsps)
url = "bambu:///rtsps___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsps"; url = "bambu:///rtsps___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsps";
else if (m_lan_proto == LiveviewLocal::LVL_Rtsp) else if (m_lan_proto == MachineObject::LVL_Rtsp)
url = "bambu:///rtsp___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsp"; url = "bambu:///rtsp___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsp";
url += "&device=" + m_machine; url += "&device=" + m_machine;
url += "&net_ver=" + agent_version; url += "&net_ver=" + agent_version;
@@ -472,8 +312,8 @@ void MediaPlayCtrl::Play()
// !m_lan_mode && !m_remote_proto && m_lan_proto == LVL_Disable (*) // !m_lan_mode && !m_remote_proto && m_lan_proto == LVL_Disable (*)
// !m_lan_mode && !m_remote_proto && m_lan_proto == LVL_None (x) // !m_lan_mode && !m_remote_proto && m_lan_proto == LVL_None (x)
if (m_lan_proto <= LiveviewLocal::LVL_Disable && (m_lan_mode || !m_remote_proto)) { if (m_lan_proto <= MachineObject::LVL_Disable && (m_lan_mode || !m_remote_proto)) {
Stop(m_lan_proto == LiveviewLocal::LVL_None Stop(m_lan_proto == MachineObject::LVL_None
? _L("A problem occurred. Please update the printer firmware and try again.") ? _L("A problem occurred. Please update the printer firmware and try again.")
: _L("LAN Only Liveview is off. Please turn on the liveview on printer screen.")); : _L("LAN Only Liveview is off. Please turn on the liveview on printer screen."));
return; return;
@@ -541,70 +381,8 @@ void MediaPlayCtrl::Play()
void start_ping_test(); void start_ping_test();
void MediaPlayCtrl::StopWebStream()
{
if (m_last_state == MEDIASTATE_IDLE)
return;
if (m_web_ctrl)
m_web_ctrl->Stop();
m_button_play->SetIcon("media_play");
m_last_state = MEDIASTATE_IDLE;
SetStatus(_L("Video Stopped."), false);
}
void MediaPlayCtrl::Stop(wxString const &msg, wxString const &msg2) void MediaPlayCtrl::Stop(wxString const &msg, wxString const &msg2)
{ {
const bool webrtc_active = m_webrtc_ctrl && m_last_mode == CameraStreamMode::webrtc;
BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::Stop: last_state=" << m_last_state
<< " webrtc_active=" << webrtc_active << " failed_code=" << m_failed_code
<< " msg='" << msg.ToUTF8().data() << "'";
if (webrtc_active) {
m_webrtc_stopping = true;
m_webrtc_ctrl->StopSession();
m_media_ctrl->EndExternalStream();
m_webrtc_stopping = false;
}
switch (m_last_mode) {
case CameraStreamMode::http:
case CameraStreamMode::https:
case CameraStreamMode::http_snapshot: {
const bool snapshot = m_last_mode == CameraStreamMode::http_snapshot;
if (m_last_state != MEDIASTATE_IDLE) {
if (snapshot) {
if (m_web_ctrl) m_web_ctrl->Stop();
} else {
// http/https mode plays through the ffmpeg backend (m_media_ctrl), not
// the webview - tear its read thread down too, otherwise it keeps
// pulling and painting frames after the UI says "Video Stopped".
boost::unique_lock lock(m_mutex);
m_tasks.push_back("<stop>");
m_cond.notify_all();
}
m_button_play->SetIcon("media_play");
m_last_state = MEDIASTATE_IDLE;
if (!msg.IsEmpty())
SetStatus(msg);
else
SetStatus(_L("Video Stopped."), false);
// Keep retries bounded for an explicit or retry-driven playback attempt.
// m_failed_retry is cleared on success (onStateChanged) and on a deliberate
// machine switch (SetMachineObject); manual playback via TogglePlay resets it.
if (m_failed_code != 0) {
const bool auto_retry = wxGetApp().app_config->get("liveview", "auto_retry") != "false";
++m_failed_retry;
m_next_retry = auto_retry
? wxDateTime::Now() + wxTimeSpan::Seconds(std::min(5 * m_failed_retry, 30))
: wxDateTime::Now() + wxTimeSpan::Days(1); // "off": wait for a manual retry
}
} else if (!msg.IsEmpty()) {
SetStatus(msg, false);
}
return;
}
default:
break;
}
int last_state = m_last_state; int last_state = m_last_state;
if (m_last_state != MEDIASTATE_IDLE) { if (m_last_state != MEDIASTATE_IDLE) {
@@ -676,38 +454,15 @@ void MediaPlayCtrl::Stop(wxString const &msg, wxString const &msg2)
m_next_retry = wxDateTime::Now() + wxTimeSpan::Seconds(5 * m_failed_retry); m_next_retry = wxDateTime::Now() + wxTimeSpan::Seconds(5 * m_failed_retry);
} }
void MediaPlayCtrl::on_webrtc_status(WebRtcMediaController::Status status)
{
// Drop CallAfter-queued events from a superseded StartSession attempt.
if (status.epoch != m_webrtc_epoch)
return;
if (status.kind == WebRtcMediaController::Status::Connecting) {
m_last_state = MEDIASTATE_INITIALIZING;
SetStatus(_L("Initializing..."), false);
} else if (status.kind == WebRtcMediaController::Status::Playing) {
m_last_state = wxMEDIASTATE_PLAYING;
m_failed_code = 0;
m_failed_retry = 0;
SetStatus(_L("Playing..."), false);
} else if (status.kind == WebRtcMediaController::Status::Failed) {
m_failed_code = static_cast<int>(status.code) + 1;
Stop();
}
// Status::Stopped needs no action: a genuine failure arrives as Failed, and
// a stop we initiated is already handled by Stop() itself.
}
void MediaPlayCtrl::TogglePlay() void MediaPlayCtrl::TogglePlay()
{ {
BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::TogglePlay"; BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl::TogglePlay";
if (m_last_state != MEDIASTATE_IDLE) { if (m_last_state != MEDIASTATE_IDLE) {
m_next_retry = wxDateTime(); m_next_retry = wxDateTime();
m_web_user_stopped = true;
Stop(); Stop();
} else { } else {
m_failed_retry = 0; m_failed_retry = 0;
m_user_triggered = true; m_user_triggered = true;
m_web_user_stopped = false;
if (m_last_user_play + wxTimeSpan::Minutes(5) < wxDateTime::Now()) { if (m_last_user_play + wxTimeSpan::Minutes(5) < wxDateTime::Now()) {
m_last_failed_codes.clear(); m_last_failed_codes.clear();
m_last_user_play = wxDateTime::Now(); m_last_user_play = wxDateTime::Now();
@@ -773,13 +528,13 @@ void MediaPlayCtrl::ToggleStream()
wxGetApp().app_config->set("not_show_vcamera_stop_prev", "1"); wxGetApp().app_config->set("not_show_vcamera_stop_prev", "1");
if (res == wxID_CANCEL) return; if (res == wxID_CANCEL) return;
} }
if (m_lan_proto > LiveviewLocal::LVL_Disable && (m_lan_mode || !m_remote_proto) && !m_disable_lan && !m_lan_ip.empty()) { if (m_lan_proto > MachineObject::LVL_Disable && (m_lan_mode || !m_remote_proto) && !m_disable_lan && !m_lan_ip.empty()) {
std::string url; std::string url;
if (m_lan_proto == LiveviewLocal::LVL_Local) if (m_lan_proto == MachineObject::LVL_Local)
url = "bambu:///local/" + m_lan_ip + ".?port=6000&user=" + m_lan_user + "&passwd=" + m_lan_passwd; url = "bambu:///local/" + m_lan_ip + ".?port=6000&user=" + m_lan_user + "&passwd=" + m_lan_passwd;
else if (m_lan_proto == LiveviewLocal::LVL_Rtsps) else if (m_lan_proto == MachineObject::LVL_Rtsps)
url = "bambu:///rtsps___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsps"; url = "bambu:///rtsps___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsps";
else if (m_lan_proto == LiveviewLocal::LVL_Rtsp) else if (m_lan_proto == MachineObject::LVL_Rtsp)
url = "bambu:///rtsp___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsp"; url = "bambu:///rtsp___" + m_lan_user + ":" + m_lan_passwd + "@" + m_lan_ip + "/streaming/live/1?proto=rtsp";
url += "&device=" + into_u8(m_machine); url += "&device=" + into_u8(m_machine);
url += "&dev_ver=" + m_dev_ver; url += "&dev_ver=" + m_dev_ver;
@@ -911,8 +666,7 @@ void MediaPlayCtrl::load()
{ {
m_last_state = MEDIASTATE_LOADING; m_last_state = MEDIASTATE_LOADING;
SetStatus(_L("Loading...")); SetStatus(_L("Loading..."));
const auto mode = current_mode(); if (wxGetApp().app_config->get("internal_developer_mode") == "true") {
if (mode == CameraStreamMode::none && wxGetApp().app_config->get("internal_developer_mode") == "true") {
std::string file_h264 = data_dir() + "/video.h264"; std::string file_h264 = data_dir() + "/video.h264";
std::string file_info = data_dir() + "/video.info"; std::string file_info = data_dir() + "/video.info";
BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl dump video to " << file_h264; BOOST_LOG_TRIVIAL(info) << "MediaPlayCtrl dump video to " << file_h264;
@@ -932,8 +686,9 @@ void MediaPlayCtrl::on_show_hide(wxShowEvent &evt)
evt.Skip(); evt.Skip();
if (m_isBeingDeleted) return; if (m_isBeingDeleted) return;
m_failed_retry = 0; m_failed_retry = 0;
if (!IsShownOnScreen()) if (m_next_retry.IsValid()) // Try open 2 seconds later, to avoid quick play/stop
Stop(); m_next_retry = wxDateTime::Now() + wxTimeSpan::Seconds(2);
IsShownOnScreen() ? Play() : Stop();
} }
void MediaPlayCtrl::media_proc() void MediaPlayCtrl::media_proc()
-17
View File
@@ -9,9 +9,6 @@
#define MediaPlayCtrl_h #define MediaPlayCtrl_h
#include "wxMediaCtrl3.h" #include "wxMediaCtrl3.h"
#include "IMediaController.hpp"
#include "WebRtcMediaController.hpp"
#include "slic3r/Utils/IPrinterAgent.hpp"
#include <wx/panel.h> #include <wx/panel.h>
@@ -39,10 +36,6 @@ public:
void SetMachineObject(MachineObject * obj); void SetMachineObject(MachineObject * obj);
void SetWebMediaController(IMediaController *ctrl);
void StopWebStream();
bool IsStreaming() const; bool IsStreaming() const;
void ToggleStream(); void ToggleStream();
@@ -61,7 +54,6 @@ protected:
void TogglePlay(); void TogglePlay();
void SetStatus(wxString const &msg, bool hyperlink = true); void SetStatus(wxString const &msg, bool hyperlink = true);
void on_webrtc_status(WebRtcMediaController::Status status);
private: private:
void load(); void load();
@@ -74,8 +66,6 @@ private:
static bool get_stream_url(std::string *url = nullptr); static bool get_stream_url(std::string *url = nullptr);
CameraStreamMode current_mode() const;
private: private:
static inline const wxMediaState MEDIASTATE_IDLE = static_cast<wxMediaState>(3); static inline const wxMediaState MEDIASTATE_IDLE = static_cast<wxMediaState>(3);
static inline const wxMediaState MEDIASTATE_INITIALIZING = static_cast<wxMediaState>(4); static inline const wxMediaState MEDIASTATE_INITIALIZING = static_cast<wxMediaState>(4);
@@ -86,13 +76,6 @@ private:
std::shared_ptr<int> m_token = std::make_shared<int>(0); std::shared_ptr<int> m_token = std::make_shared<int>(0);
wxMediaCtrl3 * m_media_ctrl; wxMediaCtrl3 * m_media_ctrl;
IMediaController * m_web_ctrl = nullptr;
std::unique_ptr<WebRtcMediaController> m_webrtc_ctrl;
CameraStreamMode m_last_mode = CameraStreamMode::none;
bool m_webrtc_stopping = false;
std::uint64_t m_webrtc_epoch = 0;
std::string m_agent_camera_url;
bool m_web_user_stopped = false;
wxMediaState m_last_state = MEDIASTATE_IDLE; wxMediaState m_last_state = MEDIASTATE_IDLE;
std::string m_machine; std::string m_machine;
int m_lan_proto = 0; int m_lan_proto = 0;
+1 -11
View File
@@ -34,8 +34,6 @@
#include "DeviceCore/DevManager.h" #include "DeviceCore/DevManager.h"
#include <boost/log/trivial.hpp>
namespace Slic3r { namespace Slic3r {
namespace GUI { namespace GUI {
@@ -261,7 +259,6 @@ void MonitorPanel::msw_rescale()
void MonitorPanel::select_machine(std::string machine_sn) void MonitorPanel::select_machine(std::string machine_sn)
{ {
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: MonitorPanel::select_machine queueing machine_sn=" << machine_sn;
wxCommandEvent *event = new wxCommandEvent(wxEVT_COMMAND_CHOICE_SELECTED); wxCommandEvent *event = new wxCommandEvent(wxEVT_COMMAND_CHOICE_SELECTED);
event->SetString(machine_sn); event->SetString(machine_sn);
wxQueueEvent(this, event); wxQueueEvent(this, event);
@@ -279,20 +276,13 @@ void MonitorPanel::on_timer(wxTimerEvent& event)
void MonitorPanel::on_select_printer(wxCommandEvent& event) void MonitorPanel::on_select_printer(wxCommandEvent& event)
{ {
Slic3r::DeviceManager* dev = Slic3r::GUI::wxGetApp().getDeviceManager(); Slic3r::DeviceManager* dev = Slic3r::GUI::wxGetApp().getDeviceManager();
const std::string requested_dev_id = event.GetString().ToStdString();
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: MonitorPanel::on_select_printer requested_dev_id="
<< requested_dev_id << " device_manager=" << (dev ? "set" : "null");
if (!dev) return; if (!dev) return;
if ( dev->get_selected_machine() && (dev->get_selected_machine()->get_dev_id() != event.GetString().ToStdString()) && m_hms_panel) { if ( dev->get_selected_machine() && (dev->get_selected_machine()->get_dev_id() != event.GetString().ToStdString()) && m_hms_panel) {
m_hms_panel->clear_hms_tag(); m_hms_panel->clear_hms_tag();
} }
const bool selected = dev->set_selected_machine(requested_dev_id); if (!dev->set_selected_machine(event.GetString().ToStdString()))
BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: MonitorPanel::on_select_printer set_selected_machine result="
<< selected << " selected_dev_id="
<< (dev->get_selected_machine() ? dev->get_selected_machine()->get_dev_id() : "<null>");
if (!selected)
return; return;
set_default(); set_default();
+10 -2
View File
@@ -3,7 +3,6 @@
#include "GUI_App.hpp" #include "GUI_App.hpp"
#include "MainFrame.hpp" #include "MainFrame.hpp"
#include "DeviceCore/DevConfigUtil.h"
namespace Slic3r { namespace Slic3r {
namespace GUI { namespace GUI {
@@ -109,12 +108,21 @@ bool DeviceItem::is_blocking_printing(MachineObject* obj_)
{ {
DeviceManager* dev = Slic3r::GUI::wxGetApp().getDeviceManager(); DeviceManager* dev = Slic3r::GUI::wxGetApp().getDeviceManager();
if (!dev) return true; if (!dev) return true;
auto target_model = obj_->printer_type;
std::string source_model = ""; std::string source_model = "";
PresetBundle* preset_bundle = wxGetApp().preset_bundle; PresetBundle* preset_bundle = wxGetApp().preset_bundle;
source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle); source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle);
return !DevPrinterConfigUtil::is_printer_model_compatible(source_model, *obj_); if (source_model != target_model) {
std::vector<std::string> compatible_machine = obj_->get_compatible_machine();
vector<std::string>::iterator it = find(compatible_machine.begin(), compatible_machine.end(), source_model);
if (it == compatible_machine.end()) {
return true;
}
}
return false;
} }
void DeviceItem::update_item(const DeviceItem* item) void DeviceItem::update_item(const DeviceItem* item)
+7 -1
View File
@@ -1053,7 +1053,13 @@ void PartPlate::render_grid(bool bottom) {
void PartPlate::render_height_limit(PartPlate::HeightLimitMode mode) void PartPlate::render_height_limit(PartPlate::HeightLimitMode mode)
{ {
if (m_print && m_print->config().print_sequence == PrintSequence::ByObject && mode != HEIGHT_LIMIT_NONE) // Orca: a prime tower compacted by "No sparse layers" drags the nozzle back down to the plate on
// every toolchange, so the rod and the lid limit how tall a neighbouring object may be exactly as
// they do in sequential printing. The reference lines are just as useful there.
const bool relevant_for_print_mode = m_print && (m_print->config().print_sequence == PrintSequence::ByObject ||
(m_print->config().print_sequence == PrintSequence::ByLayer &&
wipe_tower_sparse_layers_skipped(m_print->config()) && m_print->has_wipe_tower()));
if (relevant_for_print_mode && mode != HEIGHT_LIMIT_NONE)
{ {
// draw lower limit // draw lower limit
// ORCA: OpenGL Core Profile // ORCA: OpenGL Core Profile
+24 -89
View File
@@ -2002,14 +2002,12 @@ bool Sidebar::priv::sync_extruder_list(bool &only_external_material, bool is_man
std::string machine_print_name = obj->get_show_printer_type(); std::string machine_print_name = obj->get_show_printer_type();
PresetBundle *preset_bundle = wxGetApp().preset_bundle; PresetBundle *preset_bundle = wxGetApp().preset_bundle;
std::string target_model_id = preset_bundle->printers.get_selected_preset().get_printer_type(preset_bundle); std::string target_model_id = preset_bundle->printers.get_selected_preset().get_printer_type(preset_bundle);
const bool optional_printer_model = DevPrinterConfigUtil::is_optional_printer_model_id(obj->printer_type); Preset* machine_preset = get_printer_preset(obj);
const bool optional_target_model = DevPrinterConfigUtil::is_optional_printer_model_id(target_model_id); if (!machine_preset) {
Preset* machine_preset = optional_printer_model ? nullptr : get_printer_preset(obj);
if (!optional_printer_model && !optional_target_model && !machine_preset) {
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << __LINE__ << "check error: machine_preset empty"; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << __LINE__ << "check error: machine_preset empty";
return false; return false;
} }
if (!optional_printer_model && !optional_target_model && machine_print_name != target_model_id) { if (machine_print_name != target_model_id) {
MessageDialog dlg(this->plater, _L("The currently selected machine preset is inconsistent with the connected printer type.\n" MessageDialog dlg(this->plater, _L("The currently selected machine preset is inconsistent with the connected printer type.\n"
"Are you sure to continue syncing?"), _L("Sync printer information"), wxICON_WARNING | wxYES | wxNO); "Are you sure to continue syncing?"), _L("Sync printer information"), wxICON_WARNING | wxYES | wxNO);
if (dlg.ShowModal() == wxID_NO) { if (dlg.ShowModal() == wxID_NO) {
@@ -2201,11 +2199,6 @@ void Sidebar::priv::update_sync_status(const MachineObject *obj)
return; return;
} }
if (DevPrinterConfigUtil::is_optional_printer_model_id(obj->printer_type)) {
clear_all_sync_status();
return;
}
bool printer_synced = false; bool printer_synced = false;
// 1. update printer status // 1. update printer status
const Preset &cur_preset = wxGetApp().preset_bundle->printers.get_edited_preset(); const Preset &cur_preset = wxGetApp().preset_bundle->printers.get_edited_preset();
@@ -5806,30 +5799,11 @@ void Sidebar::load_ams_list(MachineObject* obj)
filament_ams_list = build_filament_ams_list(obj); filament_ams_list = build_filament_ams_list(obj);
} }
bool device_change = false;
const std::string& device = obj ? obj->get_dev_id() : ""; const std::string& device = obj ? obj->get_dev_id() : "";
const bool same_device = p->ams_list_device == device; if (p->ams_list_device != device) {
// Keep sync metadata out of the device payload, but preserve it across a
// subscription refresh when the physical filament in a slot is unchanged.
// Otherwise the refreshed configs differ only by the missing
// filament_changed key, causing combo boxes to rebuild and lose their
// transient post-sync badges.
auto &previous_filament_ams_list = wxGetApp().preset_bundle->filament_ams_list;
for (auto &entry : filament_ams_list) {
auto previous = previous_filament_ams_list.find(entry.first);
const auto *previous_changed = previous == previous_filament_ams_list.end() ? nullptr :
dynamic_cast<const ConfigOptionBool *>(previous->second.option("filament_changed"));
if (!same_device || previous_changed == nullptr ||
previous->second.opt_string("filament_id", 0u) != entry.second.opt_string("filament_id", 0u)) {
continue;
}
entry.second.set_key_value("filament_changed",
new ConfigOptionBool{previous_changed->value});
}
bool device_change = !same_device;
if (device_change) {
p->ams_list_device = device; p->ams_list_device = device;
device_change = true;
} }
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": %1% items") % filament_ams_list.size(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": %1% items") % filament_ams_list.size();
if (wxGetApp().preset_bundle->filament_ams_list == filament_ams_list && !device_change) if (wxGetApp().preset_bundle->filament_ams_list == filament_ams_list && !device_change)
@@ -5839,27 +5813,9 @@ void Sidebar::load_ams_list(MachineObject* obj)
wxGetApp().preset_bundle->filament_ams_list = filament_ams_list; wxGetApp().preset_bundle->filament_ams_list = filament_ams_list;
for (auto c : p->combos_filament){ for (auto c : p->combos_filament){
c->set_sync_badge(false);
c->update(); c->update();
} if (device_change) {
c->ShowBadge(false);//change printer,then clear badge
if (!device_change) {
size_t combo_index = 0;
for (const auto &entry : filament_ams_list) {
const auto &tray = entry.second;
const bool has_filament = !tray.opt_string("filament_id", 0u).empty();
const bool is_placeholder = tray.has("filament_slot_placeholder") &&
tray.opt_bool("filament_slot_placeholder", 0u);
if (!has_filament && !is_placeholder) {
continue;
}
if (combo_index >= p->combos_filament.size()) {
break;
}
const auto *filament_changed = dynamic_cast<const ConfigOptionBool *>(tray.option("filament_changed"));
p->combos_filament[combo_index]->set_sync_badge(
has_filament && !is_placeholder && filament_changed != nullptr && filament_changed->value);
++combo_index;
} }
} }
@@ -6033,32 +5989,18 @@ void Sidebar::sync_ams_list(bool is_from_big_sync_btn)
auto tip = sync_color_only ? _L("Only filament color information has been synchronized from printer.") : auto tip = sync_color_only ? _L("Only filament color information has been synchronized from printer.") :
_L("Filament type and color information have been synchronized, but slot information is not included."); _L("Filament type and color information have been synchronized, but slot information is not included.");
c->SetToolTip(tip); c->SetToolTip(tip);
c->set_sync_badge(true); c->ShowBadge(true);
}; };
{ // badge ams filament { // badge ams filament
clear_combos_filament_badge(); clear_combos_filament_badge();
if (sync_result.direct_sync) { if (sync_result.direct_sync) {
// A placeholder contributes a preserved project filament to the // Orca: PresetBundle::sync_ams_list rebuilds combos_filament
// overwrite result, but it is not AMS-sourced and must not get a // 1:1 from the AMS trays that produce a combo (loaded trays + placeholders; non-placeholder
// sync badge. Non-placeholder empty trays are omitted entirely. // empty trays are skipped), so every resulting combo is AMS-sourced and gets a badge. The
size_t combo_index = 0; // previous per-tray index walked the full filament_ams_list (including the skipped empties),
for (const auto &entry : wxGetApp().preset_bundle->filament_ams_list) { // so an empty slot before a loaded one dropped the badge for the trailing filaments.
const auto &tray = entry.second; for (auto &c : p->combos_filament) {
const bool has_filament = !tray.opt_string("filament_id", 0u).empty(); badge_combox_filament(c);
const bool is_placeholder = tray.has("filament_slot_placeholder") &&
tray.opt_bool("filament_slot_placeholder", 0u);
if (!has_filament && !is_placeholder) {
continue;
}
if (combo_index >= p->combos_filament.size()) {
break;
}
if (is_placeholder) {
p->combos_filament[combo_index]->set_sync_badge(false);
} else {
badge_combox_filament(p->combos_filament[combo_index]);
}
++combo_index;
} }
} }
} }
@@ -6326,11 +6268,6 @@ template<typename T> void setup_dialog_position(T& info)
void Sidebar::pop_sync_nozzle_and_ams_dialog() { void Sidebar::pop_sync_nozzle_and_ams_dialog() {
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " begin pop_sync_nozzle_and_ams_dialog"; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " begin pop_sync_nozzle_and_ams_dialog";
auto agent = wxGetApp().getAgent();
if (!agent || agent->get_filament_sync_mode() == FilamentSyncMode::none) {
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " filament synchronization is not supported; skipping dialog";
return;
}
wxTheApp->CallAfter([this]() { wxTheApp->CallAfter([this]() {
SyncNozzleAndAmsDialog::InputInfo temp_na_info; SyncNozzleAndAmsDialog::InputInfo temp_na_info;
wxPoint big_btn_pt; wxPoint big_btn_pt;
@@ -6462,14 +6399,17 @@ void Sidebar::clear_combos_filament_badge()
{ {
auto &combos_filament = p->combos_filament; auto &combos_filament = p->combos_filament;
for (auto &c : combos_filament) { // clear flag for (auto &c : combos_filament) { // clear flag
c->set_sync_badge(false); c->ShowBadge(false);
} }
} }
void Sidebar::udpate_combos_filament_badge() { void Sidebar::udpate_combos_filament_badge() {
auto &combos_filament = p->combos_filament; auto &combos_filament = p->combos_filament;
for (auto &c : combos_filament) { for (auto &c : combos_filament) {
c->update_badge_according_flag(); auto selection = c->GetSelection();
auto select_flag = c->GetFlag(selection);
auto ok = select_flag == (int) PresetComboBox::FilamentAMSType::FROM_AMS;
c->ShowBadge(ok);
} }
} }
@@ -12279,7 +12219,7 @@ void Plater::priv::on_select_preset(wxCommandEvent &evt)
sidebar->auto_calc_flushing_volumes(idx); sidebar->auto_calc_flushing_volumes(idx);
} }
auto select_flag = combo->GetFlag(selection); auto select_flag = combo->GetFlag(selection);
combo->set_sync_badge(select_flag == (int)PresetComboBox::FilamentAMSType::FROM_AMS); combo->ShowBadge(select_flag == (int)PresetComboBox::FilamentAMSType::FROM_AMS);
q->on_filament_change(idx); q->on_filament_change(idx);
} }
bool select_preset = !combo->selection_is_changed_according_to_physical_printers(); bool select_preset = !combo->selection_is_changed_according_to_physical_printers();
@@ -20877,14 +20817,9 @@ bool Plater::is_same_printer_for_connected_and_selected(bool popup_warning)
} }
if (!check_printer_initialized(obj, true, popup_warning)) if (!check_printer_initialized(obj, true, popup_warning))
return false; return false;
const std::string machine_model = obj->printer_type; Preset * machine_preset = get_printer_preset(obj);
PresetBundle *preset_bundle = wxGetApp().preset_bundle; if (!machine_preset)
const std::string selected_model = preset_bundle ? preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle) : std::string();
if (!DevPrinterConfigUtil::is_optional_printer_model_id(machine_model) &&
!DevPrinterConfigUtil::is_optional_printer_model_id(selected_model) &&
!get_printer_preset(obj)) {
return false; return false;
}
if (wxGetApp().is_blocking_printing()) { if (wxGetApp().is_blocking_printing()) {
if (popup_warning) { if (popup_warning) {
-18
View File
@@ -11,7 +11,6 @@ namespace Slic3r
// IMPORTANT: ordinal order is the Plugins dialog Status sort priority. // IMPORTANT: ordinal order is the Plugins dialog Status sort priority.
Activated, Activated,
Error, Error,
RuntimeError,
Inactive, Inactive,
Loading Loading
}; };
@@ -22,28 +21,11 @@ namespace Slic3r
{ {
case PluginStatus::Activated: return "Activated"; case PluginStatus::Activated: return "Activated";
case PluginStatus::Error: return "Error"; case PluginStatus::Error: return "Error";
case PluginStatus::RuntimeError: return "RuntimeError";
case PluginStatus::Inactive: return "Inactive"; case PluginStatus::Inactive: return "Inactive";
case PluginStatus::Loading: return "Loading"; case PluginStatus::Loading: return "Loading";
} }
return "Inactive"; return "Inactive";
} }
// why: a plugin whose module is live but whose catalog carries an error is a
// RUNTIME fault (e.g. a capability rejected at register time) - it stays
// loaded/checked and is only flagged, distinct from a load-time Error where
// the module never came up. Loading wins over both so an in-flight reload
// never flashes an error.
inline PluginStatus resolve_plugin_status(bool loading, bool has_error, bool is_loaded)
{
if (loading)
return PluginStatus::Loading;
if (has_error)
return is_loaded ? PluginStatus::RuntimeError : PluginStatus::Error;
if (is_loaded)
return PluginStatus::Activated;
return PluginStatus::Inactive;
}
} }
} // namespace Slic3r::GUI } // namespace Slic3r::GUI
+8 -5
View File
@@ -237,7 +237,6 @@ nlohmann::json build_plugin_payload_item(const PluginDialogItem& dialog_item)
payload_item["label"] = dialog_item.display_name; payload_item["label"] = dialog_item.display_name;
payload_item["source"] = to_string(dialog_item.source); payload_item["source"] = to_string(dialog_item.source);
payload_item["status"] = to_string(dialog_item.status); payload_item["status"] = to_string(dialog_item.status);
payload_item["is_loaded"] = dialog_item.is_loaded;
payload_item["error"] = dialog_item.error_text; payload_item["error"] = dialog_item.error_text;
payload_item["update_status"] = to_string(dialog_item.update_status); payload_item["update_status"] = to_string(dialog_item.update_status);
payload_item["unauthorized"] = dialog_item.unauthorized; payload_item["unauthorized"] = dialog_item.unauthorized;
@@ -382,7 +381,14 @@ PluginDialogItem build_plugin_dialog_item(const PluginDescriptor& descriptor)
item.sharing_token = descriptor.sharing_token; item.sharing_token = descriptor.sharing_token;
item.thumbnail_url = descriptor.thumbnail_url; item.thumbnail_url = descriptor.thumbnail_url;
item.status = resolve_plugin_status(item.loading, item.has_error, item.is_loaded); if (item.loading)
item.status = PluginStatus::Loading;
else if (item.has_error)
item.status = PluginStatus::Error;
else if (item.is_loaded)
item.status = PluginStatus::Activated;
else
item.status = PluginStatus::Inactive;
item.available_actions = evaluate_action_policy(item); item.available_actions = evaluate_action_policy(item);
const bool has_enabled_script = std::any_of(item.capabilities.begin(), item.capabilities.end(), const bool has_enabled_script = std::any_of(item.capabilities.begin(), item.capabilities.end(),
@@ -658,9 +664,6 @@ void PluginsDialog::toggle_plugin(const std::string& plugin_key, bool enabled)
} }
BOOST_LOG_TRIVIAL(info) << "Plugin unloaded from Plugins dialog: " << plugin_key; BOOST_LOG_TRIVIAL(info) << "Plugin unloaded from Plugins dialog: " << plugin_key;
// A user-disabled plugin has no meaningful error state.
if (!manager.clear_plugin_error(plugin_key))
BOOST_LOG_TRIVIAL(warning) << "Failed to clear plugin error for " << plugin_key << " (failed to find)";
// A prior activation of this plugin is moot now; drop it so no stale "Activated" arrives later. // A prior activation of this plugin is moot now; drop it so no stale "Activated" arrives later.
if (m_activating_plugin_key == plugin_key) if (m_activating_plugin_key == plugin_key)
m_activating_plugin_key.clear(); m_activating_plugin_key.clear();
+1 -2
View File
@@ -63,7 +63,6 @@ std::string PrePrintChecker::get_print_status_info(PrintDialogStatus status)
case PrintStatusRackReading: return "PrintStatusRackReading"; case PrintStatusRackReading: return "PrintStatusRackReading";
case PrintStatusRackNozzleNumUnmeetWarning: return "PrintStatusRackNozzleNumUnmeetWarning"; case PrintStatusRackNozzleNumUnmeetWarning: return "PrintStatusRackNozzleNumUnmeetWarning";
case PrintStatusHasUnreliableNozzleWarning: return "PrintStatusHasUnreliableNozzleWarning"; case PrintStatusHasUnreliableNozzleWarning: return "PrintStatusHasUnreliableNozzleWarning";
case PrintStatusOptionalPrinterModel: return "PrintStatusOptionalPrinterModel";
case PrintStatusWarningExtFilamentNotMatch: return "PrintStatusWarningExtFilamentNotMatch"; case PrintStatusWarningExtFilamentNotMatch: return "PrintStatusWarningExtFilamentNotMatch";
case PrintStatusFilamentWarningNozzleHRC: return "PrintStatusFilamentWarningNozzleHRC"; case PrintStatusFilamentWarningNozzleHRC: return "PrintStatusFilamentWarningNozzleHRC";
case PrintStatusTPUUnsupportCaliOn: return "PrintStatusTPUUnsupportCaliOn"; case PrintStatusTPUUnsupportCaliOn: return "PrintStatusTPUUnsupportCaliOn";
@@ -105,7 +104,6 @@ wxString PrePrintChecker::get_pre_state_msg(PrintDialogStatus status)
case PrintStatusNeedConsistencyUpgrading: return _L("Cannot send the print job to a printer whose firmware must be updated."); case PrintStatusNeedConsistencyUpgrading: return _L("Cannot send the print job to a printer whose firmware must be updated.");
case PrintStatusBlankPlate: return _L("Cannot send a print job for an empty plate."); case PrintStatusBlankPlate: return _L("Cannot send a print job for an empty plate.");
case PrintStatusTimelapseNoSdcard: return _L("Storage needs to be inserted to record timelapse."); case PrintStatusTimelapseNoSdcard: return _L("Storage needs to be inserted to record timelapse.");
case PrintStatusOptionalPrinterModel: return _L("The selected printer model could not be identified, so compatibility with the print file configuration cannot be verified. Please verify the printer preset before sending.");
case PrintStatusMixAmsAndVtSlotWarning: return _L("You have selected both external and AMS filaments for an extruder. You will need to manually switch the external filament during printing."); case PrintStatusMixAmsAndVtSlotWarning: return _L("You have selected both external and AMS filaments for an extruder. You will need to manually switch the external filament during printing.");
case PrintStatusTPUUnsupportAutoCali: return _L("TPU 90A/TPU 85A is too soft and does not support automatic Flow Dynamics calibration."); case PrintStatusTPUUnsupportAutoCali: return _L("TPU 90A/TPU 85A is too soft and does not support automatic Flow Dynamics calibration.");
case PrintStatusWarningKvalueNotUsed: return _L("Set dynamic flow calibration to 'OFF' to enable custom dynamic flow value."); case PrintStatusWarningKvalueNotUsed: return _L("Set dynamic flow calibration to 'OFF' to enable custom dynamic flow value.");
@@ -381,3 +379,4 @@ bool PrinterMsgPanel::UpdateInfos(const std::vector<prePrintInfo>& infos)
} }
}; };
-1
View File
@@ -112,7 +112,6 @@ enum PrintDialogStatus : unsigned int {
// Orca: a nozzle diameter that differs from the one the printer remembers is a warning, // Orca: a nozzle diameter that differs from the one the printer remembers is a warning,
// not an error, so non-standard nozzles can still be printed with. // not an error, so non-standard nozzles can still be printed with.
PrintStatusNozzleDiameterMismatch, PrintStatusNozzleDiameterMismatch,
PrintStatusOptionalPrinterModel,
PrintStatusPrinterWarningEnd, PrintStatusPrinterWarningEnd,
// Warnings for filament // Warnings for filament
+3 -11
View File
@@ -361,8 +361,7 @@ wxString PresetComboBox::get_preset_item_name(unsigned int index)
return GetString(index); return GetString(index);
} }
std::map<std::string, MachineObject *> machine_list = std::map<std::string, MachineObject *> machine_list = dev->get_my_machine_list();
dev->get_my_machine_list(dev->get_current_printer_agent_id());
if (machine_list.empty()) { if (machine_list.empty()) {
assert(false); assert(false);
m_selected_dev_id.clear(); m_selected_dev_id.clear();
@@ -480,8 +479,7 @@ void PresetComboBox::add_connected_printers(std::string selected, bool alias_nam
if (!dev) if (!dev)
return; return;
std::map<std::string, MachineObject *> machine_list = std::map<std::string, MachineObject *> machine_list = dev->get_my_machine_list();
dev->get_my_machine_list(dev->get_current_printer_agent_id());
if (machine_list.empty()) if (machine_list.empty())
return; return;
@@ -1001,13 +999,7 @@ void PlaterPresetComboBox::update_badge_according_flag() {
auto selection = GetSelection(); auto selection = GetSelection();
auto select_flag = GetFlag(selection); auto select_flag = GetFlag(selection);
auto ok = select_flag == (int) PresetComboBox::FilamentAMSType::FROM_AMS; auto ok = select_flag == (int) PresetComboBox::FilamentAMSType::FROM_AMS;
ShowBadge(m_sync_badge || ok); ShowBadge(ok);
}
void PlaterPresetComboBox::set_sync_badge(bool show)
{
m_sync_badge = show;
ShowBadge(show);
} }
bool PlaterPresetComboBox::switch_to_tab() bool PlaterPresetComboBox::switch_to_tab()
-2
View File
@@ -205,7 +205,6 @@ public:
void msw_rescale() override; void msw_rescale() override;
void OnSelect(wxCommandEvent& evt) override; void OnSelect(wxCommandEvent& evt) override;
void update_badge_according_flag(); void update_badge_according_flag();
void set_sync_badge(bool show);
FilamentColor get_cur_color_info(); FilamentColor get_cur_color_info();
void show_default_color_picker(); void show_default_color_picker();
@@ -215,7 +214,6 @@ public:
private: private:
// BBS // BBS
wxColor m_color; wxColor m_color;
bool m_sync_badge{false};
}; };
+3 -9
View File
@@ -1736,8 +1736,7 @@ void InputIpAddressDialog::set_machine_obj(MachineObject* obj)
auto str_ip = m_input_ip->GetTextCtrl()->GetValue(); auto str_ip = m_input_ip->GetTextCtrl()->GetValue();
auto str_access_code = m_input_access_code->GetTextCtrl()->GetValue(); auto str_access_code = m_input_access_code->GetTextCtrl()->GetValue();
// ORCA enabling / disabling buttons with conditions enough to change its style // ORCA enabling / disabling buttons with conditions enough to change its style
m_button_ok->Enable(isIp(str_ip.ToStdString()) && m_button_ok->Enable(isIp(str_ip.ToStdString()) && str_access_code.Length() == 8);
(str_access_code.IsEmpty() || str_access_code.Length() >= 8));
Layout(); Layout();
Fit(); Fit();
@@ -1802,8 +1801,6 @@ void InputIpAddressDialog::on_ok(wxMouseEvent& evt)
m_trouble_shoot->Hide(); m_trouble_shoot->Hide();
std::string str_ip = m_input_ip->GetTextCtrl()->GetValue().ToStdString(); std::string str_ip = m_input_ip->GetTextCtrl()->GetValue().ToStdString();
std::string str_access_code = m_input_access_code->GetTextCtrl()->GetValue().ToStdString(); std::string str_access_code = m_input_access_code->GetTextCtrl()->GetValue().ToStdString();
if (str_access_code.empty())
str_access_code = "88888888";
std::string str_name = m_input_printer_name->GetTextCtrl()->GetValue().Strip(wxString::both).ToStdString(); std::string str_name = m_input_printer_name->GetTextCtrl()->GetValue().Strip(wxString::both).ToStdString();
// Serial number should not contain lower case letters, and bambu_network plugin crashes // Serial number should not contain lower case letters, and bambu_network plugin crashes
// if user entered the wrong serial number, so we call `Upper()` here. // if user entered the wrong serial number, so we call `Upper()` here.
@@ -1838,8 +1835,6 @@ void InputIpAddressDialog::on_send_retry()
Fit(); Fit();
wxString ip = m_input_ip->GetTextCtrl()->GetValue(); wxString ip = m_input_ip->GetTextCtrl()->GetValue();
wxString str_access_code = m_input_access_code->GetTextCtrl()->GetValue(); wxString str_access_code = m_input_access_code->GetTextCtrl()->GetValue();
if (str_access_code.IsEmpty())
str_access_code = "88888888";
// check support function // check support function
if (!m_obj) return; if (!m_obj) return;
@@ -2061,7 +2056,7 @@ void InputIpAddressDialog::on_text(wxCommandEvent &evt)
auto str_ip = m_input_ip->GetTextCtrl()->GetValue(); auto str_ip = m_input_ip->GetTextCtrl()->GetValue();
auto str_access_code = m_input_access_code->GetTextCtrl()->GetValue(); auto str_access_code = m_input_access_code->GetTextCtrl()->GetValue();
if (str_access_code.IsEmpty()) { if (str_access_code.empty()) {
str_access_code = "88888888"; str_access_code = "88888888";
} }
@@ -2077,8 +2072,7 @@ void InputIpAddressDialog::on_text(wxCommandEvent &evt)
} }
// ORCA enabling / disabling buttons with conditions enough to change its style // ORCA enabling / disabling buttons with conditions enough to change its style
bool valid_access_code_length = str_access_code.IsEmpty() || str_access_code.Length() >= 8; bool enable_btns = isIp(str_ip.ToStdString()) && str_access_code.Length() == 8 && invalid_access_code;
bool enable_btns = isIp(str_ip.ToStdString()) && valid_access_code_length && invalid_access_code;
m_button_manual_setup->Enable(enable_btns); m_button_manual_setup->Enable(enable_btns);
m_button_ok->Enable(enable_btns); m_button_ok->Enable(enable_btns);
+34 -16
View File
@@ -62,7 +62,7 @@ static char marker_by_type(Preset::Type type, PrinterTechnology pt)
} }
} }
std::string Option::opt_key() const { return into_u8(key).substr(2); } std::string Option::opt_key() const { return key.size() < 2 ? std::string() : into_u8(key).substr(2); }
void FoundOption::get_marked_label_and_tooltip(const char **label_, const char **tooltip_) const void FoundOption::get_marked_label_and_tooltip(const char **label_, const char **tooltip_) const
{ {
@@ -116,6 +116,7 @@ void OptionsSearcher::append_options(DynamicPrintConfig *config, Preset::Type ty
case coFloats: change_opt_key<ConfigOptionFloats>(opt_key, config, cnt); break; case coFloats: change_opt_key<ConfigOptionFloats>(opt_key, config, cnt); break;
case coStrings: change_opt_key<ConfigOptionStrings>(opt_key, config, cnt); break; case coStrings: change_opt_key<ConfigOptionStrings>(opt_key, config, cnt); break;
case coPercents: change_opt_key<ConfigOptionPercents>(opt_key, config, cnt); break; case coPercents: change_opt_key<ConfigOptionPercents>(opt_key, config, cnt); break;
case coFloatsOrPercents: change_opt_key<ConfigOptionVector<FloatOrPercent>>(opt_key, config, cnt); break;
case coPoints: change_opt_key<ConfigOptionPoints>(opt_key, config, cnt); break; case coPoints: change_opt_key<ConfigOptionPoints>(opt_key, config, cnt); break;
// BBS // BBS
case coEnums: change_opt_key<ConfigOptionInts>(opt_key, config, cnt); break; case coEnums: change_opt_key<ConfigOptionInts>(opt_key, config, cnt); break;
@@ -334,29 +335,46 @@ const Option &OptionsSearcher::get_option(size_t pos_in_filter) const
const Option &OptionsSearcher::get_option(const std::string &opt_key, Preset::Type type, int &variant_index) const const Option &OptionsSearcher::get_option(const std::string &opt_key, Preset::Type type, int &variant_index) const
{ {
auto not_found = [&variant_index]() -> const Option& {
static const Option empty_option;
variant_index = -2;
return empty_option;
};
variant_index = -1;
std::string opt_key2 = opt_key; std::string opt_key2 = opt_key;
if (auto n = opt_key.find('#'); n != std::string::npos) { if (auto n = opt_key.find('#'); n != std::string::npos) {
variant_index = std::atoi(opt_key.c_str() + n + 1); variant_index = std::atoi(opt_key.c_str() + n + 1);
opt_key2 = opt_key.substr(0, n); opt_key2 = opt_key.substr(0, n);
} }
auto it = std::lower_bound(options.begin(), options.end(), Option({boost::nowide::widen(get_key(opt_key2, type))})); const std::wstring key = boost::nowide::widen(get_key(opt_key2, type));
// BBS: return the 0th option when not found in searcher caused by mode difference auto it = std::lower_bound(options.begin(), options.end(), Option({key}));
// assert(it != options.end()); if (it == options.end()) return not_found();
if (it == options.end()) { variant_index = -2 ; return options[0]; } if (it->key == key) {
if (it->opt_key() == opt_key2) {
variant_index = -1; variant_index = -1;
} else { } else {
const std::string opt_key3 = opt_key2 + "#"; const std::wstring prefix = key + L"#";
it = std::lower_bound(it, options.end(), Option({boost::nowide::widen(get_key(opt_key3, type))})); it = std::lower_bound(it, options.end(), Option({prefix}));
if (it == options.end() || it->opt_key().compare(0, opt_key3.length(), opt_key3) != 0) { if (it == options.end() || it->key.compare(0, prefix.length(), prefix) != 0)
variant_index = -2; // Not found return not_found();
return options[0]; // Orca: Copy-parameters dialogs request the base key, without a vector index.
if (variant_index < 0) return *it;
const bool has_mode = type == Preset::TYPE_PRINTER && printer_options_with_variant_2.count(opt_key2) > 0;
const bool has_variant =
(type == Preset::TYPE_PRINT && print_options_with_variant.count(opt_key2) > 0) ||
(type == Preset::TYPE_FILAMENT && filament_options_with_variant.count(opt_key2) > 0) ||
(type == Preset::TYPE_PRINTER && printer_options_with_variant_1.count(opt_key2) > 0) || has_mode;
if (!has_variant || has_mode) {
// Orca: Machine limits store (Normal, Silent) pairs per variant; the UI registers only #0/#1.
const std::wstring indexed_key = has_mode ? prefix + std::to_wstring(variant_index % 2) :
boost::nowide::widen(get_key(opt_key, type));
it = std::lower_bound(it, options.end(), Option({indexed_key}));
if (it == options.end() || it->key != indexed_key)
return not_found();
if (!has_variant)
variant_index = -1;
} }
auto it2 = it;
++it2;
if (it2 != options.end() && it2->opt_key().compare(0, opt_key3.length(), opt_key3) == 0
&& printer_options_with_variant_1.find(opt_key2) == printer_options_with_variant_1.end())
variant_index = -2;
} }
return options[it - options.begin()]; return options[it - options.begin()];
+29 -76
View File
@@ -21,7 +21,6 @@
#include "Jobs/PlaterWorker.hpp" #include "Jobs/PlaterWorker.hpp"
#include "DeviceCore/DevConfig.h" #include "DeviceCore/DevConfig.h"
#include "DeviceCore/DevConfigUtil.h"
#include "DeviceCore/DevNozzleSystem.h" #include "DeviceCore/DevNozzleSystem.h"
#include "DeviceCore/DevNozzleRack.h" #include "DeviceCore/DevNozzleRack.h"
#include "DeviceCore/DevExtensionTool.h" #include "DeviceCore/DevExtensionTool.h"
@@ -1126,10 +1125,7 @@ bool SelectMachineDialog::do_ams_mapping(MachineObject *obj_,bool use_ams)
int filament_result = 0; int filament_result = 0;
std::vector<bool> map_opt; //four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext std::vector<bool> map_opt; //four values: use_left_ams, use_right_ams, use_left_ext, use_right_ext
// Orca: only do the per-physical-extruder left/right split when the device actually reports if (nozzle_nums > 1){
// 2+ extruders. A non-BBL multi-nozzle printer (e.g. Snapmaker U1) reports a single extruder
// with one filament pool, so it maps as a single surface via the else branch below.
if (nozzle_nums > 1 && obj_->GetExtderSystem()->GetTotalExtderCount() > 1){
//get nozzle property, the extders are same? //get nozzle property, the extders are same?
if (true/*!can_hybrid_mapping(obj_get_extder_data())*/){ if (true/*!can_hybrid_mapping(obj_get_extder_data())*/){
std::vector<FilamentInfo> m_ams_mapping_result_left, m_ams_mapping_result_right; std::vector<FilamentInfo> m_ams_mapping_result_left, m_ams_mapping_result_right;
@@ -2288,7 +2284,9 @@ void SelectMachineDialog::show_status(PrintDialogStatus status, std::vector<wxSt
// Fill the real per-printer max color count into the %s template. // Fill the real per-printer max color count into the %s template.
if (!params.empty()) if (!params.empty())
msg = wxString::Format(m_pre_print_checker.get_pre_state_msg(status), params[0], params[0]); msg = wxString::Format(m_pre_print_checker.get_pre_state_msg(status), params[0], params[0]);
} else if (status == PrintDialogStatus::PrintStatusAmsMappingU0Invalid) { }
else if (status == PrintDialogStatus::PrintStatusAmsMappingU0Invalid) {
wxString msg_text; wxString msg_text;
if (params.size() > 1) if (params.size() > 1)
msg_text = wxString::Format(_L("Filament %s does not match the filament in AMS slot %s. Please update the printer firmware to support AMS slot assignment."), params[0], params[1]); msg_text = wxString::Format(_L("Filament %s does not match the filament in AMS slot %s. Please update the printer firmware to support AMS slot assignment."), params[0], params[1]);
@@ -2314,10 +2312,8 @@ void SelectMachineDialog::show_status(PrintDialogStatus status, std::vector<wxSt
} else if (status == PrintDialogStatus::PrintStatusNoSdcard) { } else if (status == PrintDialogStatus::PrintStatusNoSdcard) {
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
Enable_Send_Button(false); Enable_Send_Button(false);
} else if (status == PrintDialogStatus::PrintStatusUnsupportedPrinter || }else if (status == PrintDialogStatus::PrintStatusUnsupportedPrinter) {
status == PrintDialogStatus::PrintStatusOptionalPrinterModel) {
wxString msg_text; wxString msg_text;
const bool block_send = status == PrintDialogStatus::PrintStatusUnsupportedPrinter;
try try
{ {
DeviceManager* dev = Slic3r::GUI::wxGetApp().getDeviceManager(); DeviceManager* dev = Slic3r::GUI::wxGetApp().getDeviceManager();
@@ -2343,21 +2339,17 @@ void SelectMachineDialog::show_status(PrintDialogStatus status, std::vector<wxSt
auto target_print_name = wxString(DevPrinterConfigUtil::get_printer_display_name(target_model_id)); auto target_print_name = wxString(DevPrinterConfigUtil::get_printer_display_name(target_model_id));
target_print_name.Replace(wxT("Bambu Lab "), wxEmptyString); target_print_name.Replace(wxT("Bambu Lab "), wxEmptyString);
if (block_send) { msg_text = wxString::Format(_L("The selected printer (%s) is incompatible with the print file configuration (%s). Please adjust the printer preset in the prepare page or choose a compatible printer on this page."), sourcet_print_name, target_print_name);
msg_text = wxString::Format(_L("The selected printer (%s) is incompatible with the print file configuration (%s). Please adjust the printer preset in the prepare page or choose a compatible printer on this page."), sourcet_print_name, target_print_name);
} else {
msg_text = wxString::Format(_L("The selected printer (%s) has an unknown model, so compatibility with the print file configuration (%s) cannot be verified. Please verify the printer preset before sending."), sourcet_print_name, target_print_name);
}
msg = msg_text; msg = msg_text;
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
Enable_Send_Button(!block_send); Enable_Send_Button(false);
} }
catch (...) catch (...)
{ {
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
Enable_Send_Button(!block_send); Enable_Send_Button(false);
} }
@@ -2534,7 +2526,15 @@ bool SelectMachineDialog::is_blocking_printing(MachineObject* obj_)
} }
} }
return !DevPrinterConfigUtil::is_printer_model_compatible(source_model, *obj_); if (source_model != target_model) {
std::vector<std::string> compatible_machine = obj_->get_compatible_machine();
vector<std::string>::iterator it = find(compatible_machine.begin(), compatible_machine.end(), source_model);
if (it == compatible_machine.end()) {
return true;
}
}
return false;
} }
static std::unordered_set<int> _get_used_nozzle_idxes() static std::unordered_set<int> _get_used_nozzle_idxes()
@@ -2622,10 +2622,6 @@ bool SelectMachineDialog::is_same_printer_model()
if(preset_bundle == nullptr) return result; if(preset_bundle == nullptr) return result;
const auto source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle); const auto source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle);
const auto target_model = obj_->printer_type; const auto target_model = obj_->printer_type;
if (DevPrinterConfigUtil::is_optional_printer_model_id(source_model) ||
DevPrinterConfigUtil::is_optional_printer_model_id(target_model)) {
return true;
}
// Orca: ignore P1P -> P1S // Orca: ignore P1P -> P1S
if (source_model != target_model) { if (source_model != target_model) {
if ((source_model == "C12" && target_model == "C11") || (source_model == "C11" && target_model == "C12") || if ((source_model == "C12" && target_model == "C11") || (source_model == "C11" && target_model == "C12") ||
@@ -3700,32 +3696,10 @@ void SelectMachineDialog::on_send_print()
m_print_job->on_success([this]() { finish_mode(); }); m_print_job->on_success([this]() { finish_mode(); });
m_print_job->on_check_ip_address_fail([this]() { m_print_job->on_check_ip_address_fail([this]() {
// Invoked from the PrintJob worker thread when the LAN pre-flight (file upload wxCommandEvent* evt = new wxCommandEvent(EVT_CLEAR_IPADDRESS);
// verification) fails. Marshal device/UI access to the main thread. wxQueueEvent(this, evt);
CallAfter([this]() wxGetApp().show_ip_address_enter_dialog();
{ });
// Reset the dialog out of sending mode so the user can retry.
wxCommandEvent* evt = new wxCommandEvent(EVT_CLEAR_IPADDRESS);
wxQueueEvent(this, evt);
DeviceManager* dev = wxGetApp().getDeviceManager();
MachineObject* obj = dev ? dev->get_selected_machine() : nullptr;
if (obj && obj->is_connected())
{
// Connected: failed on file upload
MessageDialog dlg(this,
_L("Failed to upload the file to the printer's storage. Please try again."),
_L("Send Failed"), wxOK | wxICON_ERROR);
dlg.ShowModal();
}
else
{
// Not connected: reenter ip and access code
wxGetApp().show_ip_address_enter_dialog();
}
});
});
// update ota version // update ota version
NetworkAgent* agent = wxGetApp().getAgent(); NetworkAgent* agent = wxGetApp().getAgent();
@@ -4559,13 +4533,11 @@ bool SelectMachineDialog::CheckErrorExtruderNozzleWithSlicing(MachineObject* obj
// check nozzle data valid // check nozzle data valid
{ {
// Commented out the following as ntUndefine and 0.0f are default values if (installed_ext_nozzle.GetNozzleType() == NozzleType::ntUndefine ||
// (signifying that the value is not given) that should PASS, not fail installed_ext_nozzle.GetNozzleDiameter() <= 0.0f) {
// if (installed_ext_nozzle.GetNozzleType() == NozzleType::ntUndefine || show_status(PrintDialogStatus::PrintStatusNozzleDataInvalid);
// installed_ext_nozzle.GetNozzleDiameter() <= 0.0f) { return false;
// show_status(PrintDialogStatus::PrintStatusNozzleDataInvalid); }
// return false;
// }
if (obj_->is_nozzle_flow_type_supported() && if (obj_->is_nozzle_flow_type_supported() &&
installed_ext_nozzle.GetNozzleFlowType() == NozzleFlowType::NONE_FLOWTYPE) { installed_ext_nozzle.GetNozzleFlowType() == NozzleFlowType::NONE_FLOWTYPE) {
@@ -4594,10 +4566,7 @@ bool SelectMachineDialog::CheckErrorExtruderNozzleWithSlicing(MachineObject* obj
// check nozzle diameter // check nozzle diameter
{ {
// 0.0f is default when there is no nozzle diameter is given. if (slicing_ext.nozzle_diameter != installed_ext_nozzle.GetNozzleDiameter()) {
// In nozzle_diameter == 0.0f case, it passes and does not require a comparison
if (installed_ext_nozzle.GetNozzleDiameter() > 0.0f &&
slicing_ext.nozzle_diameter != installed_ext_nozzle.GetNozzleDiameter()) {
std::vector<wxString> msg_params; std::vector<wxString> msg_params;
if (ext_sys->GetTotalExtderCount() == 2) { if (ext_sys->GetTotalExtderCount() == 2) {
const wxString& mismatch_nozzle_str = _get_nozzle_name(ext_sys->GetTotalExtderCount(), slicing_ext_idx); const wxString& mismatch_nozzle_str = _get_nozzle_name(ext_sys->GetTotalExtderCount(), slicing_ext_idx);
@@ -4791,22 +4760,6 @@ void SelectMachineDialog::update_show_status(MachineObject* obj_)
return; return;
} }
bool has_optional_printer_model = DevPrinterConfigUtil::is_optional_printer_model_id(obj_->printer_type);
if (m_print_type == PrintFromType::FROM_NORMAL) {
PresetBundle* preset_bundle = wxGetApp().preset_bundle;
has_optional_printer_model = has_optional_printer_model ||
(preset_bundle && DevPrinterConfigUtil::is_optional_printer_model_id(
preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle)));
} else if (m_print_type == PrintFromType::FROM_SDCARD_VIEW && !m_required_data_plate_data_list.empty()) {
has_optional_printer_model = has_optional_printer_model ||
DevPrinterConfigUtil::is_optional_printer_model_id(
m_required_data_plate_data_list[m_print_plate_idx]->printer_model_id);
}
if (has_optional_printer_model) {
show_status(PrintDialogStatus::PrintStatusOptionalPrinterModel);
}
if (is_blocking_printing(obj_)) { if (is_blocking_printing(obj_)) {
show_status(PrintDialogStatus::PrintStatusUnsupportedPrinter); show_status(PrintDialogStatus::PrintStatusUnsupportedPrinter);
return; return;
@@ -5529,8 +5482,8 @@ void SelectMachineDialog::reset_and_sync_ams_list()
item = new MaterialItem(m_filament_left_panel, colour_rgb, _L(display_materials[extruder])); item = new MaterialItem(m_filament_left_panel, colour_rgb, _L(display_materials[extruder]));
m_sizer_ams_mapping_left->Add(item, 0, wxALL, FromDIP(5)); m_sizer_ams_mapping_left->Add(item, 0, wxALL, FromDIP(5));
} }
else // map == 2, or (non-BBL multi-nozzle) 3+; update_material_item_pos() collapses else if (m_filaments_map[extruder] == 2)
{ // these into the single panel when the device reports < 2 extruders. {
item = new MaterialItem(m_filament_right_panel, colour_rgb, _L(display_materials[extruder])); item = new MaterialItem(m_filament_right_panel, colour_rgb, _L(display_materials[extruder]));
m_sizer_ams_mapping_right->Add(item, 0, wxALL, FromDIP(5)); m_sizer_ams_mapping_right->Add(item, 0, wxALL, FromDIP(5));
} }
+82 -122
View File
@@ -24,7 +24,6 @@
#include "BitmapCache.hpp" #include "BitmapCache.hpp"
#include "DeviceCore/DevManager.h" #include "DeviceCore/DevManager.h"
#include "DeviceCore/DevConfigUtil.h"
#include "DeviceCore/DevStorage.h" #include "DeviceCore/DevStorage.h"
#include "slic3r/Utils/FileTransferUtils.hpp" #include "slic3r/Utils/FileTransferUtils.hpp"
@@ -301,7 +300,7 @@ SendToPrinterDialog::SendToPrinterDialog(Plater *plater)
m_storage_panel->Layout(); m_storage_panel->Layout();
// try to connect // try to connect
m_statictext_printer_msg = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(FromDIP(400), -1), wxALIGN_CENTER_HORIZONTAL); m_statictext_printer_msg = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_HORIZONTAL);
m_statictext_printer_msg->SetFont(::Label::Body_13); m_statictext_printer_msg->SetFont(::Label::Body_13);
m_statictext_printer_msg->SetForegroundColour(*wxBLACK); m_statictext_printer_msg->SetForegroundColour(*wxBLACK);
m_statictext_printer_msg->Hide(); m_statictext_printer_msg->Hide();
@@ -761,25 +760,9 @@ void SendToPrinterDialog::update_priner_status_msg(wxString msg, bool is_warning
if (str_new != str_old) { if (str_new != str_old) {
if (m_statictext_printer_msg->GetLabel() != msg) { if (m_statictext_printer_msg->GetLabel() != msg) {
m_statictext_printer_msg->SetLabel(msg); m_statictext_printer_msg->SetLabel(msg);
const int wrap_width = FromDIP(400); m_statictext_printer_msg->SetMinSize(wxSize(FromDIP(400), -1));
m_statictext_printer_msg->Wrap(wrap_width); m_statictext_printer_msg->SetMaxSize(wxSize(FromDIP(400), -1));
int line_count = 1; m_statictext_printer_msg->Wrap(FromDIP(400));
const wxString wrapped_label = m_statictext_printer_msg->GetLabel();
for (size_t i = 0; i < wrapped_label.length(); ++i) {
if (wrapped_label[i] == '\n')
++line_count;
}
wxCoord text_width = 0;
wxCoord text_height = 0;
m_statictext_printer_msg->GetTextExtent(msg, &text_width, &text_height);
const int extent_line_count = text_width > 0 ?
std::max(1, (static_cast<int>(text_width) + wrap_width - 1) / wrap_width) : 1;
line_count = std::max(line_count, extent_line_count);
const int line_height = std::max(m_statictext_printer_msg->GetCharHeight(), static_cast<int>(text_height));
const int min_height = std::max(m_statictext_printer_msg->GetBestSize().GetHeight(),
line_count * line_height + FromDIP(2));
m_statictext_printer_msg->SetMinSize(wxSize(wrap_width, min_height));
m_statictext_printer_msg->SetMaxSize(wxDefaultSize);
m_statictext_printer_msg->Show(); m_statictext_printer_msg->Show();
Layout(); Layout();
Fit(); Fit();
@@ -1119,7 +1102,7 @@ void SendToPrinterDialog::update_user_printer()
wxArrayString machine_list_name; wxArrayString machine_list_name;
std::map<std::string, MachineObject*> option_list; std::map<std::string, MachineObject*> option_list;
option_list = dev->get_my_machine_list(dev->get_current_printer_agent_id()); option_list = dev->get_my_machine_list();
// same machine only appear once // same machine only appear once
for (auto it = option_list.begin(); it != option_list.end(); it++) { for (auto it = option_list.begin(); it != option_list.end(); it++) {
@@ -1349,7 +1332,17 @@ bool SendToPrinterDialog::is_blocking_printing(MachineObject* obj_)
PresetBundle* preset_bundle = wxGetApp().preset_bundle; PresetBundle* preset_bundle = wxGetApp().preset_bundle;
auto source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle); auto source_model = preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle);
return !DevPrinterConfigUtil::is_printer_model_compatible(source_model, *obj_); auto target_model = obj_->printer_type;
if (source_model != target_model) {
std::vector<std::string> compatible_machine = obj_->get_compatible_machine();
vector<std::string>::iterator it = find(compatible_machine.begin(), compatible_machine.end(), source_model);
if (it == compatible_machine.end()) {
return true;
}
}
return false;
} }
void SendToPrinterDialog::Enable_Refresh_Button(bool en) void SendToPrinterDialog::Enable_Refresh_Button(bool en)
@@ -1420,68 +1413,79 @@ void SendToPrinterDialog::show_status(PrintDialogStatus status, std::vector<wxSt
update_print_status_msg(wxEmptyString, false, false); update_print_status_msg(wxEmptyString, false, false);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusInvalidPrinter) { }
else if (status == PrintDialogStatus::PrintStatusInvalidPrinter) {
update_print_status_msg(wxEmptyString, true, true); update_print_status_msg(wxEmptyString, true, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusConnectingServer) { }
else if (status == PrintDialogStatus::PrintStatusConnectingServer) {
wxString msg_text = _L("Connecting to server..."); wxString msg_text = _L("Connecting to server...");
update_print_status_msg(msg_text, true, true); update_print_status_msg(msg_text, true, true);
Enable_Send_Button(true); Enable_Send_Button(true);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusReading) { }
else if (status == PrintDialogStatus::PrintStatusReading) {
wxString msg_text = _L("Synchronizing device information..."); wxString msg_text = _L("Synchronizing device information...");
update_print_status_msg(msg_text, false, true); update_print_status_msg(msg_text, false, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(false); Enable_Refresh_Button(false);
} else if (status == PrintDialogStatus::PrintStatusReadingFinished) { }
else if (status == PrintDialogStatus::PrintStatusReadingFinished) {
update_print_status_msg(wxEmptyString, false, true); update_print_status_msg(wxEmptyString, false, true);
Enable_Send_Button(true); Enable_Send_Button(true);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusReadingTimeout) { }
else if (status == PrintDialogStatus::PrintStatusReadingTimeout) {
wxString msg_text = _L("Synchronizing device information timed out."); wxString msg_text = _L("Synchronizing device information timed out.");
update_print_status_msg(msg_text, true, true); update_print_status_msg(msg_text, true, true);
Enable_Send_Button(true); Enable_Send_Button(true);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusInUpgrading) { }
else if (status == PrintDialogStatus::PrintStatusInUpgrading) {
wxString msg_text = _L("Cannot send print tasks when an update is in progress"); wxString msg_text = _L("Cannot send print tasks when an update is in progress");
update_print_status_msg(msg_text, true, true); update_print_status_msg(msg_text, true, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusUnsupportedPrinter) { }
else if (status == PrintDialogStatus::PrintStatusUnsupportedPrinter) {
wxString msg_text = _L("The selected printer is incompatible with the chosen printer presets."); wxString msg_text = _L("The selected printer is incompatible with the chosen printer presets.");
update_print_status_msg(msg_text, true, true); update_print_status_msg(msg_text, true, true);
Enable_Send_Button(true); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusRefreshingMachineList) { }
else if (status == PrintDialogStatus::PrintStatusRefreshingMachineList) {
update_print_status_msg(wxEmptyString, false, true); update_print_status_msg(wxEmptyString, false, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(false); Enable_Refresh_Button(false);
} else if (status == PrintDialogStatus::PrintStatusSending) { }
else if (status == PrintDialogStatus::PrintStatusSending) {
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(false); Enable_Refresh_Button(false);
} else if (status == PrintDialogStatus::PrintStatusSendingCanceled) { }
else if (status == PrintDialogStatus::PrintStatusSendingCanceled) {
Enable_Send_Button(true); Enable_Send_Button(true);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusNoSdcard) { }
else if (status == PrintDialogStatus::PrintStatusNoSdcard) {
wxString msg_text = _L("Storage needs to be inserted before send to printer."); wxString msg_text = _L("Storage needs to be inserted before send to printer.");
update_print_status_msg(msg_text, true, true); update_print_status_msg(msg_text, true, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusNotOnTheSameLAN) { }
else if (status == PrintDialogStatus::PrintStatusNotOnTheSameLAN) {
wxString msg_text = _L("The printer is required to be on the same LAN as Orca Slicer."); wxString msg_text = _L("The printer is required to be on the same LAN as Orca Slicer.");
update_print_status_msg(msg_text, true, true); update_print_status_msg(msg_text, true, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusNotSupportedSendToSDCard) { }
else if (status == PrintDialogStatus::PrintStatusNotSupportedSendToSDCard) {
wxString msg_text = _L("The printer does not support sending to printer storage."); wxString msg_text = _L("The printer does not support sending to printer storage.");
update_print_status_msg(msg_text, true, true); update_print_status_msg(msg_text, true, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusPublicInitFailed) { } else if (status == PrintDialogStatus::PrintStatusPublicInitFailed) {
wxString msg_text = _L(
"Failed to initialize the printer file transfer. Please check the connection and try again.");
update_print_status_msg(msg_text, true, true);
Enable_Send_Button(false); Enable_Send_Button(false);
Enable_Refresh_Button(true); Enable_Refresh_Button(true);
} else if (status == PrintDialogStatus::PrintStatusPublicUploadFiled) { } else if (status == PrintDialogStatus::PrintStatusPublicUploadFiled) {
@@ -1659,18 +1663,30 @@ extern void refresh_agora_url(char const *device, char const *dev_ver, char
void SendToPrinterDialog::GetConnection() void SendToPrinterDialog::GetConnection()
{ {
DeviceManager *dm = GUI::wxGetApp().getDeviceManager(); DeviceManager *dm = GUI::wxGetApp().getDeviceManager();
MachineObject *obj = dm ? dm->get_selected_machine() : nullptr;
if (!obj) MachineObject *obj = dm->get_selected_machine();
if (obj == nullptr) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " : obj is empty"; BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " : obj is empty";
if (obj && !obj->get_file_remote()) m_connection_status = ConnectionStatus::NOT_START;
}
int remote_proto = obj->get_file_remote();
if (!remote_proto) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " : remote_proto is not support"; BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " : remote_proto is not support";
if (obj && obj->is_camera_busy_off()) m_connection_status = ConnectionStatus::NOT_START;
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " : camera is busy"; }
NetworkAgent* agent = wxGetApp().getAgent(); if (obj->is_camera_busy_off()) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " : camera is busy";
m_connection_status = ConnectionStatus::NOT_START;
}
if (m_url_timer && m_url_timer->IsRunning()) NetworkAgent *agent = wxGetApp().getAgent();
std::string agent_version = agent ? agent->get_version() : "";
std::string dev_ver = obj->get_ota_version();
std::string dev_id = obj->get_dev_id();
if (m_url_timer && m_url_timer->IsRunning())
{ {
m_url_timer->Stop(); m_url_timer->Stop();
} }
@@ -1693,40 +1709,19 @@ void SendToPrinterDialog::GetConnection()
m_url_timer->GetId()); m_url_timer->GetId());
m_url_timer->StartOnce(8000); m_url_timer->StartOnce(8000);
if (obj && agent) if (agent) {
{
std::string dev_ver = obj->get_ota_version();
std::string dev_id = obj->get_dev_id();
if (m_tcp_try_connect) { if (m_tcp_try_connect) {
std::string devIP = obj->get_dev_ip(); std::string devIP = obj->get_dev_ip();
std::string accessCode = obj->get_access_code(); std::string accessCode = obj->get_access_code();
std::string url = "bambu:///local/" + devIP + "?port=6000&user=" + "bblp" + "&passwd=" + accessCode; std::string url = "bambu:///local/" + devIP + "?port=6000&user=" + "bblp" + "&passwd=" + accessCode;
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Connect method tcp, dev_id=" << dev_id BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Connect method tcp";
<< ", dev_ip=" << devIP << ", access_code_len=" << accessCode.size(); m_filetransfer_tunnel = std::make_unique<FileTransferTunnel>(module(), url);
m_filetransfer_tunnel->on_connection([this](bool is_success, int err_code, std::string error_msg) {
try CallAfter([this, is_success, err_code, error_msg]() {
{ OnConnection(is_success, err_code, error_msg);
m_filetransfer_tunnel = std::make_unique<FileTransferTunnel>(module(), url);
m_filetransfer_tunnel->on_connection([this](bool is_success, int err_code, std::string error_msg)
{
CallAfter([this, is_success, err_code, error_msg]()
{
OnConnection(is_success, err_code, error_msg);
});
}); });
m_filetransfer_tunnel->start_connect(); });
} m_filetransfer_tunnel->start_connect();
catch (const std::exception& e)
{
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": tcp FileTransferTunnel unavailable for dev_id=" <<
dev_id
<< " dev_ip=" << devIP << ": " << e.what();
if (m_url_timer && m_url_timer->IsRunning()) m_url_timer->Stop();
m_filetransfer_tunnel.reset();
m_connection_status = ConnectionStatus::CONNECTION_FAILED;
show_status(PrintDialogStatus::PrintStatusPublicInitFailed);
}
} }
else if (m_tutk_try_connect) else if (m_tutk_try_connect)
{ {
@@ -1754,28 +1749,11 @@ void SendToPrinterDialog::GetConnection()
if (boost::algorithm::starts_with(url, "bambu:///")) if (boost::algorithm::starts_with(url, "bambu:///"))
{ {
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Connect method tutk"; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Connect method tutk";
try m_filetransfer_tunnel = std::make_unique<FileTransferTunnel>(module(), url);
{ m_filetransfer_tunnel->on_connection([this](bool is_success, int err_code, std::string error_msg) {
m_filetransfer_tunnel = std::make_unique<FileTransferTunnel>(module(), url); CallAfter([this, is_success, err_code, error_msg]() { OnConnection(is_success, err_code, error_msg); });
m_filetransfer_tunnel->on_connection( });
[this](bool is_success, int err_code, std::string error_msg) m_filetransfer_tunnel->start_connect();
{
CallAfter([this, is_success, err_code, error_msg]()
{
OnConnection(is_success, err_code, error_msg);
});
});
m_filetransfer_tunnel->start_connect();
}
catch (const std::exception& e)
{
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": tutk FileTransferTunnel unavailable: " << e.
what();
if (m_url_timer && m_url_timer->IsRunning()) m_url_timer->Stop();
m_filetransfer_tunnel.reset();
m_connection_status = ConnectionStatus::CONNECTION_FAILED;
show_status(PrintDialogStatus::PrintStatusPublicInitFailed);
}
} }
else else
{ {
@@ -1874,17 +1852,8 @@ void SendToPrinterDialog::ResetTunnelAndJob()
void SendToPrinterDialog::CreateMediaAbilityJob() void SendToPrinterDialog::CreateMediaAbilityJob()
{ {
nlohmann::json media_ability = {{"cmd_type", 7}}; nlohmann::json media_ability = {{"cmd_type", 7}};
try m_filetransfer_mediability_job = std::make_unique<FileTransferJob>(module(), std::string(media_ability.dump()));
{
m_filetransfer_mediability_job = std::make_unique<FileTransferJob>(module(), std::string(media_ability.dump()));
}
catch (const std::exception& e)
{
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": FileTransferJob unavailable: " << e.what();
show_status(PrintDialogStatus::PrintStatusPublicInitFailed);
return;
}
m_filetransfer_mediability_job->on_result([this](int res, int resp_ec, std::string json_res, std::vector<std::byte> bin_res) { m_filetransfer_mediability_job->on_result([this](int res, int resp_ec, std::string json_res, std::vector<std::byte> bin_res) {
//this pl //this pl
CallAfter([this, res, resp_ec, json_res] { CallAfter([this, res, resp_ec, json_res] {
@@ -1939,20 +1908,11 @@ void SendToPrinterDialog::CreateUploadFileJob(const std::string &path, const std
{"cmd_type", 5}, {"cmd_type", 5},
}; };
upload_params["dest_storage"] = m_selected_storage; upload_params["dest_storage"] = m_selected_storage;
upload_params["dest_name"] = name; // filenme no path upload_params["dest_name"] = name; // filenme no path
upload_params["file_path"] = path; upload_params["file_path"] = path;
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Begin CreateUploadFileJob"; BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Begin CreateUploadFileJob";
try m_filetransfer_uploadfile_job = std::make_unique<FileTransferJob>(module(), std::string(upload_params.dump()));
{
m_filetransfer_uploadfile_job = std::make_unique<FileTransferJob>(module(), std::string(upload_params.dump()));
}
catch (const std::exception& e)
{
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": FileTransferJob unavailable: " << e.what();
show_status(PrintDialogStatus::PrintStatusPublicUploadFiled);
return;
}
m_filetransfer_uploadfile_job->on_result([this](int res, int resp_ec, std::string json_res, std::vector<std::byte> bin_res) { // m_filetransfer_uploadfile_job->on_result([this](int res, int resp_ec, std::string json_res, std::vector<std::byte> bin_res) { //
CallAfter([this, res, resp_ec, json_res, bin_res] { CallAfter([this, res, resp_ec, json_res, bin_res] {
UploadFileRessultCallback(res, resp_ec,json_res, bin_res); UploadFileRessultCallback(res, resp_ec,json_res, bin_res);
+104 -105
View File
@@ -22,7 +22,6 @@
#include <wx/mstream.h> #include <wx/mstream.h>
#include <wx/sstream.h> #include <wx/sstream.h>
#include <wx/zstream.h> #include <wx/zstream.h>
#include <chrono>
#include "DeviceCore/DevBed.h" #include "DeviceCore/DevBed.h"
#include "DeviceCore/DevCtrl.h" #include "DeviceCore/DevCtrl.h"
@@ -1463,7 +1462,7 @@ wxBoxSizer *StatusBasePanel::create_monitoring_page()
#if !BBL_RELEASE_TO_PUBLIC #if !BBL_RELEASE_TO_PUBLIC
m_staticText_timelapse->Show(); m_staticText_timelapse->Show();
m_bmToggleBtn_timelapse->Show(); m_bmToggleBtn_timelapse->Show();
m_bmToggleBtn_timelapse->Bind(wxEVT_TOGGLEBUTTON, [](wxCommandEvent &e) { m_bmToggleBtn_timelapse->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent &e) {
if (e.IsChecked()) if (e.IsChecked())
wxGetApp().getAgent()->start_subscribe("tunnel"); wxGetApp().getAgent()->start_subscribe("tunnel");
else else
@@ -1494,26 +1493,27 @@ wxBoxSizer *StatusBasePanel::create_monitoring_page()
m_setting_button->SetMinSize(wxSize(FromDIP(38), FromDIP(24))); m_setting_button->SetMinSize(wxSize(FromDIP(38), FromDIP(24)));
m_setting_button->SetBackgroundColour(STATUS_TITLE_BG); m_setting_button->SetBackgroundColour(STATUS_TITLE_BG);
// m_camera_switch_button = new wxStaticBitmap(m_panel_monitoring_title, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxSize(FromDIP(38), FromDIP(24)), 0); m_camera_switch_button = new wxStaticBitmap(m_panel_monitoring_title, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxSize(FromDIP(38), FromDIP(24)), 0);
// m_camera_switch_button->SetMinSize(wxSize(FromDIP(38), FromDIP(24))); m_camera_switch_button->SetMinSize(wxSize(FromDIP(38), FromDIP(24)));
// m_camera_switch_button->SetBackgroundColour(STATUS_TITLE_BG); m_camera_switch_button->SetBackgroundColour(STATUS_TITLE_BG);
// m_camera_switch_button->SetBitmap(m_bitmap_switch_camera.bmp()); m_camera_switch_button->SetBitmap(m_bitmap_switch_camera.bmp());
// m_camera_switch_button->Bind(wxEVT_RIGHT_DOWN, [this](auto& e) { m_camera_switch_button->Bind(wxEVT_LEFT_DOWN, &StatusBasePanel::on_camera_switch_toggled, this);
// const std::string js_request_pip = R"( m_camera_switch_button->Bind(wxEVT_RIGHT_DOWN, [this](auto& e) {
// document.querySelector('video').requestPictureInPicture(); const std::string js_request_pip = R"(
// )"; document.querySelector('video').requestPictureInPicture();
// m_custom_camera_view->RunScript(js_request_pip); )";
// }); m_custom_camera_view->RunScript(js_request_pip);
// m_camera_switch_button->Hide(); });
m_camera_switch_button->Hide();
m_bitmap_sdcard_img->SetToolTip(_L("Storage")); m_bitmap_sdcard_img->SetToolTip(_L("Storage"));
m_bitmap_timelapse_img->SetToolTip(_L("Timelapse")); m_bitmap_timelapse_img->SetToolTip(_L("Timelapse"));
m_bitmap_recording_img->SetToolTip(_L("Video")); m_bitmap_recording_img->SetToolTip(_L("Video"));
m_bitmap_vcamera_img->SetToolTip(_L("Go Live")); m_bitmap_vcamera_img->SetToolTip(_L("Go Live"));
m_setting_button->SetToolTip(_L("Camera Setting")); m_setting_button->SetToolTip(_L("Camera Setting"));
// m_camera_switch_button->SetToolTip(_L("Switch Camera View")); m_camera_switch_button->SetToolTip(_L("Switch Camera View"));
// bSizer_monitoring_title->Add(m_camera_switch_button, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5)); bSizer_monitoring_title->Add(m_camera_switch_button, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5));
bSizer_monitoring_title->Add(m_bitmap_sdcard_img, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5)); bSizer_monitoring_title->Add(m_bitmap_sdcard_img, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5));
bSizer_monitoring_title->Add(m_bitmap_timelapse_img, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5)); bSizer_monitoring_title->Add(m_bitmap_timelapse_img, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5));
bSizer_monitoring_title->Add(m_bitmap_recording_img, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5)); bSizer_monitoring_title->Add(m_bitmap_recording_img, 0, wxALIGN_CENTER_VERTICAL | wxALL, FromDIP(5));
@@ -1536,18 +1536,19 @@ wxBoxSizer *StatusBasePanel::create_monitoring_page()
m_custom_camera_view = WebView::CreateWebView(this, wxEmptyString); m_custom_camera_view = WebView::CreateWebView(this, wxEmptyString);
m_custom_camera_view->EnableContextMenu(false); m_custom_camera_view->EnableContextMenu(false);
Bind(wxEVT_WEBVIEW_NAVIGATING, &StatusBasePanel::on_webview_navigating, this, m_custom_camera_view->GetId()); Bind(wxEVT_WEBVIEW_NAVIGATING, &StatusBasePanel::on_webview_navigating, this, m_custom_camera_view->GetId());
m_web_media_controller = std::make_unique<WebMediaController>(m_custom_camera_view);
m_media_play_ctrl = new MediaPlayCtrl(this, m_media_ctrl, wxDefaultPosition, wxSize(-1, FromDIP(40))); m_media_play_ctrl = new MediaPlayCtrl(this, m_media_ctrl, wxDefaultPosition, wxSize(-1, FromDIP(40)));
m_media_play_ctrl->SetWebMediaController(m_web_media_controller.get());
m_custom_camera_view->Hide(); m_custom_camera_view->Hide();
// m_custom_camera_view->Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, [this](wxWebViewEvent& evt) { m_custom_camera_view->Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, [this](wxWebViewEvent& evt) {
// if (evt.GetString() == "leavepictureinpicture") { if (evt.GetString() == "leavepictureinpicture") {
// // When leaving PiP, video gets paused in some cases and toggling play // When leaving PiP, video gets paused in some cases and toggling play
// // programmatically does not work. // programmatically does not work.
// m_custom_camera_view->Reload(); m_custom_camera_view->Reload();
// } }
// }); else if (evt.GetString() == "enterpictureinpicture") {
toggle_builtin_camera();
}
});
sizer->Add(m_media_ctrl, 1, wxEXPAND | wxALL, 0); sizer->Add(m_media_ctrl, 1, wxEXPAND | wxALL, 0);
sizer->Add(m_custom_camera_view, 1, wxEXPAND | wxALL, 0); sizer->Add(m_custom_camera_view, 1, wxEXPAND | wxALL, 0);
@@ -1557,6 +1558,10 @@ wxBoxSizer *StatusBasePanel::create_monitoring_page()
// //
// sizer->Add(media_ctrl_panel, 1, wxEXPAND | wxALL, 1); // sizer->Add(media_ctrl_panel, 1, wxEXPAND | wxALL, 1);
if (wxGetApp().app_config->get("camera", "enable_custom_source") == "true") {
handle_camera_source_change();
}
return sizer; return sizer;
} }
@@ -2306,27 +2311,6 @@ void StatusPanel::update_camera_state(MachineObject* obj)
{ {
if (!obj) return; if (!obj) return;
auto agent = wxGetApp().getAgent();
const auto camera_mode = agent ? agent->get_camera_stream_mode() : CameraStreamMode::none;
const bool use_webview = camera_mode == CameraStreamMode::http_snapshot;
if (use_webview) {
//m_camera_switch_button->Hide();
if (!m_custom_camera_view->IsShown()) {
// why: do not reload the WebView URL per tick, or redirects can cause a reload loop.
// MediaPlayCtrl (via its WebMediaController) owns loading/playing the stream itself.
m_custom_camera_view->Show();
m_media_ctrl->Hide();
}
} else {
if (m_custom_camera_view->IsShown()) {
m_custom_camera_view->Hide();
// Stop the snapshot WebView before switching to native playback
// or leaving the camera mode.
m_media_play_ctrl->StopWebStream();
}
m_media_ctrl->Show();
}
//sdcard //sdcard
auto sdcard_state = obj->GetStorage()->get_sdcard_state(); auto sdcard_state = obj->GetStorage()->get_sdcard_state();
if (m_last_sdcard != sdcard_state) { if (m_last_sdcard != sdcard_state) {
@@ -2358,12 +2342,7 @@ void StatusPanel::update_camera_state(MachineObject* obj)
m_last_recording = obj->is_recording() ? 1 : 0; m_last_recording = obj->is_recording() ? 1 : 0;
} }
if (use_webview) { if (!m_bitmap_recording_img->IsShown()) {
if (m_bitmap_recording_img->IsShown()) {
m_bitmap_recording_img->Hide();
m_panel_monitoring_title->Layout();
}
} else if (!m_bitmap_recording_img->IsShown()) {
m_bitmap_recording_img->Show(); m_bitmap_recording_img->Show();
m_panel_monitoring_title->Layout(); m_panel_monitoring_title->Layout();
} }
@@ -2420,8 +2399,6 @@ void StatusPanel::update_camera_state(MachineObject* obj)
bool show_vcamera = m_media_play_ctrl->IsStreaming(); bool show_vcamera = m_media_play_ctrl->IsStreaming();
m_camera_popup->update(show_vcamera); m_camera_popup->update(show_vcamera);
} }
m_setting_button->Show(!use_webview);
} }
StatusPanel::StatusPanel(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name) StatusPanel::StatusPanel(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style, const wxString &name)
@@ -3943,60 +3920,39 @@ void StatusPanel::update_cloud_subtask(MachineObject *obj)
update_calib_bitmap(); update_calib_bitmap();
if (obj->slice_info) { if (obj->slice_info) {
m_request_url = wxString(obj->slice_info->thumbnail_url); m_request_url = wxString(obj->slice_info->thumbnail_url);
load_thumbnail_from_url(m_request_url, obj); if (!m_request_url.IsEmpty()) {
wxImage img;
std::map<wxString, wxImage>::iterator it = img_list.find(m_request_url);
if (it != img_list.end()) {
if (m_current_print_mode != PrintingTaskType::CALIBRATION ||(m_calib_mode == CalibMode::Calib_Flow_Rate && m_calib_method == CalibrationMethod::CALI_METHOD_MANUAL)) {
img = it->second;
wxImage resize_img = img.Scale(m_project_task_panel->get_bitmap_thumbnail()->GetSize().x, m_project_task_panel->get_bitmap_thumbnail()->GetSize().y);
m_project_task_panel->set_thumbnail_img(resize_img, "");
m_project_task_panel->set_brightness_value(get_brightness_value(resize_img));
}
if (this->obj) {
m_project_task_panel->set_plate_index(obj->m_plate_index);
} else {
m_project_task_panel->set_plate_index(-1);
}
task_thumbnail_state = ThumbnailState::TASK_THUMBNAIL;
BOOST_LOG_TRIVIAL(trace) << "web_request: use cache image";
} else {
web_request = wxWebSession::GetDefault().CreateRequest(this, m_request_url);
BOOST_LOG_TRIVIAL(trace) << "monitor: start request thumbnail, url = " << m_request_url;
web_request.Start();
m_start_loading_thumbnail = false;
}
}
} }
} }
} }
bool StatusPanel::load_thumbnail_from_url(const wxString &url, MachineObject *obj)
{
if (url.IsEmpty())
return false;
wxImage img;
std::map<wxString, wxImage>::iterator it = img_list.find(url);
if (it != img_list.end()) {
if (m_current_print_mode != PrintingTaskType::CALIBRATION ||(m_calib_mode == CalibMode::Calib_Flow_Rate && m_calib_method == CalibrationMethod::CALI_METHOD_MANUAL)) {
img = it->second;
wxImage resize_img = img.Scale(m_project_task_panel->get_bitmap_thumbnail()->GetSize().x, m_project_task_panel->get_bitmap_thumbnail()->GetSize().y);
m_project_task_panel->set_thumbnail_img(resize_img, "");
m_project_task_panel->set_brightness_value(get_brightness_value(resize_img));
}
if (this->obj) {
m_project_task_panel->set_plate_index(obj->m_plate_index);
} else {
m_project_task_panel->set_plate_index(-1);
}
task_thumbnail_state = ThumbnailState::TASK_THUMBNAIL;
BOOST_LOG_TRIVIAL(trace) << "web_request: use cache image";
} else {
m_request_url = url;
web_request = wxWebSession::GetDefault().CreateRequest(this, m_request_url);
BOOST_LOG_TRIVIAL(trace) << "monitor: start request thumbnail, url = " << m_request_url;
web_request.Start();
m_start_loading_thumbnail = false;
}
return true;
}
void StatusPanel::update_sdcard_subtask(MachineObject *obj) void StatusPanel::update_sdcard_subtask(MachineObject *obj)
{ {
if (!obj) return; if (!obj) return;
const wxString thumbnail_url = wxString(obj->m_agent_thumbnail_url); if (!m_load_sdcard_thumbnail) {
if (!thumbnail_url.IsEmpty()) {
if (m_request_url != thumbnail_url || !m_load_sdcard_thumbnail) {
if (web_request.IsOk() && web_request.GetState() == wxWebRequest::State_Active)
web_request.Cancel();
update_calib_bitmap();
m_request_url = thumbnail_url;
load_thumbnail_from_url(thumbnail_url, obj);
m_load_sdcard_thumbnail = true;
}
return;
}
if (!m_load_sdcard_thumbnail || !m_request_url.IsEmpty()) {
update_calib_bitmap(); update_calib_bitmap();
if (m_current_print_mode != PrintingTaskType::CALIBRATION) { if (m_current_print_mode != PrintingTaskType::CALIBRATION) {
m_project_task_panel->get_bitmap_thumbnail()->SetBitmap(m_thumbnail_sdcard.bmp()); m_project_task_panel->get_bitmap_thumbnail()->SetBitmap(m_thumbnail_sdcard.bmp());
@@ -4004,7 +3960,6 @@ void StatusPanel::update_sdcard_subtask(MachineObject *obj)
} }
task_thumbnail_state = ThumbnailState::SDCARD_THUMBNAIL; task_thumbnail_state = ThumbnailState::SDCARD_THUMBNAIL;
m_load_sdcard_thumbnail = true; m_load_sdcard_thumbnail = true;
m_request_url.clear();
} }
} }
@@ -5004,6 +4959,7 @@ void StatusPanel::on_camera_enter(wxMouseEvent& event)
} }
sdcard_hint_dlg->on_show(); sdcard_hint_dlg->on_show();
}); });
m_camera_popup->Bind(EVT_CAM_SOURCE_CHANGE, &StatusPanel::on_camera_source_change, this);
wxWindow* ctrl = (wxWindow*)event.GetEventObject(); wxWindow* ctrl = (wxWindow*)event.GetEventObject();
wxPoint pos = ctrl->ClientToScreen(wxPoint(0, 0)); wxPoint pos = ctrl->ClientToScreen(wxPoint(0, 0));
wxSize sz = ctrl->GetSize(); wxSize sz = ctrl->GetSize();
@@ -5015,6 +4971,54 @@ void StatusPanel::on_camera_enter(wxMouseEvent& event)
} }
} }
void StatusBasePanel::on_camera_source_change(wxCommandEvent& event)
{
handle_camera_source_change();
}
void StatusBasePanel::handle_camera_source_change()
{
const auto new_cam_url = wxGetApp().app_config->get("camera", "custom_source");
const auto enabled = wxGetApp().app_config->get("camera", "enable_custom_source") == "true";
if (enabled && !new_cam_url.empty()) {
m_custom_camera_view->LoadURL(new_cam_url);
toggle_custom_camera();
m_camera_switch_button->Show();
} else {
toggle_builtin_camera();
m_camera_switch_button->Hide();
}
}
void StatusBasePanel::toggle_builtin_camera()
{
m_custom_camera_view->Hide();
m_media_ctrl->Show();
m_media_play_ctrl->Show();
}
void StatusBasePanel::toggle_custom_camera()
{
const auto enabled = wxGetApp().app_config->get("camera", "enable_custom_source") == "true";
if (enabled) {
m_custom_camera_view->Show();
m_media_ctrl->Hide();
m_media_play_ctrl->Hide();
}
}
void StatusBasePanel::on_camera_switch_toggled(wxMouseEvent& event)
{
const auto enabled = wxGetApp().app_config->get("camera", "enable_custom_source") == "true";
if (enabled && m_media_ctrl->IsShown()) {
toggle_custom_camera();
} else {
toggle_builtin_camera();
}
}
void StatusBasePanel::remove_controls() void StatusBasePanel::remove_controls()
{ {
const std::string js_cleanup_video_element = R"( const std::string js_cleanup_video_element = R"(
@@ -5167,11 +5171,6 @@ bool StatusPanel::is_stage_list_info_changed(MachineObject *obj)
void StatusPanel::set_default() void StatusPanel::set_default()
{ {
BOOST_LOG_TRIVIAL(trace) << "status_panel: set_default"; BOOST_LOG_TRIVIAL(trace) << "status_panel: set_default";
if (m_custom_camera_view->IsShown()) {
m_custom_camera_view->Hide();
m_media_ctrl->Show();
m_media_play_ctrl->StopWebStream();
}
obj = nullptr; obj = nullptr;
last_subtask = nullptr; last_subtask = nullptr;
last_tray_exist_bits = -1; last_tray_exist_bits = -1;
+6 -6
View File
@@ -14,9 +14,7 @@
#include <wx/sizer.h> #include <wx/sizer.h>
#include <wx/gbsizer.h> #include <wx/gbsizer.h>
#include <wx/webrequest.h> #include <wx/webrequest.h>
#include <memory>
#include "MediaPlayCtrl.h" #include "MediaPlayCtrl.h"
#include "WebMediaController.hpp"
#include "AMSSetting.hpp" #include "AMSSetting.hpp"
#include "Calibration.hpp" #include "Calibration.hpp"
#include "CalibrationWizardPage.hpp" #include "CalibrationWizardPage.hpp"
@@ -441,7 +439,7 @@ protected:
wxStaticBitmap *m_bitmap_sdcard_img; wxStaticBitmap *m_bitmap_sdcard_img;
wxStaticBitmap *m_bitmap_static_use_time; wxStaticBitmap *m_bitmap_static_use_time;
wxStaticBitmap *m_bitmap_static_use_weight; wxStaticBitmap *m_bitmap_static_use_weight;
// wxStaticBitmap* m_camera_switch_button; wxStaticBitmap* m_camera_switch_button;
wxMediaCtrl3 * m_media_ctrl; wxMediaCtrl3 * m_media_ctrl;
@@ -463,8 +461,6 @@ protected:
ScalableButton *m_button_abort; ScalableButton *m_button_abort;
Button * m_button_clean; Button * m_button_clean;
wxWebView * m_custom_camera_view{nullptr}; wxWebView * m_custom_camera_view{nullptr};
std::unique_ptr<WebMediaController> m_web_media_controller;
wxSimplebook* m_extruder_book; wxSimplebook* m_extruder_book;
std::vector<ExtruderImage *> m_extruderImage; std::vector<ExtruderImage *> m_extruderImage;
@@ -580,8 +576,13 @@ protected:
virtual void on_axis_ctrl_e_up_10(wxCommandEvent &event) { event.Skip(); } virtual void on_axis_ctrl_e_up_10(wxCommandEvent &event) { event.Skip(); }
virtual void on_axis_ctrl_e_down_10(wxCommandEvent &event) { event.Skip(); } virtual void on_axis_ctrl_e_down_10(wxCommandEvent &event) { event.Skip(); }
virtual void on_nozzle_selected(wxCommandEvent &event) { event.Skip(); } virtual void on_nozzle_selected(wxCommandEvent &event) { event.Skip(); }
void on_camera_source_change(wxCommandEvent& event);
void handle_camera_source_change();
void remove_controls(); void remove_controls();
void on_webview_navigating(wxWebViewEvent& evt); void on_webview_navigating(wxWebViewEvent& evt);
void on_camera_switch_toggled(wxMouseEvent& event);
void toggle_custom_camera();
void toggle_builtin_camera();
public: public:
StatusBasePanel(wxWindow * parent, StatusBasePanel(wxWindow * parent,
@@ -628,7 +629,6 @@ class StatusPanel : public StatusBasePanel
{ {
private: private:
friend class MonitorPanel; friend class MonitorPanel;
bool load_thumbnail_from_url(const wxString &url, MachineObject *obj);
protected: protected:
std::shared_ptr<SliceInfoPopup> m_slice_info_popup; std::shared_ptr<SliceInfoPopup> m_slice_info_popup;
+10 -10
View File
@@ -1863,6 +1863,7 @@ bool SyncAmsInfoDialog::is_blocking_printing(MachineObject *obj_)
{ {
DeviceManager *dev = Slic3r::GUI::wxGetApp().getDeviceManager(); DeviceManager *dev = Slic3r::GUI::wxGetApp().getDeviceManager();
if (!dev) return true; if (!dev) return true;
auto target_model = obj_->printer_type;
std::string source_model = ""; std::string source_model = "";
if (m_print_type == PrintFromType::FROM_NORMAL) { if (m_print_type == PrintFromType::FROM_NORMAL) {
@@ -1873,7 +1874,13 @@ bool SyncAmsInfoDialog::is_blocking_printing(MachineObject *obj_)
if (m_required_data_plate_data_list.size() > 0) { source_model = m_required_data_plate_data_list[m_print_plate_idx]->printer_model_id; } if (m_required_data_plate_data_list.size() > 0) { source_model = m_required_data_plate_data_list[m_print_plate_idx]->printer_model_id; }
} }
return !DevPrinterConfigUtil::is_printer_model_compatible(source_model, *obj_); if (source_model != target_model) {
std::vector<std::string> compatible_machine = obj_->get_compatible_machine();
vector<std::string>::iterator it = find(compatible_machine.begin(), compatible_machine.end(), source_model);
if (it == compatible_machine.end()) { return true; }
}
return false;
} }
bool SyncAmsInfoDialog::is_same_nozzle_type(std::string &filament_type, NozzleType &tag_nozzle_type) bool SyncAmsInfoDialog::is_same_nozzle_type(std::string &filament_type, NozzleType &tag_nozzle_type)
@@ -1923,13 +1930,7 @@ bool SyncAmsInfoDialog::is_same_printer_model()
if (obj_ == nullptr) { return result; } if (obj_ == nullptr) { return result; }
PresetBundle *preset_bundle = wxGetApp().preset_bundle; PresetBundle *preset_bundle = wxGetApp().preset_bundle;
const std::string source_model = preset_bundle ? preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle) : std::string(); if (preset_bundle && preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle) != obj_->printer_type) {
if (DevPrinterConfigUtil::is_optional_printer_model_id(source_model) ||
DevPrinterConfigUtil::is_optional_printer_model_id(obj_->printer_type)) {
return true;
}
if (preset_bundle && source_model != obj_->printer_type) {
if ((obj_->is_support_upgrade_kit && obj_->installed_upgrade_kit) && (preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle) == "C12")) { if ((obj_->is_support_upgrade_kit && obj_->installed_upgrade_kit) && (preset_bundle->printers.get_edited_preset().get_printer_type(preset_bundle) == "C12")) {
return true; return true;
} }
@@ -2130,7 +2131,7 @@ void SyncAmsInfoDialog::update_user_printer()
std::map<std::string, MachineObject *> option_list; std::map<std::string, MachineObject *> option_list;
// user machine list // user machine list
option_list = dev->get_my_machine_list(dev->get_current_printer_agent_id()); option_list = dev->get_my_machine_list();
// same machine only appear once // same machine only appear once
for (auto it = option_list.begin(); it != option_list.end(); it++) { for (auto it = option_list.begin(); it != option_list.end(); it++) {
@@ -3205,7 +3206,6 @@ SyncAmsInfoDialog::~SyncAmsInfoDialog() {
void SyncAmsInfoDialog::set_info(SyncInfo &info) void SyncAmsInfoDialog::set_info(SyncInfo &info)
{ {
m_input_info = info; m_input_info = info;
reinit_dialog();
} }
void SyncAmsInfoDialog::update_lan_machine_list() void SyncAmsInfoDialog::update_lan_machine_list()
+35
View File
@@ -1992,6 +1992,20 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value)
// reload scene to update timelapse wipe tower // reload scene to update timelapse wipe tower
if (opt_key == "timelapse_type") { if (opt_key == "timelapse_type") {
// Smooth timelapse parks the nozzle on the prime tower every layer, so it needs a tower on
// every layer. That is exactly what "No sparse layers" removes, and with both on the tower is
// planned full height and then dropped on emission. Drop "No sparse layers" and tell the user.
if (boost::any_cast<int>(value) == (int) TimelapseType::tlSmooth && m_config->opt_bool("wipe_tower_no_sparse_layers")) {
MessageDialog dlg(wxGetApp().plater(),
_L("Smooth timelapse needs a prime tower on every layer, which is not compatible with \"No sparse layers\". "
"\"No sparse layers\" has been turned off."),
_L("Warning"), wxICON_WARNING | wxOK);
dlg.ShowModal();
DynamicPrintConfig new_conf = *m_config;
new_conf.set_key_value("wipe_tower_no_sparse_layers", new ConfigOptionBool(false));
m_config_manipulation.apply(m_config, &new_conf);
}
bool wipe_tower_enabled = m_config->option<ConfigOptionBool>("enable_prime_tower")->value; bool wipe_tower_enabled = m_config->option<ConfigOptionBool>("enable_prime_tower")->value;
if (!wipe_tower_enabled && boost::any_cast<int>(value) == (int)TimelapseType::tlSmooth) { if (!wipe_tower_enabled && boost::any_cast<int>(value) == (int)TimelapseType::tlSmooth) {
MessageDialog dlg(wxGetApp().plater(), _L("A prime tower is required for smooth timelapse mode. There may be flaws on the model without prime tower. Do you want to enable the prime tower\?"), MessageDialog dlg(wxGetApp().plater(), _L("A prime tower is required for smooth timelapse mode. There may be flaws on the model without prime tower. Do you want to enable the prime tower\?"),
@@ -2007,6 +2021,23 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value)
} }
} }
// Mirror of the timelapse_type branch above: enabling "No sparse layers" while smooth timelapse
// is active would leave the tower on every layer anyway, so fall back to traditional timelapse.
if (opt_key == "wipe_tower_no_sparse_layers" && boost::any_cast<bool>(value)) {
auto timelapse_type = m_config->option<ConfigOptionEnum<TimelapseType>>("timelapse_type");
if (timelapse_type && timelapse_type->value == TimelapseType::tlSmooth) {
MessageDialog dlg(wxGetApp().plater(),
_L("\"No sparse layers\" is not compatible with smooth timelapse, which needs a prime tower on every layer. "
"Timelapse has been switched to traditional mode."),
_L("Warning"), wxICON_WARNING | wxOK);
dlg.ShowModal();
DynamicPrintConfig new_conf = *m_config;
new_conf.set_key_value("timelapse_type", new ConfigOptionEnum<TimelapseType>(TimelapseType::tlTraditional));
m_config_manipulation.apply(m_config, &new_conf);
wxGetApp().plater()->update();
}
}
if (opt_key == "print_sequence" && m_config->opt_enum<PrintSequence>("print_sequence") == PrintSequence::ByObject) { if (opt_key == "print_sequence" && m_config->opt_enum<PrintSequence>("print_sequence") == PrintSequence::ByObject) {
auto printer_structure_opt = m_preset_bundle->printers.get_edited_preset().config.option<ConfigOptionEnum<PrinterStructure>>("printer_structure"); auto printer_structure_opt = m_preset_bundle->printers.get_edited_preset().config.option<ConfigOptionEnum<PrinterStructure>>("printer_structure");
if (printer_structure_opt && printer_structure_opt->value == PrinterStructure::psI3) { if (printer_structure_opt && printer_structure_opt->value == PrinterStructure::psI3) {
@@ -2763,6 +2794,7 @@ void TabPrint::build()
optgroup = page->new_optgroup(L("Overhangs"), L"param_overhang"); optgroup = page->new_optgroup(L("Overhangs"), L"param_overhang");
optgroup->append_single_option_line("detect_overhang_wall", "quality_settings_overhangs#detect-overhang-wall"); optgroup->append_single_option_line("detect_overhang_wall", "quality_settings_overhangs#detect-overhang-wall");
optgroup->append_single_option_line("unsupported_wall_last", "quality_settings_overhangs#unsupported-wall-last");
optgroup->append_single_option_line("make_overhang_printable", "quality_settings_overhangs#make-overhang-printable"); optgroup->append_single_option_line("make_overhang_printable", "quality_settings_overhangs#make-overhang-printable");
optgroup->append_single_option_line("make_overhang_printable_angle", "quality_settings_overhangs#maximum-angle"); optgroup->append_single_option_line("make_overhang_printable_angle", "quality_settings_overhangs#maximum-angle");
optgroup->append_single_option_line("make_overhang_printable_hole_size", "quality_settings_overhangs#hole-area"); optgroup->append_single_option_line("make_overhang_printable_hole_size", "quality_settings_overhangs#hole-area");
@@ -3026,6 +3058,8 @@ void TabPrint::build()
optgroup = page->new_optgroup(L("Advanced"), L"advanced"); optgroup = page->new_optgroup(L("Advanced"), L"advanced");
optgroup->append_single_option_line("interlocking_beam", "multimaterial_settings_advanced#interlocking-beam"); optgroup->append_single_option_line("interlocking_beam", "multimaterial_settings_advanced#interlocking-beam");
optgroup->append_single_option_line("toolchange_ordering", "multimaterial_settings_advanced#toolchange-ordering"); optgroup->append_single_option_line("toolchange_ordering", "multimaterial_settings_advanced#toolchange-ordering");
optgroup->append_single_option_line("toolchange_cyclic_order", "multimaterial_settings_advanced#toolchange-order");
optgroup->append_single_option_line("toolchange_cyclic_first_layer", "multimaterial_settings_advanced#toolchange-order");
optgroup->append_single_option_line("interface_shells", "multimaterial_settings_advanced#interface-shells"); optgroup->append_single_option_line("interface_shells", "multimaterial_settings_advanced#interface-shells");
optgroup->append_single_option_line("mmu_segmented_region_max_width", "multimaterial_settings_advanced#maximum-width-of-segmented-region"); optgroup->append_single_option_line("mmu_segmented_region_max_width", "multimaterial_settings_advanced#maximum-width-of-segmented-region");
optgroup->append_single_option_line("mmu_segmented_region_interlocking_depth", "multimaterial_settings_advanced#interlocking-depth-of-segmented-region"); optgroup->append_single_option_line("mmu_segmented_region_interlocking_depth", "multimaterial_settings_advanced#interlocking-depth-of-segmented-region");
@@ -5107,6 +5141,7 @@ void TabPrinter::build_fff()
optgroup = page->new_optgroup(L("Extruder Clearance"), "param_extruder_clearance"); optgroup = page->new_optgroup(L("Extruder Clearance"), "param_extruder_clearance");
optgroup->append_single_option_line("extruder_clearance_radius", "printer_basic_information_extruder_clearance#radius"); optgroup->append_single_option_line("extruder_clearance_radius", "printer_basic_information_extruder_clearance#radius");
optgroup->append_single_option_line("extruder_clearance_dist_to_rod", "printer_basic_information_extruder_clearance#distance-to-rod");
optgroup->append_single_option_line("extruder_clearance_height_to_rod", "printer_basic_information_extruder_clearance#height-to-rod"); optgroup->append_single_option_line("extruder_clearance_height_to_rod", "printer_basic_information_extruder_clearance#height-to-rod");
optgroup->append_single_option_line("extruder_clearance_height_to_lid", "printer_basic_information_extruder_clearance#height-to-lid"); optgroup->append_single_option_line("extruder_clearance_height_to_lid", "printer_basic_information_extruder_clearance#height-to-lid");
+38 -16
View File
@@ -1490,7 +1490,15 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, DynamicConfig * config
for (const std::string &opt_key : config->keys()) { for (const std::string &opt_key : config->keys()) {
int variant_index = -2; int variant_index = -2;
const Search::Option &option = searcher.get_option(opt_key, type, variant_index); Search::Option option = searcher.get_option(opt_key, type, variant_index);
if (variant_index == -2) {
// Orca: Every transferred setting must remain visible even when it is absent from the search index.
const ConfigOptionDef* def = print_config_def.get(opt_key);
const std::string label = def ? (def->full_label.empty() ? def->label : def->full_label) : std::string();
option.label_local = (label.empty() ? from_u8(opt_key) : _L(label)).ToStdWstring();
option.category_local = (def && !def->category.empty() ?
Tab::translate_category(from_u8(def->category), type) : _L("Other")).ToStdWstring();
}
auto category = option.category_local; auto category = option.category_local;
auto opt = dynamic_cast<ConfigOptionVectorBase*>(config->option(opt_key)); auto opt = dynamic_cast<ConfigOptionVectorBase*>(config->option(opt_key));
std::string value_from = opt->vserialize()[from]; std::string value_from = opt->vserialize()[from];
@@ -1518,6 +1526,8 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, PresetCollection* pres
else else
presets_list.emplace_back(presets_); presets_list.emplace_back(presets_);
const bool multiple_extruders = wxGetApp().preset_bundle->get_printer_extruder_count() > 1;
// Display a dialog showing the dirty options in a human readable form. // Display a dialog showing the dirty options in a human readable form.
for (PresetCollection* presets : presets_list) for (PresetCollection* presets : presets_list)
{ {
@@ -1553,29 +1563,41 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, PresetCollection* pres
auto variant_key = Preset::get_iot_type_string(type) + "_extruder_variant"; auto variant_key = Preset::get_iot_type_string(type) + "_extruder_variant";
auto id_key = Preset::get_iot_type_string(type) + "_extruder_id"; auto id_key = Preset::get_iot_type_string(type) + "_extruder_id";
auto extruder_variant = dynamic_cast<ConfigOptionStrings const *>(old_config.option(variant_key)); // Orca: Dirty indices belong to the edited config, which may contain newly added variants.
auto extruder_id = dynamic_cast<ConfigOptionInts const *>(old_config.option(id_key)); auto extruder_variant = dynamic_cast<ConfigOptionStrings const *>(new_config.option(variant_key));
auto extruder_id = dynamic_cast<ConfigOptionInts const *>(new_config.option(id_key));
for (const std::string& opt_key : dirty_options) { for (const std::string& opt_key : dirty_options) {
int variant_index = -2; int variant_index = -2;
const Search::Option &option = searcher.get_option(opt_key, type, variant_index); const Search::Option &option = searcher.get_option(opt_key, type, variant_index);
if (option.opt_key() != opt_key && variant_index < -1) { if (variant_index == -2) {
// When founded option isn't the correct one. // When founded option isn't the correct one.
// It can be for dirty_options: "default_print_profile", "printer_model", "printer_settings_id", // It can be for dirty_options: "default_print_profile", "printer_model", "printer_settings_id",
// because of they don't exist in searcher // because of they don't exist in searcher
continue; continue;
} }
auto category = option.category_local; wxString category = option.category_local;
if (variant_index >= 0) { wxString label = option.label_local;
if (printer_options_with_variant_2.count(opt_key.substr(0, opt_key.find_last_of('#'))) > 0) if (type == Preset::TYPE_PRINTER && variant_index >= 0 &&
variant_index /= 2; printer_options_with_variant_2.count(get_pure_opt_key(opt_key)) > 0) {
if (boost::nowide::narrow(category).find("Extruder ") == 0) // Orca: silent_mode is obsolete on import, but its option and two-column UI still exist.
category = category.substr(0, 8); // Keep mode labels for configs that explicitly enable it; omit them in the default single-mode UI.
if (extruder_id) if (new_config.opt_bool("silent_mode"))
category = category + (wxString(" {") + (extruder_id->values[variant_index] == 1 ? _L("Left: ") : _L("Right: ")) label += " (" + (variant_index % 2 == 0 ? _L("Normal") : _L("Silent")) + ")";
+ L(extruder_variant->values[variant_index]) + "}"); variant_index /= 2;
else }
category = category + (wxString(" {") + L(extruder_variant->values[variant_index]) + "}"); if (variant_index >= 0 && extruder_variant && variant_index < extruder_variant->size()) {
// Orca: Match the untranslated category and use the same extruder names as the printer tabs.
if (option.category.compare(0, 9, L"Extruder ") == 0)
category = _L("Extruder");
wxString variant_label = L(extruder_variant->values[variant_index]);
// Orca: An extruder name only disambiguates variants on printers with multiple extruders.
if (multiple_extruders && extruder_id && variant_index < extruder_id->size() && extruder_id->values[variant_index] > 0) {
const wxString extruder_name = Tab::translate_category(
wxString::Format("Extruder %d", extruder_id->values[variant_index]), Preset::TYPE_PRINTER);
variant_label = extruder_name + " (" + variant_label + ")";
}
category = variant_label + ": " + category;
} }
/*m_tree->Append(opt_key, type, option.category_local, option.group_local, option.label_local, /*m_tree->Append(opt_key, type, option.category_local, option.group_local, option.label_local,
@@ -1584,7 +1606,7 @@ void UnsavedChangesDialog::update_tree(Preset::Type type, PresetCollection* pres
//PresetItem pi = {opt_key, type, 1983}; //PresetItem pi = {opt_key, type, 1983};
//m_presetitems.push_back() //m_presetitems.push_back()
PresetItem pi = {type, opt_key, category, option.group_local, option.label_local, get_string_value(opt_key, old_config), get_string_value(opt_key, new_config)}; PresetItem pi = {type, opt_key, category, option.group_local, label, get_string_value(opt_key, old_config), get_string_value(opt_key, new_config)};
m_presetitems.push_back(pi); m_presetitems.push_back(pi);
} }
-76
View File
@@ -1,76 +0,0 @@
#include "WebMediaController.hpp"
#include <wx/webview.h>
namespace Slic3r { namespace GUI {
WebMediaController::WebMediaController(wxWebView* webview) : m_webview(webview)
{
if (!m_webview)
return;
m_webview->SetBackgroundColour(*wxBLACK);
m_webview->SetPage("<html><head><style>html,body{margin:0;height:100%;background:#000;}</style></head><body></body></html>", "");
}
void WebMediaController::Load(wxURI url) { Load(url, CameraStreamMode::http); }
void WebMediaController::Load(wxURI url, CameraStreamMode mode)
{
m_url = url.BuildURI().ToStdString();
m_stream_mode = mode;
}
void WebMediaController::Play()
{
if (!m_webview)
return;
wxString url = wxString::FromUTF8(m_url);
wxString html = "<html><head><style>"
"html,body{margin:0;height:100%;background:#000;overflow:hidden;}"
"img{width:100%;height:100%;object-fit:contain;display:block;}"
"</style></head><body><img id=\"camera-frame\"";
if (m_stream_mode == CameraStreamMode::http_snapshot) {
html += " data-camera-url=\"" + url +
"\"><script>"
"const cameraFrame=document.getElementById('camera-frame');"
"const cameraUrl=cameraFrame.dataset.cameraUrl;"
"let cameraFrameLoading=false;"
"function refreshCameraFrame(){"
"if(cameraFrameLoading)return;"
"cameraFrameLoading=true;"
"const nextFrame=new Image();"
"nextFrame.onload=function(){cameraFrame.src=nextFrame.src;cameraFrameLoading=false;};"
"nextFrame.onerror=function(){cameraFrameLoading=false;};"
"nextFrame.src=cameraUrl+(cameraUrl.indexOf('?')>=0?'&':'?')+'_orca_frame='+Date.now();"
"}"
"let cameraRefreshInterval=null;"
"function stopCameraRefresh(){"
"if(cameraRefreshInterval!==null){"
"clearInterval(cameraRefreshInterval);"
"cameraRefreshInterval=null;"
"}"
"}"
"refreshCameraFrame();"
"cameraRefreshInterval = setInterval(refreshCameraFrame,200);"
"</script></body></html>";
m_webview->SetPage(html, url);
} else {
// Load MJPEG streams as the top-level document. Some embedded WebView
// backends buffer a multipart stream when it is used as an <img> resource,
// which introduces noticeable live-view latency.
m_webview->LoadURL(url);
}
}
void WebMediaController::Stop()
{
if (m_webview) {
m_webview->RunScript("if(typeof stopCameraRefresh==='function') stopCameraRefresh();");
m_webview->Stop();
}
m_url.clear();
}
}} // namespace Slic3r::GUI
-30
View File
@@ -1,30 +0,0 @@
#pragma once
#include <slic3r/GUI/IMediaController.hpp>
#include <string>
class wxWebView;
namespace Slic3r { namespace GUI {
class WebMediaController : public IMediaController
{
public:
explicit WebMediaController(wxWebView* webview);
void Load(wxURI url) override;
void Load(wxURI url, CameraStreamMode mode) override;
void Play() override;
void Stop() override;
private:
wxWebView* m_webview;
std::string m_url;
CameraStreamMode m_stream_mode = CameraStreamMode::http;
};
}} // namespace Slic3r::GUI
-395
View File
@@ -1,395 +0,0 @@
#include "WebRtcMediaController.hpp"
#include <rtc/common.hpp>
#include <rtc/rtc.hpp>
#include <mutex>
#include <wx/mstream.h>
#include <boost/log/trivial.hpp>
namespace {
void init_rtc_logger_once()
{
static std::once_flag flag;
std::call_once(flag, [] {
rtc::InitLogger(rtc::LogLevel::Warning, [](rtc::LogLevel level, std::string message) {
BOOST_LOG_TRIVIAL(trace) << "[rtc:" << static_cast<int>(level) << "] " << message;
});
});
}
} // namespace
namespace Slic3r { namespace GUI {
WebRtcMediaController::WebRtcMediaController(std::function<void(const wxImage&, wxSize)> frame_sink,
std::function<void(Status)> on_status)
: m_frame_sink(std::move(frame_sink))
, m_on_status(std::move(on_status))
{
}
WebRtcMediaController::~WebRtcMediaController()
{
StopSession();
}
void WebRtcMediaController::report(Status status)
{
status.epoch = m_epoch.load();
BOOST_LOG_TRIVIAL(info) << "WebRTC: report kind=" << static_cast<int>(status.kind)
<< " code=" << static_cast<int>(status.code) << " epoch=" << status.epoch;
{
std::lock_guard<std::mutex> lock(m_mutex);
if (status.kind == Status::Connecting)
m_state = static_cast<wxMediaState>(4);
else if (status.kind == Status::Playing)
m_state = wxMEDIASTATE_PLAYING;
else
m_state = static_cast<wxMediaState>(3);
}
if (m_on_status)
m_on_status(status);
}
void WebRtcMediaController::StartSession(std::unique_ptr<ICameraSignalingChannel> channel)
{
// Tear down any previous attempt WITHOUT notifying: the Stopped that would
// otherwise be delivered (async, via CallAfter) races the new attempt's
// Connecting and makes the consumer cancel a session that is mid-connect.
teardown(false);
if (!channel)
return;
m_epoch.fetch_add(1);
m_alive.store(true);
{
std::lock_guard<std::mutex> lock(m_mutex);
m_signaling = std::move(channel);
m_jpeg_queue.clear();
m_pending_candidates.clear();
m_remote_description_set = false;
m_video_size = wxDefaultSize;
m_has_frame = false;
m_last_frame_time = {};
}
ICameraSignalingChannel* signaling = nullptr;
{
std::lock_guard<std::mutex> lock(m_mutex);
signaling = m_signaling.get();
}
signaling->on_ready = [this](std::vector<CameraIceServer> servers) {
if (m_alive.load())
on_ready(std::move(servers));
};
signaling->on_answer = [this](std::string sdp) {
if (m_alive.load())
on_answer(std::move(sdp));
};
signaling->on_ice = [this](std::string candidate, std::string mid) {
if (m_alive.load())
on_ice(std::move(candidate), std::move(mid));
};
signaling->on_unavailable = [this](CameraUnavailableReason reason, std::string detail) {
if (m_alive.load())
on_unavailable(reason, std::move(detail));
};
m_decode_thread = std::thread([this] { decode_loop(); });
report({Status::Connecting});
signaling->open();
}
void WebRtcMediaController::StopSession()
{
teardown(true);
}
void WebRtcMediaController::teardown(bool notify)
{
const bool was_alive = m_alive.exchange(false);
if (!was_alive && !m_decode_thread.joinable())
return;
m_cond.notify_all();
std::unique_ptr<ICameraSignalingChannel> signaling;
std::shared_ptr<rtc::PeerConnection> peer_connection;
{
std::lock_guard<std::mutex> lock(m_mutex);
signaling = std::move(m_signaling);
peer_connection = std::move(m_peer_connection);
m_data_channel.reset();
}
if (signaling)
signaling->close();
if (peer_connection)
peer_connection->close();
if (m_decode_thread.joinable())
m_decode_thread.join();
{
std::lock_guard<std::mutex> lock(m_mutex);
m_jpeg_queue.clear();
}
if (was_alive && notify)
report({Status::Stopped});
}
wxMediaState WebRtcMediaController::GetState()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_state;
}
wxSize WebRtcMediaController::GetVideoSize() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_video_size;
}
void WebRtcMediaController::bind_data_channel(const std::shared_ptr<rtc::DataChannel>& dc)
{
const std::string label = dc->label();
dc->onOpen([label] { BOOST_LOG_TRIVIAL(info) << "WebRTC: data channel '" << label << "' open"; });
dc->onClosed([label] { BOOST_LOG_TRIVIAL(info) << "WebRTC: data channel '" << label << "' closed"; });
dc->onError([label](std::string e) {
BOOST_LOG_TRIVIAL(warning) << "WebRTC: data channel '" << label << "' error: " << e;
});
dc->onMessage(
[this](rtc::binary data) {
if (m_alive.load())
enqueue_jpeg(std::vector<std::byte>(data.begin(), data.end()));
},
[](rtc::string) {});
}
void WebRtcMediaController::on_ready(std::vector<CameraIceServer> servers)
{
init_rtc_logger_once();
rtc::Configuration configuration;
// Allow complete-JPEG DataChannel messages up to 1 MiB. This value is
// advertised in SDP and becomes the upper bound for frames OrcaSonar can
// send to OrcaSlicer.
configuration.maxMessageSize = 1024 * 1024;
for (const CameraIceServer& server : servers) {
try {
rtc::IceServer ice_server(server.urls);
ice_server.username = server.username;
ice_server.password = server.credential;
configuration.iceServers.emplace_back(std::move(ice_server));
} catch (const std::exception& e) {
BOOST_LOG_TRIVIAL(warning) << "WebRTC: invalid ICE server: " << e.what();
}
}
BOOST_LOG_TRIVIAL(info) << "WebRTC: creating peer connection with " << configuration.iceServers.size() << " ice servers";
auto peer_connection = std::make_shared<rtc::PeerConnection>(std::move(configuration));
peer_connection->onLocalDescription([this](rtc::Description description) {
if (!m_alive.load())
return;
const std::string sdp(description);
BOOST_LOG_TRIVIAL(info) << "WebRTC: local description ready (" << description.typeString()
<< "), OFFER SDP:\n" << sdp;
std::lock_guard<std::mutex> lock(m_mutex);
if (m_signaling)
m_signaling->send_offer(sdp);
});
peer_connection->onLocalCandidate([this](rtc::Candidate candidate) {
if (!m_alive.load())
return;
std::lock_guard<std::mutex> lock(m_mutex);
if (m_signaling)
m_signaling->send_ice(std::string(candidate), candidate.mid());
});
peer_connection->onStateChange([this](rtc::PeerConnection::State state) {
BOOST_LOG_TRIVIAL(info) << "WebRTC: peer state -> " << static_cast<int>(state);
if (!m_alive.load())
return;
if (state == rtc::PeerConnection::State::Failed || state == rtc::PeerConnection::State::Disconnected)
report({Status::Failed, Status::ICE_FAILED});
});
peer_connection->onGatheringStateChange([](rtc::PeerConnection::GatheringState state) {
BOOST_LOG_TRIVIAL(info) << "WebRTC: gathering state -> " << static_cast<int>(state);
});
// Accept a DataChannel opened by the remote peer (OrcaSonar may create the
// "camera" channel from its side rather than answering the one we offer).
peer_connection->onDataChannel([this](std::shared_ptr<rtc::DataChannel> dc) {
BOOST_LOG_TRIVIAL(info) << "WebRTC: remote opened data channel '" << dc->label() << "'";
bind_data_channel(dc);
std::lock_guard<std::mutex> lock(m_mutex);
m_data_channel = std::move(dc);
});
rtc::DataChannelInit init;
init.reliability.unordered = true;
// init.reliability.maxPacketLifeTime = std::chrono::milliseconds(350);
// Request one complete JPEG frame per DataChannel message. OrcaSonar
// keeps the legacy chunked protocol for clients that omit this property.
init.protocol = "orca-jpeg";
auto data_channel = peer_connection->createDataChannel("camera", init);
if (data_channel)
bind_data_channel(data_channel);
// Camera media is carried as one complete JPEG per DataChannel message;
// no RTP video track or application-level framing is required.
std::shared_ptr<rtc::PeerConnection> peer_for_description;
{
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_alive.load())
return;
m_peer_connection = std::move(peer_connection);
peer_for_description = m_peer_connection;
m_data_channel = std::move(data_channel);
}
if (peer_for_description)
peer_for_description->setLocalDescription();
}
void WebRtcMediaController::on_answer(std::string sdp)
{
std::shared_ptr<rtc::PeerConnection> peer_connection;
{
std::lock_guard<std::mutex> lock(m_mutex);
peer_connection = m_peer_connection;
}
BOOST_LOG_TRIVIAL(info) << "WebRTC: applying remote answer (" << sdp.size() << " bytes), ANSWER SDP:\n" << sdp;
if (!peer_connection)
return;
try {
peer_connection->setRemoteDescription(rtc::Description(sdp, "answer"));
} catch (const std::exception& e) {
BOOST_LOG_TRIVIAL(warning) << "WebRTC: setRemoteDescription failed: " << e.what();
report({Status::Failed, Status::ICE_FAILED});
return;
}
// Flush any remote candidates that arrived before the answer.
std::vector<std::pair<std::string, std::string>> pending;
{
std::lock_guard<std::mutex> lock(m_mutex);
m_remote_description_set = true;
pending.swap(m_pending_candidates);
}
BOOST_LOG_TRIVIAL(info) << "WebRTC: remote description set, flushing " << pending.size()
<< " buffered candidate(s)";
for (const auto& c : pending) {
try {
peer_connection->addRemoteCandidate(rtc::Candidate(c.first, c.second));
} catch (const std::exception& e) {
BOOST_LOG_TRIVIAL(warning) << "WebRTC: addRemoteCandidate (buffered) failed: " << e.what();
}
}
}
void WebRtcMediaController::on_ice(std::string candidate, std::string mid)
{
std::shared_ptr<rtc::PeerConnection> peer_connection;
{
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_remote_description_set) {
m_pending_candidates.emplace_back(std::move(candidate), std::move(mid));
return;
}
peer_connection = m_peer_connection;
}
if (!peer_connection)
return;
try {
peer_connection->addRemoteCandidate(rtc::Candidate(candidate, mid));
} catch (const std::exception& e) {
BOOST_LOG_TRIVIAL(warning) << "WebRTC: addRemoteCandidate failed: " << e.what();
}
}
void WebRtcMediaController::on_unavailable(CameraUnavailableReason reason, std::string detail)
{
BOOST_LOG_TRIVIAL(warning) << "WebRTC camera unavailable: " << detail;
Status::Code code = Status::UNAVAILABLE_ERROR;
if (reason == CameraUnavailableReason::Busy)
code = Status::UNAVAILABLE_BUSY;
else if (reason == CameraUnavailableReason::Disabled)
code = Status::UNAVAILABLE_DISABLED;
else if (reason == CameraUnavailableReason::Closed)
code = Status::SIGNALING_CLOSED;
report({Status::Failed, code});
}
void WebRtcMediaController::enqueue_jpeg(std::vector<std::byte> jpeg)
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_jpeg_queue.size() >= 4)
m_jpeg_queue.pop_front();
m_jpeg_queue.emplace_back(std::move(jpeg));
m_cond.notify_one();
}
void WebRtcMediaController::deliver_jpeg(std::vector<std::byte> jpeg)
{
const auto now = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_last_frame_time != std::chrono::steady_clock::time_point{} &&
now - m_last_frame_time < std::chrono::milliseconds(33))
return;
m_last_frame_time = now;
}
wxMemoryInputStream stream(jpeg.data(), jpeg.size());
wxImage image;
if (!image.LoadFile(stream, wxBITMAP_TYPE_JPEG)) {
report({Status::Failed, Status::DECODE_ERROR});
return;
}
bool first_frame = false;
{
std::lock_guard<std::mutex> lock(m_mutex);
m_video_size = image.GetSize();
first_frame = !m_has_frame;
m_has_frame = true;
}
if (m_frame_sink)
m_frame_sink(image, image.GetSize());
if (first_frame)
report({Status::Playing});
}
void WebRtcMediaController::decode_loop()
{
int stall_polls = 0;
std::unique_lock<std::mutex> lock(m_mutex);
while (m_alive.load()) {
const bool woke = m_cond.wait_for(lock, std::chrono::seconds(2), [this] {
return !m_alive.load() || !m_jpeg_queue.empty();
});
if (!m_alive.load())
break;
if (!woke && !m_has_frame) {
const int pc_state = m_peer_connection ? static_cast<int>(m_peer_connection->state()) : -1;
std::string dc = "none";
if (m_data_channel)
dc = "label='" + m_data_channel->label() + "' open=" +
(m_data_channel->isOpen() ? "1" : "0");
lock.unlock();
BOOST_LOG_TRIVIAL(info) << "WebRTC: waiting for frames; peer_state=" << pc_state
<< " data_channel=" << dc;
if (++stall_polls >= 8) { // ~16s connected with no frame -> give up so the UI can retry
report({Status::Failed, Status::TIMEOUT});
lock.lock();
break;
}
lock.lock();
continue;
}
stall_polls = 0;
if (!m_jpeg_queue.empty()) {
auto jpeg = std::move(m_jpeg_queue.front());
m_jpeg_queue.pop_front();
lock.unlock();
deliver_jpeg(std::move(jpeg));
lock.lock();
}
}
}
}} // namespace Slic3r::GUI
-92
View File
@@ -1,92 +0,0 @@
#pragma once
#include "IMediaController.hpp"
#include <wx/image.h>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
namespace rtc {
class DataChannel;
class PeerConnection;
}
namespace Slic3r { namespace GUI {
class WebRtcMediaController : public IMediaController {
public:
struct Status {
enum Kind { Connecting, Playing, Stopped, Failed } kind = Stopped;
enum Code {
ICE_FAILED,
SIGNALING_CLOSED,
UNAVAILABLE_BUSY,
UNAVAILABLE_ERROR,
UNAVAILABLE_DISABLED,
DECODE_ERROR,
TIMEOUT,
} code = ICE_FAILED;
// Identifies the StartSession attempt this status belongs to, so the
// consumer can drop CallAfter-queued events from a superseded attempt.
std::uint64_t epoch = 0;
};
WebRtcMediaController(std::function<void(const wxImage&, wxSize)> frame_sink,
std::function<void(Status)> on_status);
~WebRtcMediaController() override;
void StartSession(std::unique_ptr<ICameraSignalingChannel> channel) override;
void StopSession() override;
std::uint64_t epoch() const { return m_epoch.load(); }
bool is_active() const { return m_alive.load(); }
void Load(wxURI) override {}
void Play() override {}
void Stop() override { StopSession(); }
wxMediaState GetState() override;
wxSize GetVideoSize() const override;
private:
void teardown(bool notify);
void report(Status status);
void bind_data_channel(const std::shared_ptr<rtc::DataChannel>& dc);
void on_ready(std::vector<CameraIceServer> servers);
void on_answer(std::string sdp);
void on_ice(std::string candidate, std::string mid);
void on_unavailable(CameraUnavailableReason reason, std::string detail);
void decode_loop();
void enqueue_jpeg(std::vector<std::byte> jpeg);
void deliver_jpeg(std::vector<std::byte> jpeg);
mutable std::mutex m_mutex;
std::condition_variable m_cond;
std::deque<std::vector<std::byte>> m_jpeg_queue;
// Remote candidates can arrive before the answer; libdatachannel rejects
// addRemoteCandidate until a remote description is set, so buffer them.
std::vector<std::pair<std::string, std::string>> m_pending_candidates;
bool m_remote_description_set = false;
std::unique_ptr<ICameraSignalingChannel> m_signaling;
std::shared_ptr<rtc::PeerConnection> m_peer_connection;
std::shared_ptr<rtc::DataChannel> m_data_channel;
std::thread m_decode_thread;
std::atomic<bool> m_alive{false};
std::atomic<std::uint64_t> m_epoch{0};
wxMediaState m_state = static_cast<wxMediaState>(3);
wxSize m_video_size = wxDefaultSize;
std::function<void(const wxImage&, wxSize)> m_frame_sink;
std::function<void(Status)> m_on_status;
bool m_has_frame = false;
std::chrono::steady_clock::time_point m_last_frame_time{};
};
}} // namespace Slic3r::GUI
+81 -363
View File
@@ -4,14 +4,6 @@
#include "libslic3r/Utils.hpp" #include "libslic3r/Utils.hpp"
#include <boost/log/trivial.hpp> #include <boost/log/trivial.hpp>
#include <wx/dcclient.h> #include <wx/dcclient.h>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <mutex>
extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/log.h>
}
#ifdef __WIN32__ #ifdef __WIN32__
#include <versionhelpers.h> #include <versionhelpers.h>
#include <wx/msw/registry.h> #include <wx/msw/registry.h>
@@ -51,13 +43,9 @@ wxMediaCtrl3::~wxMediaCtrl3()
m_thread.join(); m_thread.join();
} }
static void adjust_frame_size(wxSize& frame, wxSize const& video, wxSize const& window);
void wxMediaCtrl3::Load(wxURI url) void wxMediaCtrl3::Load(wxURI url)
{ {
std::unique_lock<std::mutex> lk(m_mutex); std::unique_lock<std::mutex> lk(m_mutex);
if (m_external)
return;
m_video_size = wxDefaultSize; m_video_size = wxDefaultSize;
m_error = 0; m_error = 0;
m_url.reset(new wxURI(url)); m_url.reset(new wxURI(url));
@@ -67,8 +55,6 @@ void wxMediaCtrl3::Load(wxURI url)
void wxMediaCtrl3::Play() void wxMediaCtrl3::Play()
{ {
std::unique_lock<std::mutex> lk(m_mutex); std::unique_lock<std::mutex> lk(m_mutex);
if (m_external)
return;
if (m_state != wxMEDIASTATE_PLAYING) { if (m_state != wxMEDIASTATE_PLAYING) {
m_state = wxMEDIASTATE_PLAYING; m_state = wxMEDIASTATE_PLAYING;
wxMediaEvent event(wxEVT_MEDIA_STATECHANGED); wxMediaEvent event(wxEVT_MEDIA_STATECHANGED);
@@ -88,62 +74,6 @@ void wxMediaCtrl3::Stop()
Refresh(); Refresh();
} }
void wxMediaCtrl3::SetExternalFrame(const wxImage& frame, wxSize videoSize)
{
if (!frame.IsOk())
return;
{
std::unique_lock<std::mutex> lk(m_mutex);
if (!m_external)
return;
m_frame = frame;
m_video_size = videoSize.IsFullySpecified() ? videoSize : frame.GetSize();
adjust_frame_size(m_frame_size, m_video_size, GetSize());
}
CallAfter([this] { Refresh(); });
}
#ifdef _WIN32
void wxMediaCtrl3::SetExternalFrame(const wxBitmap& frame, wxSize videoSize)
{
if (!frame.IsOk())
return;
{
std::unique_lock<std::mutex> lk(m_mutex);
if (!m_external)
return;
m_frame = frame;
m_video_size = videoSize.IsFullySpecified() ? videoSize : frame.GetSize();
adjust_frame_size(m_frame_size, m_video_size, GetSize());
}
CallAfter([this] { Refresh(); });
}
#endif
void wxMediaCtrl3::BeginExternalStream()
{
std::unique_lock<std::mutex> lk(m_mutex);
m_external = true;
m_url.reset();
m_active_url.reset();
m_video_size = wxDefaultSize;
m_frame = wxImage(m_idle_image);
m_cond.notify_all();
Refresh();
}
void wxMediaCtrl3::EndExternalStream()
{
std::unique_lock<std::mutex> lk(m_mutex);
m_external = false;
m_url.reset();
m_active_url.reset();
m_video_size = wxDefaultSize;
m_frame = wxImage(m_idle_image);
m_cond.notify_all();
Refresh();
}
void wxMediaCtrl3::SetIdleImage(wxString const &image) void wxMediaCtrl3::SetIdleImage(wxString const &image)
{ {
if (m_idle_image == image) if (m_idle_image == image)
@@ -255,210 +185,6 @@ void wxMediaCtrl3::bambu_log(void *ctx, int level, tchar const *msg2)
BOOST_LOG_TRIVIAL(info) << msg.ToUTF8().data(); BOOST_LOG_TRIVIAL(info) << msg.ToUTF8().data();
} }
// FFmpeg's own diagnostics (HTTP status, "Invalid data found", demuxer choice,
// missing stream dimensions, ...) are otherwise swallowed: a failed camera open
// only surfaces as wxMediaCtrl3's generic error code, which MediaPlayCtrl maps to
// the misleading "Player is malfunctioning" string. Forward them to the Orca log
// instead. Verbosity defaults to AV_LOG_VERBOSE and can be raised at runtime with
// ORCA_FFMPEG_LOG_LEVEL=debug|trace|... (or lowered to warning/error/quiet).
static int ffmpeg_log_level_from_env()
{
const char *env = std::getenv("ORCA_FFMPEG_LOG_LEVEL");
if (env == nullptr || *env == '\0')
return AV_LOG_VERBOSE;
const wxString v = wxString(env).Lower();
if (v == "quiet") return AV_LOG_QUIET;
if (v == "panic") return AV_LOG_PANIC;
if (v == "fatal") return AV_LOG_FATAL;
if (v == "error") return AV_LOG_ERROR;
if (v == "warning") return AV_LOG_WARNING;
if (v == "info") return AV_LOG_INFO;
if (v == "verbose") return AV_LOG_VERBOSE;
if (v == "debug") return AV_LOG_DEBUG;
if (v == "trace") return AV_LOG_TRACE;
return AV_LOG_VERBOSE;
}
static void ffmpeg_log_callback(void *avcl, int level, const char *fmt, va_list vl)
{
if (level > av_log_get_level())
return;
thread_local int print_prefix = 1;
char line[1024];
av_log_format_line2(avcl, level, fmt, vl, line, (int) sizeof(line), &print_prefix);
size_t len = std::strlen(line);
while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r' || line[len - 1] == ' '))
line[--len] = '\0';
if (len == 0)
return;
if (level <= AV_LOG_ERROR)
BOOST_LOG_TRIVIAL(error) << "ffmpeg: " << line;
else if (level <= AV_LOG_WARNING)
BOOST_LOG_TRIVIAL(warning) << "ffmpeg: " << line;
else if (level <= AV_LOG_INFO)
BOOST_LOG_TRIVIAL(info) << "ffmpeg: " << line;
else
BOOST_LOG_TRIVIAL(debug) << "ffmpeg: " << line;
}
static void install_ffmpeg_logger()
{
av_log_set_level(ffmpeg_log_level_from_env());
av_log_set_callback(&ffmpeg_log_callback);
}
int wxMediaCtrl3::ffmpeg_interrupt_callback(void *opaque)
{
auto *ctrl = static_cast<wxMediaCtrl3 *>(opaque);
std::lock_guard<std::mutex> lock(ctrl->m_mutex);
return ctrl->m_url != ctrl->m_active_url;
}
int wxMediaCtrl3::PlayFfmpeg(std::shared_ptr<wxURI> const &url, std::unique_lock<std::mutex> &lock)
{
static std::once_flag logger_once;
std::call_once(logger_once, install_ffmpeg_logger);
if (avformat_network_init() < 0)
return 2;
AVFormatContext *format_context = avformat_alloc_context();
if (!format_context) {
avformat_network_deinit();
return 2;
}
format_context->interrupt_callback = {&wxMediaCtrl3::ffmpeg_interrupt_callback, this};
format_context->flags |= AVFMT_FLAG_NOBUFFER;
format_context->max_delay = 0;
m_active_url = url;
auto finish = [&](int error) {
lock.unlock();
avformat_close_input(&format_context);
avformat_network_deinit();
lock.lock();
m_active_url.reset();
return error;
};
const std::string uri = url->BuildURI().ToUTF8().data();
const wxString scheme = url->GetScheme();
const bool http_stream = scheme.CmpNoCase("http") == 0 || scheme.CmpNoCase("https") == 0;
AVDictionary *options = nullptr;
if (http_stream) {
// Live multipart MJPEG. fflags=nobuffer / AVFMT_FLAG_NOBUFFER / max_delay=0
// (set above) are the low-latency levers - they disable the demuxer
// read-ahead queue. probesize / analyzeduration only bound the one-off
// avformat_find_stream_info() at open; a 32-byte budget returned before a
// whole JPEG frame was seen, so width/height came back unset and the open
// was rejected. Give it room to identify one frame (a startup cost only).
// rw_timeout / timeout bound a wedged connect or read so a stale stream
// fails fast and is retried, instead of the reader thread hanging.
// avioflags=direct is deliberately NOT set: unbuffered reads make the
// mpjpeg demuxer emit "Packet corrupt" and bail on any short read across
// a multipart boundary.
av_dict_set(&options, "fflags", "nobuffer", 0);
av_dict_set(&options, "probesize", "5000000", 0);
av_dict_set(&options, "analyzeduration", "1000000", 0);
av_dict_set(&options, "rw_timeout", "5000000", 0);
av_dict_set(&options, "timeout", "5000000", 0);
} else {
av_dict_set(&options, "rtsp_transport", "tcp", 0);
}
lock.unlock();
int error = avformat_open_input(&format_context, uri.c_str(), nullptr, &options);
av_dict_free(&options);
lock.lock();
if (error < 0)
return finish(2);
lock.unlock();
error = avformat_find_stream_info(format_context, nullptr);
lock.lock();
if (error < 0)
return finish(2);
const int video_stream = av_find_best_stream(format_context, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
if (video_stream < 0)
return finish(2);
AVVideoDecoder decoder;
if (decoder.open(*format_context->streams[video_stream]->codecpar) < 0)
return finish(2);
// Prefer the dimensions the container reported. A small probe budget, or a
// camera that doesn't announce a size up front, can leave these unset - in
// that case fill them in from the first frame that decodes (below) rather
// than failing the open outright.
auto apply_video_size = [&](wxSize size) {
if (!size.IsFullySpecified() || size.x <= 0 || size.y <= 0)
return false;
m_video_size = size;
adjust_frame_size(m_frame_size, m_video_size, GetSize());
NotifyStopped();
return true;
};
bool have_size = apply_video_size({format_context->streams[video_stream]->codecpar->width,
format_context->streams[video_stream]->codecpar->height});
int size_probe_frames = 0; // frames spent still waiting for a usable size
AVPacket *packet = av_packet_alloc();
if (!packet)
return finish(2);
while (m_url == url) {
lock.unlock();
error = av_read_frame(format_context, packet);
lock.lock();
if (m_url != url)
break;
if (error < 0)
break;
if (packet->stream_index == video_stream) {
const int decode_error = decoder.decode(*packet);
if (decode_error == 0) {
if (!have_size) {
have_size = apply_video_size(decoder.decoded_frame_size());
if (!have_size) {
av_packet_unref(packet);
// MJPEG yields a sized frame on the first full packet; if
// several seconds of frames never do, treat it as a bad
// stream instead of sitting in "Loading..." forever.
if (++size_probe_frames > 120)
break;
continue;
}
}
auto frame_size = m_frame_size;
lock.unlock();
#ifdef _WIN32
wxBitmap frame;
decoder.toWxBitmap(frame, frame_size);
#else
wxImage frame;
decoder.toWxImage(frame, frame_size);
#endif
lock.lock();
if (m_url != url)
break;
if (frame.IsOk())
m_frame = frame;
if (!m_refresh_pending.exchange(true)) {
CallAfter([this] {
m_refresh_pending.store(false);
Refresh();
});
}
}
}
av_packet_unref(packet);
}
av_packet_free(&packet);
return finish(m_url == url ? 2 : 1);
}
void wxMediaCtrl3::PlayThread() void wxMediaCtrl3::PlayThread()
{ {
using namespace std::chrono_literals; using namespace std::chrono_literals;
@@ -471,22 +197,42 @@ void wxMediaCtrl3::PlayThread()
continue; continue;
if (!url->HasScheme()) if (!url->HasScheme())
break; break;
const wxString scheme = url->GetScheme(); lk.unlock();
const bool generic_ffmpeg = scheme.CmpNoCase("http") == 0 || scheme.CmpNoCase("https") == 0 || Bambu_Tunnel tunnel = nullptr;
scheme.CmpNoCase("rtsp") == 0 || scheme.CmpNoCase("rtsps") == 0; int error = Bambu_Create(&tunnel, m_url->BuildURI().ToUTF8());
int error = 0; if (error == 0) {
if (generic_ffmpeg) { Bambu_SetLogger(tunnel, &wxMediaCtrl3::bambu_log, this);
error = PlayFfmpeg(url, lk); error = Bambu_Open(tunnel);
} else { if (error == 0)
lk.unlock(); error = Bambu_would_block;
Bambu_Tunnel tunnel = nullptr; }
error = Bambu_Create(&tunnel, m_url->BuildURI().ToUTF8()); lk.lock();
if (error == 0) { while (error == int(Bambu_would_block)) {
Bambu_SetLogger(tunnel, &wxMediaCtrl3::bambu_log, this); m_cond.wait_for(lk, 100ms);
error = Bambu_Open(tunnel); if (m_url != url) {
if (error == 0) error = 1;
error = Bambu_would_block; break;
} }
lk.unlock();
error = Bambu_StartStream(tunnel, true);
lk.lock();
}
Bambu_StreamInfo info;
if (error == 0)
error = Bambu_GetStreamInfo(tunnel, 0, &info);
AVVideoDecoder decoder;
int minFrameDuration = 0;
if (error == 0) {
decoder.open(info);
m_video_size = { info.format.video.width, info.format.video.height };
adjust_frame_size(m_frame_size, m_video_size, GetSize());
minFrameDuration = 800 / info.format.video.frame_rate; // 80%
NotifyStopped();
}
Bambu_Sample sample;
while (error == 0) {
lk.unlock();
error = Bambu_ReadSample(tunnel, &sample);
lk.lock(); lk.lock();
while (error == int(Bambu_would_block)) { while (error == int(Bambu_would_block)) {
m_cond.wait_for(lk, 100ms); m_cond.wait_for(lk, 100ms);
@@ -494,88 +240,60 @@ void wxMediaCtrl3::PlayThread()
error = 1; error = 1;
break; break;
} }
lk.unlock();
error = Bambu_StartStream(tunnel, true);
lk.lock();
}
Bambu_StreamInfo info;
if (error == 0)
error = Bambu_GetStreamInfo(tunnel, 0, &info);
AVVideoDecoder decoder;
int minFrameDuration = 0;
if (error == 0) {
decoder.open(info);
m_video_size = { info.format.video.width, info.format.video.height };
adjust_frame_size(m_frame_size, m_video_size, GetSize());
minFrameDuration = 800 / info.format.video.frame_rate; // 80%
NotifyStopped();
}
Bambu_Sample sample;
while (error == 0) {
lk.unlock(); lk.unlock();
error = Bambu_ReadSample(tunnel, &sample); error = Bambu_ReadSample(tunnel, &sample);
lk.lock(); lk.lock();
while (error == int(Bambu_would_block)) {
m_cond.wait_for(lk, 100ms);
if (m_url != url) {
error = 1;
break;
}
lk.unlock();
error = Bambu_ReadSample(tunnel, &sample);
lk.lock();
}
if (error == 0) {
auto frame_size = m_frame_size;
lk.unlock();
decoder.decode(sample);
#ifdef _WIN32
wxBitmap bm;
decoder.toWxBitmap(bm, frame_size);
#else
wxImage bm;
decoder.toWxImage(bm, frame_size);
#endif
lk.lock();
if (m_url != url) {
error = 1;
break;
}
if (bm.IsOk()) {
auto now = std::chrono::system_clock::now();
if (m_last_PTS && (sample.decode_time - m_last_PTS) < 30000000ULL) { // 3s
auto next_PTS_expected = m_last_PTS_expected + std::chrono::milliseconds((sample.decode_time - m_last_PTS) / 10000ULL);
// The frame is late, catch up a little
auto next_PTS_practical = m_last_PTS_practical + std::chrono::milliseconds(minFrameDuration);
auto next_PTS = std::max(next_PTS_expected, next_PTS_practical);
if(now < next_PTS)
std::this_thread::sleep_until(next_PTS);
else
next_PTS = now;
//auto text = wxString::Format(L"wxMediaCtrl3 pts diff %ld\n", std::chrono::duration_cast<std::chrono::milliseconds>(next_PTS - next_PTS_expected).count());
//OutputDebugString(text);
m_last_PTS = sample.decode_time;
m_last_PTS_expected = next_PTS_expected;
m_last_PTS_practical = next_PTS;
} else {
// Resync
m_last_PTS = sample.decode_time;
m_last_PTS_expected = now;
m_last_PTS_practical = now;
}
m_frame = bm;
}
CallAfter([this] { Refresh(); });
}
} }
if (tunnel) { if (error == 0) {
auto frame_size = m_frame_size;
lk.unlock(); lk.unlock();
Bambu_Close(tunnel); decoder.decode(sample);
Bambu_Destroy(tunnel); #ifdef _WIN32
tunnel = nullptr; wxBitmap bm;
decoder.toWxBitmap(bm, frame_size);
#else
wxImage bm;
decoder.toWxImage(bm, frame_size);
#endif
lk.lock(); lk.lock();
if (m_url != url) {
error = 1;
break;
}
if (bm.IsOk()) {
auto now = std::chrono::system_clock::now();
if (m_last_PTS && (sample.decode_time - m_last_PTS) < 30000000ULL) { // 3s
auto next_PTS_expected = m_last_PTS_expected + std::chrono::milliseconds((sample.decode_time - m_last_PTS) / 10000ULL);
// The frame is late, catch up a little
auto next_PTS_practical = m_last_PTS_practical + std::chrono::milliseconds(minFrameDuration);
auto next_PTS = std::max(next_PTS_expected, next_PTS_practical);
if(now < next_PTS)
std::this_thread::sleep_until(next_PTS);
else
next_PTS = now;
//auto text = wxString::Format(L"wxMediaCtrl3 pts diff %ld\n", std::chrono::duration_cast<std::chrono::milliseconds>(next_PTS - next_PTS_expected).count());
//OutputDebugString(text);
m_last_PTS = sample.decode_time;
m_last_PTS_expected = next_PTS_expected;
m_last_PTS_practical = next_PTS;
} else {
// Resync
m_last_PTS = sample.decode_time;
m_last_PTS_expected = now;
m_last_PTS_practical = now;
}
m_frame = bm;
}
CallAfter([this] { Refresh(); });
} }
} }
if (tunnel) {
lk.unlock();
Bambu_Close(tunnel);
Bambu_Destroy(tunnel);
tunnel = nullptr;
lk.lock();
}
if (m_url == url) if (m_url == url)
m_error = error; m_error = error;
m_frame_size = wxDefaultSize; m_frame_size = wxDefaultSize;
+2 -16
View File
@@ -19,10 +19,11 @@ wxDECLARE_EVENT(EVT_MEDIA_CTRL_STAT, wxCommandEvent);
void wxMediaCtrl_OnSize(wxWindow * ctrl, wxSize const & videoSize, int width, int height); void wxMediaCtrl_OnSize(wxWindow * ctrl, wxSize const & videoSize, int width, int height);
#define BAMBU_DYNAMIC #define BAMBU_DYNAMIC
#include <atomic>
#include <condition_variable> #include <condition_variable>
#include <thread> #include <thread>
#ifndef _WIN32
#include <wx/image.h> #include <wx/image.h>
#endif
#include "Printer/BambuTunnel.h" #include "Printer/BambuTunnel.h"
class AVVideoDecoder; class AVVideoDecoder;
@@ -40,16 +41,6 @@ public:
void Stop(); void Stop();
// Render frames supplied by a controller which owns its own transport.
// The frame is copied while m_mutex is held; callers may release it after
// this method returns.
void SetExternalFrame(const wxImage& frame, wxSize videoSize);
#ifdef _WIN32
void SetExternalFrame(const wxBitmap& frame, wxSize videoSize);
#endif
void BeginExternalStream();
void EndExternalStream();
void SetIdleImage(wxString const & image); void SetIdleImage(wxString const & image);
wxMediaState GetState(); wxMediaState GetState();
@@ -68,10 +59,8 @@ protected:
void DoSetSize(int x, int y, int width, int height, int sizeFlags) override; void DoSetSize(int x, int y, int width, int height, int sizeFlags) override;
static void bambu_log(void *ctx, int level, tchar const *msg); static void bambu_log(void *ctx, int level, tchar const *msg);
static int ffmpeg_interrupt_callback(void *opaque);
void PlayThread(); void PlayThread();
int PlayFfmpeg(std::shared_ptr<wxURI> const &url, std::unique_lock<std::mutex> &lock);
void NotifyStopped(); void NotifyStopped();
@@ -88,15 +77,12 @@ private:
#endif #endif
std::shared_ptr<wxURI> m_url; std::shared_ptr<wxURI> m_url;
std::shared_ptr<wxURI> m_active_url;
bool m_external = false;
std::uint64_t m_last_PTS{0}; std::uint64_t m_last_PTS{0};
std::chrono::system_clock::time_point m_last_PTS_expected; std::chrono::system_clock::time_point m_last_PTS_expected;
std::chrono::system_clock::time_point m_last_PTS_practical; std::chrono::system_clock::time_point m_last_PTS_practical;
std::mutex m_mutex; std::mutex m_mutex;
std::condition_variable m_cond; std::condition_variable m_cond;
std::thread m_thread; std::thread m_thread;
std::atomic_bool m_refresh_pending{false};
}; };
#endif /* wxMediaCtrl3_h */ #endif /* wxMediaCtrl3_h */
-1
View File
@@ -28,7 +28,6 @@ public:
// Communication // Communication
int send_message(std::string dev_id, std::string json_str, int qos, int flag) override; int send_message(std::string dev_id, std::string json_str, int qos, int flag) override;
std::string default_lan_username() const override { return "bblp"; }
int connect_printer(std::string dev_id, std::string dev_ip, std::string username, std::string password, bool use_ssl) override; int connect_printer(std::string dev_id, std::string dev_ip, std::string username, std::string password, bool use_ssl) override;
int disconnect_printer() override; int disconnect_printer() override;
int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override; int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override;
+1 -1
View File
@@ -282,7 +282,7 @@ bool CrealityPrintAgent::parse_cfs_response(const std::string& response,
return true; return true;
} }
bool CrealityPrintAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/) bool CrealityPrintAgent::fetch_filament_info(std::string dev_id)
{ {
if (device_info.dev_ip.empty()) { if (device_info.dev_ip.empty()) {
BOOST_LOG_TRIVIAL(warning) BOOST_LOG_TRIVIAL(warning)
+1 -1
View File
@@ -41,7 +41,7 @@ public:
static AgentInfo get_agent_info_static(); static AgentInfo get_agent_info_static();
AgentInfo get_agent_info() override { return get_agent_info_static(); } AgentInfo get_agent_info() override { return get_agent_info_static(); }
bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override; bool fetch_filament_info(std::string dev_id) override;
// Parse the boxsInfo JSON returned by CrealityPrint::query_boxes_info() into // Parse the boxsInfo JSON returned by CrealityPrint::query_boxes_info() into
// a flat list of loaded slots, plus the count of CFS boxes the printer reports. // a flat list of loaded slots, plus the count of CFS boxes the printer reports.
@@ -1,40 +0,0 @@
#pragma once
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace Slic3r {
struct CameraIceServer {
std::string urls;
std::string username;
std::string credential;
};
enum class CameraUnavailableReason {
Busy,
Error,
Disabled,
Closed,
};
class ICameraSignalingChannel {
public:
virtual ~ICameraSignalingChannel() = default;
virtual void open() = 0;
virtual void close() = 0;
virtual void send_offer(std::string sdp) = 0;
virtual void send_ice(std::string candidate, std::string mid) = 0;
// These callbacks are invoked by the channel's worker thread. Consumers
// must marshal UI work to the GUI thread themselves.
std::function<void(std::vector<CameraIceServer>)> on_ready;
std::function<void(std::string)> on_answer;
std::function<void(std::string, std::string)> on_ice;
std::function<void(CameraUnavailableReason, std::string)> on_unavailable;
};
} // namespace Slic3r
+9 -163
View File
@@ -11,13 +11,6 @@
#define ORCA_NETWORK_ERR_CAP_NOT_AVAILABLE -7020 // a translation exists; this printer lacks the capability #define ORCA_NETWORK_ERR_CAP_NOT_AVAILABLE -7020 // a translation exists; this printer lacks the capability
#include <string> #include <string>
#include <memory> #include <memory>
#include <vector>
#include <functional>
#include <cstdint>
#include <cmath>
#include <nlohmann/json.hpp>
#include <boost/format.hpp>
#include "ICameraSignalingChannel.hpp"
namespace Slic3r { namespace Slic3r {
@@ -50,15 +43,6 @@ enum class FilamentSyncMode {
pull ///< On-demand fetch via REST API (blocking call) pull ///< On-demand fetch via REST API (blocking call)
}; };
enum class CameraStreamMode {
none = 0,
http, // LAN or Cloud
https, // LAN or Cloud over TLS
rtsp, // LAN only
webrtc, // Cloud only
http_snapshot // HTTP endpoint returning one image per request
};
/** /**
* IPrinterAgent - Interface for printer operations. * IPrinterAgent - Interface for printer operations.
* *
@@ -100,86 +84,6 @@ public:
*/ */
virtual int send_message(std::string dev_id, std::string json_str, int qos, int flag) = 0; virtual int send_message(std::string dev_id, std::string json_str, int qos, int flag) = 0;
// why: gcode is firmware dialect, not a waist concept - commands whose body is Bambu-dialect
// gcode live on the agent that speaks it; the default is an honest refusal that MachineObject's
// publish funnel turns into a dialog.
virtual int command_ams_refresh_rfid(std::string, std::string, int, bool)
{ return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; }
virtual int command_ams_calibrate(std::string, int, int, bool)
{ return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; }
virtual int command_ams_select_tray(std::string, std::string, int, bool)
{ return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; }
virtual int command_start_camera(std::string)
{ return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; }
private:
int publish_command_json(std::string dev_id, const nlohmann::json& j, bool lan_mode)
{
return lan_mode ? send_message_to_printer(dev_id, j.dump(), 0, 0)
: send_message(dev_id, j.dump(), 0, 0);
}
public:
virtual int command_xyz_abs(std::string dev_id, int sequence_id, bool lan_mode)
{
nlohmann::json j;
j["print"]["command"] = "gcode_line";
j["print"]["param"] = "G90 \n";
j["print"]["sequence_id"] = std::to_string(sequence_id);
return publish_command_json(dev_id, j, lan_mode);
}
virtual int command_auto_leveling(std::string dev_id, int sequence_id, bool lan_mode)
{
nlohmann::json j;
j["print"]["command"] = "gcode_line";
j["print"]["param"] = "G29 \n";
j["print"]["sequence_id"] = std::to_string(sequence_id);
return publish_command_json(dev_id, j, lan_mode);
}
virtual int command_go_home(std::string dev_id, bool is_printing, bool supports_mqtt_homing, int sequence_id, bool lan_mode)
{
nlohmann::json j;
j["print"]["sequence_id"] = std::to_string(sequence_id);
if (supports_mqtt_homing) {
j["print"]["command"] = "back_to_center";
} else {
j["print"]["command"] = "gcode_line";
j["print"]["param"] = is_printing ? "G28 X\n" : "G28 \n";
}
return publish_command_json(dev_id, j, lan_mode);
}
virtual int command_set_bed(std::string dev_id, int temp, bool supports_mqtt_bed_ctrl, int sequence_id, bool lan_mode)
{
nlohmann::json j;
j["print"]["sequence_id"] = std::to_string(sequence_id);
if (supports_mqtt_bed_ctrl) {
j["print"]["command"] = "set_bed_temp";
j["print"]["temp"] = temp;
} else {
j["print"]["command"] = "gcode_line";
j["print"]["param"] = (boost::format("M140 S%1%\n") % temp).str();
}
return publish_command_json(dev_id, j, lan_mode);
}
virtual int command_set_nozzle(std::string dev_id, int temp, int sequence_id, bool lan_mode)
{
nlohmann::json j;
j["print"]["command"] = "gcode_line";
j["print"]["param"] = (boost::format("M104 S%1%\n") % temp).str();
j["print"]["sequence_id"] = std::to_string(sequence_id);
return publish_command_json(dev_id, j, lan_mode);
}
virtual int command_axis_control(std::string dev_id, std::string axis, double unit, double input_val, int speed,
bool is_core_xy, bool supports_mqtt_axis_control, int sequence_id, bool lan_mode)
{ return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; }
/**
* Default LAN account username for this agent's protocol, if it has a fixed one.
* Returns an empty string if the agent has no fixed default (e.g. caller must supply one).
*/
virtual std::string default_lan_username() const { return {}; }
/** /**
* Establish a direct LAN connection to a printer. * Establish a direct LAN connection to a printer.
*/ */
@@ -201,16 +105,12 @@ public:
/** /**
* Validate current user certificates for the printer. * Validate current user certificates for the printer.
*/ */
virtual int check_cert() { return BAMBU_NETWORK_SUCCESS; } virtual int check_cert() = 0;
/** /**
* Install or refresh device certificate for LAN TLS. * Install or refresh device certificate for LAN TLS.
*/ */
virtual void install_device_cert(std::string dev_id, bool lan_only) virtual void install_device_cert(std::string dev_id, bool lan_only) = 0;
{
(void) dev_id;
(void) lan_only;
}
// ======================================================================== // ========================================================================
// Discovery // Discovery
@@ -226,11 +126,7 @@ public:
/** /**
* Ping the binding endpoint to check printer readiness. * Ping the binding endpoint to check printer readiness.
*/ */
virtual int ping_bind(std::string ping_code) virtual int ping_bind(std::string ping_code) = 0;
{
(void) ping_code;
return BAMBU_NETWORK_SUCCESS;
}
/** /**
* Perform binding detection/handshake on a LAN printer. * Perform binding detection/handshake on a LAN printer.
@@ -240,50 +136,23 @@ public:
/** /**
* Execute the multi-stage printer binding workflow. * Execute the multi-stage printer binding workflow.
*/ */
virtual int bind(std::string dev_ip, std::string dev_id, std::string dev_model, std::string sec_link, virtual int bind(std::string dev_ip, std::string dev_id, std::string dev_model, std::string sec_link, std::string timezone, bool improved, OnUpdateStatusFn update_fn) = 0;
std::string timezone, bool improved, OnUpdateStatusFn update_fn)
{
(void) dev_ip;
(void) dev_id;
(void) dev_model;
(void) sec_link;
(void) timezone;
(void) improved;
(void) update_fn;
return BAMBU_NETWORK_SUCCESS;
}
/** /**
* Remove the association between account and printer. * Remove the association between account and printer.
*/ */
virtual int unbind(std::string dev_id) virtual int unbind(std::string dev_id) = 0;
{
(void) dev_id;
return BAMBU_NETWORK_SUCCESS;
}
/** /**
* Request a one-time bind ticket from the server. * Request a one-time bind ticket from the server.
*/ */
virtual int request_bind_ticket(std::string* ticket) virtual int request_bind_ticket(std::string* ticket) = 0;
{
if (ticket)
*ticket = {};
return BAMBU_NETWORK_SUCCESS;
}
/** /**
* Fetch the cloud snapshot image captured at a print failure. * Fetch the cloud snapshot image captured at a print failure.
* Returns 0 if the request was dispatched; the image body arrives via callback(body, http_status). * Returns 0 if the request was dispatched; the image body arrives via callback(body, http_status).
*/ */
virtual int get_hms_snapshot(std::string dev_id, std::string file_name, virtual int get_hms_snapshot(std::string dev_id, std::string file_name, std::function<void(std::string, int)> callback) = 0;
std::function<void(std::string, int)> callback)
{
(void) dev_id;
(void) file_name;
(void) callback;
return -1;
}
/** /**
* Register callback for fatal HTTP errors. * Register callback for fatal HTTP errors.
@@ -299,7 +168,7 @@ public:
virtual std::string get_user_selected_machine() = 0; virtual std::string get_user_selected_machine() = 0;
/** /**
* Update the selected cloud machine preference. * Update the selected machine preference.
*/ */
virtual int set_user_selected_machine(std::string dev_id) = 0; virtual int set_user_selected_machine(std::string dev_id) = 0;
@@ -415,20 +284,12 @@ public:
*/ */
virtual FilamentSyncMode get_filament_sync_mode() const { return FilamentSyncMode::none; } virtual FilamentSyncMode get_filament_sync_mode() const { return FilamentSyncMode::none; }
/**
* Get the camera stream mode for this agent. This value can be deterministic and derived at
* runtime if the printer supports multiple camera stream modes. E.g. LAN => HTTP/HTTPS/RTSP, Cloud => WebRTC.
*
* @return CameraStreamMode indicating how the camera stream is obtained or used:
*/
virtual CameraStreamMode get_camera_stream_mode() const { return CameraStreamMode::none; }
/** /**
* Refresh filament info from the printer synchronously. * Refresh filament info from the printer synchronously.
* Should only be called when get_filament_sync_mode() returns FilamentSyncMode::pull. * Should only be called when get_filament_sync_mode() returns FilamentSyncMode::pull.
* Populates the MachineObject's DevFilaSystem with fetched filament data. * Populates the MachineObject's DevFilaSystem with fetched filament data.
*/ */
virtual bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) { return false; } virtual bool fetch_filament_info(std::string dev_id) { return false; }
/** /**
* Translate one filament id across the printer boundary. * Translate one filament id across the printer boundary.
@@ -439,21 +300,6 @@ public:
*/ */
virtual std::string to_orca_filament_id(const std::string& printer_filament_id) const { return printer_filament_id; } virtual std::string to_orca_filament_id(const std::string& printer_filament_id) const { return printer_filament_id; }
virtual std::string from_orca_filament_id(const std::string& orca_filament_id) const { return orca_filament_id; } virtual std::string from_orca_filament_id(const std::string& orca_filament_id) const { return orca_filament_id; }
/**
* Get the current camera stream URL for this agent's active machine.
* Only meaningful when get_camera_stream_mode() returns an HTTP, HTTPS, or RTSP mode.
*/
virtual std::string get_camera_url() const { return {}; }
// Optional native camera signaling. Plugin agents retain the default
// nullptr until a plugin-facing WebRTC contract is defined.
virtual std::unique_ptr<ICameraSignalingChannel>
create_camera_signaling_channel(const std::string& dev_id)
{
(void) dev_id;
return nullptr;
}
}; };
} // namespace Slic3r } // namespace Slic3r
+50 -1
View File
@@ -191,6 +191,14 @@ int MoonrakerPrinterAgent::disconnect_printer()
return BAMBU_NETWORK_SUCCESS; return BAMBU_NETWORK_SUCCESS;
} }
int MoonrakerPrinterAgent::check_cert() { return BAMBU_NETWORK_SUCCESS; }
void MoonrakerPrinterAgent::install_device_cert(std::string dev_id, bool lan_only)
{
(void) dev_id;
(void) lan_only;
}
bool MoonrakerPrinterAgent::start_discovery(bool start, bool sending) bool MoonrakerPrinterAgent::start_discovery(bool start, bool sending)
{ {
(void) sending; (void) sending;
@@ -200,6 +208,12 @@ bool MoonrakerPrinterAgent::start_discovery(bool start, bool sending)
return true; return true;
} }
int MoonrakerPrinterAgent::ping_bind(std::string ping_code)
{
(void) ping_code;
return BAMBU_NETWORK_SUCCESS;
}
int MoonrakerPrinterAgent::bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect) int MoonrakerPrinterAgent::bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect)
{ {
(void) sec_link; (void) sec_link;
@@ -216,6 +230,41 @@ int MoonrakerPrinterAgent::bind_detect(std::string dev_ip, std::string sec_link,
return BAMBU_NETWORK_SUCCESS; return BAMBU_NETWORK_SUCCESS;
} }
int MoonrakerPrinterAgent::bind(
std::string dev_ip, std::string dev_id, std::string dev_model, std::string sec_link, std::string timezone, bool improved, OnUpdateStatusFn update_fn)
{
(void) dev_ip;
(void) dev_id;
(void) dev_model;
(void) sec_link;
(void) timezone;
(void) improved;
(void) update_fn;
return BAMBU_NETWORK_SUCCESS;
}
int MoonrakerPrinterAgent::unbind(std::string dev_id)
{
(void) dev_id;
return BAMBU_NETWORK_SUCCESS;
}
int MoonrakerPrinterAgent::request_bind_ticket(std::string* ticket)
{
if (ticket)
*ticket = "";
return BAMBU_NETWORK_SUCCESS;
}
int MoonrakerPrinterAgent::get_hms_snapshot(std::string dev_id, std::string file_name, std::function<void(std::string, int)> callback)
{
// No BBL cloud snapshot source; report failure so the caller falls back.
(void) dev_id;
(void) file_name;
(void) callback;
return -1;
}
int MoonrakerPrinterAgent::set_server_callback(OnServerErrFn fn) int MoonrakerPrinterAgent::set_server_callback(OnServerErrFn fn)
{ {
std::lock_guard<std::recursive_mutex> lock(state_mutex); std::lock_guard<std::recursive_mutex> lock(state_mutex);
@@ -529,7 +578,7 @@ void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index,
} }
} }
bool MoonrakerPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/) bool MoonrakerPrinterAgent::fetch_filament_info(std::string dev_id)
{ {
std::vector<AmsTrayData> trays; std::vector<AmsTrayData> trays;
int max_lane_index = 0; int max_lane_index = 0;
+10 -1
View File
@@ -32,11 +32,20 @@ public:
int disconnect_printer() override; int disconnect_printer() override;
int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override; int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override;
// Certificates
int check_cert() override;
void install_device_cert(std::string dev_id, bool lan_only) override;
// Discovery // Discovery
bool start_discovery(bool start, bool sending) override; bool start_discovery(bool start, bool sending) override;
// Binding // Binding
int ping_bind(std::string ping_code) override;
int bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect) override; int bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect) override;
int bind(std::string dev_ip, std::string dev_id, std::string dev_model, std::string sec_link, std::string timezone, bool improved, OnUpdateStatusFn update_fn) override;
int unbind(std::string dev_id) override;
int request_bind_ticket(std::string* ticket) override;
int get_hms_snapshot(std::string dev_id, std::string file_name, std::function<void(std::string, int)> callback) override;
int set_server_callback(OnServerErrFn fn) override; int set_server_callback(OnServerErrFn fn) override;
// Machine Selection // Machine Selection
@@ -62,7 +71,7 @@ public:
// Pull-mode agent (on-demand filament sync) // Pull-mode agent (on-demand filament sync)
FilamentSyncMode get_filament_sync_mode() const override { return FilamentSyncMode::pull; } FilamentSyncMode get_filament_sync_mode() const override { return FilamentSyncMode::pull; }
bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override; bool fetch_filament_info(std::string dev_id) override;
protected: protected:
struct MoonrakerDeviceInfo struct MoonrakerDeviceInfo
+11 -149
View File
@@ -4,8 +4,6 @@
#include <algorithm> #include <algorithm>
#include <boost/log/trivial.hpp> #include <boost/log/trivial.hpp>
#include <nlohmann/json.hpp>
#include "IPrinterAgent.hpp"
#include "libslic3r/Utils.hpp" #include "libslic3r/Utils.hpp"
#include "NetworkAgent.hpp" #include "NetworkAgent.hpp"
#include "BBLNetworkPlugin.hpp" #include "BBLNetworkPlugin.hpp"
@@ -117,8 +115,6 @@ void NetworkAgent::add_cloud_agent(const std::string& provider, std::shared_ptr<
void NetworkAgent::set_printer_agent(std::shared_ptr<IPrinterAgent> printer_agent) void NetworkAgent::set_printer_agent(std::shared_ptr<IPrinterAgent> printer_agent)
{ {
m_user_machine_list_generation.fetch_add(1);
// Disconnect all callbacks from the old agent // Disconnect all callbacks from the old agent
auto old_printer_agent = m_printer_agent; auto old_printer_agent = m_printer_agent;
@@ -436,26 +432,10 @@ int NetworkAgent::check_user_task_report(int* task_id, bool* printable, const st
int NetworkAgent::get_user_print_info(unsigned int* http_code, std::string* http_body, const std::string& provider) int NetworkAgent::get_user_print_info(unsigned int* http_code, std::string* http_body, const std::string& provider)
{ {
const std::string request_agent_id = m_printer_agent_id;
const std::uint64_t request_generation = m_user_machine_list_generation.fetch_add(1) + 1;
const auto cloud_agent = get_cloud_agent(provider); const auto cloud_agent = get_cloud_agent(provider);
if (!cloud_agent) if (cloud_agent)
return -1; return cloud_agent->get_user_print_info(http_code, http_body);
return -1;
const int result = cloud_agent->get_user_print_info(http_code, http_body);
if (result == 0 && http_body) {
try {
nlohmann::json response = nlohmann::json::parse(*http_body);
response["provider"] = provider;
response["agent_id"] = request_agent_id;
response["generation"] = request_generation;
*http_body = response.dump();
}
catch (const std::exception& e) {
BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " metadata injection exception=" << e.what();
}
}
return result;
} }
int NetworkAgent::get_user_tasks(TaskQueryParams params, std::string* http_body, const std::string& provider) int NetworkAgent::get_user_tasks(TaskQueryParams params, std::string* http_body, const std::string& provider)
@@ -787,77 +767,6 @@ int NetworkAgent::send_message(std::string dev_id, std::string json_str, int qos
return -1; return -1;
} }
int NetworkAgent::command_ams_refresh_rfid(std::string dev_id, std::string tray_id, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_ams_refresh_rfid(dev_id, tray_id, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_ams_calibrate(std::string dev_id, int ams_id, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_ams_calibrate(dev_id, ams_id, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_ams_select_tray(std::string dev_id, std::string tray_id, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_ams_select_tray(dev_id, tray_id, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_start_camera(std::string dev_id)
{
if (m_printer_agent)
return m_printer_agent->command_start_camera(dev_id);
return -1;
}
int NetworkAgent::command_xyz_abs(std::string dev_id, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_xyz_abs(dev_id, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_auto_leveling(std::string dev_id, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_auto_leveling(dev_id, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_go_home(std::string dev_id, bool is_printing, bool supports_mqtt_homing, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_go_home(dev_id, is_printing, supports_mqtt_homing, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_set_bed(std::string dev_id, int temp, bool supports_mqtt_bed_ctrl, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_set_bed(dev_id, temp, supports_mqtt_bed_ctrl, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_set_nozzle(std::string dev_id, int temp, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_set_nozzle(dev_id, temp, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::command_axis_control(std::string dev_id, std::string axis, double unit, double input_val, int speed,
bool is_core_xy, bool supports_mqtt_axis_control, int sequence_id, bool lan_mode)
{
if (m_printer_agent)
return m_printer_agent->command_axis_control(dev_id, axis, unit, input_val, speed, is_core_xy, supports_mqtt_axis_control, sequence_id, lan_mode);
return -1;
}
int NetworkAgent::connect_printer(std::string dev_id, std::string dev_ip, std::string username, std::string password, bool use_ssl) int NetworkAgent::connect_printer(std::string dev_id, std::string dev_ip, std::string username, std::string password, bool use_ssl)
{ {
if (m_printer_agent) if (m_printer_agent)
@@ -879,13 +788,6 @@ int NetworkAgent::send_message_to_printer(std::string dev_id, std::string json_s
return -1; return -1;
} }
std::string NetworkAgent::default_lan_username() const
{
if (m_printer_agent)
return m_printer_agent->default_lan_username();
return {};
}
int NetworkAgent::check_cert() int NetworkAgent::check_cert()
{ {
if (m_printer_agent) if (m_printer_agent)
@@ -944,14 +846,8 @@ std::string NetworkAgent::get_user_selected_machine()
int NetworkAgent::set_user_selected_machine(std::string dev_id) int NetworkAgent::set_user_selected_machine(std::string dev_id)
{ {
BOOST_LOG_TRIVIAL(info) << "NetworkAgent::set_user_selected_machine: dev_id=" << dev_id if (m_printer_agent)
<< " printer_agent=" << (m_printer_agent ? m_printer_agent->get_agent_info().id : "<null>"); return m_printer_agent->set_user_selected_machine(dev_id);
if (m_printer_agent) {
const int result = m_printer_agent->set_user_selected_machine(dev_id);
BOOST_LOG_TRIVIAL(info) << "NetworkAgent::set_user_selected_machine: result=" << result;
return result;
}
BOOST_LOG_TRIVIAL(warning) << "NetworkAgent::set_user_selected_machine: no printer agent";
return -1; return -1;
} }
@@ -971,27 +867,15 @@ int NetworkAgent::stop_subscribe(std::string module)
int NetworkAgent::add_subscribe(std::vector<std::string> dev_list) int NetworkAgent::add_subscribe(std::vector<std::string> dev_list)
{ {
BOOST_LOG_TRIVIAL(info) << "NetworkAgent::add_subscribe: count=" << dev_list.size() if (m_printer_agent)
<< " printer_agent=" << (m_printer_agent ? m_printer_agent->get_agent_info().id : "<null>"); return m_printer_agent->add_subscribe(std::move(dev_list));
if (m_printer_agent) {
const int result = m_printer_agent->add_subscribe(std::move(dev_list));
BOOST_LOG_TRIVIAL(info) << "NetworkAgent::add_subscribe: result=" << result;
return result;
}
BOOST_LOG_TRIVIAL(warning) << "NetworkAgent::add_subscribe: no printer agent";
return -1; return -1;
} }
int NetworkAgent::del_subscribe(std::vector<std::string> dev_list) int NetworkAgent::del_subscribe(std::vector<std::string> dev_list)
{ {
BOOST_LOG_TRIVIAL(info) << "NetworkAgent::del_subscribe: count=" << dev_list.size() if (m_printer_agent)
<< " printer_agent=" << (m_printer_agent ? m_printer_agent->get_agent_info().id : "<null>"); return m_printer_agent->del_subscribe(std::move(dev_list));
if (m_printer_agent) {
const int result = m_printer_agent->del_subscribe(std::move(dev_list));
BOOST_LOG_TRIVIAL(info) << "NetworkAgent::del_subscribe: result=" << result;
return result;
}
BOOST_LOG_TRIVIAL(warning) << "NetworkAgent::del_subscribe: no printer agent";
return -1; return -1;
} }
@@ -1037,10 +921,10 @@ FilamentSyncMode NetworkAgent::get_filament_sync_mode() const
return FilamentSyncMode::none; return FilamentSyncMode::none;
} }
bool NetworkAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode) bool NetworkAgent::fetch_filament_info(std::string dev_id)
{ {
if (m_printer_agent) { if (m_printer_agent) {
return m_printer_agent->fetch_filament_info(dev_id, sync_mode); return m_printer_agent->fetch_filament_info(dev_id);
} }
return false; return false;
} }
@@ -1059,28 +943,6 @@ std::string NetworkAgent::from_orca_filament_id(const std::string& orca_filament
return orca_filament_id; return orca_filament_id;
} }
CameraStreamMode NetworkAgent::get_camera_stream_mode() const
{
if (m_printer_agent)
return m_printer_agent->get_camera_stream_mode();
return CameraStreamMode::none;
}
std::string NetworkAgent::get_local_camera_stream_url() const
{
if (m_printer_agent)
return m_printer_agent->get_camera_url();
return {};
}
std::unique_ptr<ICameraSignalingChannel>
NetworkAgent::create_camera_signaling_channel(const std::string& dev_id)
{
if (m_printer_agent)
return m_printer_agent->create_camera_signaling_channel(dev_id);
return nullptr;
}
int NetworkAgent::request_bind_ticket(std::string* ticket) int NetworkAgent::request_bind_ticket(std::string* ticket)
{ {
if (m_printer_agent) if (m_printer_agent)
+1 -24
View File
@@ -2,22 +2,16 @@
#define __NETWORK_Agent_HPP__ #define __NETWORK_Agent_HPP__
#include "bambu_networking.hpp" #include "bambu_networking.hpp"
#include "libslic3r/ProjectTask.hpp" #include "libslic3r/ProjectTask.hpp"
#include "ICloudServiceAgent.hpp" #include "ICloudServiceAgent.hpp"
#include "IPrinterAgent.hpp" #include "IPrinterAgent.hpp"
#include <map> #include <map>
#include <atomic>
#include <cstdint>
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
namespace Slic3r { namespace Slic3r {
class IPrinterAgent;
// Forward declaration // Forward declaration
class BBLNetworkPlugin; class BBLNetworkPlugin;
@@ -56,7 +50,6 @@ public:
// Sub-agent accessors // Sub-agent accessors
std::shared_ptr<ICloudServiceAgent> get_cloud_agent(const std::string& provider = ORCA_CLOUD_PROVIDER) const; std::shared_ptr<ICloudServiceAgent> get_cloud_agent(const std::string& provider = ORCA_CLOUD_PROVIDER) const;
std::shared_ptr<IPrinterAgent> get_printer_agent() const { return m_printer_agent; } std::shared_ptr<IPrinterAgent> get_printer_agent() const { return m_printer_agent; }
std::uint64_t get_user_machine_list_generation() const { return m_user_machine_list_generation.load(); }
// Shared agent management // Shared agent management
void add_cloud_agent(const std::string& provider, std::shared_ptr<ICloudServiceAgent> agent); void add_cloud_agent(const std::string& provider, std::shared_ptr<ICloudServiceAgent> agent);
@@ -149,21 +142,9 @@ public:
int set_on_local_message_fn(OnMessageFn fn); int set_on_local_message_fn(OnMessageFn fn);
int set_server_callback(OnServerErrFn fn); int set_server_callback(OnServerErrFn fn);
int send_message(std::string dev_id, std::string json_str, int qos, int flag); int send_message(std::string dev_id, std::string json_str, int qos, int flag);
int command_ams_refresh_rfid(std::string dev_id, std::string tray_id, int sequence_id, bool lan_mode);
int command_ams_calibrate(std::string dev_id, int ams_id, int sequence_id, bool lan_mode);
int command_ams_select_tray(std::string dev_id, std::string tray_id, int sequence_id, bool lan_mode);
int command_start_camera(std::string dev_id);
int command_xyz_abs(std::string dev_id, int sequence_id, bool lan_mode);
int command_auto_leveling(std::string dev_id, int sequence_id, bool lan_mode);
int command_go_home(std::string dev_id, bool is_printing, bool supports_mqtt_homing, int sequence_id, bool lan_mode);
int command_set_bed(std::string dev_id, int temp, bool supports_mqtt_bed_ctrl, int sequence_id, bool lan_mode);
int command_set_nozzle(std::string dev_id, int temp, int sequence_id, bool lan_mode);
int command_axis_control(std::string dev_id, std::string axis, double unit, double input_val, int speed,
bool is_core_xy, bool supports_mqtt_axis_control, int sequence_id, bool lan_mode);
int connect_printer(std::string dev_id, std::string dev_ip, std::string username, std::string password, bool use_ssl); int connect_printer(std::string dev_id, std::string dev_ip, std::string username, std::string password, bool use_ssl);
int disconnect_printer(); int disconnect_printer();
int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag); int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag);
std::string default_lan_username() const;
int check_cert(); int check_cert();
void install_device_cert(std::string dev_id, bool lan_only); void install_device_cert(std::string dev_id, bool lan_only);
bool start_discovery(bool start, bool sending); bool start_discovery(bool start, bool sending);
@@ -183,10 +164,7 @@ public:
int start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn); int start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn);
int start_sdcard_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn); int start_sdcard_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn);
FilamentSyncMode get_filament_sync_mode() const; FilamentSyncMode get_filament_sync_mode() const;
bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull); bool fetch_filament_info(std::string dev_id);
CameraStreamMode get_camera_stream_mode() const;
std::string get_local_camera_stream_url() const;
std::unique_ptr<ICameraSignalingChannel> create_camera_signaling_channel(const std::string& dev_id);
std::string to_orca_filament_id(const std::string& printer_filament_id) const; std::string to_orca_filament_id(const std::string& printer_filament_id) const;
std::string from_orca_filament_id(const std::string& orca_filament_id) const; std::string from_orca_filament_id(const std::string& orca_filament_id) const;
int request_bind_ticket(std::string* ticket); int request_bind_ticket(std::string* ticket);
@@ -217,7 +195,6 @@ private:
std::map<std::string, std::shared_ptr<ICloudServiceAgent>> m_cloud_agents; std::map<std::string, std::shared_ptr<ICloudServiceAgent>> m_cloud_agents;
std::shared_ptr<IPrinterAgent> m_printer_agent; std::shared_ptr<IPrinterAgent> m_printer_agent;
std::string m_printer_agent_id; std::string m_printer_agent_id;
std::atomic<std::uint64_t> m_user_machine_list_generation{0};
}; };
} }
+5 -33
View File
@@ -16,10 +16,8 @@
#include <mutex> #include <mutex>
#include <utility> #include <utility>
#include <slic3r/GUI/GUI_App.hpp> #include <slic3r/GUI/GUI_App.hpp>
#include <slic3r/GUI/I18N.hpp>
#include <slic3r/plugin/PluginDescriptor.hpp> #include <slic3r/plugin/PluginDescriptor.hpp>
#include <slic3r/plugin/PythonPluginInterface.hpp> #include <slic3r/plugin/PythonPluginInterface.hpp>
#include <wx/msgdlg.h>
namespace Slic3r { namespace Slic3r {
namespace { namespace {
@@ -316,21 +314,6 @@ void NetworkAgentFactory::register_python_printer_agent(const std::string& plugi
std::shared_ptr<IPrinterAgent> cached_agent; std::shared_ptr<IPrinterAgent> cached_agent;
auto reject_conflicting_capability = [plugin_key, capability_name](const std::string& error_message) {
if (!wxTheApp || GUI::wxGetApp().is_closing())
return;
GUI::wxGetApp().CallAfter([plugin_key, capability_name, error_message]() {
if (GUI::wxGetApp().is_closing())
return;
PluginManager& manager = PluginManager::instance();
manager.set_plugin_error(plugin_key, error_message);
// note: the unload callback triggered by disabling will call deregister,
// which will be a no-op since the printer agent is never registered
manager.set_capability_enabled({PluginCapabilityType::PrinterConnection, capability_name, plugin_key}, false);
wxMessageBox(wxString::FromUTF8(error_message.c_str()), _L("Plugins"), wxOK | wxICON_WARNING, GUI::wxGetApp().GetTopWindow());
});
};
{ {
std::lock_guard<std::mutex> lock(s_registry_mutex); std::lock_guard<std::mutex> lock(s_registry_mutex);
@@ -349,10 +332,9 @@ void NetworkAgentFactory::register_python_printer_agent(const std::string& plugi
auto& python_agent_ids = get_python_printer_agent_ids(); auto& python_agent_ids = get_python_printer_agent_ids();
for (const auto& pair : python_agent_ids) { for (const auto& pair : python_agent_ids) {
if (pair.first != capability_key && pair.second == info.id) { if (pair.first != capability_key && pair.second == info.id) {
const std::string error_message = "Printer-agent '" + info.name + "' could not be enabled: agent ID '" + info.id + BOOST_LOG_TRIVIAL(warning) << "Printer-agent plugin '" << capability_name << "' uses duplicate agent ID '" << info.id
"' is already registered by capability '" + pair.first.second + "' from plugin '" + pair.first.first + "'."; << "' already registered by capability '" << pair.first.second << "' from plugin '"
BOOST_LOG_TRIVIAL(warning) << error_message; << pair.first.first << "'";
reject_conflicting_capability(error_message);
return; return;
} }
} }
@@ -372,22 +354,12 @@ void NetworkAgentFactory::register_python_printer_agent(const std::string& plugi
auto& agents = get_printer_agents(); auto& agents = get_printer_agents();
auto agent_it = agents.find(info.id); auto agent_it = agents.find(info.id);
// why: reject only when the ID is owned by SOMEONE ELSE - a built-in has an empty
// plugin_identifier, another plugin/capability has a different plugin_full_ref. When it
// IS the same plugin_full_ref, this capability is just re-registering itself, so fall
// through and refresh.
if (agent_it != agents.end() && agent_it->second.plugin_identifier != plugin_full_ref) { if (agent_it != agents.end() && agent_it->second.plugin_identifier != plugin_full_ref) {
const std::string error_message = "Printer-agent '" + info.name + "' could not be enabled: agent ID '" + info.id + BOOST_LOG_TRIVIAL(warning) << "Printer-agent plugin '" << capability_name << "' uses agent ID '" << info.id
"' is already registered by '" + agent_it->second.display_name + "'."; << "' already registered by '" << agent_it->second.display_name << "'";
BOOST_LOG_TRIVIAL(warning) << error_message;
reject_conflicting_capability(error_message);
return; return;
} }
// why: insert_or_assign, not emplace - reaching here means the ID is new, or the same
// capability is re-registering (same plugin_full_ref). In the re-register case we WANT to
// overwrite so the factory closure points at the current live capability instance; emplace
// would silently keep the stale entry.
agents.insert_or_assign(info.id, PrinterAgentInfo(info.id, info.name, plugin_full_ref, std::move(factory))); agents.insert_or_assign(info.id, PrinterAgentInfo(info.id, info.name, plugin_full_ref, std::move(factory)));
python_agent_ids[capability_key] = info.id; python_agent_ids[capability_key] = info.id;
+4 -45
View File
@@ -83,7 +83,6 @@ constexpr const char* ORCA_UNSUBSCRIBE_PLUGINS = "/api/v1/plugins/subscriptions"
constexpr const char* ORCA_PLUGINS_MINE = "/api/v1/plugins/mine"; constexpr const char* ORCA_PLUGINS_MINE = "/api/v1/plugins/mine";
constexpr const char* ORCA_PLUGINS_BASE = "/api/v1/plugins"; constexpr const char* ORCA_PLUGINS_BASE = "/api/v1/plugins";
constexpr const char* ORCA_PLUGIN_DOWNLOAD_URL = "/api/v1/plugins/download"; constexpr const char* ORCA_PLUGIN_DOWNLOAD_URL = "/api/v1/plugins/download";
constexpr const char* ORCA_CLOUD_PRINTER = "/api/v1/printers";
constexpr const char* ORCA_CLOUD_LOGIN_PATH = "/orcaslicer-login"; constexpr const char* ORCA_CLOUD_LOGIN_PATH = "/orcaslicer-login";
@@ -2624,51 +2623,11 @@ int OrcaCloudServiceAgent::check_user_task_report(int* task_id, bool* printable)
int OrcaCloudServiceAgent::get_user_print_info(unsigned int* http_code, std::string* http_body) int OrcaCloudServiceAgent::get_user_print_info(unsigned int* http_code, std::string* http_body)
{ {
std::string response; BOOST_LOG_TRIVIAL(debug) << "OrcaCloudServiceAgent: get_user_print_info (stub)";
unsigned int code = 0;
int result = http_get(ORCA_CLOUD_PRINTER, &response, &code);
if (http_code) if (http_code)
*http_code = code; *http_code = 200;
if (http_body)
if (result != 0 || code != 200) *http_body = "{}";
return result != 0 ? result : BAMBU_NETWORK_ERR_GET_SETTING_LIST_FAILED;
try {
auto resp_json = nlohmann::json::parse(response);
nlohmann::json devices = nlohmann::json::array();
for (const auto& printer : resp_json.value("data", nlohmann::json::array())) {
const std::string role = printer.value("access_role", "");
if (role.empty() || role == "viewer")
continue;
nlohmann::json device;
device["dev_id"] = printer.value("id", "");
device["dev_name"] = printer.value("name", "");
if (printer.contains("model") && printer["model"].is_string())
device["dev_model_name"] = printer["model"].get<std::string>();
bool online = false;
if (printer.contains("status_snapshot") && printer["status_snapshot"].is_object()) {
const auto& status = printer["status_snapshot"].value("status", nlohmann::json::object());
online = status.value("connection", nlohmann::json::object()).value("state", "") == "online";
if (status.contains("job") && status["job"].is_object())
device["task_status"] = status["job"].value("state", "");
}
device["dev_online"] = online;
devices.push_back(std::move(device));
}
if (http_body) {
nlohmann::json out;
out["devices"] = std::move(devices);
*http_body = out.dump();
}
} catch (const std::exception&) {
return BAMBU_NETWORK_ERR_GET_SETTING_LIST_FAILED;
}
return BAMBU_NETWORK_SUCCESS; return BAMBU_NETWORK_SUCCESS;
} }
+49
View File
@@ -41,6 +41,19 @@ int OrcaPrinterAgent::send_message_to_printer(std::string dev_id, std::string js
return BAMBU_NETWORK_SUCCESS; return BAMBU_NETWORK_SUCCESS;
} }
// ============================================================================
// Certificates - All Stubs
// ============================================================================
int OrcaPrinterAgent::check_cert()
{
return BAMBU_NETWORK_SUCCESS;
}
void OrcaPrinterAgent::install_device_cert(std::string dev_id, bool lan_only)
{
}
// ============================================================================ // ============================================================================
// Discovery - Stub // Discovery - Stub
// ============================================================================ // ============================================================================
@@ -50,11 +63,47 @@ bool OrcaPrinterAgent::start_discovery(bool start, bool sending)
return true; return true;
} }
// ============================================================================
// Binding - All Stubs
// ============================================================================
int OrcaPrinterAgent::ping_bind(std::string ping_code)
{
return BAMBU_NETWORK_SUCCESS;
}
int OrcaPrinterAgent::bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect) int OrcaPrinterAgent::bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect)
{ {
return BAMBU_NETWORK_SUCCESS; return BAMBU_NETWORK_SUCCESS;
} }
int OrcaPrinterAgent::bind(
std::string dev_ip, std::string dev_id, std::string dev_model, std::string sec_link, std::string timezone, bool improved, OnUpdateStatusFn update_fn)
{
return BAMBU_NETWORK_SUCCESS;
}
int OrcaPrinterAgent::unbind(std::string dev_id)
{
return BAMBU_NETWORK_SUCCESS;
}
int OrcaPrinterAgent::request_bind_ticket(std::string* ticket)
{
if (ticket)
*ticket = "";
return BAMBU_NETWORK_SUCCESS;
}
int OrcaPrinterAgent::get_hms_snapshot(std::string dev_id, std::string file_name, std::function<void(std::string, int)> callback)
{
// No BBL cloud snapshot source; report failure so the caller falls back.
(void) dev_id;
(void) file_name;
(void) callback;
return -1;
}
int OrcaPrinterAgent::set_server_callback(OnServerErrFn fn) int OrcaPrinterAgent::set_server_callback(OnServerErrFn fn)
{ {
std::lock_guard<std::mutex> lock(state_mutex); std::lock_guard<std::mutex> lock(state_mutex);
+9
View File
@@ -32,11 +32,20 @@ public:
int disconnect_printer() override; int disconnect_printer() override;
int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override; int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override;
// Certificates
int check_cert() override;
void install_device_cert(std::string dev_id, bool lan_only) override;
// Discovery // Discovery
bool start_discovery(bool start, bool sending) override; bool start_discovery(bool start, bool sending) override;
// Binding // Binding
int ping_bind(std::string ping_code) override;
int bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect) override; int bind_detect(std::string dev_ip, std::string sec_link, detectResult& detect) override;
int bind(std::string dev_ip, std::string dev_id, std::string dev_model, std::string sec_link, std::string timezone, bool improved, OnUpdateStatusFn update_fn) override;
int unbind(std::string dev_id) override;
int request_bind_ticket(std::string* ticket) override;
int get_hms_snapshot(std::string dev_id, std::string file_name, std::function<void(std::string, int)> callback) override;
int set_server_callback(OnServerErrFn fn) override; int set_server_callback(OnServerErrFn fn) override;
// Machine Selection // Machine Selection
+204
View File
@@ -0,0 +1,204 @@
// PaintCLI.cpp — CLI paint-inspection primitives. See PaintCLI.hpp.
#include "PaintCLI.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/TriangleSelector.hpp"
#include <nlohmann/json.hpp>
#include <cmath>
#include <string>
#include <utility>
#include <vector>
namespace Slic3r {
namespace PaintCLI {
namespace {
using json = nlohmann::json;
double its_surface_area(const indexed_triangle_set &its)
{
double total = 0.0;
for (const stl_triangle_vertex_indices &t : its.indices) {
const Vec3f &a = its.vertices[t(0)];
const Vec3f &b = its.vertices[t(1)];
const Vec3f &c = its.vertices[t(2)];
total += 0.5 * (b - a).cross(c - a).norm();
}
return total;
}
// Bbox over triangle-referenced vertices only. get_facets_strict() returns
// an itset with the full source vertex list — using bounding_box() on it
// would report the whole mesh's bbox even when only a few facets are painted.
BoundingBoxf3 its_referenced_bbox(const indexed_triangle_set &its)
{
BoundingBoxf3 bb;
bool first = true;
for (const stl_triangle_vertex_indices &t : its.indices) {
for (int k = 0; k < 3; ++k) {
const Vec3d v = its.vertices[t(k)].cast<double>();
if (first) { bb.min = bb.max = v; first = false; }
else bb.merge(v);
}
}
return bb;
}
json vec3_to_json(const Vec3d &v)
{
return json::array({ v.x(), v.y(), v.z() });
}
json bbox_to_json(const BoundingBoxf3 &bb)
{
return {
{ "min", vec3_to_json(bb.min) },
{ "max", vec3_to_json(bb.max) },
{ "size", vec3_to_json(Vec3d(bb.max - bb.min)) },
};
}
// One (layer, state) row — empty ones are omitted at the caller level.
json state_entry(const std::string &label, const indexed_triangle_set &its)
{
return {
{ "state", label },
{ "facets", its.indices.size() },
{ "area_mm2", its_surface_area(its) },
{ "bbox", bbox_to_json(its_referenced_bbox(its)) },
};
}
// Iterate the states relevant to one FacetsAnnotation kind, collecting
// non-empty entries. Empty layer → {"empty": true}. `n_facets_out` is the
// running total of painted facets — bumped for the summary.
json inspect_layer(const ModelVolume &mv, const FacetsAnnotation &fa,
const std::vector<std::pair<EnforcerBlockerType, std::string>> &states,
size_t &n_facets_out)
{
if (fa.empty())
return { { "empty", true } };
json entries = json::array();
for (const auto &st : states) {
if (!fa.has_facets(mv, st.first))
continue;
indexed_triangle_set its = fa.get_facets_strict(mv, st.first);
if (its.indices.empty())
continue;
n_facets_out += its.indices.size();
entries.push_back(state_entry(st.second, its));
}
return {
{ "empty", entries.empty() },
{ "states", std::move(entries) },
};
}
const std::vector<std::pair<EnforcerBlockerType, std::string>> &supports_states()
{
static const std::vector<std::pair<EnforcerBlockerType, std::string>> s = {
{ EnforcerBlockerType::ENFORCER, "ENFORCER" },
{ EnforcerBlockerType::BLOCKER, "BLOCKER" },
};
return s;
}
const std::vector<std::pair<EnforcerBlockerType, std::string>> &fuzzy_states()
{
// FUZZY_SKIN is an enum alias for ENFORCER; the layer is single-state.
static const std::vector<std::pair<EnforcerBlockerType, std::string>> s = {
{ EnforcerBlockerType::FUZZY_SKIN, "FUZZY_SKIN" },
};
return s;
}
const std::vector<std::pair<EnforcerBlockerType, std::string>> &mmu_states()
{
static std::vector<std::pair<EnforcerBlockerType, std::string>> s = []{
std::vector<std::pair<EnforcerBlockerType, std::string>> v;
for (int i = 1; i <= int(EnforcerBlockerType::ExtruderMax); ++i)
v.emplace_back(EnforcerBlockerType(i), "extruder_" + std::to_string(i));
return v;
}();
return s;
}
} // namespace
void inspect_to_json(const Model &model, const std::vector<std::string> &source_paths,
std::ostream &out)
{
json root;
root["sources"] = source_paths;
root["frame"] = "mesh_local";
root["note"] = "Coordinates are mesh-local (each volume's own frame). "
"Paint gizmos operate in this frame.";
json objects = json::array();
size_t total_objects = 0, total_volumes = 0, total_painted = 0, total_facets = 0;
for (size_t oi = 0; oi < model.objects.size(); ++oi) {
const ModelObject *mo = model.objects[oi];
if (!mo) continue;
++total_objects;
json obj;
obj["index"] = oi;
obj["name"] = mo->name;
json volumes = json::array();
for (size_t vi = 0; vi < mo->volumes.size(); ++vi) {
const ModelVolume *mv = mo->volumes[vi];
if (!mv) continue;
++total_volumes;
const indexed_triangle_set &its = mv->mesh().its;
json vol;
vol["index"] = vi;
vol["name"] = mv->name;
vol["n_facets"] = its.indices.size();
vol["is_model_part"] = mv->is_model_part();
vol["bbox_mesh_local"] = bbox_to_json(bounding_box(its));
size_t vol_painted = 0;
json paints;
paints["supports"] = inspect_layer(*mv, mv->supported_facets,
supports_states(), vol_painted);
paints["seam"] = inspect_layer(*mv, mv->seam_facets,
supports_states(), vol_painted);
paints["mmu_segmentation"] = inspect_layer(*mv, mv->mmu_segmentation_facets,
mmu_states(), vol_painted);
paints["fuzzy_skin"] = inspect_layer(*mv, mv->fuzzy_skin_facets,
fuzzy_states(), vol_painted);
vol["paints"] = std::move(paints);
vol["painted_facets_total"] = vol_painted;
if (vol_painted > 0) ++total_painted;
total_facets += vol_painted;
volumes.push_back(std::move(vol));
}
obj["volumes"] = std::move(volumes);
objects.push_back(std::move(obj));
}
root["objects"] = std::move(objects);
root["summary"] = {
{ "objects", total_objects },
{ "volumes", total_volumes },
{ "volumes_with_paint", total_painted },
{ "painted_facets_total", total_facets },
};
// Object names and file paths are arbitrary bytes, and dump() throws on invalid
// UTF-8 by default. Replace such sequences with U+FFFD so the output is always
// valid JSON rather than an exception out of the CLI.
out << root.dump(2, ' ', false, json::error_handler_t::replace) << std::endl;
}
} // namespace PaintCLI
} // namespace Slic3r
+31
View File
@@ -0,0 +1,31 @@
// PaintCLI.hpp — CLI paint-inspection primitives.
//
// Backs the --inspect-paint CLI action. Reads the per-facet enforcer /
// blocker / extruder / fuzzy-skin state that OrcaSlicer stores on every
// ModelVolume (supports, seam, MMU color, fuzzy-skin) and emits a
// structured JSON summary — facet count, surface area, and mesh-local
// bounding box per state — so CI / scripted / AI tooling can reason
// about existing paint on a .3mf without opening the GUI.
//
// Coordinates are mesh-local (each volume's own frame), matching the
// frame that the paint gizmos operate in.
#ifndef slic3r_PaintCLI_hpp_
#define slic3r_PaintCLI_hpp_
#include <iosfwd>
#include <string>
#include <vector>
namespace Slic3r {
class Model;
namespace PaintCLI {
// `source_paths` lists every input file; the CLI merges them into one Model.
void inspect_to_json(const Model &model, const std::vector<std::string> &source_paths,
std::ostream &out);
} // namespace PaintCLI
} // namespace Slic3r
#endif
-34
View File
@@ -1,34 +0,0 @@
#pragma once
#include <string>
namespace Slic3r {
enum LiveviewLocal {
LVL_None,
LVL_Disable,
LVL_Local,
LVL_Rtsps,
LVL_Rtsp
};
enum LiveviewRemote {
LVR_None,
LVR_Tutk,
LVR_Agora,
LVR_TutkAgora
};
enum FileLocal {
FL_None,
FL_Local
};
enum FileRemote {
FR_None,
FR_Tutk,
FR_Agora,
FR_TutkAgora
};
} // namespace Slic3r

Some files were not shown because too many files have changed in this diff Show More