diff --git a/CMakeLists.txt b/CMakeLists.txt index 9a5fc8387..c6f295150 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -268,8 +268,6 @@ set(LIBDIR_BIN ${CMAKE_CURRENT_BINARY_DIR}/src) include_directories(${LIBDIR}) # For generated header files include_directories(${LIBDIR_BIN}/platform) -# For libslic3r.h -include_directories(${LIBDIR}/clipper) if(WIN32) add_definitions(-D_USE_MATH_DEFINES -D_WIN32 -D_CRT_SECURE_NO_WARNINGS -D_SCL_SECURE_NO_WARNINGS) diff --git a/lib/Slic3r/Geometry/Clipper.pm b/lib/Slic3r/Geometry/Clipper.pm index 0c35c93d9..b7a7da772 100644 --- a/lib/Slic3r/Geometry/Clipper.pm +++ b/lib/Slic3r/Geometry/Clipper.pm @@ -5,7 +5,7 @@ use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( - offset offset2 + offset offset_ex offset2_ex diff_ex diff union_ex intersection_ex JT_ROUND JT_MITER JT_SQUARE diff --git a/lib/Slic3r/Print/Object.pm b/lib/Slic3r/Print/Object.pm index 7370881ea..0385f88b8 100644 --- a/lib/Slic3r/Print/Object.pm +++ b/lib/Slic3r/Print/Object.pm @@ -7,7 +7,7 @@ use List::Util qw(min max sum first); use Slic3r::Flow ':roles'; use Slic3r::Geometry qw(scale epsilon); use Slic3r::Geometry::Clipper qw(diff diff_ex intersection intersection_ex union union_ex - offset offset2 offset_ex offset2_ex JT_MITER); + offset offset_ex offset2_ex JT_MITER); use Slic3r::Print::State ':steps'; use Slic3r::Surface ':types'; diff --git a/resources/icons/splashscreen-gcodepreview.jpg b/resources/icons/splashscreen-gcodepreview.jpg index 3bae38493..481c4a6e1 100644 Binary files a/resources/icons/splashscreen-gcodepreview.jpg and b/resources/icons/splashscreen-gcodepreview.jpg differ diff --git a/resources/icons/splashscreen.jpg b/resources/icons/splashscreen.jpg index 754e24588..08236bccc 100644 Binary files a/resources/icons/splashscreen.jpg and b/resources/icons/splashscreen.jpg differ diff --git a/resources/profiles/Anycubic.idx b/resources/profiles/Anycubic.idx index 24a881f30..cc3b55ef4 100644 --- a/resources/profiles/Anycubic.idx +++ b/resources/profiles/Anycubic.idx @@ -1,13 +1,14 @@ -min_slic3r_version = 2.3.1-beta -0.0.9 Updated bed textures -min_slic3r_version = 2.3.0-beta2 -0.0.8 Updated start and end g-code for Anycubic Mega. -0.0.7 Updated start g-code for Anycubic Mega. -0.0.6 Reduced max print height for Predator. Updated end g-code, before layer change g-code and output filename format for Kossel. -0.0.5 Updated end g-code. -min_slic3r_version = 2.3.0-alpha2 -0.0.4 Fixed predator output filename format, infill overlap, start gcode adjustments. -0.0.3 Fixed infill_overlap, start_gcode, end_gcode for Anycubic Predator -0.0.2 Added Anycubic Predator -min_slic3r_version = 2.3.0-alpha0 -0.0.1 Initial Version +min_slic3r_version = 2.3.1-beta +0.0.10 Various updates for Anycubic Mega. Added filament profiles. +0.0.9 Updated bed textures +min_slic3r_version = 2.3.0-beta2 +0.0.8 Updated start and end g-code for Anycubic Mega. +0.0.7 Updated start g-code for Anycubic Mega. +0.0.6 Reduced max print height for Predator. Updated end g-code, before layer change g-code and output filename format for Kossel. +0.0.5 Updated end g-code. +min_slic3r_version = 2.3.0-alpha2 +0.0.4 Fixed predator output filename format, infill overlap, start gcode adjustments. +0.0.3 Fixed infill_overlap, start_gcode, end_gcode for Anycubic Predator +0.0.2 Added Anycubic Predator +min_slic3r_version = 2.3.0-alpha0 +0.0.1 Initial Version diff --git a/resources/profiles/Anycubic.ini b/resources/profiles/Anycubic.ini index 44308abc8..c1b763879 100644 --- a/resources/profiles/Anycubic.ini +++ b/resources/profiles/Anycubic.ini @@ -5,7 +5,7 @@ name = Anycubic # Configuration version of this file. Config file will only be installed, if the config_version differs. # This means, the server may force the PrusaSlicer configuration to be downgraded. -config_version = 0.0.9 +config_version = 0.0.10 # Where to get the updates from? config_update_url = https://files.prusa3d.com/wp-content/uploads/repository/PrusaSlicer-settings-master/live/Anycubic/ # changelog_url = https://files.prusa3d.com/?latest=slicer-profiles&lng=%1% @@ -76,7 +76,7 @@ bridge_flow_ratio = 0.8 bridge_speed = 30 brim_width = 0 clip_multipart_objects = 1 -compatible_printers = +compatible_printers = complete_objects = 0 dont_support_bridges = 1 elefant_foot_compensation = 0 @@ -108,7 +108,7 @@ max_volumetric_extrusion_rate_slope_negative = 0 max_volumetric_extrusion_rate_slope_positive = 0 max_volumetric_speed = 0 min_skirt_length = 4 -notes = +notes = overhangs = 0 only_retract_when_crossing_perimeters = 0 ooze_prevention = 0 @@ -117,8 +117,8 @@ perimeters = 2 perimeter_extruder = 1 perimeter_extrusion_width = 0.45 perimeter_speed = 45 -post_process = -print_settings_id = +post_process = +print_settings_id = raft_layers = 0 resolution = 0 seam_position = nearest @@ -290,7 +290,7 @@ compatible_printers_condition = printer_notes=~/.*PRINTER_MODEL_AK(|LP).*/ and n # Common filament preset [filament:*common_akossel*] cooling = 0 -compatible_printers = +compatible_printers = extrusion_multiplier = 1 filament_cost = 0 filament_density = 0 @@ -375,9 +375,9 @@ filament_vendor = Generic # Common printer preset [printer:*common_akossel*] printer_technology = FFF -bed_shape = +bed_shape = before_layer_gcode = ;BEFORE_LAYER_CHANGE\nG92 E0\n;[layer_z] -between_objects_gcode = +between_objects_gcode = deretract_speed = 40 extruder_colour = #FFFF00 extruder_offset = 0x0 @@ -405,8 +405,8 @@ max_layer_height = 0.3 min_layer_height = 0.08 max_print_height = 300 nozzle_diameter = 0.4 -printer_notes = -printer_settings_id = +printer_notes = +printer_settings_id = retract_before_travel = 2 retract_before_wipe = 70% retract_layer_change = 1 @@ -419,9 +419,9 @@ retract_restart_extra = 0 retract_restart_extra_toolchange = 0 retract_speed = 60 single_extruder_multi_material = 0 -start_gcode = +start_gcode = end_gcode = M104 S0 ; turn off temperature\nM140 S0 ; turn off heatbed\nM107 ; turn off fan\nG28 ; home\nM84 ; disable motors -toolchange_gcode = +toolchange_gcode = use_firmware_retraction = 0 use_relative_e_distances = 1 use_volumetric_e = 0 @@ -435,7 +435,7 @@ default_filament_profile = Generic PLA @AKOSSEL inherits = *common_akossel* printer_model = AKLP printer_variant = 0.4 -printer_notes = Don't remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_Anycubic\nPRINTER_MODEL_AKLP\nPRINTER_HAS_BOWDEN\n +printer_notes = Do not remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_Anycubic\nPRINTER_MODEL_AKLP\nPRINTER_HAS_BOWDEN\n bed_shape = 114.562x10.0229,113.253x19.9695,111.081x29.7642,108.065x39.3323,104.225x48.6011,99.5929x57.5,94.2025x65.9613,88.0951x73.9206,81.3173x81.3173,73.9206x88.0951,65.9613x94.2025,57.5x99.5929,48.6011x104.225,39.3323x108.065,29.7642x111.081,19.9695x113.253,10.0229x114.562,7.04172e-15x115,-10.0229x114.562,-19.9695x113.253,-29.7642x111.081,-39.3323x108.065,-48.6011x104.225,-57.5x99.5929,-65.9613x94.2025,-73.9206x88.0951,-81.3173x81.3173,-88.0951x73.9206,-94.2025x65.9613,-99.5929x57.5,-104.225x48.6011,-108.065x39.3323,-111.081x29.7642,-113.253x19.9695,-114.562x10.0229,-115x1.40834e-14,-114.562x-10.0229,-113.253x-19.9695,-111.081x-29.7642,-108.065x-39.3323,-104.225x-48.6011,-99.5929x-57.5,-94.2025x-65.9613,-88.0951x-73.9206,-81.3173x-81.3173,-73.9206x-88.0951,-65.9613x-94.2025,-57.5x-99.5929,-48.6011x-104.225,-39.3323x-108.065,-29.7642x-111.081,-19.9695x-113.253,-10.0229x-114.562,-2.11252e-14x-115,10.0229x-114.562,19.9695x-113.253,29.7642x-111.081,39.3323x-108.065,48.6011x-104.225,57.5x-99.5929,65.9613x-94.2025,73.9206x-88.0951,81.3173x-81.3173,88.0951x-73.9206,94.2025x-65.9613,99.5929x-57.5,104.225x-48.6011,108.065x-39.3323,111.081x-29.7642,113.253x-19.9695,114.562x-10.0229,115x-2.81669e-14 start_gcode = G90 ; use absolute coordinates\nM83 ; extruder relative mode\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG28 ; home\nG1 X-54.672 Y95.203 Z0.3 F9000\nG92 E0.0\nG1 F1000\nG1 X-52.931 Y96.185 E0.300\nG1 X-50.985 Y97.231 E0.331\nG1 X-49.018 Y98.238 E0.331\nG1 X-47.032 Y99.205 E0.331\nG1 X-45.026 Y100.132 E0.331\nG1 X-43.003 Y101.019 E0.331\nG1 X-40.961 Y101.864 E0.331\nG1 X-38.904 Y102.668 E0.331\nG1 X-36.83 Y103.431 E0.331\nG1 X-34.742 Y104.152 E0.331\nG1 X-32.639 Y104.83 E0.331\nG1 X-30.523 Y105.466 E0.331\nG1 X-28.395 Y106.06 E0.331\nG1 X-26.255 Y106.61 E0.331\nG1 X-24.105 Y107.117 E0.331\nG1 X-21.945 Y107.581 E0.331\nG1 X-19.776 Y108.001 E0.331\nG1 X-17.599 Y108.377 E0.331\nG1 X-15.415 Y108.71 E0.331\nG1 X-13.224 Y108.998 E0.331\nG1 X-11.028 Y109.242 E0.331\nG1 X-8.828 Y109.442 E0.331\nG1 X-6.624 Y109.598 E0.331\nG1 X-4.418 Y109.709 E0.331\nG1 X-2.209 Y109.776 E0.332\nG1 X0 Y109.798 E0.331\nG1 X2.209 Y109.776 E0.690\nG1 X4.418 Y109.709 E0.691\nG1 X6.624 Y109.598 E0.690\nG1 X8.828 Y109.442 E0.690\nG1 X11.028 Y109.242 E0.690\nG1 X13.224 Y108.998 E0.690\nG1 X15.415 Y108.71 E0.691\nG1 X17.599 Y108.377 E0.690\nG1 X19.776 Y108.001 E0.690\nG1 X21.945 Y107.581 E0.690\nG1 X24.105 Y107.117 E0.690\nG1 X26.255 Y106.61 E0.690\nG1 X28.395 Y106.06 E0.690\nG1 X30.523 Y105.466 E0.690\nG1 X32.639 Y104.83 E0.690\nG1 X34.742 Y104.152 E0.690\nG1 X36.83 Y103.431 E0.690\nG1 X38.904 Y102.668 E0.691\nG1 X40.961 Y101.864 E0.690\nG1 X43.003 Y101.019 E0.691\nG1 X45.026 Y100.132 E0.690\nG1 X47.032 Y99.205 E0.691\nG1 X49.018 Y98.238 E0.690\nG1 X50.985 Y97.231 E0.691\nG1 X52.931 Y96.185 E0.690\nG1 X54.672 Y95.203 E0.625\nG92 E0.0\nG1 E-5 F3000 ; retract 5mm\nG1 X52.931 Y96.185 F1000 ; wipe\nG1 X50.985 Y97.231 F1000 ; wipe\nG1 X49.018 Y98.238 F1000 ; wipe\nG1 X0 Y109.798 F1000\nG1 E4.8 F1500; de-retract\nG92 E0.0 ; reset extrusion distance\nM221 S{if layer_height<0.075}100{else}95{endif} @@ -443,7 +443,7 @@ start_gcode = G90 ; use absolute coordinates\nM83 ; extruder relative mode\nM104 inherits = *common_akossel* printer_model = AK printer_variant = 0.4 -printer_notes = Don't remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_Anycubic\nPRINTER_MODEL_AK\nPRINTER_HAS_BOWDEN\n +printer_notes = Do not remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_Anycubic\nPRINTER_MODEL_AK\nPRINTER_HAS_BOWDEN\n bed_shape = 89.6575x7.84402,88.6327x15.6283,86.9333x23.2937,84.5723x30.7818,81.5677x38.0356,77.9423x45,73.7237x51.6219,68.944x57.8509,63.6396x63.6396,57.8509x68.944,51.6219x73.7237,45x77.9423,38.0356x81.5677,30.7818x84.5723,23.2937x86.9333,15.6283x88.6327,7.84402x89.6575,5.51091e-15x90,-7.84402x89.6575,-15.6283x88.6327,-23.2937x86.9333,-30.7818x84.5723,-38.0356x81.5677,-45x77.9423,-51.6219x73.7237,-57.8509x68.944,-63.6396x63.6396,-68.944x57.8509,-73.7237x51.6219,-77.9423x45,-81.5677x38.0356,-84.5723x30.7818,-86.9333x23.2937,-88.6327x15.6283,-89.6575x7.84402,-90x1.10218e-14,-89.6575x-7.84402,-88.6327x-15.6283,-86.9333x-23.2937,-84.5723x-30.7818,-81.5677x-38.0356,-77.9423x-45,-73.7237x-51.6219,-68.944x-57.8509,-63.6396x-63.6396,-57.8509x-68.944,-51.6219x-73.7237,-45x-77.9423,-38.0356x-81.5677,-30.7818x-84.5723,-23.2937x-86.9333,-15.6283x-88.6327,-7.84402x-89.6575,-1.65327e-14x-90,7.84402x-89.6575,15.6283x-88.6327,23.2937x-86.9333,30.7818x-84.5723,38.0356x-81.5677,45x-77.9423,51.6219x-73.7237,57.8509x-68.944,63.6396x-63.6396,68.944x-57.8509,73.7237x-51.6219,77.9423x-45,81.5677x-38.0356,84.5723x-30.7818,86.9333x-23.2937,88.6327x-15.6283,89.6575x-7.84402,90x-2.20436e-14 start_gcode = G90 ; use absolute coordinates\nM83 ; extruder relative mode\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG28 ; home\nG1 X-39.672 Y69.712 Z0.3 F9000\nG92 E0.0\nG1 F1000\nG1 X-38.457 Y70.397 E0.209\nG1 X-37.043 Y71.157 E0.241\nG1 X-35.614 Y71.889 E0.241\nG1 X-34.171 Y72.591 E0.241\nG1 X-32.714 Y73.265 E0.241\nG1 X-31.244 Y73.909 E0.241\nG1 X-29.761 Y74.523 E0.241\nG1 X-28.266 Y75.108 E0.241\nG1 X-26.759 Y75.662 E0.241\nG1 X-25.242 Y76.185 E0.241\nG1 X-23.714 Y76.678 E0.241\nG1 X-22.177 Y77.14 E0.241\nG1 X-20.63 Y77.571 E0.241\nG1 X-19.076 Y77.971 E0.241\nG1 X-17.514 Y78.34 E0.241\nG1 X-15.944 Y78.677 E0.241\nG1 X-14.368 Y78.982 E0.241\nG1 X-12.786 Y79.255 E0.241\nG1 X-11.199 Y79.497 E0.241\nG1 X-9.608 Y79.706 E0.241\nG1 X-8.013 Y79.884 E0.241\nG1 X-6.414 Y80.029 E0.241\nG1 X-4.813 Y80.142 E0.241\nG1 X-3.21 Y80.223 E0.241\nG1 X-1.605 Y80.271 E0.241\nG1 X0 Y80.287 E0.241\nG1 X1.605 Y80.271 E0.502\nG1 X3.21 Y80.223 E0.502\nG1 X4.813 Y80.142 E0.502\nG1 X6.414 Y80.029 E0.502\nG1 X8.013 Y79.884 E0.502\nG1 X9.608 Y79.706 E0.502\nG1 X11.199 Y79.497 E0.501\nG1 X12.786 Y79.255 E0.502\nG1 X14.368 Y78.982 E0.502\nG1 X15.944 Y78.677 E0.502\nG1 X17.514 Y78.34 E0.502\nG1 X19.076 Y77.971 E0.502\nG1 X20.63 Y77.571 E0.501\nG1 X22.177 Y77.14 E0.502\nG1 X23.714 Y76.678 E0.502\nG1 X25.242 Y76.185 E0.502\nG1 X26.759 Y75.662 E0.501\nG1 X28.266 Y75.108 E0.502\nG1 X29.761 Y74.523 E0.502\nG1 X31.244 Y73.909 E0.502\nG1 X32.714 Y73.265 E0.502\nG1 X34.171 Y72.591 E0.502\nG1 X35.614 Y71.889 E0.501\nG1 X37.043 Y71.157 E0.502\nG1 X38.457 Y70.397 E0.502\nG1 X39.672 Y69.712 E0.436\nG92 E0.0\nM221 S{if layer_height<0.075}100{else}95{endif} @@ -784,7 +784,7 @@ printer_model = MEGA0 printer_variant = 0.4 max_layer_height = 0.3 min_layer_height = 0.1 -printer_notes = Don't remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_ANYCUBIC\nPRINTER_MODEL_MEGA0 +printer_notes = Do not remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_ANYCUBIC\nPRINTER_MODEL_MEGA0 bed_shape = 0x0,220x0,220x220,0x220 max_print_height = 250 machine_max_acceleration_e = 5000 @@ -822,54 +822,61 @@ end_gcode = M117 Cooling down...\nM104 S0 ; turn off extruder\nM107 ; Fan off\nM [print:*common_mega*] bottom_solid_min_thickness = 0.5 -bridge_acceleration = 1800 -bridge_flow_ratio = 0.8 +bridge_acceleration = 1000 +bridge_flow_ratio = 0.95 bridge_speed = 30 compatible_printers_condition = printer_notes=~/.*PRINTER_VENDOR_ANYCUBIC.*/ and printer_notes=~/.*PRINTER_MODEL_I3_MEGA.*/ and nozzle_diameter[0]==0.4 -default_acceleration = 1800 +default_acceleration = 1000 ensure_vertical_shell_thickness = 1 -external_perimeter_extrusion_width = 0.6 -external_perimeter_speed = 40 +external_perimeter_extrusion_width = 0.45 +external_perimeter_speed = 25 extruder_clearance_height = 35 extruder_clearance_radius = 60 extrusion_width = 0.45 fill_density = 15% fill_pattern = gyroid -first_layer_acceleration = 1800 +first_layer_acceleration = 1000 first_layer_extrusion_width = 0.42 first_layer_height = 0.2 +first_layer_speed = 20 gap_fill_speed = 40 gcode_comments = 1 -infill_acceleration = 1800 +infill_acceleration = 1000 +infill_anchor = 2.5 +infill_anchor_max = 12 infill_extrusion_width = 0.45 -infill_speed = 60 +max_print_speed = 200 +min_skirt_length = 4 only_retract_when_crossing_perimeters = 0 -output_filename_format = {input_filename_base}_{nozzle_diameter[0]}n_{layer_height}mm_{filament_type[0]}_{printer_model}_{print_time}.gcode -perimeter_acceleration = 1800 +output_filename_format = {input_filename_base}_{layer_height}mm_{filament_type[0]}_{printer_model}_{print_time}.gcode +perimeter_acceleration = 800 perimeter_extrusion_width = 0.45 +perimeter_speed = 45 perimeters = 2 seam_position = nearest -skirts = 0 -slice_closing_radius = 0.05 -small_perimeter_speed = 30 +skirt_distance = 2 +skirt_height = 3 +skirts = 1 +small_perimeter_speed = 25 solid_infill_below_area = 0 -solid_infill_speed = 60 +solid_infill_extrusion_width = 0.45 +solid_infill_speed = 80 support_material_buildplate_only = 1 support_material_contact_distance = 0.1 support_material_extrusion_width = 0.35 support_material_interface_layers = 2 support_material_interface_spacing = 0.2 support_material_spacing = 2 +support_material_speed = 50 support_material_threshold = 55 -support_material_with_sheath = 0 thin_walls = 0 top_infill_extrusion_width = 0.4 top_solid_infill_speed = 40 +top_solid_layers = 5 top_solid_min_thickness = 0.6 travel_speed = 180 [print:*supported_mega*] -raft_layers = 2 support_material = 1 # XXXXXXXXXXXXXXXXXXXX @@ -911,7 +918,19 @@ inherits = *0.20mm_mega*;*supported_mega* [print:*0.30mm_mega*] inherits = *common_mega* bottom_solid_layers = 4 -bridge_flow_ratio = 0.95 +external_perimeter_extrusion_width = 0.6 +external_perimeter_speed = 35 +extrusion_width = 0.5 +fill_pattern = grid +infill_extrusion_width = 0.5 +infill_speed = 85 +layer_height = 0.3 +perimeter_extrusion_width = 0.5 +perimeter_speed = 50 +small_perimeter_speed = 30 +solid_infill_extrusion_width = 0.5 +support_material_extrusion_width = 0.38 +support_material_speed = 45 top_solid_layers = 4 [print:0.30mm DRAFT @MEGA] @@ -929,7 +948,6 @@ compatible_printers_condition = printer_notes=~/.*PRINTER_VENDOR_ANYCUBIC.*/ and end_filament_gcode = "; Filament-specific end gcode" fan_always_on = 1 fan_below_layer_time = 100 -filament_colour = #FF8000 filament_vendor = Generic min_print_speed = 15 slowdown_below_layer_time = 20 @@ -941,13 +959,13 @@ slowdown_below_layer_time = 20 cooling = 0 fan_always_on = 0 fan_below_layer_time = 20 - filament_colour = #FFF2EC + filament_colour = #3A80CA filament_cost = 27.82 filament_density = 1.04 filament_max_volumetric_speed = 11 filament_ramming_parameters = "120 100 5.70968 6.03226 7 8.25806 9 9.19355 9.3871 9.77419 10.129 10.3226 10.4516 10.5161| 0.05 5.69677 0.45 6.15484 0.95 8.76774 1.45 9.20323 1.95 9.95806 2.45 10.3871 2.95 10.5677 3.45 7.6 3.95 7.6 4.45 7.6 4.95 7.6" filament_type = ABS - first_layer_bed_temperature = 100 + first_layer_bed_temperature = 105 first_layer_temperature = 255 max_fan_speed = 30 min_fan_speed = 20 @@ -955,14 +973,14 @@ slowdown_below_layer_time = 20 [filament:Generic ABS @MEGA] inherits = *ABS_mega* - + [filament:*FLEX_mega*] inherits = *common_mega* bed_temperature = 50 bridge_fan_speed = 80 cooling = 0 extrusion_multiplier = 1.15 -fan_always_on = 0 +fan_always_on = 0 filament_colour = #008000 filament_cost = 82.00 filament_density = 1.22 @@ -970,7 +988,7 @@ filament_deretract_speed = 25 filament_max_volumetric_speed = 1.2 filament_retract_length = 0.8 filament_type = FLEX -first_layer_bed_temperature = 50 +first_layer_bed_temperature = 55 first_layer_temperature = 240 max_fan_speed = 90 min_fan_speed = 70 @@ -979,16 +997,41 @@ temperature = 240 [filament:Generic FLEX @MEGA] inherits = *FLEX_mega* +[filament:SainSmart TPU @MEGA] +inherits = *FLEX_mega* +filament_vendor = SainSmart +bed_temperature = 50 +bridge_fan_speed = 100 +cooling = 1 +disable_fan_first_layers = 4 +filament_cost = 39.99 +filament_density = 1.21 +filament_deretract_speed = 15 +filament_max_volumetric_speed = 1.8 +filament_notes = "SainSmart TPU gains popularity among 3D Printing community for its balance of rigidity and flexibility. In addition, with a 95A Shore Hardness and improved bed adhesion, it is easier to print even with a stock elementary 3D Printer like the Creality Ender 3. SainSmart TPU will not disappoint if you are looking for flexible filament. From drone parts, phone cases, to small toys, all can be printed with ease.\n\nhttps://www.sainsmart.com/collections/tpu-filament/products/all-colors-tpu-flexible-filament-1-75mm-0-8kg-1-76lb" +filament_retract_before_travel = 5 +filament_retract_length = 4 +filament_retract_speed = 40 +filament_unloading_speed = 90 +first_layer_bed_temperature = 55 +first_layer_temperature = 235 +full_fan_speed_layer = 6 +max_fan_speed = 80 +min_fan_speed = 80 +slowdown_below_layer_time = 10 +temperature = 235 + [filament:*PETG_mega*] inherits = *common_mega* bed_temperature = 90 bridge_fan_speed = 50 fan_below_layer_time = 20 +filament_colour = #FF8000 filament_cost = 27.82 filament_density = 1.27 filament_max_volumetric_speed = 8 filament_type = PETG -first_layer_bed_temperature = 85 +first_layer_bed_temperature = 90 first_layer_temperature = 230 max_fan_speed = 50 min_fan_speed = 30 @@ -997,14 +1040,63 @@ temperature = 240 [filament:Generic PETG @MEGA] inherits = *PETG_mega* +[filament:ColorFabb XT-CF20 @MEGA] +inherits = *PETG_mega* +compatible_printers_condition = nozzle_diameter[0]>=0.4 and printer_notes=~/.*PRINTER_VENDOR_ANYCUBIC.*/ and printer_notes=~/.*PRINTER_MODEL_I3_MEGA.*/ +extrusion_multiplier = 1.05 +filament_colour = #804040 +filament_cost = 66.60 +filament_density = 1.35 +filament_deretract_speed = 25 +filament_max_volumetric_speed = 2 +filament_notes = "Based on colorFabb_XT, XT-CF20 is a carbon fiber composite material. Loaded with no less than 20% specially sourced carbon fibers we have developed a very stiff and tough 3D printing filament made for functional parts. It is truly a professional printers go-to material, especially for users looking for high melt strength, high melt viscosity and good dimensional accuracy and stability.\n\nhttps://colorfabb.com/xt-cf20" +filament_retract_before_travel = 1 +filament_retract_length = 1.4 +filament_retract_speed = 40 +filament_spool_weight = 236 +filament_vendor = ColorFabb +first_layer_temperature = 260 +full_fan_speed_layer = 5 +slowdown_below_layer_time = 15 +temperature = 260 + +[filament:ERYONE PETG @MEGA] +inherits = *PETG_mega* +filament_vendor = ERYONE +filament_cost = 20.99 +filament_notes = "https://eryone.com/petg/show/10.html" + +[filament:FormFutura HDglass @MEGA] +inherits = *PETG_mega* +filament_vendor = FormFutura +filament_cost = 46.65 +filament_notes = "HDglass is a high performance PETG type of 3D printer with unsurpassed 3D printing properties and improved mechanical strength, flexibility, toughness and heat resistance.\n\nhttps://www.formfutura.com/shop/product/hdglass-2812" + +[filament:FormFutura ReForm rPET @MEGA] +inherits = *PETG_mega* +filament_vendor = FormFutura +filament_cost = 26.65 +filament_notes = "ReForm rPET is a recycled PETG type of 3D printer filament that is made from post-industrial waste streams of a nearby located plastic bottle manufacturer.\n\nhttps://www.formfutura.com/shop/product/reform-rpet-2836" +filament_spool_weight = 176 + +[filament:Janbex transparent PETG @MEGA] +inherits = *PETG_mega* +filament_vendor = Janbex +filament_cost = 31.99 +filament_spool_weight = 222 +first_layer_temperature = 215 +min_fan_speed = 100 +temperature = 210 + [filament:*PLA_mega*] inherits = *common_mega* bed_temperature = 60 disable_fan_first_layers = 1 +filament_colour = #FF3232 filament_cost = 25.40 filament_density = 1.24 filament_max_volumetric_speed = 10 -first_layer_bed_temperature = 60 +first_layer_bed_temperature = 65 first_layer_temperature = 215 min_fan_speed = 100 temperature = 210 @@ -1012,73 +1104,97 @@ temperature = 210 [filament:Generic PLA @MEGA] inherits = *PLA_mega* -[filament:*3Dmensionals PLA_mega*] +[filament:3Dmensionals PLA @MEGA] inherits = *PLA_mega* filament_vendor = 3Dmensionals -filament_cost = 23.35 +filament_cost = 22.90 +filament_notes = "Das 3DFilaments - PLA von 3Dmensionals ist ein sehr leicht zu druckendes 3D-Drucker Filament. Dabei handelt es sich um ein etwas härteres PLA mit einer exzellenten thermischen Stabilität. Das Filament zeichnet sich vor allem durch verzugfreies 3D-Drucken aus und weist minimale bis keine Verformung nach dem Abkühlen auf. Daher ist es besonders gut für den Druck größerer Objekte geeignet. Zudem bietet 3DFilaments - PLA über die gesamte Fadenläge eine hervorragende Durchmesser- und Rundheitstoleranz.\n\nhttps://www.3dmensionals.de/3dfilaments?number=PSU3DM001V" -[filament:3Dmensionals PLA @MEGA] -inherits = *3Dmensionals PLA_mega* +[filament:3D Warhorse PLA @MEGA] +inherits = *PLA_mega* +filament_vendor = 3D Warhorse +filament_cost = 19.99 -[filament:3Dmensionals PLA blue @MEGA] -inherits = *3Dmensionals PLA_mega* -filament_colour = #4155FB +[filament:AMOLEN wood PLA] +inherits = *PLA_mega* +filament_vendor = AMOLEN +compatible_printers_condition = nozzle_diameter[0]>0.35 and printer_notes=~/.*PRINTER_VENDOR_ANYCUBIC.*/ and printer_notes=~/.*PRINTER_MODEL_I3_MEGA.*/ +extrusion_multiplier = 1.1 +filament_colour = #DFC287 +filament_cost = 33.99 +filament_density = 1.23 +filament_max_volumetric_speed = 9 +filament_notes = "https://amolen.com/collections/wood/products/amolen-pla-filament-1-75mm-wood-color-3d-printer-filament-1kg2-2lb" -[filament:3Dmensionals PLA silver @MEGA] -inherits = *3Dmensionals PLA_mega* -filament_colour = #B9B5B4 +[filament:FormFutura EasyFil PLA @MEGA] +inherits = *PLA_mega* +filament_vendor = FormFutura +filament_cost = 39.93 +filament_notes = "EasyFil PLA is an easy to print PLA type of 3D printer filament that is available in a wide variety of colors. Its improved flowing behavior make 3D printed layers flow more into each other.\n\nhttps://www.formfutura.com/shop/product/easyfil-pla-2801" -[filament:3Dmensionals PLA white @MEGA] -inherits = *3Dmensionals PLA_mega* -filament_colour = #FEFEFD +[filament:FormFutura ReForm rPLA @MEGA] +inherits = *PLA_mega* +filament_vendor = FormFutura +filament_cost = 26.65 +filament_notes = "ReForm is a sustainable initiative within Formfutura to efficiently manage residual extrusion waste streams and re-use them into high-end upcycled filaments. The ideology behind ReForm is to a make 3D printing more sustainable – without having to make compromises on material properties – and yet keep it affordable.\n\nhttps://www.formfutura.com/shop/product/reform-rpla-2838" -[filament:*Verbatim PLA_mega*] +[filament:GIANTARM PLA @MEGA] +inherits = *PLA_mega* +filament_vendor = GIANTARM +filament_cost = 24.99 + +[filament:Prusament PLA @MEGA] +inherits = *PLA_mega* +filament_vendor = Prusa Polymers +filament_cost = 30.24 +filament_notes = "Affordable filament for everyday printing in premium quality manufactured in-house by Josef Prusa" +filament_spool_weight = 201 +temperature = 215 + +[filament:Verbatim PLA @MEGA] inherits = *PLA_mega* filament_vendor = Verbatim filament_cost = 23.88 -[filament:Verbatim PLA @MEGA] -inherits = *Verbatim PLA_mega* - -[filament:Verbatim PLA black @MEGA] -inherits = *Verbatim PLA_mega* -filament_colour = #333333 - [printer:*common_mega*] printer_technology = FFF bed_shape = 0x0,210x0,210x210,0x210 -before_layer_gcode = ;BEFORE_LAYER_CHANGE\n;[layer_z] +before_layer_gcode = ;BEFORE_LAYER_CHANGE\nG92 E0.0\n;[layer_z] default_filament_profile = Generic PLA @MEGA default_print_profile = 0.15mm QUALITY @MEGA -deretract_speed = 50 -end_gcode = G4 ; wait\nG92 E0\nG1{if max_layer_z < max_print_height} Z{z_offset+min(max_layer_z+30, max_print_height)}{endif} ; move print head up\nM104 S0 ; turn off temperature\nM140 S0 ; turn off heatbed\nM107 ; turn off fan\nG1 X0 Y200 F3000 ; home X axis\nM84 ; disable motors +deretract_speed = 40 +end_gcode = G1 E-1.0 F2100 ; retract\nG92 E0.0\nG1{if max_layer_z < max_print_height} Z{z_offset+min(max_layer_z+30, max_print_height)}{endif} E-34.0 F720 ; move print head up & retract filament\nG4 ; wait\nM104 S0 ; turn off temperature\nM140 S0 ; turn off heatbed\nM107 ; turn off fan\nG1 X0 Y105 F3000 ; park print head\nM84 ; disable motors extruder_colour = #808080 gcode_flavor = marlin layer_gcode = ;AFTER_LAYER_CHANGE\n;[layer_z] max_layer_height = 0.36 max_print_height = 205 +remaining_times = 1 +retract_before_travel = 1.5 retract_before_wipe = 60% retract_layer_change = 1 -retract_length = 6 -retract_lift = 0.075 +retract_length = 3.2 +retract_lift = 0.2 retract_lift_below = 204 +retract_speed = 70 silent_mode = 0 -start_gcode = G90 ; use absolute coordinates\nM83 ; extruder relative mode\nM204 S[machine_max_acceleration_extruding] T[machine_max_acceleration_retracting]\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nG28 ; home all\nG1 Y0 Z1 F100 ; move print head up\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG92 E0\nG1 Z0.2 F360\nG1 X60 E9 F700 ; intro line\nG1 X100 E12.5 F700 ; intro line\nG92 E0 +start_gcode = G90 ; use absolute coordinates\nM83 ; extruder relative mode\nM204 S[machine_max_acceleration_extruding] T[machine_max_acceleration_retracting]\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nG28 ; home all\nG1 Y1.0 Z0.3 F1000 ; move print head up\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG92 E0.0\n; initial load\nG1 X205.0 E19 F1000\nG1 Y1.6\nG1 X5.0 E19 F1000\nG92 E0.0\n; intro line\nG1 Y2.0 Z0.2 F1000\nG1 X65.0 E9.0 F1000\nG1 X105.0 E12.5 F1000\nG92 E0.0 +thumbnails = 16x16,220x124 use_relative_e_distances = 1 wipe = 1 -machine_max_acceleration_e = 5000 +machine_max_acceleration_e = 10000 machine_max_acceleration_extruding = 1250 machine_max_acceleration_retracting = 1250 -machine_max_acceleration_x = 1000 -machine_max_acceleration_y = 1000 -machine_max_acceleration_z = 200 +machine_max_acceleration_x = 3000 +machine_max_acceleration_y = 2000 +machine_max_acceleration_z = 60 machine_max_feedrate_e = 60 -machine_max_feedrate_x = 200 -machine_max_feedrate_y = 200 +machine_max_feedrate_x = 500 +machine_max_feedrate_y = 500 machine_max_feedrate_z = 6 machine_max_jerk_e = 5 -machine_max_jerk_x = 8 -machine_max_jerk_y = 8 +machine_max_jerk_x = 10 +machine_max_jerk_y = 10 machine_max_jerk_z = 0.4 [printer:Anycubic i3 Mega] @@ -1092,6 +1208,7 @@ inherits = *common_mega* printer_model = I3MEGAS printer_variant = 0.4 printer_notes = Do not remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_ANYCUBIC\nPRINTER_MODEL_I3_MEGA_S\nPRINTER_HAS_BOWDEN +machine_max_feedrate_e = 30 machine_max_feedrate_z = 8 @@ -1743,7 +1860,7 @@ machine_max_jerk_z = 5 machine_min_extruding_rate = 0 machine_min_travel_rate = 0 printer_settings_id = -printer_notes = Don't remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_ANYCUBIC\nPRINTER_MODEL_PREDATOR\nPRINTER_HAS_BOWDEN\n +printer_notes = Do not remove the following keywords! These keywords are used in the "compatible printer" condition of the print and filament profiles to link the particular print and filament profiles to this printer profile.\nPRINTER_VENDOR_ANYCUBIC\nPRINTER_MODEL_PREDATOR\nPRINTER_HAS_BOWDEN\n default_filament_profile = Generic PLA @PREDATOR [printer:Anycubic Predator 0.4 nozzle] diff --git a/resources/profiles/Anycubic/i3megas.svg b/resources/profiles/Anycubic/i3megas.svg new file mode 100644 index 000000000..dfb4ae496 --- /dev/null +++ b/resources/profiles/Anycubic/i3megas.svg @@ -0,0 +1,561 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/profiles/Anycubic/i3megas_bed.stl b/resources/profiles/Anycubic/i3megas_bed.stl new file mode 100644 index 000000000..49ff8c5b3 Binary files /dev/null and b/resources/profiles/Anycubic/i3megas_bed.stl differ diff --git a/resources/profiles/Creality.ini b/resources/profiles/Creality.ini index 524815525..717b49558 100644 --- a/resources/profiles/Creality.ini +++ b/resources/profiles/Creality.ini @@ -21,7 +21,7 @@ technology = FFF family = ENDER bed_model = ender3_bed.stl bed_texture = ender3.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER3BLTOUCH] name = Creality Ender-3 BLTouch @@ -30,7 +30,7 @@ technology = FFF family = ENDER bed_model = ender3_bed.stl bed_texture = ender3.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER3V2] name = Creality Ender-3 V2 @@ -39,7 +39,7 @@ technology = FFF family = ENDER bed_model = ender3v2_bed.stl bed_texture = ender3v2.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER3MAX] name = Creality Ender-3 Max @@ -48,7 +48,7 @@ technology = FFF family = ENDER bed_model = cr10v2_bed.stl bed_texture = cr10spro.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER4] name = Creality Ender-4 @@ -57,7 +57,7 @@ technology = FFF family = ENDER bed_model = ender3v2_bed.stl bed_texture = ender3v2.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER5] name = Creality Ender-5 @@ -66,7 +66,7 @@ technology = FFF family = ENDER bed_model = ender3_bed.stl bed_texture = ender3.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER5PLUS] name = Creality Ender-5 Plus @@ -75,7 +75,7 @@ technology = FFF family = ENDER bed_model = ender5plus_bed.stl bed_texture = ender5plus.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER6] name = Creality Ender-6 @@ -84,7 +84,7 @@ technology = FFF family = ENDER bed_model = ender6_bed.stl bed_texture = ender6.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:ENDER2] name = Creality Ender-2 @@ -93,7 +93,7 @@ technology = FFF family = ENDER bed_model = ender2_bed.stl bed_texture = ender2.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR5PRO] name = Creality CR-5 Pro @@ -102,7 +102,7 @@ technology = FFF family = CR bed_model = cr5pro_bed.stl bed_texture = cr5pro.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR5PROH] name = Creality CR-5 Pro H @@ -111,7 +111,7 @@ technology = FFF family = CR bed_model = cr5pro_bed.stl bed_texture = cr5pro.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR6SE] name = Creality CR-6 SE @@ -120,7 +120,7 @@ technology = FFF family = CR bed_model = cr6se_bed.stl bed_texture = cr6se.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR6MAX] name = Creality CR-6 Max @@ -129,7 +129,7 @@ technology = FFF family = CR bed_model = cr10s4_bed.stl bed_texture = cr10s4.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10MINI] name = Creality CR-10 Mini @@ -138,7 +138,7 @@ technology = FFF family = CR bed_model = cr10mini_bed.stl bed_texture = cr10mini.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10MAX] name = Creality CR-10 Max @@ -147,7 +147,7 @@ technology = FFF family = CR bed_model = cr10max_bed.stl bed_texture = cr10max.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10] name = Creality CR-10 @@ -156,7 +156,7 @@ technology = FFF family = CR bed_model = cr10_bed.stl bed_texture = cr10.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10V2] name = Creality CR-10 V2 @@ -165,7 +165,7 @@ technology = FFF family = CR bed_model = cr10v2_bed.stl bed_texture = cr10.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10V3] name = Creality CR-10 V3 @@ -174,7 +174,7 @@ technology = FFF family = CR bed_model = cr10v2_bed.stl bed_texture = cr10.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10S] name = Creality CR-10 S @@ -183,7 +183,7 @@ technology = FFF family = CR bed_model = cr10_bed.stl bed_texture = cr10.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10SPRO] name = Creality CR-10 S Pro @@ -192,7 +192,7 @@ technology = FFF family = CR bed_model = cr10v2_bed.stl bed_texture = cr10spro.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10SPROV2] name = Creality CR-10 S Pro V2 @@ -201,7 +201,7 @@ technology = FFF family = CR bed_model = cr10v2_bed.stl bed_texture = cr10.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10S4] name = Creality CR-10 S4 @@ -210,7 +210,7 @@ technology = FFF family = CR bed_model = cr10s4_bed.stl bed_texture = cr10s4.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR10S5] name = Creality CR-10 S5 @@ -219,7 +219,7 @@ technology = FFF family = CR bed_model = cr10s5_bed.stl bed_texture = cr10s5.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR20] name = Creality CR-20 @@ -228,7 +228,7 @@ technology = FFF family = CR bed_model = ender3_bed.stl bed_texture = cr20.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR20PRO] name = Creality CR-20 Pro @@ -237,7 +237,7 @@ technology = FFF family = CR bed_model = ender3_bed.stl bed_texture = cr20.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR200B] name = Creality CR-200B @@ -246,7 +246,7 @@ technology = FFF family = CR bed_model = cr200b_bed.stl bed_texture = cr200b.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY [printer_model:CR8] name = Creality CR-8 @@ -255,7 +255,7 @@ technology = FFF family = CR bed_model = cr8_bed.stl bed_texture = cr8.svg -default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY #[printer_model:CRX] #name = Creality CR-X @@ -264,7 +264,7 @@ default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @ #family = CR-X #bed_model = cr10v2_bed.stl #bed_texture = cr10spro.svg -#default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +#default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY #[printer_model:CRXPRO] #name = Creality CR-X Pro @@ -273,7 +273,7 @@ default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @ #family = CR-X #bed_model = cr10v2_bed.stl #bed_texture = cr10spro.svg -#default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY +#default_materials = Generic PLA @CREALITY; Generic PETG @CREALITY; Generic ABS @CREALITY; Creality PLA @CREALITY; Prusament PLA @CREALITY; Prusament PETG @CREALITY; AzureFilm PLA @CREALITY; Devil Design PLA @CREALITY; Devil Design PLA Matt @CREALITY; Devil Design PLA Galaxy @CREALITY; Extrudr PLA NX2 @CREALITY; Real Filament PLA @CREALITY; Velleman PLA @CREALITY; 3DJAKE ecoPLA @CREALITY; 3DJAKE ecoPLA Matt @CREALITY; 3DJAKE ecoPLA Tough @CREALITY; 123-3D Jupiter PLA @CREALITY # All presets starting with asterisk, for example *common*, are intermediate and they will # not make it into the user interface. @@ -326,7 +326,7 @@ notes = overhangs = 0 only_retract_when_crossing_perimeters = 0 ooze_prevention = 0 -output_filename_format = {input_filename_base}_{layer_height}mm_{filament_type[0]}_{printer_model}_{print_time}.gcode +output_filename_format = {input_filename_base}_{print_time}_{layer_height}mm_{temperature[0]}C_{filament_type[0]}_{printer_model}.gcode perimeters = 2 perimeter_extruder = 1 perimeter_extrusion_width = 0.45 @@ -639,6 +639,18 @@ filament_density = 1.24 filament_colour = #FF0000 filament_spool_weight = 256 +[filament:Devil Design PLA Matt @CREALITY] +inherits = *PLA* +filament_vendor = Devil Design +temperature = 205 +bed_temperature = 60 +first_layer_temperature = 205 +first_layer_bed_temperature = 60 +filament_cost = 20.00 +filament_density = 1.38 +filament_colour = #FF0000 +filament_spool_weight = 256 + [filament:Devil Design PLA Galaxy @CREALITY] inherits = *PLA* renamed_from = "Devil Design PLA (Galaxy) @CREALITY" diff --git a/resources/profiles/PrusaResearch/mk2.svg b/resources/profiles/PrusaResearch/mk2.svg index b8fa8d0cd..1fe5b4c57 100644 --- a/resources/profiles/PrusaResearch/mk2.svg +++ b/resources/profiles/PrusaResearch/mk2.svg @@ -1 +1,927 @@ -MK2_bottom \ No newline at end of file + + + + + + image/svg+xml + + MK2_bottom + + + + + MK2_bottom + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/profiles/PrusaResearch/mk3.svg b/resources/profiles/PrusaResearch/mk3.svg index c8f53373b..678213ac5 100644 --- a/resources/profiles/PrusaResearch/mk3.svg +++ b/resources/profiles/PrusaResearch/mk3.svg @@ -1 +1,930 @@ -MK3_bottom \ No newline at end of file + + + + + + image/svg+xml + + MK3_bottom + + + + + MK3_bottom + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/clipper/CMakeLists.txt b/src/clipper/CMakeLists.txt index 8a4e92852..0362a4d84 100644 --- a/src/clipper/CMakeLists.txt +++ b/src/clipper/CMakeLists.txt @@ -2,8 +2,9 @@ project(clipper) cmake_minimum_required(VERSION 2.6) add_library(clipper STATIC - clipper.cpp - clipper.hpp +# We are using ClipperLib compiled as part of the libslic3r project using Slic3r::Point as its base type. +# clipper.cpp +# clipper.hpp clipper_z.cpp clipper_z.hpp ) diff --git a/src/clipper/clipper.cpp b/src/clipper/clipper.cpp index cbe54a064..0285d9167 100644 --- a/src/clipper/clipper.cpp +++ b/src/clipper/clipper.cpp @@ -61,11 +61,15 @@ #define CLIPPERLIB_PROFILE_BLOCK(name) #endif -#ifdef use_xyz +#ifdef CLIPPERLIB_NAMESPACE_PREFIX +namespace CLIPPERLIB_NAMESPACE_PREFIX { +#endif // CLIPPERLIB_NAMESPACE_PREFIX + +#ifdef CLIPPERLIB_USE_XYZ namespace ClipperLib_Z { -#else /* use_xyz */ +#else /* CLIPPERLIB_USE_XYZ */ namespace ClipperLib { -#endif /* use_xyz */ +#endif /* CLIPPERLIB_USE_XYZ */ static double const pi = 3.141592653589793238; static double const two_pi = pi *2; @@ -156,7 +160,7 @@ double Area(const Path &poly) double a = 0; for (int i = 0, j = size -1; i < size; ++i) { - a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y); + a += ((double)poly[j].x() + poly[i].x()) * ((double)poly[j].y() - poly[i].y()); j = i; } return -a * 0.5; @@ -169,7 +173,7 @@ double Area(const OutRec &outRec) if (!op) return 0; double a = 0; do { - a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y); + a += (double)(op->Prev->Pt.x() + op->Pt.x()) * (double)(op->Prev->Pt.y() - op->Pt.y()); op = op->Next; } while (op != outRec.Pts); return a * 0.5; @@ -201,26 +205,26 @@ int PointInPolygon(const IntPoint &pt, const Path &path) for(size_t i = 1; i <= cnt; ++i) { IntPoint ipNext = (i == cnt ? path[0] : path[i]); - if (ipNext.Y == pt.Y && ((ipNext.X == pt.X) || (ip.Y == pt.Y && ((ipNext.X > pt.X) == (ip.X < pt.X))))) + if (ipNext.y() == pt.y() && ((ipNext.x() == pt.x()) || (ip.y() == pt.y() && ((ipNext.x() > pt.x()) == (ip.x() < pt.x()))))) return -1; - if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y)) + if ((ip.y() < pt.y()) != (ipNext.y() < pt.y())) { - if (ip.X >= pt.X) + if (ip.x() >= pt.x()) { - if (ipNext.X > pt.X) result = 1 - result; + if (ipNext.x() > pt.x()) result = 1 - result; else { - double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); + double d = (double)(ip.x() - pt.x()) * (ipNext.y() - pt.y()) - (double)(ipNext.x() - pt.x()) * (ip.y() - pt.y()); if (!d) return -1; - if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; + if ((d > 0) == (ipNext.y() > ip.y())) result = 1 - result; } } else { - if (ipNext.X > pt.X) + if (ipNext.x() > pt.x()) { - double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); + double d = (double)(ip.x() - pt.x()) * (ipNext.y() - pt.y()) - (double)(ipNext.x() - pt.x()) * (ip.y() - pt.y()); if (!d) return -1; - if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; + if ((d > 0) == (ipNext.y() > ip.y())) result = 1 - result; } } } @@ -238,29 +242,29 @@ int PointInPolygon (const IntPoint &pt, OutPt *op) OutPt* startOp = op; do { - if (op->Next->Pt.Y == pt.Y) + if (op->Next->Pt.y() == pt.y()) { - if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y && - ((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1; + if ((op->Next->Pt.x() == pt.x()) || (op->Pt.y() == pt.y() && + ((op->Next->Pt.x() > pt.x()) == (op->Pt.x() < pt.x())))) return -1; } - if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y)) + if ((op->Pt.y() < pt.y()) != (op->Next->Pt.y() < pt.y())) { - if (op->Pt.X >= pt.X) + if (op->Pt.x() >= pt.x()) { - if (op->Next->Pt.X > pt.X) result = 1 - result; + if (op->Next->Pt.x() > pt.x()) result = 1 - result; else { - double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y); + double d = (double)(op->Pt.x() - pt.x()) * (op->Next->Pt.y() - pt.y()) - (double)(op->Next->Pt.x() - pt.x()) * (op->Pt.y() - pt.y()); if (!d) return -1; - if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result; + if ((d > 0) == (op->Next->Pt.y() > op->Pt.y())) result = 1 - result; } } else { - if (op->Next->Pt.X > pt.X) + if (op->Next->Pt.x() > pt.x()) { - double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y); + double d = (double)(op->Pt.x() - pt.x()) * (op->Next->Pt.y() - pt.y()) - (double)(op->Next->Pt.x() - pt.x()) * (op->Pt.y() - pt.y()); if (!d) return -1; - if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result; + if ((d > 0) == (op->Next->Pt.y() > op->Pt.y())) result = 1 - result; } } } @@ -304,100 +308,100 @@ inline bool SlopesEqual(const cInt dx1, const cInt dy1, const cInt dx2, const cI #endif inline bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range) - { return SlopesEqual(e1.Delta.X, e1.Delta.Y, e2.Delta.X, e2.Delta.Y, UseFullInt64Range); } + { return SlopesEqual(e1.Delta.x(), e1.Delta.y(), e2.Delta.x(), e2.Delta.y(), UseFullInt64Range); } inline bool SlopesEqual(const IntPoint &pt1, const IntPoint &pt2, const IntPoint &pt3, bool UseFullInt64Range) - { return SlopesEqual(pt1.X-pt2.X, pt1.Y-pt2.Y, pt2.X-pt3.X, pt2.Y-pt3.Y, UseFullInt64Range); } + { return SlopesEqual(pt1.x()-pt2.x(), pt1.y()-pt2.y(), pt2.x()-pt3.x(), pt2.y()-pt3.y(), UseFullInt64Range); } inline bool SlopesEqual(const IntPoint &pt1, const IntPoint &pt2, const IntPoint &pt3, const IntPoint &pt4, bool UseFullInt64Range) - { return SlopesEqual(pt1.X-pt2.X, pt1.Y-pt2.Y, pt3.X-pt4.X, pt3.Y-pt4.Y, UseFullInt64Range); } + { return SlopesEqual(pt1.x()-pt2.x(), pt1.y()-pt2.y(), pt3.x()-pt4.x(), pt3.y()-pt4.y(), UseFullInt64Range); } //------------------------------------------------------------------------------ inline bool IsHorizontal(TEdge &e) { - return e.Delta.Y == 0; + return e.Delta.y() == 0; } //------------------------------------------------------------------------------ inline double GetDx(const IntPoint &pt1, const IntPoint &pt2) { - return (pt1.Y == pt2.Y) ? - HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y); + return (pt1.y() == pt2.y()) ? + HORIZONTAL : (double)(pt2.x() - pt1.x()) / (pt2.y() - pt1.y()); } //--------------------------------------------------------------------------- inline cInt TopX(TEdge &edge, const cInt currentY) { - return (currentY == edge.Top.Y) ? - edge.Top.X : - edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y)); + return (currentY == edge.Top.y()) ? + edge.Top.x() : + edge.Bot.x() + Round(edge.Dx *(currentY - edge.Bot.y())); } //------------------------------------------------------------------------------ void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip) { -#ifdef use_xyz - ip.Z = 0; +#ifdef CLIPPERLIB_USE_XYZ + ip.z() = 0; #endif double b1, b2; if (Edge1.Dx == Edge2.Dx) { - ip.Y = Edge1.Curr.Y; - ip.X = TopX(Edge1, ip.Y); + ip.y() = Edge1.Curr.y(); + ip.x() = TopX(Edge1, ip.y()); return; } - else if (Edge1.Delta.X == 0) + else if (Edge1.Delta.x() == 0) { - ip.X = Edge1.Bot.X; + ip.x() = Edge1.Bot.x(); if (IsHorizontal(Edge2)) - ip.Y = Edge2.Bot.Y; + ip.y() = Edge2.Bot.y(); else { - b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx); - ip.Y = Round(ip.X / Edge2.Dx + b2); + b2 = Edge2.Bot.y() - (Edge2.Bot.x() / Edge2.Dx); + ip.y() = Round(ip.x() / Edge2.Dx + b2); } } - else if (Edge2.Delta.X == 0) + else if (Edge2.Delta.x() == 0) { - ip.X = Edge2.Bot.X; + ip.x() = Edge2.Bot.x(); if (IsHorizontal(Edge1)) - ip.Y = Edge1.Bot.Y; + ip.y() = Edge1.Bot.y(); else { - b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx); - ip.Y = Round(ip.X / Edge1.Dx + b1); + b1 = Edge1.Bot.y() - (Edge1.Bot.x() / Edge1.Dx); + ip.y() = Round(ip.x() / Edge1.Dx + b1); } } else { - b1 = double(Edge1.Bot.X) - double(Edge1.Bot.Y) * Edge1.Dx; - b2 = double(Edge2.Bot.X) - double(Edge2.Bot.Y) * Edge2.Dx; + b1 = double(Edge1.Bot.x()) - double(Edge1.Bot.y()) * Edge1.Dx; + b2 = double(Edge2.Bot.x()) - double(Edge2.Bot.y()) * Edge2.Dx; double q = (b2-b1) / (Edge1.Dx - Edge2.Dx); - ip.Y = Round(q); - ip.X = (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx)) ? + ip.y() = Round(q); + ip.x() = (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx)) ? Round(Edge1.Dx * q + b1) : Round(Edge2.Dx * q + b2); } - if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y) + if (ip.y() < Edge1.Top.y() || ip.y() < Edge2.Top.y()) { - if (Edge1.Top.Y > Edge2.Top.Y) - ip.Y = Edge1.Top.Y; + if (Edge1.Top.y() > Edge2.Top.y()) + ip.y() = Edge1.Top.y(); else - ip.Y = Edge2.Top.Y; + ip.y() = Edge2.Top.y(); if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx)) - ip.X = TopX(Edge1, ip.Y); + ip.x() = TopX(Edge1, ip.y()); else - ip.X = TopX(Edge2, ip.Y); + ip.x() = TopX(Edge2, ip.y()); } - //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ... - if (ip.Y > Edge1.Curr.Y) + //finally, don't allow 'ip' to be BELOW curr.y() (ie bottom of scanbeam) ... + if (ip.y() > Edge1.Curr.y()) { - ip.Y = Edge1.Curr.Y; + ip.y() = Edge1.Curr.y(); //use the more vertical edge to derive X ... if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx)) - ip.X = TopX(Edge2, ip.Y); else - ip.X = TopX(Edge1, ip.Y); + ip.x() = TopX(Edge2, ip.y()); else + ip.x() = TopX(Edge1, ip.y()); } } //------------------------------------------------------------------------------ @@ -429,7 +433,7 @@ inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt) void InitEdge2(TEdge& e, PolyType Pt) { - if (e.Curr.Y >= e.Next->Curr.Y) + if (e.Curr.y() >= e.Next->Curr.y()) { e.Bot = e.Curr; e.Top = e.Next->Curr; @@ -439,11 +443,11 @@ void InitEdge2(TEdge& e, PolyType Pt) e.Bot = e.Next->Curr; } - e.Delta.X = (e.Top.X - e.Bot.X); - e.Delta.Y = (e.Top.Y - e.Bot.Y); + e.Delta.x() = (e.Top.x() - e.Bot.x()); + e.Delta.y() = (e.Top.y() - e.Bot.y()); - if (e.Delta.Y == 0) e.Dx = HORIZONTAL; - else e.Dx = (double)(e.Delta.X) / e.Delta.Y; + if (e.Delta.y() == 0) e.Dx = HORIZONTAL; + else e.Dx = (double)(e.Delta.x()) / e.Delta.y(); e.PolyTyp = Pt; } @@ -466,9 +470,9 @@ inline void ReverseHorizontal(TEdge &e) //swap horizontal edges' Top and Bottom x's so they follow the natural //progression of the bounds - ie so their xbots will align with the //adjoining lower edge. [Helpful in the ProcessHorizontal() method.] - std::swap(e.Top.X, e.Bot.X); -#ifdef use_xyz - std::swap(e.Top.Z, e.Bot.Z); + std::swap(e.Top.x(), e.Bot.x()); +#ifdef CLIPPERLIB_USE_XYZ + std::swap(e.Top.z(), e.Bot.z()); #endif } //------------------------------------------------------------------------------ @@ -477,20 +481,20 @@ bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a, IntPoint pt2b, IntPoint &pt1, IntPoint &pt2) { //precondition: segments are Collinear. - if (std::abs(pt1a.X - pt1b.X) > std::abs(pt1a.Y - pt1b.Y)) + if (std::abs(pt1a.x() - pt1b.x()) > std::abs(pt1a.y() - pt1b.y())) { - if (pt1a.X > pt1b.X) std::swap(pt1a, pt1b); - if (pt2a.X > pt2b.X) std::swap(pt2a, pt2b); - if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a; - if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b; - return pt1.X < pt2.X; + if (pt1a.x() > pt1b.x()) std::swap(pt1a, pt1b); + if (pt2a.x() > pt2b.x()) std::swap(pt2a, pt2b); + if (pt1a.x() > pt2a.x()) pt1 = pt1a; else pt1 = pt2a; + if (pt1b.x() < pt2b.x()) pt2 = pt1b; else pt2 = pt2b; + return pt1.x() < pt2.x(); } else { - if (pt1a.Y < pt1b.Y) std::swap(pt1a, pt1b); - if (pt2a.Y < pt2b.Y) std::swap(pt2a, pt2b); - if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a; - if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b; - return pt1.Y > pt2.Y; + if (pt1a.y() < pt1b.y()) std::swap(pt1a, pt1b); + if (pt2a.y() < pt2b.y()) std::swap(pt2a, pt2b); + if (pt1a.y() < pt2a.y()) pt1 = pt1a; else pt1 = pt2a; + if (pt1b.y() > pt2b.y()) pt2 = pt1b; else pt2 = pt2b; + return pt1.y() > pt2.y(); } } //------------------------------------------------------------------------------ @@ -521,14 +525,14 @@ OutPt* GetBottomPt(OutPt *pp) OutPt* p = pp->Next; while (p != pp) { - if (p->Pt.Y > pp->Pt.Y) + if (p->Pt.y() > pp->Pt.y()) { pp = p; dups = 0; } - else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X) + else if (p->Pt.y() == pp->Pt.y() && p->Pt.x() <= pp->Pt.x()) { - if (p->Pt.X < pp->Pt.X) + if (p->Pt.x() < pp->Pt.x()) { dups = 0; pp = p; @@ -558,10 +562,10 @@ bool Pt2IsBetweenPt1AndPt3(const IntPoint &pt1, { if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2)) return false; - else if (pt1.X != pt3.X) - return (pt2.X > pt1.X) == (pt2.X < pt3.X); + else if (pt1.x() != pt3.x()) + return (pt2.x() > pt1.x()) == (pt2.x() < pt3.x()); else - return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y); + return (pt2.y() > pt1.y()) == (pt2.y() < pt3.y()); } //------------------------------------------------------------------------------ @@ -582,10 +586,10 @@ inline void RangeTest(const IntPoint& Pt, bool& useFullRange) { if (useFullRange) { - if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange) + if (Pt.x() > hiRange || Pt.y() > hiRange || -Pt.x() > hiRange || -Pt.y() > hiRange) throw clipperException("Coordinate outside allowed range"); } - else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange) + else if (Pt.x() > loRange|| Pt.y() > loRange || -Pt.x() > loRange || -Pt.y() > loRange) { useFullRange = true; RangeTest(Pt, useFullRange); @@ -605,8 +609,8 @@ inline TEdge* FindNextLocMin(TEdge* E) while (IsHorizontal(*E->Prev)) E = E->Prev; TEdge* E2 = E; while (IsHorizontal(*E)) E = E->Next; - if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz. - if (E2->Prev->Bot.X < E->Bot.X) E = E2; + if (E->Top.y() == E->Prev->Bot.y()) continue; //ie just an intermediate horz. + if (E2->Prev->Bot.x() < E->Bot.x()) E = E2; break; } return E; @@ -625,14 +629,14 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) //create another LocMin and call ProcessBound once more if (NextIsForward) { - while (E->Top.Y == E->Next->Bot.Y) E = E->Next; + while (E->Top.y() == E->Next->Bot.y()) E = E->Next; //don't include top horizontals when parsing a bound a second time, //they will be contained in the opposite bound ... while (E != Result && IsHorizontal(*E)) E = E->Prev; } else { - while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev; + while (E->Top.y() == E->Prev->Bot.y()) E = E->Prev; while (E != Result && IsHorizontal(*E)) E = E->Next; } @@ -649,7 +653,7 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) else E = Result->Prev; LocalMinimum locMin; - locMin.Y = E->Bot.Y; + locMin.Y = E->Bot.y(); locMin.LeftBound = 0; locMin.RightBound = E; E->WindDelta = 0; @@ -672,17 +676,17 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) EStart = E->Next; if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge { - if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X) + if (EStart->Bot.x() != E->Bot.x() && EStart->Top.x() != E->Bot.x()) ReverseHorizontal(*E); } - else if (EStart->Bot.X != E->Bot.X) + else if (EStart->Bot.x() != E->Bot.x()) ReverseHorizontal(*E); } EStart = E; if (NextIsForward) { - while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip) + while (Result->Top.y() == Result->Next->Bot.y() && Result->Next->OutIdx != Skip) Result = Result->Next; if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip) { @@ -691,38 +695,38 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) //unless a Skip edge is encountered when that becomes the top divide Horz = Result; while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev; - if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev; + if (Horz->Prev->Top.x() > Result->Next->Top.x()) Result = Horz->Prev; } while (E != Result) { E->NextInLML = E->Next; if (IsHorizontal(*E) && E != EStart && - E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); + E->Bot.x() != E->Prev->Top.x()) ReverseHorizontal(*E); E = E->Next; } - if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X) + if (IsHorizontal(*E) && E != EStart && E->Bot.x() != E->Prev->Top.x()) ReverseHorizontal(*E); Result = Result->Next; //move to the edge just beyond current bound } else { - while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip) + while (Result->Top.y() == Result->Prev->Bot.y() && Result->Prev->OutIdx != Skip) Result = Result->Prev; if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip) { Horz = Result; while (IsHorizontal(*Horz->Next)) Horz = Horz->Next; - if (Horz->Next->Top.X == Result->Prev->Top.X || - Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next; + if (Horz->Next->Top.x() == Result->Prev->Top.x() || + Horz->Next->Top.x() > Result->Prev->Top.x()) Result = Horz->Next; } while (E != Result) { E->NextInLML = E->Prev; - if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) + if (IsHorizontal(*E) && E != EStart && E->Bot.x() != E->Next->Top.x()) ReverseHorizontal(*E); E = E->Prev; } - if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) + if (IsHorizontal(*E) && E != EStart && E->Bot.x() != E->Next->Top.x()) ReverseHorizontal(*E); Result = Result->Prev; //move to the edge just beyond current bound } @@ -755,48 +759,6 @@ bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed) return result; } -bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed) -{ - CLIPPERLIB_PROFILE_FUNC(); - std::vector num_edges(ppg.size(), 0); - int num_edges_total = 0; - for (size_t i = 0; i < ppg.size(); ++ i) { - const Path &pg = ppg[i]; - // Remove duplicate end point from a closed input path. - // Remove duplicate points from the end of the input path. - int highI = (int)pg.size() -1; - if (Closed) - while (highI > 0 && (pg[highI] == pg[0])) - --highI; - while (highI > 0 && (pg[highI] == pg[highI -1])) - --highI; - if ((Closed && highI < 2) || (!Closed && highI < 1)) - highI = -1; - num_edges[i] = highI + 1; - num_edges_total += highI + 1; - } - if (num_edges_total == 0) - return false; - - // Allocate a new edge array. - std::vector edges(num_edges_total); - // Fill in the edge array. - bool result = false; - TEdge *p_edge = edges.data(); - for (Paths::size_type i = 0; i < ppg.size(); ++i) - if (num_edges[i]) { - bool res = AddPathInternal(ppg[i], num_edges[i] - 1, PolyTyp, Closed, p_edge); - if (res) { - p_edge += num_edges[i]; - result = true; - } - } - if (result) - // At least some edges were generated. Remember the edge array. - m_edges.emplace_back(std::move(edges)); - return result; -} - bool ClipperBase::AddPathInternal(const Path &pg, int highI, PolyType PolyTyp, bool Closed, TEdge* edges) { CLIPPERLIB_PROFILE_FUNC(); @@ -887,7 +849,7 @@ bool ClipperBase::AddPathInternal(const Path &pg, int highI, PolyType PolyTyp, b { InitEdge2(*E, PolyTyp); E = E->Next; - if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false; + if (IsFlat && E->Curr.y() != eStart->Curr.y()) IsFlat = false; } while (E != eStart); @@ -903,14 +865,14 @@ bool ClipperBase::AddPathInternal(const Path &pg, int highI, PolyType PolyTyp, b } E->Prev->OutIdx = Skip; LocalMinimum locMin; - locMin.Y = E->Bot.Y; + locMin.Y = E->Bot.y(); locMin.LeftBound = 0; locMin.RightBound = E; locMin.RightBound->Side = esRight; locMin.RightBound->WindDelta = 0; for (;;) { - if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); + if (E->Bot.x() != E->Prev->Top.x()) ReverseHorizontal(*E); if (E->Next->OutIdx == Skip) break; E->NextInLML = E->Next; E = E->Next; @@ -937,7 +899,7 @@ bool ClipperBase::AddPathInternal(const Path &pg, int highI, PolyType PolyTyp, b //E and E.Prev now share a local minima (left aligned if horizontal). //Compare their slopes to find which starts which bound ... LocalMinimum locMin; - locMin.Y = E->Bot.Y; + locMin.Y = E->Bot.y(); if (E->Dx < E->Prev->Dx) { locMin.LeftBound = E->Prev; @@ -1028,27 +990,27 @@ IntRect ClipperBase::GetBounds() result.left = result.top = result.right = result.bottom = 0; return result; } - result.left = lm->LeftBound->Bot.X; - result.top = lm->LeftBound->Bot.Y; - result.right = lm->LeftBound->Bot.X; - result.bottom = lm->LeftBound->Bot.Y; + result.left = lm->LeftBound->Bot.x(); + result.top = lm->LeftBound->Bot.y(); + result.right = lm->LeftBound->Bot.x(); + result.bottom = lm->LeftBound->Bot.y(); while (lm != m_MinimaList.end()) { - result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y); + result.bottom = std::max(result.bottom, lm->LeftBound->Bot.y()); TEdge* e = lm->LeftBound; for (;;) { TEdge* bottomE = e; while (e->NextInLML) { - if (e->Bot.X < result.left) result.left = e->Bot.X; - if (e->Bot.X > result.right) result.right = e->Bot.X; + if (e->Bot.x() < result.left) result.left = e->Bot.x(); + if (e->Bot.x() > result.right) result.right = e->Bot.x(); e = e->NextInLML; } - result.left = std::min(result.left, e->Bot.X); - result.right = std::max(result.right, e->Bot.X); - result.left = std::min(result.left, e->Top.X); - result.right = std::max(result.right, e->Top.X); - result.top = std::min(result.top, e->Top.Y); + result.left = std::min(result.left, e->Bot.x()); + result.right = std::max(result.right, e->Bot.x()); + result.left = std::min(result.left, e->Top.x()); + result.right = std::max(result.right, e->Top.x()); + result.top = std::min(result.top, e->Top.y()); if (bottomE == lm->LeftBound) e = lm->RightBound; else break; } @@ -1073,7 +1035,7 @@ Clipper::Clipper(int initOptions) : m_StrictSimple = ((initOptions & ioStrictlySimple) != 0); m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0); m_HasOpenPaths = false; -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ m_ZFill = 0; #endif } @@ -1099,7 +1061,7 @@ bool Clipper::Execute(ClipType clipType, Paths &solution, CLIPPERLIB_PROFILE_FUNC(); if (m_HasOpenPaths) throw clipperException("Error: PolyTree struct is needed for open path clipping."); - solution.resize(0); + solution.clear(); m_SubjFillType = subjFillType; m_ClipFillType = clipFillType; m_ClipType = clipType; @@ -1454,7 +1416,7 @@ OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt) } if (prevE && prevE->OutIdx >= 0 && - (TopX(*prevE, Pt.Y) == TopX(*e, Pt.Y)) && + (TopX(*prevE, Pt.y()) == TopX(*e, Pt.y())) && SlopesEqual(*e, *prevE, m_UseFullRange) && (e->WindDelta != 0) && (prevE->WindDelta != 0)) { @@ -1540,7 +1502,7 @@ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) SetWindingCount(*lb); if (IsContributing(*lb)) Op1 = AddOutPt(lb, lb->Bot); - m_Scanbeam.push(lb->Top.Y); + m_Scanbeam.push(lb->Top.y()); } else { @@ -1551,13 +1513,13 @@ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) rb->WindCnt2 = lb->WindCnt2; if (IsContributing(*lb)) Op1 = AddLocalMinPoly(lb, rb, lb->Bot); - m_Scanbeam.push(lb->Top.Y); + m_Scanbeam.push(lb->Top.y()); } if (rb) { if(IsHorizontal(*rb)) AddEdgeToSEL(rb); - else m_Scanbeam.push(rb->Top.Y); + else m_Scanbeam.push(rb->Top.y()); } if (!lb || !rb) continue; @@ -1569,12 +1531,12 @@ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) for (Join &jr : m_GhostJoins) //if the horizontal Rb and a 'ghost' horizontal overlap, then convert //the 'ghost' join to a real join ready for later ... - if (HorzSegmentsOverlap(jr.OutPt1->Pt.X, jr.OffPt.X, rb->Bot.X, rb->Top.X)) + if (HorzSegmentsOverlap(jr.OutPt1->Pt.x(), jr.OffPt.x(), rb->Bot.x(), rb->Top.x())) m_Joins.emplace_back(Join(jr.OutPt1, Op1, jr.OffPt)); } if (lb->OutIdx >= 0 && lb->PrevInAEL && - lb->PrevInAEL->Curr.X == lb->Bot.X && + lb->PrevInAEL->Curr.x() == lb->Bot.x() && lb->PrevInAEL->OutIdx >= 0 && SlopesEqual(*lb->PrevInAEL, *lb, m_UseFullRange) && (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0)) @@ -1637,14 +1599,14 @@ void Clipper::DeleteFromSEL(TEdge *e) } //------------------------------------------------------------------------------ -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2) { - if (pt.Z != 0 || !m_ZFill) return; - else if (pt == e1.Bot) pt.Z = e1.Bot.Z; - else if (pt == e1.Top) pt.Z = e1.Top.Z; - else if (pt == e2.Bot) pt.Z = e2.Bot.Z; - else if (pt == e2.Top) pt.Z = e2.Top.Z; + if (pt.z() != 0 || !m_ZFill) return; + else if (pt == e1.Bot) pt.z() = e1.Bot.z(); + else if (pt == e1.Top) pt.z() = e1.Top.z(); + else if (pt == e2.Bot) pt.z() = e2.Bot.z(); + else if (pt == e2.Top) pt.z() = e2.Top.z(); else m_ZFill(e1.Bot, e1.Top, e2.Bot, e2.Top, pt); } //------------------------------------------------------------------------------ @@ -1655,7 +1617,7 @@ void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt) bool e1Contributing = ( e1->OutIdx >= 0 ); bool e2Contributing = ( e2->OutIdx >= 0 ); -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ SetZ(Pt, *e1, *e2); #endif @@ -1872,10 +1834,10 @@ OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2) outRec2->BottomPt = GetBottomPt(outRec2->Pts); OutPt *OutPt1 = outRec1->BottomPt; OutPt *OutPt2 = outRec2->BottomPt; - if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1; - else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2; - else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1; - else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2; + if (OutPt1->Pt.y() > OutPt2->Pt.y()) return outRec1; + else if (OutPt1->Pt.y() < OutPt2->Pt.y()) return outRec2; + else if (OutPt1->Pt.x() < OutPt2->Pt.x()) return outRec1; + else if (OutPt1->Pt.x() > OutPt2->Pt.x()) return outRec2; else if (OutPt1->Next == OutPt1) return outRec2; else if (OutPt2->Next == OutPt2) return outRec1; else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1; @@ -2081,13 +2043,13 @@ void Clipper::ProcessHorizontals() inline bool IsMaxima(TEdge *e, const cInt Y) { - return e && e->Top.Y == Y && !e->NextInLML; + return e && e->Top.y() == Y && !e->NextInLML; } //------------------------------------------------------------------------------ inline bool IsIntermediate(TEdge *e, const cInt Y) { - return e->Top.Y == Y && e->NextInLML; + return e->Top.y() == Y && e->NextInLML; } //------------------------------------------------------------------------------ @@ -2202,15 +2164,15 @@ void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2) inline void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right) { - if (HorzEdge.Bot.X < HorzEdge.Top.X) + if (HorzEdge.Bot.x() < HorzEdge.Top.x()) { - Left = HorzEdge.Bot.X; - Right = HorzEdge.Top.X; + Left = HorzEdge.Bot.x(); + Right = HorzEdge.Top.x(); Dir = dLeftToRight; } else { - Left = HorzEdge.Top.X; - Right = HorzEdge.Bot.X; + Left = HorzEdge.Top.x(); + Right = HorzEdge.Bot.x(); Dir = dRightToLeft; } } @@ -2219,8 +2181,8 @@ inline void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& /******************************************************************************* * Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or * * Bottom of a scanbeam) are processed as if layered. The order in which HEs * -* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] * -* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), * +* are processed doesn't matter. HEs intersect with other HE Bot.x()s only [#] * +* (or they could intersect with Top.x()s only, ie EITHER Bot.x()s OR Top.x()s), * * and with other non-horizontal edges [*]. Once these intersections are * * processed, intermediate HEs then 'promote' the Edge above (NextInLML) into * * the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. * @@ -2248,15 +2210,15 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge) if (dir == dLeftToRight) { maxIt = m_Maxima.begin(); - while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) ++maxIt; - if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X) + while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.x()) ++maxIt; + if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.x()) maxIt = m_Maxima.end(); } else { maxRit = m_Maxima.rbegin(); - while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) ++maxRit; - if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X) + while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.x()) ++maxRit; + if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.x()) maxRit = m_Maxima.rend(); } } @@ -2278,30 +2240,30 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge) { if (dir == dLeftToRight) { - while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X) + while (maxIt != m_Maxima.end() && *maxIt < e->Curr.x()) { if (horzEdge->OutIdx >= 0 && !IsOpen) - AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y)); + AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.y())); ++maxIt; } } else { - while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X) + while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.x()) { if (horzEdge->OutIdx >= 0 && !IsOpen) - AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y)); + AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.y())); ++maxRit; } } }; - if ((dir == dLeftToRight && e->Curr.X > horzRight) || - (dir == dRightToLeft && e->Curr.X < horzLeft)) break; + if ((dir == dLeftToRight && e->Curr.x() > horzRight) || + (dir == dRightToLeft && e->Curr.x() < horzLeft)) break; //Also break if we've got to the end of an intermediate horizontal edge ... //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal. - if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML && + if (e->Curr.x() == horzEdge->Top.x() && horzEdge->NextInLML && e->Dx < horzEdge->NextInLML->Dx) break; if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times @@ -2311,8 +2273,8 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge) while (eNextHorz) { if (eNextHorz->OutIdx >= 0 && - HorzSegmentsOverlap(horzEdge->Bot.X, - horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X)) + HorzSegmentsOverlap(horzEdge->Bot.x(), + horzEdge->Top.x(), eNextHorz->Bot.x(), eNextHorz->Top.x())) { OutPt* op2 = GetLastOutPt(eNextHorz); m_Joins.emplace_back(Join(op2, op1, eNextHorz->Top)); @@ -2335,12 +2297,12 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge) if(dir == dLeftToRight) { - IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y); + IntPoint Pt = IntPoint(e->Curr.x(), horzEdge->Curr.y()); IntersectEdges(horzEdge, e, Pt); } else { - IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y); + IntPoint Pt = IntPoint(e->Curr.x(), horzEdge->Curr.y()); IntersectEdges( e, horzEdge, Pt); } TEdge* eNext = (dir == dLeftToRight) ? e->NextInAEL : e->PrevInAEL; @@ -2364,8 +2326,8 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge) while (eNextHorz) { if (eNextHorz->OutIdx >= 0 && - HorzSegmentsOverlap(horzEdge->Bot.X, - horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X)) + HorzSegmentsOverlap(horzEdge->Bot.x(), + horzEdge->Top.x(), eNextHorz->Bot.x(), eNextHorz->Top.x())) { OutPt* op2 = GetLastOutPt(eNextHorz); m_Joins.emplace_back(Join(op2, op1, eNextHorz->Top)); @@ -2385,17 +2347,17 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge) //nb: HorzEdge is no longer horizontal here TEdge* ePrev = horzEdge->PrevInAEL; TEdge* eNext = horzEdge->NextInAEL; - if (ePrev && ePrev->Curr.X == horzEdge->Bot.X && - ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 && - (ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y && + if (ePrev && ePrev->Curr.x() == horzEdge->Bot.x() && + ePrev->Curr.y() == horzEdge->Bot.y() && ePrev->WindDelta != 0 && + (ePrev->OutIdx >= 0 && ePrev->Curr.y() > ePrev->Top.y() && SlopesEqual(*horzEdge, *ePrev, m_UseFullRange))) { OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot); m_Joins.emplace_back(Join(op1, op2, horzEdge->Top)); } - else if (eNext && eNext->Curr.X == horzEdge->Bot.X && - eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 && - eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y && + else if (eNext && eNext->Curr.x() == horzEdge->Bot.x() && + eNext->Curr.y() == horzEdge->Bot.y() && eNext->WindDelta != 0 && + eNext->OutIdx >= 0 && eNext->Curr.y() > eNext->Top.y() && SlopesEqual(*horzEdge, *eNext, m_UseFullRange)) { OutPt* op2 = AddOutPt(eNext, horzEdge->Bot); @@ -2433,7 +2395,7 @@ void Clipper::UpdateEdgeIntoAEL(TEdge *&e) e->PrevInAEL = AelPrev; e->NextInAEL = AelNext; if (!IsHorizontal(*e)) - m_Scanbeam.push(e->Top.Y); + m_Scanbeam.push(e->Top.y()); } //------------------------------------------------------------------------------ @@ -2476,7 +2438,7 @@ void Clipper::BuildIntersectList(const cInt topY) { e->PrevInSEL = e->PrevInAEL; e->NextInSEL = e->NextInAEL; - e->Curr.X = TopX( *e, topY ); + e->Curr.x() = TopX( *e, topY ); e = e->NextInAEL; } @@ -2490,7 +2452,7 @@ void Clipper::BuildIntersectList(const cInt topY) { TEdge *eNext = e->NextInSEL; IntPoint Pt; - if(e->Curr.X > eNext->Curr.X) + if(e->Curr.x() > eNext->Curr.x()) { IntersectPoint(*e, *eNext, Pt); m_IntersectList.emplace_back(IntersectNode(e, eNext, Pt)); @@ -2522,7 +2484,7 @@ bool Clipper::FixupIntersectionOrder() //Now it's crucial that intersections are made only between adjacent edges, //so to ensure this the order of intersections may need adjusting ... CopyAELToSEL(); - std::sort(m_IntersectList.begin(), m_IntersectList.end(), [](const IntersectNode &node1, const IntersectNode &node2) { return node2.Pt.Y < node1.Pt.Y; }); + std::sort(m_IntersectList.begin(), m_IntersectList.end(), [](const IntersectNode &node1, const IntersectNode &node2) { return node2.Pt.y() < node1.Pt.y(); }); size_t cnt = m_IntersectList.size(); for (size_t i = 0; i < cnt; ++i) @@ -2610,7 +2572,7 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY) if(IsMaximaEdge) { - if (m_StrictSimple) m_Maxima.push_back(e->Top.X); + if (m_StrictSimple) m_Maxima.push_back(e->Top.x()); TEdge* ePrev = e->PrevInAEL; DoMaxima(e); if( !ePrev ) e = m_ActiveEdges; @@ -2618,7 +2580,7 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY) } else { - //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ... + //2. promote horizontal edges, otherwise update Curr.x() and Curr.y() ... if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML)) { UpdateEdgeIntoAEL(e); @@ -2628,8 +2590,8 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY) } else { - e->Curr.X = TopX( *e, topY ); - e->Curr.Y = topY; + e->Curr.x() = TopX( *e, topY ); + e->Curr.y() = topY; } //When StrictlySimple and 'e' is being touched by another edge, then @@ -2638,10 +2600,10 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY) { TEdge* ePrev = e->PrevInAEL; if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) && - (ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0)) + (ePrev->Curr.x() == e->Curr.x()) && (ePrev->WindDelta != 0)) { IntPoint pt = e->Curr; -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ SetZ(pt, *ePrev, *e); #endif OutPt* op = AddOutPt(ePrev, pt); @@ -2673,18 +2635,18 @@ void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY) //if output polygons share an edge, they'll need joining later ... TEdge* ePrev = e->PrevInAEL; TEdge* eNext = e->NextInAEL; - if (ePrev && ePrev->Curr.X == e->Bot.X && - ePrev->Curr.Y == e->Bot.Y && op && - ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y && + if (ePrev && ePrev->Curr.x() == e->Bot.x() && + ePrev->Curr.y() == e->Bot.y() && op && + ePrev->OutIdx >= 0 && ePrev->Curr.y() > ePrev->Top.y() && SlopesEqual(*e, *ePrev, m_UseFullRange) && (e->WindDelta != 0) && (ePrev->WindDelta != 0)) { OutPt* op2 = AddOutPt(ePrev, e->Bot); m_Joins.emplace_back(Join(op, op2, e->Top)); } - else if (eNext && eNext->Curr.X == e->Bot.X && - eNext->Curr.Y == e->Bot.Y && op && - eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y && + else if (eNext && eNext->Curr.x() == e->Bot.x() && + eNext->Curr.y() == e->Bot.y() && op && + eNext->OutIdx >= 0 && eNext->Curr.y() > eNext->Top.y() && SlopesEqual(*e, *eNext, m_UseFullRange) && (e->WindDelta != 0) && (eNext->WindDelta != 0)) { @@ -2861,13 +2823,13 @@ void Clipper::BuildResult2(PolyTree& polytree) inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2) { - if (e2.Curr.X == e1.Curr.X) + if (e2.Curr.x() == e1.Curr.x()) { - if (e2.Top.Y > e1.Top.Y) - return e2.Top.X < TopX(e1, e2.Top.Y); - else return e1.Top.X > TopX(e2, e1.Top.Y); + if (e2.Top.y() > e1.Top.y()) + return e2.Top.x() < TopX(e1, e2.Top.y()); + else return e1.Top.x() > TopX(e2, e1.Top.y()); } - else return e2.Curr.X < e1.Curr.X; + else return e2.Curr.x() < e1.Curr.x(); } //------------------------------------------------------------------------------ @@ -2956,8 +2918,8 @@ OutPt* Clipper::DupOutPt(OutPt* outPt, bool InsertAfter) bool Clipper::JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, const IntPoint &Pt, bool DiscardLeft) { - Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight); - Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight); + Direction Dir1 = (op1->Pt.x() > op1b->Pt.x() ? dRightToLeft : dLeftToRight); + Direction Dir2 = (op2->Pt.x() > op2b->Pt.x() ? dRightToLeft : dLeftToRight); if (Dir1 == Dir2) return false; //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we @@ -2967,10 +2929,10 @@ bool Clipper::JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.) if (Dir1 == dLeftToRight) { - while (op1->Next->Pt.X <= Pt.X && - op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) + while (op1->Next->Pt.x() <= Pt.x() && + op1->Next->Pt.x() >= op1->Pt.x() && op1->Next->Pt.y() == Pt.y()) op1 = op1->Next; - if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next; + if (DiscardLeft && (op1->Pt.x() != Pt.x())) op1 = op1->Next; op1b = this->DupOutPt(op1, !DiscardLeft); if (op1b->Pt != Pt) { @@ -2981,10 +2943,10 @@ bool Clipper::JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, } else { - while (op1->Next->Pt.X >= Pt.X && - op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) + while (op1->Next->Pt.x() >= Pt.x() && + op1->Next->Pt.x() <= op1->Pt.x() && op1->Next->Pt.y() == Pt.y()) op1 = op1->Next; - if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next; + if (!DiscardLeft && (op1->Pt.x() != Pt.x())) op1 = op1->Next; op1b = this->DupOutPt(op1, DiscardLeft); if (op1b->Pt != Pt) { @@ -2996,10 +2958,10 @@ bool Clipper::JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, if (Dir2 == dLeftToRight) { - while (op2->Next->Pt.X <= Pt.X && - op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y) + while (op2->Next->Pt.x() <= Pt.x() && + op2->Next->Pt.x() >= op2->Pt.x() && op2->Next->Pt.y() == Pt.y()) op2 = op2->Next; - if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next; + if (DiscardLeft && (op2->Pt.x() != Pt.x())) op2 = op2->Next; op2b = this->DupOutPt(op2, !DiscardLeft); if (op2b->Pt != Pt) { @@ -3009,10 +2971,10 @@ bool Clipper::JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, }; } else { - while (op2->Next->Pt.X >= Pt.X && - op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y) + while (op2->Next->Pt.x() >= Pt.x() && + op2->Next->Pt.x() <= op2->Pt.x() && op2->Next->Pt.y() == Pt.y()) op2 = op2->Next; - if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next; + if (!DiscardLeft && (op2->Pt.x() != Pt.x())) op2 = op2->Next; op2b = this->DupOutPt(op2, DiscardLeft); if (op2b->Pt != Pt) { @@ -3052,7 +3014,7 @@ bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2) //location at the Bottom of the overlapping segment (& Join.OffPt is above). //3. StrictSimple joins where edges touch but are not collinear and where //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point. - bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y); + bool isHorizontal = (j->OutPt1->Pt.y() == j->OffPt.y()); if (isHorizontal && (j->OffPt == j->OutPt1->Pt) && (j->OffPt == j->OutPt2->Pt)) @@ -3062,11 +3024,11 @@ bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2) op1b = j->OutPt1->Next; while (op1b != op1 && (op1b->Pt == j->OffPt)) op1b = op1b->Next; - bool reverse1 = (op1b->Pt.Y > j->OffPt.Y); + bool reverse1 = (op1b->Pt.y() > j->OffPt.y()); op2b = j->OutPt2->Next; while (op2b != op2 && (op2b->Pt == j->OffPt)) op2b = op2b->Next; - bool reverse2 = (op2b->Pt.Y > j->OffPt.Y); + bool reverse2 = (op2b->Pt.y() > j->OffPt.y()); if (reverse1 == reverse2) return false; if (reverse1) { @@ -3098,22 +3060,22 @@ bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2) //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt //may be anywhere along the horizontal edge. op1b = op1; - while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2) + while (op1->Prev->Pt.y() == op1->Pt.y() && op1->Prev != op1b && op1->Prev != op2) op1 = op1->Prev; - while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2) + while (op1b->Next->Pt.y() == op1b->Pt.y() && op1b->Next != op1 && op1b->Next != op2) op1b = op1b->Next; if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon' op2b = op2; - while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b) + while (op2->Prev->Pt.y() == op2->Pt.y() && op2->Prev != op2b && op2->Prev != op1b) op2 = op2->Prev; - while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1) + while (op2b->Next->Pt.y() == op2b->Pt.y() && op2b->Next != op2 && op2b->Next != op1) op2b = op2b->Next; if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon' cInt Left, Right; //Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges - if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right)) + if (!GetOverlap(op1->Pt.x(), op1b->Pt.x(), op2->Pt.x(), op2b->Pt.x(), Left, Right)) return false; //DiscardLeftSide: when overlapping edges are joined, a spike will created @@ -3121,51 +3083,51 @@ bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2) //on the discard Side as either may still be needed for other joins ... IntPoint Pt; bool DiscardLeftSide; - if (op1->Pt.X >= Left && op1->Pt.X <= Right) + if (op1->Pt.x() >= Left && op1->Pt.x() <= Right) { - Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X); + Pt = op1->Pt; DiscardLeftSide = (op1->Pt.x() > op1b->Pt.x()); } - else if (op2->Pt.X >= Left&& op2->Pt.X <= Right) + else if (op2->Pt.x() >= Left&& op2->Pt.x() <= Right) { - Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X); + Pt = op2->Pt; DiscardLeftSide = (op2->Pt.x() > op2b->Pt.x()); } - else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right) + else if (op1b->Pt.x() >= Left && op1b->Pt.x() <= Right) { - Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X; + Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.x() > op1->Pt.x(); } else { - Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X); + Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.x() > op2->Pt.x()); } j->OutPt1 = op1; j->OutPt2 = op2; return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide); } else { //nb: For non-horizontal joins ... - // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y - // 2. Jr.OutPt1.Pt > Jr.OffPt.Y + // 1. Jr.OutPt1.Pt.y() == Jr.OutPt2.Pt.y() + // 2. Jr.OutPt1.Pt > Jr.OffPt.y() //make sure the polygons are correctly oriented ... op1b = op1->Next; while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next; - bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) || + bool Reverse1 = ((op1b->Pt.y() > op1->Pt.y()) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)); if (Reverse1) { op1b = op1->Prev; while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev; - if ((op1b->Pt.Y > op1->Pt.Y) || + if ((op1b->Pt.y() > op1->Pt.y()) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false; }; op2b = op2->Next; while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next; - bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) || + bool Reverse2 = ((op2b->Pt.y() > op2->Pt.y()) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)); if (Reverse2) { op2b = op2->Prev; while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev; - if ((op2b->Pt.Y > op2->Pt.Y) || + if ((op2b->Pt.y() > op2->Pt.y()) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false; } @@ -3334,11 +3296,11 @@ void Clipper::JoinCommonEdges() DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2) { - if(pt2.X == pt1.X && pt2.Y == pt1.Y) + if(pt2.x() == pt1.x() && pt2.y() == pt1.y()) return DoublePoint(0, 0); - double Dx = double(pt2.X - pt1.X); - double dy = double(pt2.Y - pt1.Y); + double Dx = double(pt2.x() - pt1.x()); + double dy = double(pt2.y() - pt1.y()); double f = 1.0 / std::sqrt( Dx*Dx + dy*dy ); Dx *= f; dy *= f; @@ -3354,7 +3316,7 @@ void ClipperOffset::Clear() for (int i = 0; i < m_polyNodes.ChildCount(); ++i) delete m_polyNodes.Childs[i]; m_polyNodes.Childs.clear(); - m_lowest.X = -1; + m_lowest.x() = -1; } //------------------------------------------------------------------------------ @@ -3373,8 +3335,8 @@ void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType for (; highI > 0; -- highI) { bool same = false; if (has_shortest_edge_length) { - double dx = double(path[highI].X - path[0].X); - double dy = double(path[highI].Y - path[0].Y); + double dx = double(path[highI].x() - path[0].x()); + double dy = double(path[highI].y() - path[0].y()); same = dx*dx + dy*dy < shortest_edge_length2; } else same = path[0] == path[highI]; @@ -3387,8 +3349,8 @@ void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType for (int i = 1; i <= highI; i++) { bool same = false; if (has_shortest_edge_length) { - double dx = double(path[i].X - newNode->Contour[j].X); - double dy = double(path[i].Y - newNode->Contour[j].Y); + double dx = double(path[i].x() - newNode->Contour[j].x()); + double dy = double(path[i].y() - newNode->Contour[j].y()); same = dx*dx + dy*dy < shortest_edge_length2; } else same = newNode->Contour[j] == path[i]; @@ -3396,9 +3358,9 @@ void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType continue; j++; newNode->Contour.push_back(path[i]); - if (path[i].Y > newNode->Contour[k].Y || - (path[i].Y == newNode->Contour[k].Y && - path[i].X < newNode->Contour[k].X)) k = j; + if (path[i].y() > newNode->Contour[k].y() || + (path[i].y() == newNode->Contour[k].y() && + path[i].x() < newNode->Contour[k].x())) k = j; } if (endType == etClosedPolygon && j < 2) { @@ -3409,32 +3371,25 @@ void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType //if this path's lowest pt is lower than all the others then update m_lowest if (endType != etClosedPolygon) return; - if (m_lowest.X < 0) + if (m_lowest.x() < 0) m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k); else { - IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y]; - if (newNode->Contour[k].Y > ip.Y || - (newNode->Contour[k].Y == ip.Y && - newNode->Contour[k].X < ip.X)) + IntPoint ip = m_polyNodes.Childs[(int)m_lowest.x()]->Contour[(int)m_lowest.y()]; + if (newNode->Contour[k].y() > ip.y() || + (newNode->Contour[k].y() == ip.y() && + newNode->Contour[k].x() < ip.x())) m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k); } } //------------------------------------------------------------------------------ -void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType) -{ - for (const Path &path : paths) - AddPath(path, joinType, endType); -} -//------------------------------------------------------------------------------ - void ClipperOffset::FixOrientations() { //fixup orientations of all closed paths if the orientation of the //closed path with the lowermost vertex is wrong ... - if (m_lowest.X >= 0 && - !Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour)) + if (m_lowest.x() >= 0 && + !Orientation(m_polyNodes.Childs[(int)m_lowest.x()]->Contour)) { for (int i = 0; i < m_polyNodes.ChildCount(); ++i) { @@ -3582,8 +3537,8 @@ void ClipperOffset::DoOffset(double delta) for (cInt j = 1; j <= steps; j++) { m_destPoly.push_back(IntPoint( - Round(m_srcPoly[0].X + X * delta), - Round(m_srcPoly[0].Y + Y * delta))); + Round(m_srcPoly[0].x() + X * delta), + Round(m_srcPoly[0].y() + Y * delta))); double X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; @@ -3595,8 +3550,8 @@ void ClipperOffset::DoOffset(double delta) for (int j = 0; j < 4; ++j) { m_destPoly.push_back(IntPoint( - Round(m_srcPoly[0].X + X * delta), - Round(m_srcPoly[0].Y + Y * delta))); + Round(m_srcPoly[0].x() + X * delta), + Round(m_srcPoly[0].y() + Y * delta))); if (X < 0) X = 1; else if (Y < 0) Y = 1; else X = -1; @@ -3632,8 +3587,8 @@ void ClipperOffset::DoOffset(double delta) //re-build m_normals ... DoublePoint n = m_normals[len -1]; for (int j = len - 1; j > 0; j--) - m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); - m_normals[0] = DoublePoint(-n.X, -n.Y); + m_normals[j] = DoublePoint(-m_normals[j - 1].x(), -m_normals[j - 1].y()); + m_normals[0] = DoublePoint(-n.x(), -n.y()); k = 0; for (int j = len - 1; j >= 0; j--) OffsetPoint(j, k, node.m_jointype); @@ -3649,9 +3604,9 @@ void ClipperOffset::DoOffset(double delta) if (node.m_endtype == etOpenButt) { int j = len - 1; - pt1 = IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * delta), Round(m_srcPoly[j].Y + m_normals[j].Y * delta)); + pt1 = IntPoint(Round(m_srcPoly[j].x() + m_normals[j].x() * delta), Round(m_srcPoly[j].y() + m_normals[j].y() * delta)); m_destPoly.push_back(pt1); - pt1 = IntPoint(Round(m_srcPoly[j].X - m_normals[j].X * delta), Round(m_srcPoly[j].Y - m_normals[j].Y * delta)); + pt1 = IntPoint(Round(m_srcPoly[j].x() - m_normals[j].x() * delta), Round(m_srcPoly[j].y() - m_normals[j].y() * delta)); m_destPoly.push_back(pt1); } else @@ -3659,7 +3614,7 @@ void ClipperOffset::DoOffset(double delta) int j = len - 1; k = len - 2; m_sinA = 0; - m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y); + m_normals[j] = DoublePoint(-m_normals[j].x(), -m_normals[j].y()); if (node.m_endtype == etOpenSquare) DoSquare(j, k); else @@ -3668,17 +3623,17 @@ void ClipperOffset::DoOffset(double delta) //re-build m_normals ... for (int j = len - 1; j > 0; j--) - m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); - m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y); + m_normals[j] = DoublePoint(-m_normals[j - 1].x(), -m_normals[j - 1].y()); + m_normals[0] = DoublePoint(-m_normals[1].x(), -m_normals[1].y()); k = len - 1; for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype); if (node.m_endtype == etOpenButt) { - pt1 = IntPoint(Round(m_srcPoly[0].X - m_normals[0].X * delta), Round(m_srcPoly[0].Y - m_normals[0].Y * delta)); + pt1 = IntPoint(Round(m_srcPoly[0].x() - m_normals[0].x() * delta), Round(m_srcPoly[0].y() - m_normals[0].y() * delta)); m_destPoly.push_back(pt1); - pt1 = IntPoint(Round(m_srcPoly[0].X + m_normals[0].X * delta), Round(m_srcPoly[0].Y + m_normals[0].Y * delta)); + pt1 = IntPoint(Round(m_srcPoly[0].x() + m_normals[0].x() * delta), Round(m_srcPoly[0].y() + m_normals[0].y() * delta)); m_destPoly.push_back(pt1); } else @@ -3699,15 +3654,15 @@ void ClipperOffset::DoOffset(double delta) void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) { //cross product ... - m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y); + m_sinA = (m_normals[k].x() * m_normals[j].y() - m_normals[j].x() * m_normals[k].y()); if (std::fabs(m_sinA * m_delta) < 1.0) { //dot product ... - double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y ); + double cosA = (m_normals[k].x() * m_normals[j].x() + m_normals[j].y() * m_normals[k].y() ); if (cosA > 0) // angle => 0 degrees { - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); + m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].x() + m_normals[k].x() * m_delta), + Round(m_srcPoly[j].y() + m_normals[k].y() * m_delta))); return; } //else angle => 180 degrees @@ -3717,19 +3672,19 @@ void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) if (m_sinA * m_delta < 0) { - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); + m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].x() + m_normals[k].x() * m_delta), + Round(m_srcPoly[j].y() + m_normals[k].y() * m_delta))); m_destPoly.push_back(m_srcPoly[j]); - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); + m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].x() + m_normals[j].x() * m_delta), + Round(m_srcPoly[j].y() + m_normals[j].y() * m_delta))); } else switch (jointype) { case jtMiter: { - double r = 1 + (m_normals[j].X * m_normals[k].X + - m_normals[j].Y * m_normals[k].Y); + double r = 1 + (m_normals[j].x() * m_normals[k].x() + + m_normals[j].y() * m_normals[k].y()); if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k); break; } @@ -3743,43 +3698,43 @@ void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) void ClipperOffset::DoSquare(int j, int k) { double dx = std::tan(std::atan2(m_sinA, - m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4); + m_normals[k].x() * m_normals[j].x() + m_normals[k].y() * m_normals[j].y()) / 4); m_destPoly.push_back(IntPoint( - Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)), - Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx)))); + Round(m_srcPoly[j].x() + m_delta * (m_normals[k].x() - m_normals[k].y() * dx)), + Round(m_srcPoly[j].y() + m_delta * (m_normals[k].y() + m_normals[k].x() * dx)))); m_destPoly.push_back(IntPoint( - Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)), - Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx)))); + Round(m_srcPoly[j].x() + m_delta * (m_normals[j].x() + m_normals[j].y() * dx)), + Round(m_srcPoly[j].y() + m_delta * (m_normals[j].y() - m_normals[j].x() * dx)))); } //------------------------------------------------------------------------------ void ClipperOffset::DoMiter(int j, int k, double r) { double q = m_delta / r; - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q), - Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q))); + m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].x() + (m_normals[k].x() + m_normals[j].x()) * q), + Round(m_srcPoly[j].y() + (m_normals[k].y() + m_normals[j].y()) * q))); } //------------------------------------------------------------------------------ void ClipperOffset::DoRound(int j, int k) { double a = std::atan2(m_sinA, - m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); + m_normals[k].x() * m_normals[j].x() + m_normals[k].y() * m_normals[j].y()); auto steps = std::max(Round(m_StepsPerRad * std::fabs(a)), 1); - double X = m_normals[k].X, Y = m_normals[k].Y, X2; + double X = m_normals[k].x(), Y = m_normals[k].y(), X2; for (int i = 0; i < steps; ++i) { m_destPoly.push_back(IntPoint( - Round(m_srcPoly[j].X + X * m_delta), - Round(m_srcPoly[j].Y + Y * m_delta))); + Round(m_srcPoly[j].x() + X * m_delta), + Round(m_srcPoly[j].y() + Y * m_delta))); X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } m_destPoly.push_back(IntPoint( - Round(m_srcPoly[j].X + m_normals[j].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); + Round(m_srcPoly[j].x() + m_normals[j].x() * m_delta), + Round(m_srcPoly[j].y() + m_normals[j].y() * m_delta))); } //------------------------------------------------------------------------------ @@ -3871,34 +3826,22 @@ void ReversePaths(Paths& p) } //------------------------------------------------------------------------------ -void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType) +Paths SimplifyPolygon(const Path &in_poly, PolyFillType fillType) { Clipper c; c.StrictlySimple(true); c.AddPath(in_poly, ptSubject, true); - c.Execute(ctUnion, out_polys, fillType, fillType); + Paths out; + c.Execute(ctUnion, out, fillType, fillType); + return out; } -//------------------------------------------------------------------------------ -void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType) -{ - Clipper c; - c.StrictlySimple(true); - c.AddPaths(in_polys, ptSubject, true); - c.Execute(ctUnion, out_polys, fillType, fillType); -} -//------------------------------------------------------------------------------ - -void SimplifyPolygons(Paths &polys, PolyFillType fillType) -{ - SimplifyPolygons(polys, polys, fillType); -} //------------------------------------------------------------------------------ inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2) { - auto Dx = double(pt1.X - pt2.X); - auto dy = double(pt1.Y - pt2.Y); + auto Dx = double(pt1.x() - pt2.x()); + auto dy = double(pt1.y() - pt2.y()); return (Dx*Dx + dy*dy); } //------------------------------------------------------------------------------ @@ -3912,10 +3855,10 @@ double DistanceFromLineSqrd( //A = (y¹ - y²); B = (x² - x¹); C = (y² - y¹)x¹ - (x² - x¹)y¹ //perpendicular distance of point (x³,y³) = (Ax³ + By³ + C)/Sqrt(A² + B²) //see http://en.wikipedia.org/wiki/Perpendicular_distance - double A = double(ln1.Y - ln2.Y); - double B = double(ln2.X - ln1.X); - double C = A * ln1.X + B * ln1.Y; - C = A * pt.X + B * pt.Y - C; + double A = double(ln1.y() - ln2.y()); + double B = double(ln2.x() - ln1.x()); + double C = A * ln1.x() + B * ln1.y(); + C = A * pt.x() + B * pt.y() - C; return (C * C) / (A * A + B * B); } //--------------------------------------------------------------------------- @@ -3926,20 +3869,20 @@ bool SlopesNearCollinear(const IntPoint& pt1, //this function is more accurate when the point that's geometrically //between the other 2 points is the one that's tested for distance. //ie makes it more likely to pick up 'spikes' ... - if (std::abs(pt1.X - pt2.X) > std::abs(pt1.Y - pt2.Y)) + if (std::abs(pt1.x() - pt2.x()) > std::abs(pt1.y() - pt2.y())) { - if ((pt1.X > pt2.X) == (pt1.X < pt3.X)) + if ((pt1.x() > pt2.x()) == (pt1.x() < pt3.x())) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; - else if ((pt2.X > pt1.X) == (pt2.X < pt3.X)) + else if ((pt2.x() > pt1.x()) == (pt2.x() < pt3.x())) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; } else { - if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y)) + if ((pt1.y() > pt2.y()) == (pt1.y() < pt3.y())) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; - else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y)) + else if ((pt2.y() > pt1.y()) == (pt2.y() < pt3.y())) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; @@ -3949,8 +3892,8 @@ bool SlopesNearCollinear(const IntPoint& pt1, bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd) { - auto Dx = double(pt1.X - pt2.X); - auto dy = double(pt1.Y - pt2.Y); + auto Dx = double(pt1.x() - pt2.x()); + auto dy = double(pt1.y() - pt2.y()); return ((Dx * Dx) + (dy * dy) <= distSqrd); } //------------------------------------------------------------------------------ @@ -4058,7 +4001,7 @@ void Minkowski(const Path& poly, const Path& path, Path p; p.reserve(polyCnt); for (size_t j = 0; j < poly.size(); ++j) - p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y)); + p.push_back(IntPoint(path[i].x() + poly[j].x(), path[i].y() + poly[j].y())); pp.push_back(p); } else @@ -4067,7 +4010,7 @@ void Minkowski(const Path& poly, const Path& path, Path p; p.reserve(polyCnt); for (size_t j = 0; j < poly.size(); ++j) - p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y)); + p.push_back(IntPoint(path[i].x() - poly[j].x(), path[i].y() - poly[j].y())); pp.push_back(p); } @@ -4102,7 +4045,7 @@ void TranslatePath(const Path& input, Path& output, const IntPoint& delta) //precondition: input != output output.resize(input.size()); for (size_t i = 0; i < input.size(); ++i) - output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y); + output[i] = IntPoint(input[i].x() + delta.x(), input[i].y() + delta.y()); } //------------------------------------------------------------------------------ @@ -4178,7 +4121,7 @@ void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths) std::ostream& operator <<(std::ostream &s, const IntPoint &p) { - s << "(" << p.X << "," << p.Y << ")"; + s << "(" << p.x() << "," << p.y() << ")"; return s; } //------------------------------------------------------------------------------ @@ -4188,8 +4131,8 @@ std::ostream& operator <<(std::ostream &s, const Path &p) if (p.empty()) return s; Path::size_type last = p.size() -1; for (Path::size_type i = 0; i < last; i++) - s << "(" << p[i].X << "," << p[i].Y << "), "; - s << "(" << p[last].X << "," << p[last].Y << ")\n"; + s << "(" << p[i].x() << "," << p[i].y() << "), "; + s << "(" << p[last].x() << "," << p[last].y() << ")\n"; return s; } //------------------------------------------------------------------------------ @@ -4204,3 +4147,7 @@ std::ostream& operator <<(std::ostream &s, const Paths &p) //------------------------------------------------------------------------------ } //ClipperLib namespace + +#ifdef CLIPPERLIB_NAMESPACE_PREFIX +} // namespace CLIPPERLIB_NAMESPACE_PREFIX +#endif // CLIPPERLIB_NAMESPACE_PREFIX diff --git a/src/clipper/clipper.hpp b/src/clipper/clipper.hpp index 48e83d046..74e6601f9 100644 --- a/src/clipper/clipper.hpp +++ b/src/clipper/clipper.hpp @@ -37,10 +37,12 @@ #include #include +#include + #define CLIPPER_VERSION "6.2.6" -//use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance. -//#define use_xyz +//CLIPPERLIB_USE_XYZ: adds a Z member to IntPoint. Adds a minor cost to perfomance. +//#define CLIPPERLIB_USE_XYZ //use_lines: Enables line clipping. Adds a very minor cost to performance. #define use_lines @@ -57,11 +59,15 @@ #include #include -#ifdef use_xyz -namespace ClipperLib_Z { -#else /* use_xyz */ -namespace ClipperLib { -#endif /* use_xyz */ +#ifdef CLIPPERLIB_NAMESPACE_PREFIX + namespace CLIPPERLIB_NAMESPACE_PREFIX { +#endif // CLIPPERLIB_NAMESPACE_PREFIX + +#ifdef CLIPPERLIB_USE_XYZ + namespace ClipperLib_Z { +#else + namespace ClipperLib { +#endif enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor }; enum PolyType { ptSubject, ptClip }; @@ -88,29 +94,24 @@ enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative }; static constexpr cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL; #endif // CLIPPERLIB_INT32 -struct IntPoint { - cInt X; - cInt Y; -#ifdef use_xyz - cInt Z; - IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {}; -#else - IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {}; -#endif +#ifdef CLIPPERLIB_INTPOINT_TYPE +using IntPoint = CLIPPERLIB_INTPOINT_TYPE; +#else // CLIPPERLIB_INTPOINT_TYPE +using IntPoint = Eigen::Matrix; +#endif // CLIPPERLIB_INTPOINT_TYPE + +using DoublePoint = Eigen::Matrix; - friend inline bool operator== (const IntPoint& a, const IntPoint& b) - { - return a.X == b.X && a.Y == b.Y; - } - friend inline bool operator!= (const IntPoint& a, const IntPoint& b) - { - return a.X != b.X || a.Y != b.Y; - } -}; //------------------------------------------------------------------------------ -typedef std::vector< IntPoint > Path; -typedef std::vector< Path > Paths; +typedef std::vector Path; +typedef std::vector Paths; inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;} inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;} @@ -119,16 +120,9 @@ std::ostream& operator <<(std::ostream &s, const IntPoint &p); std::ostream& operator <<(std::ostream &s, const Path &p); std::ostream& operator <<(std::ostream &s, const Paths &p); -struct DoublePoint -{ - double X; - double Y; - DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {} - DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {} -}; //------------------------------------------------------------------------------ -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ typedef std::function ZFillCallback; #endif @@ -197,9 +191,7 @@ double Area(const Path &poly); inline bool Orientation(const Path &poly) { return Area(poly) >= 0; } int PointInPolygon(const IntPoint &pt, const Path &path); -void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd); -void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd); -void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd); +Paths SimplifyPolygon(const Path &in_poly, PolyFillType fillType = pftEvenOdd); void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415); void CleanPolygon(Path& poly, double distance = 1.415); @@ -269,11 +261,11 @@ enum EdgeSide { esLeft = 1, esRight = 2}; }; // Point of an output polygon. - // 36B on 64bit system without use_xyz. + // 36B on 64bit system without CLIPPERLIB_USE_XYZ. struct OutPt { // 4B int Idx; - // 16B without use_xyz / 24B with use_xyz + // 16B without CLIPPERLIB_USE_XYZ / 24B with CLIPPERLIB_USE_XYZ IntPoint Pt; // 4B on 32bit system, 8B on 64bit system OutPt *Next; @@ -306,7 +298,58 @@ public: m_HasOpenPaths(false) {} ~ClipperBase() { Clear(); } bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed); - bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed); + + template + bool AddPaths(PathsProvider &&paths_provider, PolyType PolyTyp, bool Closed) + { + size_t num_paths = paths_provider.size(); + if (num_paths == 0) + return false; + if (num_paths == 1) + return AddPath(*paths_provider.begin(), PolyTyp, Closed); + + std::vector num_edges(num_paths, 0); + int num_edges_total = 0; + size_t i = 0; + for (const Path &pg : paths_provider) { + // Remove duplicate end point from a closed input path. + // Remove duplicate points from the end of the input path. + int highI = (int)pg.size() -1; + if (Closed) + while (highI > 0 && (pg[highI] == pg[0])) + --highI; + while (highI > 0 && (pg[highI] == pg[highI -1])) + --highI; + if ((Closed && highI < 2) || (!Closed && highI < 1)) + highI = -1; + num_edges[i ++] = highI + 1; + num_edges_total += highI + 1; + } + if (num_edges_total == 0) + return false; + + // Allocate a new edge array. + std::vector edges(num_edges_total); + // Fill in the edge array. + bool result = false; + TEdge *p_edge = edges.data(); + i = 0; + for (const Path &pg : paths_provider) { + if (num_edges[i]) { + bool res = AddPathInternal(pg, num_edges[i] - 1, PolyTyp, Closed, p_edge); + if (res) { + p_edge += num_edges[i]; + result = true; + } + } + ++ i; + } + if (result) + // At least some edges were generated. Remember the edge array. + m_edges.emplace_back(std::move(edges)); + return result; + } + void Clear(); IntRect GetBounds(); // By default, when three or more vertices are collinear in input polygons (subject or clip), the Clipper object removes the 'inner' vertices before clipping. @@ -368,7 +411,7 @@ public: bool StrictlySimple() const {return m_StrictSimple;}; void StrictlySimple(bool value) {m_StrictSimple = value;}; //set the callback function for z value filling on intersections (otherwise Z is 0) -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ void ZFillFunction(ZFillCallback zFillFunc) { m_ZFill = zFillFunc; } #endif protected: @@ -401,7 +444,7 @@ private: // Does the result go to a PolyTree or Paths? bool m_UsingPolyTree; bool m_StrictSimple; -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ ZFillCallback m_ZFill; //custom callback #endif void SetWindingCount(TEdge& edge) const; @@ -454,7 +497,7 @@ private: void DoSimplePolygons(); void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec) const; void FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec) const; -#ifdef use_xyz +#ifdef CLIPPERLIB_USE_XYZ void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2); #endif }; @@ -467,7 +510,11 @@ public: MiterLimit(miterLimit), ArcTolerance(roundPrecision), ShortestEdgeLength(shortestEdgeLength), m_lowest(-1, 0) {} ~ClipperOffset() { Clear(); } void AddPath(const Path& path, JoinType joinType, EndType endType); - void AddPaths(const Paths& paths, JoinType joinType, EndType endType); + template + void AddPaths(PathsProvider &&paths, JoinType joinType, EndType endType) { + for (const Path &path : paths) + AddPath(path, joinType, endType); + } void Execute(Paths& solution, double delta); void Execute(PolyTree& solution, double delta); void Clear(); @@ -504,8 +551,20 @@ class clipperException : public std::exception }; //------------------------------------------------------------------------------ +template +inline Paths SimplifyPolygons(PathsProvider &&in_polys, PolyFillType fillType = pftEvenOdd) { + Clipper c; + c.StrictlySimple(true); + c.AddPaths(std::forward(in_polys), ptSubject, true); + Paths out; + c.Execute(ctUnion, out, fillType, fillType); + return out; +} + } //ClipperLib namespace +#ifdef CLIPPERLIB_NAMESPACE_PREFIX +} // namespace CLIPPERLIB_NAMESPACE_PREFIX +#endif // CLIPPERLIB_NAMESPACE_PREFIX + #endif //clipper_hpp - - diff --git a/src/clipper/clipper_z.cpp b/src/clipper/clipper_z.cpp index 4a54ef346..f26be7089 100644 --- a/src/clipper/clipper_z.cpp +++ b/src/clipper/clipper_z.cpp @@ -1,7 +1,7 @@ // Hackish wrapper around the ClipperLib library to compile the Clipper library with the Z support. // Enable the Z coordinate support. -#define use_xyz +#define CLIPPERLIB_USE_XYZ // and let it compile #include "clipper.cpp" diff --git a/src/clipper/clipper_z.hpp b/src/clipper/clipper_z.hpp index e5e7d48ce..20596d8e1 100644 --- a/src/clipper/clipper_z.hpp +++ b/src/clipper/clipper_z.hpp @@ -2,17 +2,17 @@ #ifndef clipper_z_hpp #ifdef clipper_hpp -#error "You should include the clipper_z.hpp first" +#error "You should include clipper_z.hpp before clipper.hpp" #endif #define clipper_z_hpp // Enable the Z coordinate support. -#define use_xyz +#define CLIPPERLIB_USE_XYZ #include "clipper.hpp" #undef clipper_hpp -#undef use_xyz +#undef CLIPPERLIB_USE_XYZ #endif // clipper_z_hpp diff --git a/src/libnest2d/CMakeLists.txt b/src/libnest2d/CMakeLists.txt index 3892ed30b..c18dc31cb 100644 --- a/src/libnest2d/CMakeLists.txt +++ b/src/libnest2d/CMakeLists.txt @@ -12,11 +12,8 @@ set(LIBNEST2D_SRCFILES include/libnest2d/placers/bottomleftplacer.hpp include/libnest2d/placers/nfpplacer.hpp include/libnest2d/selections/selection_boilerplate.hpp - #include/libnest2d/selections/filler.hpp include/libnest2d/selections/firstfit.hpp - #include/libnest2d/selections/djd_heuristic.hpp - include/libnest2d/backends/clipper/geometries.hpp - include/libnest2d/backends/clipper/clipper_polygon.hpp + include/libnest2d/backends/libslic3r/geometries.hpp include/libnest2d/optimizers/nlopt/nlopt_boilerplate.hpp include/libnest2d/optimizers/nlopt/simplex.hpp include/libnest2d/optimizers/nlopt/subplex.hpp @@ -27,5 +24,5 @@ set(LIBNEST2D_SRCFILES add_library(libnest2d STATIC ${LIBNEST2D_SRCFILES}) target_include_directories(libnest2d PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include) -target_link_libraries(libnest2d PUBLIC clipper NLopt::nlopt TBB::tbb Boost::boost) -target_compile_definitions(libnest2d PUBLIC LIBNEST2D_THREADING_tbb LIBNEST2D_STATIC LIBNEST2D_OPTIMIZER_nlopt LIBNEST2D_GEOMETRIES_clipper) +target_link_libraries(libnest2d PUBLIC NLopt::nlopt TBB::tbb Boost::boost libslic3r) +target_compile_definitions(libnest2d PUBLIC LIBNEST2D_THREADING_tbb LIBNEST2D_STATIC LIBNEST2D_OPTIMIZER_nlopt LIBNEST2D_GEOMETRIES_libslic3r) diff --git a/src/libnest2d/include/libnest2d/backends/clipper/clipper_polygon.hpp b/src/libnest2d/include/libnest2d/backends/clipper/clipper_polygon.hpp deleted file mode 100644 index 6511fbb72..000000000 --- a/src/libnest2d/include/libnest2d/backends/clipper/clipper_polygon.hpp +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef CLIPPER_POLYGON_HPP -#define CLIPPER_POLYGON_HPP - -#include - -namespace ClipperLib { - -struct Polygon { - Path Contour; - Paths Holes; - - inline Polygon() = default; - - inline explicit Polygon(const Path& cont): Contour(cont) {} -// inline explicit Polygon(const Paths& holes): -// Holes(holes) {} - inline Polygon(const Path& cont, const Paths& holes): - Contour(cont), Holes(holes) {} - - inline explicit Polygon(Path&& cont): Contour(std::move(cont)) {} -// inline explicit Polygon(Paths&& holes): Holes(std::move(holes)) {} - inline Polygon(Path&& cont, Paths&& holes): - Contour(std::move(cont)), Holes(std::move(holes)) {} -}; - -inline IntPoint& operator +=(IntPoint& p, const IntPoint& pa ) { - // This could be done with SIMD - p.X += pa.X; - p.Y += pa.Y; - return p; -} - -inline IntPoint operator+(const IntPoint& p1, const IntPoint& p2) { - IntPoint ret = p1; - ret += p2; - return ret; -} - -inline IntPoint& operator -=(IntPoint& p, const IntPoint& pa ) { - p.X -= pa.X; - p.Y -= pa.Y; - return p; -} - -inline IntPoint operator -(const IntPoint& p ) { - IntPoint ret = p; - ret.X = -ret.X; - ret.Y = -ret.Y; - return ret; -} - -inline IntPoint operator-(const IntPoint& p1, const IntPoint& p2) { - IntPoint ret = p1; - ret -= p2; - return ret; -} - -inline IntPoint& operator *=(IntPoint& p, const IntPoint& pa ) { - p.X *= pa.X; - p.Y *= pa.Y; - return p; -} - -inline IntPoint operator*(const IntPoint& p1, const IntPoint& p2) { - IntPoint ret = p1; - ret *= p2; - return ret; -} - -} - -#endif // CLIPPER_POLYGON_HPP diff --git a/src/libnest2d/include/libnest2d/backends/clipper/geometries.hpp b/src/libnest2d/include/libnest2d/backends/clipper/geometries.hpp deleted file mode 100644 index 9586db35c..000000000 --- a/src/libnest2d/include/libnest2d/backends/clipper/geometries.hpp +++ /dev/null @@ -1,356 +0,0 @@ -#ifndef CLIPPER_BACKEND_HPP -#define CLIPPER_BACKEND_HPP - -#include -#include -#include -#include -#include - -#include -#include - -#include "clipper_polygon.hpp" - -namespace libnest2d { - -// Aliases for convinience -using PointImpl = ClipperLib::IntPoint; -using PathImpl = ClipperLib::Path; -using HoleStore = ClipperLib::Paths; -using PolygonImpl = ClipperLib::Polygon; - -template<> struct ShapeTag { using Type = PolygonTag; }; -template<> struct ShapeTag { using Type = PathTag; }; -template<> struct ShapeTag { using Type = PointTag; }; - -// Type of coordinate units used by Clipper. Enough to specialize for point, -// the rest of the types will work (Path, Polygon) -template<> struct CoordType { - using Type = ClipperLib::cInt; - static const constexpr ClipperLib::cInt MM_IN_COORDS = 1000000; -}; - -// Enough to specialize for path, it will work for multishape and Polygon -template<> struct PointType { using Type = PointImpl; }; - -// This is crucial. CountourType refers to itself by default, so we don't have -// to secialize for clipper Path. ContourType::Type is PathImpl. -template<> struct ContourType { using Type = PathImpl; }; - -// The holes are contained in Clipper::Paths -template<> struct HolesContainer { using Type = ClipperLib::Paths; }; - -namespace pointlike { - -// Tell libnest2d how to extract the X coord from a ClipperPoint object -template<> inline ClipperLib::cInt x(const PointImpl& p) -{ - return p.X; -} - -// Tell libnest2d how to extract the Y coord from a ClipperPoint object -template<> inline ClipperLib::cInt y(const PointImpl& p) -{ - return p.Y; -} - -// Tell libnest2d how to extract the X coord from a ClipperPoint object -template<> inline ClipperLib::cInt& x(PointImpl& p) -{ - return p.X; -} - -// Tell libnest2d how to extract the Y coord from a ClipperPoint object -template<> inline ClipperLib::cInt& y(PointImpl& p) -{ - return p.Y; -} - -} - -// Using the libnest2d default area implementation -#define DISABLE_BOOST_AREA - -namespace shapelike { - -template<> -inline void offset(PolygonImpl& sh, TCoord distance, const PolygonTag&) -{ - #define DISABLE_BOOST_OFFSET - - using ClipperLib::ClipperOffset; - using ClipperLib::jtSquare; - using ClipperLib::etClosedPolygon; - using ClipperLib::Paths; - - Paths result; - - try { - ClipperOffset offs; - offs.AddPath(sh.Contour, jtSquare, etClosedPolygon); - offs.AddPaths(sh.Holes, jtSquare, etClosedPolygon); - offs.Execute(result, static_cast(distance)); - } catch (ClipperLib::clipperException &) { - throw GeometryException(GeomErr::OFFSET); - } - - // Offsetting reverts the orientation and also removes the last vertex - // so boost will not have a closed polygon. - - // we plan to replace contours - sh.Holes.clear(); - - bool found_the_contour = false; - for(auto& r : result) { - if(ClipperLib::Orientation(r)) { - // We don't like if the offsetting generates more than one contour - // but throwing would be an overkill. Instead, we should warn the - // caller about the inability to create correct geometries - if(!found_the_contour) { - sh.Contour = std::move(r); - ClipperLib::ReversePath(sh.Contour); - auto front_p = sh.Contour.front(); - sh.Contour.emplace_back(std::move(front_p)); - found_the_contour = true; - } else { - dout() << "Warning: offsetting result is invalid!"; - /* TODO warning */ - } - } else { - // TODO If there are multiple contours we can't be sure which hole - // belongs to the first contour. (But in this case the situation is - // bad enough to let it go...) - sh.Holes.emplace_back(std::move(r)); - ClipperLib::ReversePath(sh.Holes.back()); - auto front_p = sh.Holes.back().front(); - sh.Holes.back().emplace_back(std::move(front_p)); - } - } -} - -template<> -inline void offset(PathImpl& sh, TCoord distance, const PathTag&) -{ - PolygonImpl p(std::move(sh)); - offset(p, distance, PolygonTag()); - sh = p.Contour; -} - -// Tell libnest2d how to make string out of a ClipperPolygon object -template<> inline std::string toString(const PolygonImpl& sh) -{ - std::stringstream ss; - - ss << "Contour {\n"; - for(auto p : sh.Contour) { - ss << "\t" << p.X << " " << p.Y << "\n"; - } - ss << "}\n"; - - for(auto& h : sh.Holes) { - ss << "Holes {\n"; - for(auto p : h) { - ss << "\t{\n"; - ss << "\t\t" << p.X << " " << p.Y << "\n"; - ss << "\t}\n"; - } - ss << "}\n"; - } - - return ss.str(); -} - -template<> -inline PolygonImpl create(const PathImpl& path, const HoleStore& holes) -{ - PolygonImpl p; - p.Contour = path; - p.Holes = holes; - - return p; -} - -template<> inline PolygonImpl create( PathImpl&& path, HoleStore&& holes) { - PolygonImpl p; - p.Contour.swap(path); - p.Holes.swap(holes); - - return p; -} - -template<> -inline const THolesContainer& holes(const PolygonImpl& sh) -{ - return sh.Holes; -} - -template<> inline THolesContainer& holes(PolygonImpl& sh) -{ - return sh.Holes; -} - -template<> -inline TContour& hole(PolygonImpl& sh, unsigned long idx) -{ - return sh.Holes[idx]; -} - -template<> -inline const TContour& hole(const PolygonImpl& sh, - unsigned long idx) -{ - return sh.Holes[idx]; -} - -template<> inline size_t holeCount(const PolygonImpl& sh) -{ - return sh.Holes.size(); -} - -template<> inline PathImpl& contour(PolygonImpl& sh) -{ - return sh.Contour; -} - -template<> -inline const PathImpl& contour(const PolygonImpl& sh) -{ - return sh.Contour; -} - -#define DISABLE_BOOST_TRANSLATE -template<> -inline void translate(PolygonImpl& sh, const PointImpl& offs) -{ - for(auto& p : sh.Contour) { p += offs; } - for(auto& hole : sh.Holes) for(auto& p : hole) { p += offs; } -} - -#define DISABLE_BOOST_ROTATE -template<> -inline void rotate(PolygonImpl& sh, const Radians& rads) -{ - using Coord = TCoord; - - auto cosa = rads.cos(); - auto sina = rads.sin(); - - for(auto& p : sh.Contour) { - p = { - static_cast(p.X * cosa - p.Y * sina), - static_cast(p.X * sina + p.Y * cosa) - }; - } - for(auto& hole : sh.Holes) for(auto& p : hole) { - p = { - static_cast(p.X * cosa - p.Y * sina), - static_cast(p.X * sina + p.Y * cosa) - }; - } -} - -} // namespace shapelike - -#define DISABLE_BOOST_NFP_MERGE -inline TMultiShape clipper_execute( - ClipperLib::Clipper& clipper, - ClipperLib::ClipType clipType, - ClipperLib::PolyFillType subjFillType = ClipperLib::pftEvenOdd, - ClipperLib::PolyFillType clipFillType = ClipperLib::pftEvenOdd) -{ - TMultiShape retv; - - ClipperLib::PolyTree result; - clipper.Execute(clipType, result, subjFillType, clipFillType); - - retv.reserve(static_cast(result.Total())); - - std::function processHole; - - auto processPoly = [&retv, &processHole](ClipperLib::PolyNode *pptr) { - PolygonImpl poly; - poly.Contour.swap(pptr->Contour); - - assert(!pptr->IsHole()); - - if(!poly.Contour.empty() ) { - auto front_p = poly.Contour.front(); - auto &back_p = poly.Contour.back(); - if(front_p.X != back_p.X || front_p.Y != back_p.X) - poly.Contour.emplace_back(front_p); - } - - for(auto h : pptr->Childs) { processHole(h, poly); } - retv.push_back(poly); - }; - - processHole = [&processPoly](ClipperLib::PolyNode *pptr, PolygonImpl& poly) - { - poly.Holes.emplace_back(std::move(pptr->Contour)); - - assert(pptr->IsHole()); - - if(!poly.Contour.empty() ) { - auto front_p = poly.Contour.front(); - auto &back_p = poly.Contour.back(); - if(front_p.X != back_p.X || front_p.Y != back_p.X) - poly.Contour.emplace_back(front_p); - } - - for(auto c : pptr->Childs) processPoly(c); - }; - - auto traverse = [&processPoly] (ClipperLib::PolyNode *node) - { - for(auto ch : node->Childs) processPoly(ch); - }; - - traverse(&result); - - return retv; -} - -namespace nfp { - -template<> inline TMultiShape -merge(const TMultiShape& shapes) -{ - ClipperLib::Clipper clipper(ClipperLib::ioReverseSolution); - - bool closed = true; - bool valid = true; - - for(auto& path : shapes) { - valid &= clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed); - - for(auto& h : path.Holes) - valid &= clipper.AddPath(h, ClipperLib::ptSubject, closed); - } - - if(!valid) throw GeometryException(GeomErr::MERGE); - - return clipper_execute(clipper, ClipperLib::ctUnion, ClipperLib::pftNegative); -} - -} - -} - -#define DISABLE_BOOST_CONVEX_HULL - -//#define DISABLE_BOOST_SERIALIZE -//#define DISABLE_BOOST_UNSERIALIZE - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4244) -#pragma warning(disable: 4267) -#endif -// All other operators and algorithms are implemented with boost -#include -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif // CLIPPER_BACKEND_HPP diff --git a/src/libnest2d/include/libnest2d/backends/libslic3r/geometries.hpp b/src/libnest2d/include/libnest2d/backends/libslic3r/geometries.hpp new file mode 100644 index 000000000..14b075b19 --- /dev/null +++ b/src/libnest2d/include/libnest2d/backends/libslic3r/geometries.hpp @@ -0,0 +1,283 @@ +#ifndef CLIPPER_BACKEND_HPP +#define CLIPPER_BACKEND_HPP + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace Slic3r { + +template struct IsVec_ : public std::false_type {}; + +template struct IsVec_< Vec<2, T> >: public std::true_type {}; + +template +static constexpr const bool IsVec = IsVec_>::value; + +template using VecOnly = std::enable_if_t, O>; + +inline Point operator+(const Point& p1, const Point& p2) { + Point ret = p1; + ret += p2; + return ret; +} + +inline Point operator -(const Point& p ) { + Point ret = p; + ret.x() = -ret.x(); + ret.y() = -ret.y(); + return ret; +} + +inline Point operator-(const Point& p1, const Point& p2) { + Point ret = p1; + ret -= p2; + return ret; +} + +inline Point& operator *=(Point& p, const Point& pa ) { + p.x() *= pa.x(); + p.y() *= pa.y(); + return p; +} + +inline Point operator*(const Point& p1, const Point& p2) { + Point ret = p1; + ret *= p2; + return ret; +} + +} // namespace Slic3r + +namespace libnest2d { + +template using Vec = Slic3r::Vec<2, T>; + +// Aliases for convinience +using PointImpl = Slic3r::Point; +using PathImpl = Slic3r::Polygon; +using HoleStore = Slic3r::Polygons; +using PolygonImpl = Slic3r::ExPolygon; + +template<> struct ShapeTag { using Type = PointTag; }; +template<> struct ShapeTag { using Type = PointTag; }; + +template<> struct ShapeTag> { using Type = PathTag; }; +template<> struct ShapeTag { using Type = PathTag; }; +template<> struct ShapeTag { using Type = PathTag; }; +template<> struct ShapeTag { using Type = PolygonTag; }; +template<> struct ShapeTag { using Type = MultiPolygonTag; }; + +// Type of coordinate units used by Clipper. Enough to specialize for point, +// the rest of the types will work (Path, Polygon) +template<> struct CoordType { + using Type = coord_t; + static const constexpr coord_t MM_IN_COORDS = 1000000; +}; + +template<> struct CoordType { + using Type = coord_t; + static const constexpr coord_t MM_IN_COORDS = 1000000; +}; + +// Enough to specialize for path, it will work for multishape and Polygon +template<> struct PointType> { using Type = Slic3r::Vec2crd; }; +template<> struct PointType { using Type = Slic3r::Point; }; +template<> struct PointType { using Type = Slic3r::Point; }; + +// This is crucial. CountourType refers to itself by default, so we don't have +// to secialize for clipper Path. ContourType::Type is PathImpl. +template<> struct ContourType { using Type = Slic3r::Polygon; }; + +// The holes are contained in Clipper::Paths +template<> struct HolesContainer { using Type = Slic3r::Polygons; }; + +template<> +struct OrientationType { + static const constexpr Orientation Value = Orientation::COUNTER_CLOCKWISE; +}; + +template<> +struct OrientationType { + static const constexpr Orientation Value = Orientation::COUNTER_CLOCKWISE; +}; + +template<> +struct ClosureType { + static const constexpr Closure Value = Closure::OPEN; +}; + +template<> +struct ClosureType { + static const constexpr Closure Value = Closure::OPEN; +}; + +template<> struct MultiShape { using Type = Slic3r::ExPolygons; }; +template<> struct ContourType { using Type = Slic3r::Polygon; }; + +// Using the libnest2d default area implementation +#define DISABLE_BOOST_AREA + +namespace shapelike { + +template<> +inline void offset(Slic3r::ExPolygon& sh, coord_t distance, const PolygonTag&) +{ +#define DISABLE_BOOST_OFFSET + auto res = Slic3r::offset_ex(sh, distance, Slic3r::ClipperLib::jtSquare); + if (!res.empty()) sh = res.front(); +} + +template<> +inline void offset(Slic3r::Polygon& sh, coord_t distance, const PathTag&) +{ + auto res = Slic3r::offset(sh, distance, Slic3r::ClipperLib::jtSquare); + if (!res.empty()) sh = res.front(); +} + +// Tell libnest2d how to make string out of a ClipperPolygon object +template<> inline std::string toString(const Slic3r::ExPolygon& sh) +{ + std::stringstream ss; + + ss << "Contour {\n"; + for(auto &p : sh.contour.points) { + ss << "\t" << p.x() << " " << p.y() << "\n"; + } + ss << "}\n"; + + for(auto& h : sh.holes) { + ss << "Holes {\n"; + for(auto p : h.points) { + ss << "\t{\n"; + ss << "\t\t" << p.x() << " " << p.y() << "\n"; + ss << "\t}\n"; + } + ss << "}\n"; + } + + return ss.str(); +} + +template<> +inline Slic3r::ExPolygon create(const Slic3r::Polygon& path, const Slic3r::Polygons& holes) +{ + Slic3r::ExPolygon p; + p.contour = path; + p.holes = holes; + + return p; +} + +template<> inline Slic3r::ExPolygon create(Slic3r::Polygon&& path, Slic3r::Polygons&& holes) { + Slic3r::ExPolygon p; + p.contour.points.swap(path.points); + p.holes.swap(holes); + + return p; +} + +template<> +inline const THolesContainer& holes(const Slic3r::ExPolygon& sh) +{ + return sh.holes; +} + +template<> inline THolesContainer& holes(Slic3r::ExPolygon& sh) +{ + return sh.holes; +} + +template<> +inline Slic3r::Polygon& hole(Slic3r::ExPolygon& sh, unsigned long idx) +{ + return sh.holes[idx]; +} + +template<> +inline const Slic3r::Polygon& hole(const Slic3r::ExPolygon& sh, unsigned long idx) +{ + return sh.holes[idx]; +} + +template<> inline size_t holeCount(const Slic3r::ExPolygon& sh) +{ + return sh.holes.size(); +} + +template<> inline Slic3r::Polygon& contour(Slic3r::ExPolygon& sh) +{ + return sh.contour; +} + +template<> +inline const Slic3r::Polygon& contour(const Slic3r::ExPolygon& sh) +{ + return sh.contour; +} + +template<> +inline void reserve(Slic3r::Polygon& p, size_t vertex_capacity, const PathTag&) +{ + p.points.reserve(vertex_capacity); +} + +template<> +inline void addVertex(Slic3r::Polygon& sh, const PathTag&, const Slic3r::Point &p) +{ + sh.points.emplace_back(p); +} + +#define DISABLE_BOOST_TRANSLATE +template<> +inline void translate(Slic3r::ExPolygon& sh, const Slic3r::Point& offs) +{ + sh.translate(offs); +} + +#define DISABLE_BOOST_ROTATE +template<> +inline void rotate(Slic3r::ExPolygon& sh, const Radians& rads) +{ + sh.rotate(rads); +} + +} // namespace shapelike + +namespace nfp { + +#define DISABLE_BOOST_NFP_MERGE +template<> +inline TMultiShape merge(const TMultiShape& shapes) +{ + return Slic3r::union_ex(shapes); +} + +} // namespace nfp +} // namespace libnest2d + +#define DISABLE_BOOST_CONVEX_HULL + +//#define DISABLE_BOOST_SERIALIZE +//#define DISABLE_BOOST_UNSERIALIZE + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4244) +#pragma warning(disable: 4267) +#endif +// All other operators and algorithms are implemented with boost +#include +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // CLIPPER_BACKEND_HPP diff --git a/src/libnest2d/include/libnest2d/geometry_traits.hpp b/src/libnest2d/include/libnest2d/geometry_traits.hpp index 3095c717d..7ea437339 100644 --- a/src/libnest2d/include/libnest2d/geometry_traits.hpp +++ b/src/libnest2d/include/libnest2d/geometry_traits.hpp @@ -128,22 +128,32 @@ template struct ContourType> { using Type = typename ContourType::Type; }; -enum class Orientation { - CLOCKWISE, - COUNTER_CLOCKWISE -}; +enum class Orientation { CLOCKWISE, COUNTER_CLOCKWISE }; template struct OrientationType { // Default Polygon orientation that the library expects - static const Orientation Value = Orientation::CLOCKWISE; + static const constexpr Orientation Value = Orientation::CLOCKWISE; }; -template inline /*constexpr*/ bool is_clockwise() { +template inline constexpr bool is_clockwise() { return OrientationType>::Value == Orientation::CLOCKWISE; } +template +inline const constexpr Orientation OrientationTypeV = + OrientationType>::Value; + +enum class Closure { OPEN, CLOSED }; + +template struct ClosureType { + static const constexpr Closure Value = Closure::CLOSED; +}; + +template +inline const constexpr Closure ClosureTypeV = + ClosureType>::Value; /** * \brief A point pair base class for other point pairs (segment, box, ...). @@ -587,9 +597,9 @@ inline void reserve(RawPath& p, size_t vertex_capacity, const PathTag&) } template -inline void addVertex(S& sh, const PathTag&, Args...args) +inline void addVertex(S& sh, const PathTag&, const TPoint &p) { - sh.emplace_back(std::forward(args)...); + sh.emplace_back(p); } template @@ -841,9 +851,9 @@ template auto rbegin(P& p) -> decltype(_backward(end(p))) return _backward(end(p)); } -template auto rcbegin(const P& p) -> decltype(_backward(end(p))) +template auto rcbegin(const P& p) -> decltype(_backward(cend(p))) { - return _backward(end(p)); + return _backward(cend(p)); } template auto rend(P& p) -> decltype(_backward(begin(p))) @@ -873,16 +883,16 @@ inline void reserve(T& sh, size_t vertex_capacity) { reserve(sh, vertex_capacity, Tag()); } -template -inline void addVertex(S& sh, const PolygonTag&, Args...args) +template +inline void addVertex(S& sh, const PolygonTag&, const TPoint &p) { - addVertex(contour(sh), PathTag(), std::forward(args)...); + addVertex(contour(sh), PathTag(), p); } -template // Tag dispatcher -inline void addVertex(S& sh, Args...args) +template // Tag dispatcher +inline void addVertex(S& sh, const TPoint &p) { - addVertex(sh, Tag(), std::forward(args)...); + addVertex(sh, Tag(), p); } template diff --git a/src/libnest2d/include/libnest2d/geometry_traits_nfp.hpp b/src/libnest2d/include/libnest2d/geometry_traits_nfp.hpp index 6b3ff60c1..d9f947802 100644 --- a/src/libnest2d/include/libnest2d/geometry_traits_nfp.hpp +++ b/src/libnest2d/include/libnest2d/geometry_traits_nfp.hpp @@ -28,7 +28,7 @@ inline void buildPolygon(const EdgeList& edgelist, auto& rsh = sl::contour(rpoly); - sl::reserve(rsh, 2*edgelist.size()); + sl::reserve(rsh, 2 * edgelist.size()); // Add the two vertices from the first edge into the final polygon. sl::addVertex(rsh, edgelist.front().first()); @@ -57,7 +57,6 @@ inline void buildPolygon(const EdgeList& edgelist, tmp = std::next(tmp); } - } template @@ -214,17 +213,24 @@ inline NfpResult nfpConvexOnly(const RawShape& sh, // Reserve the needed memory edgelist.reserve(cap); sl::reserve(rsh, static_cast(cap)); + auto add_edge = [&edgelist](const Vertex &v1, const Vertex &v2) { + Edge e{v1, v2}; + if (e.sqlength() > 0) + edgelist.emplace_back(e); + }; { // place all edges from sh into edgelist auto first = sl::cbegin(sh); auto next = std::next(first); while(next != sl::cend(sh)) { - if (pl::magnsq(*next - *first) > 0) - edgelist.emplace_back(*(first), *(next)); + add_edge(*(first), *(next)); ++first; ++next; } + + if constexpr (ClosureTypeV == Closure::OPEN) + add_edge(*sl::rcbegin(sh), *sl::cbegin(sh)); } { // place all edges from other into edgelist @@ -232,17 +238,19 @@ inline NfpResult nfpConvexOnly(const RawShape& sh, auto next = std::next(first); while(next != sl::cend(other)) { - if (pl::magnsq(*next - *first) > 0) - edgelist.emplace_back(*(next), *(first)); + add_edge(*(next), *(first)); ++first; ++next; } + + if constexpr (ClosureTypeV == Closure::OPEN) + add_edge(*sl::cbegin(other), *sl::rcbegin(other)); } - std::sort(edgelist.begin(), edgelist.end(), - [](const Edge& e1, const Edge& e2) + std::sort(edgelist.begin(), edgelist.end(), + [](const Edge& e1, const Edge& e2) { - Vertex ax(1, 0); // Unit vector for the X axis + const Vertex ax(1, 0); // Unit vector for the X axis // get cectors from the edges Vertex p1 = e1.second() - e1.first(); @@ -288,12 +296,18 @@ inline NfpResult nfpConvexOnly(const RawShape& sh, // If Ratio is an actual rational type, there is no precision loss auto pcos1 = Ratio(lcos[0]) / lsq1 * sign * lcos[0]; auto pcos2 = Ratio(lcos[1]) / lsq2 * sign * lcos[1]; - - return q[0] < 2 ? pcos1 < pcos2 : pcos1 > pcos2; + + if constexpr (is_clockwise()) + return q[0] < 2 ? pcos1 < pcos2 : pcos1 > pcos2; + else + return q[0] < 2 ? pcos1 > pcos2 : pcos1 < pcos2; } // If in different quadrants, compare the quadrant indices only. - return q[0] > q[1]; + if constexpr (is_clockwise()) + return q[0] > q[1]; + else + return q[0] < q[1]; }); __nfp::buildPolygon(edgelist, rsh, top_nfp); diff --git a/src/libnest2d/include/libnest2d/libnest2d.hpp b/src/libnest2d/include/libnest2d/libnest2d.hpp index 9d24a2569..a4cf7dc56 100644 --- a/src/libnest2d/include/libnest2d/libnest2d.hpp +++ b/src/libnest2d/include/libnest2d/libnest2d.hpp @@ -7,6 +7,10 @@ #include #endif +#ifdef LIBNEST2D_GEOMETRIES_libslic3r +#include +#endif + #ifdef LIBNEST2D_OPTIMIZER_nlopt // We include the stock optimizers for local and global optimization #include // Local subplex for NfpPlacer diff --git a/src/libnest2d/include/libnest2d/nester.hpp b/src/libnest2d/include/libnest2d/nester.hpp index 20da9b9a1..52c738a4c 100644 --- a/src/libnest2d/include/libnest2d/nester.hpp +++ b/src/libnest2d/include/libnest2d/nester.hpp @@ -96,7 +96,7 @@ public: * @return The orientation type identifier for the _Item type. */ static BP2D_CONSTEXPR Orientation orientation() { - return OrientationType::Value; + return OrientationType>::Value; } /** @@ -446,44 +446,32 @@ private: } }; +template Sh create_rect(TCoord width, TCoord height) +{ + auto sh = sl::create( + {{0, 0}, {0, height}, {width, height}, {width, 0}}); + + if constexpr (ClosureTypeV == Closure::CLOSED) + sl::addVertex(sh, {0, 0}); + + if constexpr (OrientationTypeV == Orientation::COUNTER_CLOCKWISE) + std::reverse(sl::begin(sh), sl::end(sh)); + + return sh; +} + /** * \brief Subclass of _Item for regular rectangle items. */ -template -class _Rectangle: public _Item { - using _Item::vertex; +template +class _Rectangle: public _Item { + using _Item::vertex; using TO = Orientation; public: - using Unit = TCoord>; + using Unit = TCoord; - template::Value> - inline _Rectangle(Unit width, Unit height, - // disable this ctor if o != CLOCKWISE - enable_if_t< o == TO::CLOCKWISE, int> = 0 ): - _Item( sl::create( { - {0, 0}, - {0, height}, - {width, height}, - {width, 0}, - {0, 0} - } )) - { - } - - template::Value> - inline _Rectangle(Unit width, Unit height, - // disable this ctor if o != COUNTER_CLOCKWISE - enable_if_t< o == TO::COUNTER_CLOCKWISE, int> = 0 ): - _Item( sl::create( { - {0, 0}, - {width, 0}, - {width, height}, - {0, height}, - {0, 0} - } )) - { - } + inline _Rectangle(Unit w, Unit h): _Item{create_rect(w, h)} {} inline Unit width() const BP2D_NOEXCEPT { return getX(vertex(2)); diff --git a/src/libnest2d/include/libnest2d/placers/bottomleftplacer.hpp b/src/libnest2d/include/libnest2d/placers/bottomleftplacer.hpp index e1a4ffbd9..a067194dc 100644 --- a/src/libnest2d/include/libnest2d/placers/bottomleftplacer.hpp +++ b/src/libnest2d/include/libnest2d/placers/bottomleftplacer.hpp @@ -365,44 +365,50 @@ protected: // the additional vertices for maintaning min object distance sl::reserve(rsh, finish-start+4); - /*auto addOthers = [&rsh, finish, start, &item](){ + auto addOthers_ = [&rsh, finish, start, &item](){ for(size_t i = start+1; i < finish; i++) sl::addVertex(rsh, item.vertex(i)); - };*/ + }; - auto reverseAddOthers = [&rsh, finish, start, &item](){ + auto reverseAddOthers_ = [&rsh, finish, start, &item](){ for(auto i = finish-1; i > start; i--) - sl::addVertex(rsh, item.vertex( - static_cast(i))); + sl::addVertex(rsh, item.vertex(static_cast(i))); + }; + + auto addOthers = [&addOthers_, &reverseAddOthers_]() { + if constexpr (!is_clockwise()) + addOthers_(); + else + reverseAddOthers_(); }; // Final polygon construction... - static_assert(OrientationType::Value == - Orientation::CLOCKWISE, - "Counter clockwise toWallPoly() Unimplemented!"); - // Clockwise polygon construction sl::addVertex(rsh, topleft_vertex); - if(dir == Dir::LEFT) reverseAddOthers(); + if(dir == Dir::LEFT) addOthers(); else { - sl::addVertex(rsh, getX(topleft_vertex), 0); - sl::addVertex(rsh, getX(bottomleft_vertex), 0); + sl::addVertex(rsh, {getX(topleft_vertex), 0}); + sl::addVertex(rsh, {getX(bottomleft_vertex), 0}); } sl::addVertex(rsh, bottomleft_vertex); if(dir == Dir::LEFT) { - sl::addVertex(rsh, 0, getY(bottomleft_vertex)); - sl::addVertex(rsh, 0, getY(topleft_vertex)); + sl::addVertex(rsh, {0, getY(bottomleft_vertex)}); + sl::addVertex(rsh, {0, getY(topleft_vertex)}); } - else reverseAddOthers(); + else addOthers(); // Close the polygon - sl::addVertex(rsh, topleft_vertex); + if constexpr (ClosureTypeV == Closure::CLOSED) + sl::addVertex(rsh, topleft_vertex); + + if constexpr (!is_clockwise()) + std::reverse(rsh.begin(), rsh.end()); return ret; } diff --git a/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp b/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp index bd9c60355..47ba7bbdc 100644 --- a/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp +++ b/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp @@ -250,8 +250,8 @@ template class EdgeCache { Vertex ret = edge.first(); // Get the point on the edge which lies in ed distance from the start - ret += { static_cast(std::round(ed*std::cos(angle))), - static_cast(std::round(ed*std::sin(angle))) }; + ret += Vertex(static_cast(std::round(ed*std::cos(angle))), + static_cast(std::round(ed*std::sin(angle)))); return ret; } @@ -724,8 +724,7 @@ private: auto rawobjfunc = [_objfunc, iv, startpos] (Vertex v, Item& itm) { - auto d = v - iv; - d += startpos; + auto d = (v - iv) + startpos; itm.translation(d); return _objfunc(itm); }; @@ -742,8 +741,7 @@ private: &item, &bin, &iv, &startpos] (const Optimum& o) { auto v = getNfpPoint(o); - auto d = v - iv; - d += startpos; + auto d = (v - iv) + startpos; item.translation(d); merged_pile.emplace_back(item.transformedShape()); @@ -877,8 +875,7 @@ private: } if( best_score < global_score ) { - auto d = getNfpPoint(optimum) - iv; - d += startpos; + auto d = (getNfpPoint(optimum) - iv) + startpos; final_tr = d; final_rot = initial_rot + rot; can_pack = true; diff --git a/src/libnest2d/include/libnest2d/utils/boost_alg.hpp b/src/libnest2d/include/libnest2d/utils/boost_alg.hpp index 16dee513b..d6213d0ed 100644 --- a/src/libnest2d/include/libnest2d/utils/boost_alg.hpp +++ b/src/libnest2d/include/libnest2d/utils/boost_alg.hpp @@ -19,7 +19,7 @@ #pragma warning(pop) #endif // this should be removed to not confuse the compiler -// #include +// #include "../libnest2d.hpp" namespace bp2d { @@ -30,6 +30,10 @@ using libnest2d::PolygonImpl; using libnest2d::PathImpl; using libnest2d::Orientation; using libnest2d::OrientationType; +using libnest2d::OrientationTypeV; +using libnest2d::ClosureType; +using libnest2d::Closure; +using libnest2d::ClosureTypeV; using libnest2d::getX; using libnest2d::getY; using libnest2d::setX; @@ -213,8 +217,15 @@ struct ToBoostOrienation { static const order_selector Value = counterclockwise; }; -static const bp2d::Orientation RealOrientation = - bp2d::OrientationType::Value; +template struct ToBoostClosure {}; + +template<> struct ToBoostClosure { + static const constexpr closure_selector Value = closure_selector::open; +}; + +template<> struct ToBoostClosure { + static const constexpr closure_selector Value = closure_selector::closed; +}; // Ring implementation ///////////////////////////////////////////////////////// @@ -225,12 +236,13 @@ template<> struct tag { template<> struct point_order { static const order_selector value = - ToBoostOrienation::Value; + ToBoostOrienation>::Value; }; // All our Paths should be closed for the bin packing application template<> struct closure { - static const closure_selector value = closed; + static const constexpr closure_selector value = + ToBoostClosure< bp2d::ClosureTypeV >::Value; }; // Polygon implementation ////////////////////////////////////////////////////// diff --git a/src/libslic3r/Arrange.cpp b/src/libslic3r/Arrange.cpp index 3800d49e3..61a32678b 100644 --- a/src/libslic3r/Arrange.cpp +++ b/src/libslic3r/Arrange.cpp @@ -3,7 +3,7 @@ #include "BoundingBox.hpp" -#include +#include #include #include #include @@ -54,23 +54,22 @@ namespace Slic3r { template, int...EigenArgs> inline constexpr Eigen::Matrix unscaled( - const ClipperLib::IntPoint &v) noexcept + const Slic3r::ClipperLib::IntPoint &v) noexcept { - return Eigen::Matrix{unscaled(v.X), - unscaled(v.Y)}; + return Eigen::Matrix{unscaled(v.x()), + unscaled(v.y())}; } namespace arrangement { using namespace libnest2d; -namespace clppr = ClipperLib; // Get the libnest2d types for clipper backend -using Item = _Item; -using Box = _Box; -using Circle = _Circle; -using Segment = _Segment; -using MultiPolygon = TMultiShape; +using Item = _Item; +using Box = _Box; +using Circle = _Circle; +using Segment = _Segment; +using MultiPolygon = ExPolygons; // Summon the spatial indexing facilities from boost namespace bgi = boost::geometry::index; @@ -127,8 +126,8 @@ template class AutoArranger { public: // Useful type shortcuts... - using Placer = typename placers::_NofitPolyPlacer; - using Selector = selections::_FirstFitSelection; + using Placer = typename placers::_NofitPolyPlacer; + using Selector = selections::_FirstFitSelection; using Packer = _Nester; using PConfig = typename Packer::PlacementConfig; using Distance = TCoord; @@ -168,7 +167,7 @@ protected: // as it possibly can be but at the same time, it has to provide // reasonable results. std::tuple - objfunc(const Item &item, const clppr::IntPoint &bincenter) + objfunc(const Item &item, const Point &bincenter) { const double bin_area = m_bin_area; const SpatIndex& spatindex = m_rtree; @@ -220,12 +219,12 @@ protected: switch (compute_case) { case BIG_ITEM: { - const clppr::IntPoint& minc = ibb.minCorner(); // bottom left corner - const clppr::IntPoint& maxc = ibb.maxCorner(); // top right corner + const Point& minc = ibb.minCorner(); // bottom left corner + const Point& maxc = ibb.maxCorner(); // top right corner // top left and bottom right corners - clppr::IntPoint top_left{getX(minc), getY(maxc)}; - clppr::IntPoint bottom_right{getX(maxc), getY(minc)}; + Point top_left{getX(minc), getY(maxc)}; + Point bottom_right{getX(maxc), getY(minc)}; // Now the distance of the gravity center will be calculated to the // five anchor points and the smallest will be chosen. @@ -452,7 +451,7 @@ template<> std::function AutoArranger::get_objfn() // Specialization for a generalized polygon. // Warning: this is unfinished business. It may or may not work. template<> -std::function AutoArranger::get_objfn() +std::function AutoArranger::get_objfn() { auto bincenter = sl::boundingBox(m_bin).center(); return [this, bincenter](const Item &item) { @@ -521,7 +520,7 @@ void _arrange( inline Box to_nestbin(const BoundingBox &bb) { return Box{{bb.min(X), bb.min(Y)}, {bb.max(X), bb.max(Y)}};} inline Circle to_nestbin(const CircleBed &c) { return Circle({c.center()(0), c.center()(1)}, c.radius()); } -inline clppr::Polygon to_nestbin(const Polygon &p) { return sl::create(Slic3rMultiPoint_to_ClipperPath(p)); } +inline ExPolygon to_nestbin(const Polygon &p) { return ExPolygon{p}; } inline Box to_nestbin(const InfiniteBed &bed) { return Box::infinite({bed.center.x(), bed.center.y()}); } inline coord_t width(const BoundingBox& box) { return box.max.x() - box.min.x(); } @@ -568,19 +567,12 @@ static void process_arrangeable(const ArrangePolygon &arrpoly, const Vec2crd &offs = arrpoly.translation; double rotation = arrpoly.rotation; - if (p.is_counter_clockwise()) p.reverse(); - - clppr::Polygon clpath(Slic3rMultiPoint_to_ClipperPath(p)); - // This fixes: // https://github.com/prusa3d/PrusaSlicer/issues/2209 - if (clpath.Contour.size() < 3) + if (p.points.size() < 3) return; - auto firstp = clpath.Contour.front(); - clpath.Contour.emplace_back(firstp); - - outp.emplace_back(std::move(clpath)); + outp.emplace_back(std::move(p)); outp.back().rotation(rotation); outp.back().translation({offs.x(), offs.y()}); outp.back().binId(arrpoly.bed_idx); @@ -624,7 +616,7 @@ void arrange(ArrangePolygons & arrangables, const BedT & bed, const ArrangeParams & params) { - namespace clppr = ClipperLib; + namespace clppr = Slic3r::ClipperLib; std::vector items, fixeditems; items.reserve(arrangables.size()); @@ -643,8 +635,8 @@ void arrange(ArrangePolygons & arrangables, _arrange(items, fixeditems, to_nestbin(bed), params, pri, cfn); for(size_t i = 0; i < items.size(); ++i) { - clppr::IntPoint tr = items[i].translation(); - arrangables[i].translation = {coord_t(tr.X), coord_t(tr.Y)}; + Point tr = items[i].translation(); + arrangables[i].translation = {coord_t(tr.x()), coord_t(tr.y())}; arrangables[i].rotation = items[i].rotation(); arrangables[i].bed_idx = items[i].binId(); } diff --git a/src/libslic3r/BridgeDetector.cpp b/src/libslic3r/BridgeDetector.cpp index 671ebbdaa..03d671db4 100644 --- a/src/libslic3r/BridgeDetector.cpp +++ b/src/libslic3r/BridgeDetector.cpp @@ -58,7 +58,7 @@ void BridgeDetector::initialize() // detect anchors as intersection between our bridge expolygon and the lower slices // safety offset required to avoid Clipper from detecting empty intersection while Boost actually found some edges - this->_anchor_regions = intersection_ex(grown, to_polygons(this->lower_slices), true); + this->_anchor_regions = intersection_ex(grown, union_safety_offset(this->lower_slices)); /* if (0) { @@ -227,29 +227,33 @@ void ExPolygon::get_trapezoids(ExPolygon clone, Polygons* polygons, double angle // This algorithm may return more trapezoids than necessary // (i.e. it may break a single trapezoid in several because // other parts of the object have x coordinates in the middle) -static void get_trapezoids2(const ExPolygon &expoly, Polygons* polygons) +static void get_trapezoids2(const ExPolygon& expoly, Polygons* polygons) { Polygons src_polygons = to_polygons(expoly); // get all points of this ExPolygon - const Points pp = to_points(src_polygons); - + const Points pp = to_points(src_polygons); + // build our bounding box BoundingBox bb(pp); - + // get all x coordinates std::vector xx; xx.reserve(pp.size()); for (Points::const_iterator p = pp.begin(); p != pp.end(); ++p) xx.push_back(p->x()); std::sort(xx.begin(), xx.end()); - + // find trapezoids by looping from first to next-to-last coordinate + Polygons rectangle; + rectangle.emplace_back(Polygon()); for (std::vector::const_iterator x = xx.begin(); x != xx.end()-1; ++x) { coord_t next_x = *(x + 1); - if (*x != next_x) + if (*x != next_x) { // intersect with rectangle // append results to return value - polygons_append(*polygons, intersection({ { { *x, bb.min.y() }, { next_x, bb.min.y() }, { next_x, bb.max.y() }, { *x, bb.max.y() } } }, src_polygons)); + rectangle.front() = { { *x, bb.min.y() }, { next_x, bb.min.y() }, { next_x, bb.max.y() }, { *x, bb.max.y() } }; + polygons_append(*polygons, intersection(rectangle, src_polygons)); + } } } @@ -302,7 +306,7 @@ Polygons BridgeDetector::coverage(double angle) const covered = union_(covered); // Intersect trapezoids with actual bridge area to remove extra margins and append it to result. polygons_rotate(covered, -(PI/2.0 - angle)); - covered = intersection(covered, to_polygons(this->expolygons)); + covered = intersection(this->expolygons, covered); #if 0 { my @lines = map @{$_->lines}, @$trapezoids; diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 08bedc5c0..68851e051 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -78,7 +78,7 @@ static ConstPrintObjectPtrs get_top_level_objects_with_brim(const Print &print) // Assign the maximum Z from four points. This values is valid index of the island clipper.ZFillFunction([](const ClipperLib_Z::IntPoint &e1bot, const ClipperLib_Z::IntPoint &e1top, const ClipperLib_Z::IntPoint &e2bot, const ClipperLib_Z::IntPoint &e2top, ClipperLib_Z::IntPoint &pt) { - pt.Z = std::max(std::max(e1bot.Z, e1top.Z), std::max(e2bot.Z, e2top.Z)); + pt.z() = std::max(std::max(e1bot.z(), e1top.z()), std::max(e2bot.z(), e2top.z())); }); // Add islands clipper.AddPaths(islands_clip, ClipperLib_Z::ptSubject, true); @@ -90,9 +90,9 @@ static ConstPrintObjectPtrs get_top_level_objects_with_brim(const Print &print) ConstPrintObjectPtrs top_level_objects_with_brim; for (int i = 0; i < islands_polytree.ChildCount(); ++i) { for (const ClipperLib_Z::IntPoint &point : islands_polytree.Childs[i]->Contour) { - if (point.Z != 0 && processed_objects_idx.find(island_to_object[point.Z - 1]->id().id) == processed_objects_idx.end()) { - top_level_objects_with_brim.emplace_back(island_to_object[point.Z - 1]); - processed_objects_idx.insert(island_to_object[point.Z - 1]->id().id); + if (point.z() != 0 && processed_objects_idx.find(island_to_object[point.z() - 1]->id().id) == processed_objects_idx.end()) { + top_level_objects_with_brim.emplace_back(island_to_object[point.z() - 1]); + processed_objects_idx.insert(island_to_object[point.z() - 1]->id().id); } } } @@ -139,7 +139,7 @@ static ExPolygons top_level_outer_brim_area(const Print &print, const ConstPrint Polygons no_brim_area_object; for (const ExPolygon &ex_poly : object->layers().front()->lslices) { if ((brim_type == BrimType::btOuterOnly || brim_type == BrimType::btOuterAndInner) && is_top_outer_brim) - append(brim_area_object, diff_ex(offset_ex(ex_poly.contour, brim_width + brim_offset), offset_ex(ex_poly.contour, brim_offset))); + append(brim_area_object, diff_ex(offset(ex_poly.contour, brim_width + brim_offset), offset(ex_poly.contour, brim_offset))); if (brim_type == BrimType::btOuterOnly || brim_type == BrimType::btNoBrim) append(no_brim_area_object, offset(ex_poly.holes, -no_brim_offset)); @@ -156,7 +156,7 @@ static ExPolygons top_level_outer_brim_area(const Print &print, const ConstPrint } } - return diff_ex(to_polygons(std::move(brim_area)), no_brim_area); + return diff_ex(brim_area, no_brim_area); } static ExPolygons inner_brim_area(const Print &print, const ConstPrintObjectPtrs &top_level_objects_with_brim, const float no_brim_offset) @@ -183,14 +183,14 @@ static ExPolygons inner_brim_area(const Print &print, const ConstPrintObjectPtrs if (top_outer_brim) no_brim_area_object.emplace_back(ex_poly); else - append(brim_area_object, diff_ex(offset_ex(ex_poly.contour, brim_width + brim_offset), offset_ex(ex_poly.contour, brim_offset))); + append(brim_area_object, diff_ex(offset(ex_poly.contour, brim_width + brim_offset), offset(ex_poly.contour, brim_offset))); } if (brim_type == BrimType::btInnerOnly || brim_type == BrimType::btOuterAndInner) append(brim_area_object, diff_ex(offset_ex(ex_poly.holes, -brim_offset), offset_ex(ex_poly.holes, -brim_width - brim_offset))); if (brim_type == BrimType::btInnerOnly || brim_type == BrimType::btNoBrim) - append(no_brim_area_object, offset_ex(ex_poly.contour, no_brim_offset)); + append(no_brim_area_object, to_expolygons(offset(ex_poly.contour, no_brim_offset))); if (brim_type == BrimType::btOuterOnly || brim_type == BrimType::btNoBrim) append(no_brim_area_object, offset_ex(ex_poly.holes, -no_brim_offset)); @@ -317,7 +317,7 @@ static void make_inner_brim(const Print &print, const ConstPrintObjectPtrs &top_ islands_ex = offset_ex(islands_ex, -float(flow.scaled_spacing()), jtSquare); } - loops = union_pt_chained_outside_in(loops, false); + loops = union_pt_chained_outside_in(loops); std::reverse(loops.begin(), loops.end()); extrusion_entities_append_loops(brim.entities, std::move(loops), erSkirt, float(flow.mm3_per_mm()), float(flow.width()), float(print.skirt_first_layer_height())); @@ -342,7 +342,7 @@ ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cance poly.douglas_peucker(SCALED_RESOLUTION); polygons_append(loops, offset(islands, -0.5f * float(flow.scaled_spacing()))); } - loops = union_pt_chained_outside_in(loops, false); + loops = union_pt_chained_outside_in(loops); std::vector loops_pl_by_levels; { @@ -456,7 +456,7 @@ ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cance clipper.ZFillFunction([](const ClipperLib_Z::IntPoint& e1bot, const ClipperLib_Z::IntPoint& e1top, const ClipperLib_Z::IntPoint& e2bot, const ClipperLib_Z::IntPoint& e2top, ClipperLib_Z::IntPoint& pt) { // Assign a valid input loop identifier. Such an identifier is strictly positive, the next line is safe even in case one side of a segment // hat the Z coordinate not set to the contour coordinate. - pt.Z = std::max(std::max(e1bot.Z, e1top.Z), std::max(e2bot.Z, e2top.Z)); + pt.z() = std::max(std::max(e1bot.z(), e1top.z()), std::max(e2bot.z(), e2top.z())); }); // add polygons clipper.AddPaths(input_clip, ClipperLib_Z::ptSubject, false); @@ -474,8 +474,8 @@ ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cance for (const ClipperLib_Z::Path &path : loops_trimmed) { size_t input_idx = 0; for (const ClipperLib_Z::IntPoint &pt : path) - if (pt.Z > 0) { - input_idx = (size_t)pt.Z; + if (pt.z() > 0) { + input_idx = (size_t)pt.z(); break; } assert(input_idx != 0); @@ -492,14 +492,14 @@ ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cance size_t j = i + 1; for (; j < loops_trimmed_order.size() && loops_trimmed_order[i].second == loops_trimmed_order[j].second; ++ j) ; const ClipperLib_Z::Path &first_path = *loops_trimmed_order[i].first; - if (i + 1 == j && first_path.size() > 3 && first_path.front().X == first_path.back().X && first_path.front().Y == first_path.back().Y) { + if (i + 1 == j && first_path.size() > 3 && first_path.front().x() == first_path.back().x() && first_path.front().y() == first_path.back().y()) { auto *loop = new ExtrusionLoop(); brim.entities.emplace_back(loop); loop->paths.emplace_back(erSkirt, float(flow.mm3_per_mm()), float(flow.width()), float(print.skirt_first_layer_height())); Points &points = loop->paths.front().polyline.points; points.reserve(first_path.size()); for (const ClipperLib_Z::IntPoint &pt : first_path) - points.emplace_back(coord_t(pt.X), coord_t(pt.Y)); + points.emplace_back(coord_t(pt.x()), coord_t(pt.y())); i = j; } else { //FIXME The path chaining here may not be optimal. @@ -511,7 +511,7 @@ ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cance Points &points = static_cast(this_loop_trimmed.entities.back())->polyline.points; points.reserve(path.size()); for (const ClipperLib_Z::IntPoint &pt : path) - points.emplace_back(coord_t(pt.X), coord_t(pt.Y)); + points.emplace_back(coord_t(pt.x()), coord_t(pt.y())); } chain_and_reorder_extrusion_entities(this_loop_trimmed.entities, &last_pt); brim.entities.reserve(brim.entities.size() + this_loop_trimmed.entities.size()); diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index 2abe94656..0cf67597a 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -23,6 +23,8 @@ add_library(libslic3r STATIC BridgeDetector.hpp Brim.cpp Brim.hpp + clipper.cpp + clipper.hpp ClipperUtils.cpp ClipperUtils.hpp Config.cpp @@ -161,6 +163,7 @@ add_library(libslic3r STATIC AppConfig.hpp Print.cpp Print.hpp + PrintApply.cpp PrintBase.cpp PrintBase.hpp PrintConfig.cpp diff --git a/src/libslic3r/ClipperUtils.cpp b/src/libslic3r/ClipperUtils.cpp index cd243dfb1..724224604 100644 --- a/src/libslic3r/ClipperUtils.cpp +++ b/src/libslic3r/ClipperUtils.cpp @@ -24,7 +24,6 @@ namespace Slic3r { #ifdef CLIPPER_UTILS_DEBUG -bool clipper_export_enabled = false; // For debugging the Clipper library, for providing bug reports to the Clipper author. bool export_clipper_input_polygons_bin(const char *path, const ClipperLib::Paths &input_subject, const ClipperLib::Paths &input_clip) { @@ -57,425 +56,284 @@ err: } #endif /* CLIPPER_UTILS_DEBUG */ -#ifdef CLIPPERUTILS_OFFSET_SCALE -void scaleClipperPolygon(ClipperLib::Path &polygon) -{ - CLIPPERUTILS_PROFILE_FUNC(); - for (ClipperLib::Path::iterator pit = polygon.begin(); pit != polygon.end(); ++pit) { - pit->X <<= CLIPPER_OFFSET_POWER_OF_2; - pit->Y <<= CLIPPER_OFFSET_POWER_OF_2; - } +namespace ClipperUtils { + Points EmptyPathsProvider::s_empty_points; + Points SinglePathProvider::s_end; } -void scaleClipperPolygons(ClipperLib::Paths &polygons) +static ExPolygons PolyTreeToExPolygons(ClipperLib::PolyTree &&polytree) { - CLIPPERUTILS_PROFILE_FUNC(); - for (ClipperLib::Paths::iterator it = polygons.begin(); it != polygons.end(); ++it) - for (ClipperLib::Path::iterator pit = (*it).begin(); pit != (*it).end(); ++pit) { - pit->X <<= CLIPPER_OFFSET_POWER_OF_2; - pit->Y <<= CLIPPER_OFFSET_POWER_OF_2; + struct Inner { + static void PolyTreeToExPolygonsRecursive(ClipperLib::PolyNode &&polynode, ExPolygons *expolygons) + { + size_t cnt = expolygons->size(); + expolygons->resize(cnt + 1); + (*expolygons)[cnt].contour.points = std::move(polynode.Contour); + (*expolygons)[cnt].holes.resize(polynode.ChildCount()); + for (int i = 0; i < polynode.ChildCount(); ++ i) { + (*expolygons)[cnt].holes[i].points = std::move(polynode.Childs[i]->Contour); + // Add outer polygons contained by (nested within) holes. + for (int j = 0; j < polynode.Childs[i]->ChildCount(); ++ j) + PolyTreeToExPolygonsRecursive(std::move(*polynode.Childs[i]->Childs[j]), expolygons); + } } -} -void unscaleClipperPolygon(ClipperLib::Path &polygon) -{ - CLIPPERUTILS_PROFILE_FUNC(); - for (ClipperLib::Path::iterator pit = polygon.begin(); pit != polygon.end(); ++pit) { - pit->X += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA; - pit->Y += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA; - pit->X >>= CLIPPER_OFFSET_POWER_OF_2; - pit->Y >>= CLIPPER_OFFSET_POWER_OF_2; - } -} - -void unscaleClipperPolygons(ClipperLib::Paths &polygons) -{ - CLIPPERUTILS_PROFILE_FUNC(); - for (ClipperLib::Paths::iterator it = polygons.begin(); it != polygons.end(); ++it) - for (ClipperLib::Path::iterator pit = (*it).begin(); pit != (*it).end(); ++pit) { - pit->X += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA; - pit->Y += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA; - pit->X >>= CLIPPER_OFFSET_POWER_OF_2; - pit->Y >>= CLIPPER_OFFSET_POWER_OF_2; + static size_t PolyTreeCountExPolygons(const ClipperLib::PolyNode &polynode) + { + size_t cnt = 1; + for (int i = 0; i < polynode.ChildCount(); ++ i) { + for (int j = 0; j < polynode.Childs[i]->ChildCount(); ++ j) + cnt += PolyTreeCountExPolygons(*polynode.Childs[i]->Childs[j]); + } + return cnt; } -} -#endif // CLIPPERUTILS_OFFSET_SCALE + }; -//----------------------------------------------------------- -// legacy code from Clipper documentation -void AddOuterPolyNodeToExPolygons(ClipperLib::PolyNode& polynode, ExPolygons* expolygons) -{ - size_t cnt = expolygons->size(); - expolygons->resize(cnt + 1); - (*expolygons)[cnt].contour = ClipperPath_to_Slic3rPolygon(polynode.Contour); - (*expolygons)[cnt].holes.resize(polynode.ChildCount()); - for (int i = 0; i < polynode.ChildCount(); ++i) - { - (*expolygons)[cnt].holes[i] = ClipperPath_to_Slic3rPolygon(polynode.Childs[i]->Contour); - //Add outer polygons contained by (nested within) holes ... - for (int j = 0; j < polynode.Childs[i]->ChildCount(); ++j) - AddOuterPolyNodeToExPolygons(*polynode.Childs[i]->Childs[j], expolygons); - } -} - -ExPolygons PolyTreeToExPolygons(ClipperLib::PolyTree& polytree) -{ ExPolygons retval; - for (int i = 0; i < polytree.ChildCount(); ++i) - AddOuterPolyNodeToExPolygons(*polytree.Childs[i], &retval); - return retval; -} -//----------------------------------------------------------- - -Slic3r::Polygon ClipperPath_to_Slic3rPolygon(const ClipperLib::Path &input) -{ - Polygon retval; - for (ClipperLib::Path::const_iterator pit = input.begin(); pit != input.end(); ++pit) - retval.points.emplace_back(pit->X, pit->Y); + size_t cnt = 0; + for (int i = 0; i < polytree.ChildCount(); ++ i) + cnt += Inner::PolyTreeCountExPolygons(*polytree.Childs[i]); + retval.reserve(cnt); + for (int i = 0; i < polytree.ChildCount(); ++ i) + Inner::PolyTreeToExPolygonsRecursive(std::move(*polytree.Childs[i]), &retval); return retval; } -Slic3r::Polyline ClipperPath_to_Slic3rPolyline(const ClipperLib::Path &input) +Polylines PolyTreeToPolylines(ClipperLib::PolyTree &&polytree) { - Polyline retval; - for (ClipperLib::Path::const_iterator pit = input.begin(); pit != input.end(); ++pit) - retval.points.emplace_back(pit->X, pit->Y); - return retval; -} + struct Inner { + static void AddPolyNodeToPaths(ClipperLib::PolyNode &polynode, Polylines &out) + { + if (! polynode.Contour.empty()) + out.emplace_back(std::move(polynode.Contour)); + for (ClipperLib::PolyNode *child : polynode.Childs) + AddPolyNodeToPaths(*child, out); + } + }; -Slic3r::Polygons ClipperPaths_to_Slic3rPolygons(const ClipperLib::Paths &input) -{ - Slic3r::Polygons retval; - retval.reserve(input.size()); - for (ClipperLib::Paths::const_iterator it = input.begin(); it != input.end(); ++it) - retval.emplace_back(ClipperPath_to_Slic3rPolygon(*it)); - return retval; -} - -Slic3r::Polylines ClipperPaths_to_Slic3rPolylines(const ClipperLib::Paths &input) -{ - Slic3r::Polylines retval; - retval.reserve(input.size()); - for (ClipperLib::Paths::const_iterator it = input.begin(); it != input.end(); ++it) - retval.emplace_back(ClipperPath_to_Slic3rPolyline(*it)); - return retval; + Polylines out; + out.reserve(polytree.Total()); + Inner::AddPolyNodeToPaths(polytree, out); + return out; } ExPolygons ClipperPaths_to_Slic3rExPolygons(const ClipperLib::Paths &input) { - // init Clipper ClipperLib::Clipper clipper; - clipper.Clear(); - - // perform union clipper.AddPaths(input, ClipperLib::ptSubject, true); ClipperLib::PolyTree polytree; clipper.Execute(ClipperLib::ctUnion, polytree, ClipperLib::pftEvenOdd, ClipperLib::pftEvenOdd); // offset results work with both EvenOdd and NonZero - - // write to ExPolygons object - return PolyTreeToExPolygons(polytree); + return PolyTreeToExPolygons(std::move(polytree)); } -ClipperLib::Path Slic3rMultiPoint_to_ClipperPath(const MultiPoint &input) +// Offset outside by 10um, one by one. +template +static ClipperLib::Paths safety_offset(PathsProvider &&paths) { - ClipperLib::Path retval; - for (Points::const_iterator pit = input.points.begin(); pit != input.points.end(); ++pit) - retval.emplace_back((*pit)(0), (*pit)(1)); - return retval; -} - -ClipperLib::Path Slic3rMultiPoint_to_ClipperPath_reversed(const Slic3r::MultiPoint &input) -{ - ClipperLib::Path output; - output.reserve(input.points.size()); - for (Slic3r::Points::const_reverse_iterator pit = input.points.rbegin(); pit != input.points.rend(); ++pit) - output.emplace_back((*pit)(0), (*pit)(1)); - return output; -} - -ClipperLib::Paths Slic3rMultiPoints_to_ClipperPaths(const Polygons &input) -{ - ClipperLib::Paths retval; - for (Polygons::const_iterator it = input.begin(); it != input.end(); ++it) - retval.emplace_back(Slic3rMultiPoint_to_ClipperPath(*it)); - return retval; -} - -ClipperLib::Paths Slic3rMultiPoints_to_ClipperPaths(const ExPolygons &input) -{ - ClipperLib::Paths retval; - for (auto &ep : input) { - retval.emplace_back(Slic3rMultiPoint_to_ClipperPath(ep.contour)); - - for (auto &h : ep.holes) - retval.emplace_back(Slic3rMultiPoint_to_ClipperPath(h)); + ClipperLib::ClipperOffset co; + ClipperLib::Paths out; + out.reserve(paths.size()); + ClipperLib::Paths out_this; + for (const ClipperLib::Path &path : paths) { + co.Clear(); + co.MiterLimit = 2.; + // Execute reorients the contours so that the outer most contour has a positive area. Thus the output + // contours will be CCW oriented even though the input paths are CW oriented. + // Offset is applied after contour reorientation, thus the signum of the offset value is reversed. + co.AddPath(path, ClipperLib::jtMiter, ClipperLib::etClosedPolygon); + bool ccw = ClipperLib::Orientation(path); + co.Execute(out_this, ccw ? ClipperSafetyOffset : - ClipperSafetyOffset); + if (! ccw) { + // Reverse the resulting contours. + for (ClipperLib::Path &path : out_this) + std::reverse(path.begin(), path.end()); + } + append(out, std::move(out_this)); } - - return retval; + return out; } -ClipperLib::Paths Slic3rMultiPoints_to_ClipperPaths(const Polylines &input) +// Only safe for a single path. +template +ClipperLib::Paths _offset(PathsProvider &&input, ClipperLib::EndType endType, const float delta, ClipperLib::JoinType joinType, double miterLimit) { - ClipperLib::Paths retval; - for (Polylines::const_iterator it = input.begin(); it != input.end(); ++it) - retval.emplace_back(Slic3rMultiPoint_to_ClipperPath(*it)); - return retval; -} - -ClipperLib::Paths _offset(ClipperLib::Paths &&input, ClipperLib::EndType endType, const float delta, ClipperLib::JoinType joinType, double miterLimit) -{ -#ifdef CLIPPERUTILS_OFFSET_SCALE - // scale input - scaleClipperPolygons(input); -#endif // CLIPPERUTILS_OFFSET_SCALE - // perform offset ClipperLib::ClipperOffset co; if (joinType == jtRound) co.ArcTolerance = miterLimit; else co.MiterLimit = miterLimit; -#ifdef CLIPPERUTILS_OFFSET_SCALE - float delta_scaled = delta * float(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE float delta_scaled = delta; -#endif // CLIPPERUTILS_OFFSET_SCALE co.ShortestEdgeLength = double(std::abs(delta_scaled * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR)); - co.AddPaths(input, joinType, endType); + co.AddPaths(std::forward(input), joinType, endType); ClipperLib::Paths retval; co.Execute(retval, delta_scaled); - -#ifdef CLIPPERUTILS_OFFSET_SCALE - // unscale output - unscaleClipperPolygons(retval); -#endif // CLIPPERUTILS_OFFSET_SCALE return retval; } -ClipperLib::Paths _offset(ClipperLib::Path &&input, ClipperLib::EndType endType, const float delta, ClipperLib::JoinType joinType, double miterLimit) -{ - ClipperLib::Paths paths; - paths.emplace_back(std::move(input)); - return _offset(std::move(paths), endType, delta, joinType, miterLimit); -} +Slic3r::Polygons offset(const Slic3r::Polygon& polygon, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(ClipperUtils::SinglePathProvider(polygon.points), ClipperLib::etClosedPolygon, delta, joinType, miterLimit)); } -// This is a safe variant of the polygon offset, tailored for a single ExPolygon: -// a single polygon with multiple non-overlapping holes. -// Each contour and hole is offsetted separately, then the holes are subtracted from the outer contours. -ClipperLib::Paths _offset(const Slic3r::ExPolygon &expolygon, const float delta, - ClipperLib::JoinType joinType, double miterLimit) +#ifdef CLIPPERUTILS_UNSAFE_OFFSET +Slic3r::Polygons offset(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(ClipperUtils::PolygonsProvider(polygons), ClipperLib::etClosedPolygon, delta, joinType, miterLimit)); } +Slic3r::ExPolygons offset_ex(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return ClipperPaths_to_Slic3rExPolygons(_offset(ClipperUtils::PolygonsProvider(polygons), ClipperLib::etClosedPolygon, delta, joinType, miterLimit)); } +#endif // CLIPPERUTILS_UNSAFE_OFFSET + +Slic3r::Polygons offset(const Slic3r::Polyline &polyline, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(ClipperUtils::SinglePathProvider(polyline.points), ClipperLib::etOpenButt, delta, joinType, miterLimit)); } +Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(ClipperUtils::PolylinesProvider(polylines), ClipperLib::etOpenButt, delta, joinType, miterLimit)); } + +// returns number of expolygons collected (0 or 1). +static int offset_expolygon_inner(const Slic3r::ExPolygon &expoly, const float delta, ClipperLib::JoinType joinType, double miterLimit, ClipperLib::Paths &out) { -// printf("new ExPolygon offset\n"); // 1) Offset the outer contour. -#ifdef CLIPPERUTILS_OFFSET_SCALE - float delta_scaled = delta * float(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE - float delta_scaled = delta; -#endif // CLIPPERUTILS_OFFSET_SCALE ClipperLib::Paths contours; { - ClipperLib::Path input = Slic3rMultiPoint_to_ClipperPath(expolygon.contour); -#ifdef CLIPPERUTILS_OFFSET_SCALE - scaleClipperPolygon(input); -#endif // CLIPPERUTILS_OFFSET_SCALE ClipperLib::ClipperOffset co; if (joinType == jtRound) -#ifdef CLIPPERUTILS_OFFSET_SCALE - co.ArcTolerance = miterLimit * double(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE co.ArcTolerance = miterLimit; -#endif // CLIPPERUTILS_OFFSET_SCALE else co.MiterLimit = miterLimit; - co.ShortestEdgeLength = double(std::abs(delta_scaled * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR)); - co.AddPath(input, joinType, ClipperLib::etClosedPolygon); - co.Execute(contours, delta_scaled); + co.ShortestEdgeLength = double(std::abs(delta * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR)); + co.AddPath(expoly.contour.points, joinType, ClipperLib::etClosedPolygon); + co.Execute(contours, delta); } + if (contours.empty()) + // No need to try to offset the holes. + return 0; - // 2) Offset the holes one by one, collect the results. - ClipperLib::Paths holes; - { - holes.reserve(expolygon.holes.size()); - for (Polygons::const_iterator it_hole = expolygon.holes.begin(); it_hole != expolygon.holes.end(); ++ it_hole) { - ClipperLib::Path input = Slic3rMultiPoint_to_ClipperPath_reversed(*it_hole); -#ifdef CLIPPERUTILS_OFFSET_SCALE - scaleClipperPolygon(input); -#endif // CLIPPERUTILS_OFFSET_SCALE - ClipperLib::ClipperOffset co; - if (joinType == jtRound) -#ifdef CLIPPERUTILS_OFFSET_SCALE - co.ArcTolerance = miterLimit * double(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE - co.ArcTolerance = miterLimit; -#endif // CLIPPERUTILS_OFFSET_SCALE - else - co.MiterLimit = miterLimit; - co.ShortestEdgeLength = double(std::abs(delta_scaled * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR)); - co.AddPath(input, joinType, ClipperLib::etClosedPolygon); - ClipperLib::Paths out; - co.Execute(out, - delta_scaled); - append(holes, std::move(out)); + if (expoly.holes.empty()) { + // No need to subtract holes from the offsetted expolygon, we are done. + append(out, std::move(contours)); + } else { + // 2) Offset the holes one by one, collect the offsetted holes. + ClipperLib::Paths holes; + { + for (const Polygon &hole : expoly.holes) { + ClipperLib::ClipperOffset co; + if (joinType == jtRound) + co.ArcTolerance = miterLimit; + else + co.MiterLimit = miterLimit; + co.ShortestEdgeLength = double(std::abs(delta * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR)); + co.AddPath(hole.points, joinType, ClipperLib::etClosedPolygon); + ClipperLib::Paths out2; + // Execute reorients the contours so that the outer most contour has a positive area. Thus the output + // contours will be CCW oriented even though the input paths are CW oriented. + // Offset is applied after contour reorientation, thus the signum of the offset value is reversed. + co.Execute(out2, - delta); + append(holes, std::move(out2)); + } + } + + // 3) Subtract holes from the contours. + if (holes.empty()) { + // No hole remaining after an offset. Just copy the outer contour. + append(out, std::move(contours)); + } else if (delta < 0) { + // Negative offset. There is a chance, that the offsetted hole intersects the outer contour. + // Subtract the offsetted holes from the offsetted contours. + ClipperLib::Clipper clipper; + clipper.Clear(); + clipper.AddPaths(contours, ClipperLib::ptSubject, true); + clipper.AddPaths(holes, ClipperLib::ptClip, true); + ClipperLib::Paths output; + clipper.Execute(ClipperLib::ctDifference, output, ClipperLib::pftNonZero, ClipperLib::pftNonZero); + if (! output.empty()) { + append(out, std::move(output)); + } else { + // The offsetted holes have eaten up the offsetted outer contour. + return 0; + } + } else { + // Positive offset. As long as the Clipper offset does what one expects it to do, the offsetted hole will have a smaller + // area than the original hole or even disappear, therefore there will be no new intersections. + // Just collect the reversed holes. + out.reserve(contours.size() + holes.size()); + append(out, std::move(contours)); + // Reverse the holes in place. + for (size_t i = 0; i < holes.size(); ++ i) + std::reverse(holes[i].begin(), holes[i].end()); + append(out, std::move(holes)); } } - // 3) Subtract holes from the contours. - ClipperLib::Paths output; - if (holes.empty()) { - output = std::move(contours); - } else { - ClipperLib::Clipper clipper; - clipper.Clear(); - clipper.AddPaths(contours, ClipperLib::ptSubject, true); - clipper.AddPaths(holes, ClipperLib::ptClip, true); - clipper.Execute(ClipperLib::ctDifference, output, ClipperLib::pftNonZero, ClipperLib::pftNonZero); - } - - // 4) Unscale the output. -#ifdef CLIPPERUTILS_OFFSET_SCALE - unscaleClipperPolygons(output); -#endif // CLIPPERUTILS_OFFSET_SCALE - return output; + return 1; +} + +static int offset_expolygon_inner(const Slic3r::Surface &surface, const float delta, ClipperLib::JoinType joinType, double miterLimit, ClipperLib::Paths &out) + { return offset_expolygon_inner(surface.expolygon, delta, joinType, miterLimit, out); } +static int offset_expolygon_inner(const Slic3r::Surface *surface, const float delta, ClipperLib::JoinType joinType, double miterLimit, ClipperLib::Paths &out) + { return offset_expolygon_inner(surface->expolygon, delta, joinType, miterLimit, out); } + +ClipperLib::Paths _offset(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType, double miterLimit) +{ + ClipperLib::Paths out; + offset_expolygon_inner(expolygon, delta, joinType, miterLimit, out); + return out; } // This is a safe variant of the polygons offset, tailored for multiple ExPolygons. // It is required, that the input expolygons do not overlap and that the holes of each ExPolygon don't intersect with their respective outer contours. // Each ExPolygon is offsetted separately, then the offsetted ExPolygons are united. -ClipperLib::Paths _offset(const Slic3r::ExPolygons &expolygons, const float delta, - ClipperLib::JoinType joinType, double miterLimit) +template +ClipperLib::Paths _offset(const ExPolygonVector &expolygons, const float delta, ClipperLib::JoinType joinType, double miterLimit) { -#ifdef CLIPPERUTILS_OFFSET_SCALE - float delta_scaled = delta * float(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE - float delta_scaled = delta; -#endif // CLIPPERUTILS_OFFSET_SCALE // Offsetted ExPolygons before they are united. - ClipperLib::Paths contours_cummulative; - contours_cummulative.reserve(expolygons.size()); - // How many non-empty offsetted expolygons were actually collected into contours_cummulative? + ClipperLib::Paths output; + output.reserve(expolygons.size()); + // How many non-empty offsetted expolygons were actually collected into output? // If only one, then there is no need to do a final union. size_t expolygons_collected = 0; - for (Slic3r::ExPolygons::const_iterator it_expoly = expolygons.begin(); it_expoly != expolygons.end(); ++ it_expoly) { - // 1) Offset the outer contour. - ClipperLib::Paths contours; - { - ClipperLib::Path input = Slic3rMultiPoint_to_ClipperPath(it_expoly->contour); -#ifdef CLIPPERUTILS_OFFSET_SCALE - scaleClipperPolygon(input); -#endif // CLIPPERUTILS_OFFSET_SCALE - ClipperLib::ClipperOffset co; - if (joinType == jtRound) -#ifdef CLIPPERUTILS_OFFSET_SCALE - co.ArcTolerance = miterLimit * double(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE - co.ArcTolerance = miterLimit; -#endif // CLIPPERUTILS_OFFSET_SCALE - else - co.MiterLimit = miterLimit; - co.ShortestEdgeLength = double(std::abs(delta_scaled * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR)); - co.AddPath(input, joinType, ClipperLib::etClosedPolygon); - co.Execute(contours, delta_scaled); - } - if (contours.empty()) - // No need to try to offset the holes. - continue; - - if (it_expoly->holes.empty()) { - // No need to subtract holes from the offsetted expolygon, we are done. - contours_cummulative.insert(contours_cummulative.end(), contours.begin(), contours.end()); - ++ expolygons_collected; - } else { - // 2) Offset the holes one by one, collect the offsetted holes. - ClipperLib::Paths holes; - { - for (Polygons::const_iterator it_hole = it_expoly->holes.begin(); it_hole != it_expoly->holes.end(); ++ it_hole) { - ClipperLib::Path input = Slic3rMultiPoint_to_ClipperPath_reversed(*it_hole); -#ifdef CLIPPERUTILS_OFFSET_SCALE - scaleClipperPolygon(input); -#endif // CLIPPERUTILS_OFFSET_SCALE - ClipperLib::ClipperOffset co; - if (joinType == jtRound) -#ifdef CLIPPERUTILS_OFFSET_SCALE - co.ArcTolerance = miterLimit * double(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE - co.ArcTolerance = miterLimit; -#endif // CLIPPERUTILS_OFFSET_SCALE - else - co.MiterLimit = miterLimit; - co.ShortestEdgeLength = double(std::abs(delta_scaled * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR)); - co.AddPath(input, joinType, ClipperLib::etClosedPolygon); - ClipperLib::Paths out; - co.Execute(out, - delta_scaled); - holes.insert(holes.end(), out.begin(), out.end()); - } - } - - // 3) Subtract holes from the contours. - if (holes.empty()) { - // No hole remaining after an offset. Just copy the outer contour. - contours_cummulative.insert(contours_cummulative.end(), contours.begin(), contours.end()); - ++ expolygons_collected; - } else if (delta < 0) { - // Negative offset. There is a chance, that the offsetted hole intersects the outer contour. - // Subtract the offsetted holes from the offsetted contours. - ClipperLib::Clipper clipper; - clipper.Clear(); - clipper.AddPaths(contours, ClipperLib::ptSubject, true); - clipper.AddPaths(holes, ClipperLib::ptClip, true); - ClipperLib::Paths output; - clipper.Execute(ClipperLib::ctDifference, output, ClipperLib::pftNonZero, ClipperLib::pftNonZero); - if (! output.empty()) { - contours_cummulative.insert(contours_cummulative.end(), output.begin(), output.end()); - ++ expolygons_collected; - } else { - // The offsetted holes have eaten up the offsetted outer contour. - } - } else { - // Positive offset. As long as the Clipper offset does what one expects it to do, the offsetted hole will have a smaller - // area than the original hole or even disappear, therefore there will be no new intersections. - // Just collect the reversed holes. - contours_cummulative.reserve(contours.size() + holes.size()); - contours_cummulative.insert(contours_cummulative.end(), contours.begin(), contours.end()); - // Reverse the holes in place. - for (size_t i = 0; i < holes.size(); ++ i) - std::reverse(holes[i].begin(), holes[i].end()); - contours_cummulative.insert(contours_cummulative.end(), holes.begin(), holes.end()); - ++ expolygons_collected; - } - } - } + for (const auto &expoly : expolygons) + expolygons_collected += offset_expolygon_inner(expoly, delta, joinType, miterLimit, output); // 4) Unite the offsetted expolygons. - ClipperLib::Paths output; if (expolygons_collected > 1 && delta > 0) { // There is a chance that the outwards offsetted expolygons may intersect. Perform a union. ClipperLib::Clipper clipper; clipper.Clear(); - clipper.AddPaths(contours_cummulative, ClipperLib::ptSubject, true); + clipper.AddPaths(output, ClipperLib::ptSubject, true); clipper.Execute(ClipperLib::ctUnion, output, ClipperLib::pftNonZero, ClipperLib::pftNonZero); } else { // Negative offset. The shrunk expolygons shall not mutually intersect. Just copy the output. - output = std::move(contours_cummulative); } -#ifdef CLIPPERUTILS_OFFSET_SCALE - // 4) Unscale the output. - unscaleClipperPolygons(output); -#endif // CLIPPERUTILS_OFFSET_SCALE return output; } -ClipperLib::Paths -_offset2(const Polygons &polygons, const float delta1, const float delta2, - const ClipperLib::JoinType joinType, const double miterLimit) +Slic3r::Polygons offset(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(expolygon, delta, joinType, miterLimit)); } +Slic3r::Polygons offset(const Slic3r::ExPolygons &expolygons, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(expolygons, delta, joinType, miterLimit)); } +Slic3r::Polygons offset(const Slic3r::Surfaces &surfaces, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(surfaces, delta, joinType, miterLimit)); } +Slic3r::Polygons offset(const Slic3r::SurfacesPtr &surfaces, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return to_polygons(_offset(surfaces, delta, joinType, miterLimit)); } +Slic3r::ExPolygons offset_ex(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return ClipperPaths_to_Slic3rExPolygons(_offset(expolygon, delta, joinType, miterLimit)); } +Slic3r::ExPolygons offset_ex(const Slic3r::ExPolygons &expolygons, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return ClipperPaths_to_Slic3rExPolygons(_offset(expolygons, delta, joinType, miterLimit)); } +Slic3r::ExPolygons offset_ex(const Slic3r::Surfaces &surfaces, const float delta, ClipperLib::JoinType joinType, double miterLimit) + { return ClipperPaths_to_Slic3rExPolygons(_offset(surfaces, delta, joinType, miterLimit)); } + +#ifdef CLIPPERUTILS_UNSAFE_OFFSET +Slic3r::Polygons union_safety_offset(const Slic3r::Polygons &polygons) + { return offset(polygons, ClipperSafetyOffset); } +Slic3r::ExPolygons union_safety_offset_ex(const Slic3r::Polygons &polygons) + { return offset_ex(polygons, ClipperSafetyOffset); } +#endif // CLIPPERUTILS_UNSAFE_OFFSET + +Slic3r::Polygons union_safety_offset(const Slic3r::ExPolygons &expolygons) + { return offset(expolygons, ClipperSafetyOffset); } +Slic3r::ExPolygons union_safety_offset_ex(const Slic3r::ExPolygons &expolygons) + { return offset_ex(expolygons, ClipperSafetyOffset); } + +ClipperLib::Paths _offset2(const Polygons &polygons, const float delta1, const float delta2, const ClipperLib::JoinType joinType, const double miterLimit) { - // read input - ClipperLib::Paths input = Slic3rMultiPoints_to_ClipperPaths(polygons); - -#ifdef CLIPPERUTILS_OFFSET_SCALE - // scale input - scaleClipperPolygons(input); -#endif // CLIPPERUTILS_OFFSET_SCALE - // prepare ClipperOffset object ClipperLib::ClipperOffset co; if (joinType == jtRound) { @@ -483,18 +341,13 @@ _offset2(const Polygons &polygons, const float delta1, const float delta2, } else { co.MiterLimit = miterLimit; } -#ifdef CLIPPERUTILS_OFFSET_SCALE - float delta_scaled1 = delta1 * float(CLIPPER_OFFSET_SCALE); - float delta_scaled2 = delta2 * float(CLIPPER_OFFSET_SCALE); -#else // CLIPPERUTILS_OFFSET_SCALE float delta_scaled1 = delta1; float delta_scaled2 = delta2; -#endif // CLIPPERUTILS_OFFSET_SCALE co.ShortestEdgeLength = double(std::max(std::abs(delta_scaled1), std::abs(delta_scaled2)) * CLIPPER_OFFSET_SHORTEST_EDGE_FACTOR); // perform first offset ClipperLib::Paths output1; - co.AddPaths(input, joinType, ClipperLib::etClosedPolygon); + co.AddPaths(ClipperUtils::PolygonsProvider(polygons), joinType, ClipperLib::etClosedPolygon); co.Execute(output1, delta_scaled1); // perform second offset @@ -503,106 +356,81 @@ _offset2(const Polygons &polygons, const float delta1, const float delta2, ClipperLib::Paths retval; co.Execute(retval, delta_scaled2); -#ifdef CLIPPERUTILS_OFFSET_SCALE - // unscale output - unscaleClipperPolygons(retval); -#endif // CLIPPERUTILS_OFFSET_SCALE return retval; } -Polygons -offset2(const Polygons &polygons, const float delta1, const float delta2, - const ClipperLib::JoinType joinType, const double miterLimit) +Polygons offset2(const Polygons &polygons, const float delta1, const float delta2, const ClipperLib::JoinType joinType, const double miterLimit) { - // perform offset - ClipperLib::Paths output = _offset2(polygons, delta1, delta2, joinType, miterLimit); - - // convert into ExPolygons - return ClipperPaths_to_Slic3rPolygons(output); + return to_polygons(_offset2(polygons, delta1, delta2, joinType, miterLimit)); } -ExPolygons -offset2_ex(const Polygons &polygons, const float delta1, const float delta2, - const ClipperLib::JoinType joinType, const double miterLimit) +ExPolygons offset2_ex(const Polygons &polygons, const float delta1, const float delta2, const ClipperLib::JoinType joinType, const double miterLimit) { - // perform offset - ClipperLib::Paths output = _offset2(polygons, delta1, delta2, joinType, miterLimit); - - // convert into ExPolygons - return ClipperPaths_to_Slic3rExPolygons(output); + return ClipperPaths_to_Slic3rExPolygons(_offset2(polygons, delta1, delta2, joinType, miterLimit)); } //FIXME Vojtech: This functon may likely be optimized to avoid some of the Slic3r to Clipper -// conversions and unnecessary Clipper calls. -ExPolygons offset2_ex(const ExPolygons &expolygons, const float delta1, - const float delta2, ClipperLib::JoinType joinType, double miterLimit) +// conversions and unnecessary Clipper calls. It is not that bad now as Clipper uses Slic3r's own Point / Polygon types directly. +Polygons offset2(const ExPolygons &expolygons, const float delta1, const float delta2, ClipperLib::JoinType joinType, double miterLimit) { - Polygons polys; - for (const ExPolygon &expoly : expolygons) - append(polys, - offset(offset_ex(expoly, delta1, joinType, miterLimit), - delta2, joinType, miterLimit)); - return union_ex(polys); + return offset(offset_ex(expolygons, delta1, joinType, miterLimit), delta2, joinType, miterLimit); +} +ExPolygons offset2_ex(const ExPolygons &expolygons, const float delta1, const float delta2, ClipperLib::JoinType joinType, double miterLimit) +{ + return offset_ex(offset_ex(expolygons, delta1, joinType, miterLimit), delta2, joinType, miterLimit); } -template -T _clipper_do(const ClipperLib::ClipType clipType, - TSubj && subject, - TClip && clip, - const ClipperLib::PolyFillType fillType, - const bool safety_offset_) +template +TResult _clipper_do( + const ClipperLib::ClipType clipType, + TSubj && subject, + TClip && clip, + const ClipperLib::PolyFillType fillType) { - // read input - ClipperLib::Paths input_subject = Slic3rMultiPoints_to_ClipperPaths(std::forward(subject)); - ClipperLib::Paths input_clip = Slic3rMultiPoints_to_ClipperPaths(std::forward(clip)); - - // perform safety offset - if (safety_offset_) { - if (clipType == ClipperLib::ctUnion) { - safety_offset(&input_subject); - } else { - safety_offset(&input_clip); - } - } - - // init Clipper ClipperLib::Clipper clipper; - clipper.Clear(); - - // add polygons - clipper.AddPaths(input_subject, ClipperLib::ptSubject, true); - clipper.AddPaths(input_clip, ClipperLib::ptClip, true); - - // perform operation - T retval; + clipper.AddPaths(std::forward(subject), ClipperLib::ptSubject, true); + clipper.AddPaths(std::forward(clip), ClipperLib::ptClip, true); + TResult retval; clipper.Execute(clipType, retval, fillType, fillType); return retval; } +template +TResult _clipper_do( + const ClipperLib::ClipType clipType, + TSubj && subject, + TClip && clip, + const ClipperLib::PolyFillType fillType, + const ApplySafetyOffset do_safety_offset) +{ + // Safety offset only allowed on intersection and difference. + assert(do_safety_offset == ApplySafetyOffset::No || clipType != ClipperLib::ctUnion); + return do_safety_offset == ApplySafetyOffset::Yes ? + _clipper_do(clipType, std::forward(subject), safety_offset(std::forward(clip)), fillType) : + _clipper_do(clipType, std::forward(subject), std::forward(clip), fillType); +} + // Fix of #117: A large fractal pyramid takes ages to slice // The Clipper library has difficulties processing overlapping polygons. // Namely, the function ClipperLib::JoinCommonEdges() has potentially a terrible time complexity if the output // of the operation is of the PolyTree type. -// This function implmenets a following workaround: +// This function implemenets a following workaround: // 1) Peform the Clipper operation with the output to Paths. This method handles overlaps in a reasonable time. // 2) Run Clipper Union once again to extract the PolyTree from the result of 1). -inline ClipperLib::PolyTree _clipper_do_polytree2(const ClipperLib::ClipType clipType, const Polygons &subject, - const Polygons &clip, const ClipperLib::PolyFillType fillType, const bool safety_offset_) +template +inline ClipperLib::PolyTree _clipper_do_polytree2( + const ClipperLib::ClipType clipType, + PathProvider1 &&subject, + PathProvider2 &&clip, + const ClipperLib::PolyFillType fillType) { - // read input - ClipperLib::Paths input_subject = Slic3rMultiPoints_to_ClipperPaths(subject); - ClipperLib::Paths input_clip = Slic3rMultiPoints_to_ClipperPaths(clip); - - // perform safety offset - if (safety_offset_) - safety_offset((clipType == ClipperLib::ctUnion) ? &input_subject : &input_clip); - ClipperLib::Clipper clipper; - clipper.AddPaths(input_subject, ClipperLib::ptSubject, true); - clipper.AddPaths(input_clip, ClipperLib::ptClip, true); + clipper.AddPaths(std::forward(subject), ClipperLib::ptSubject, true); + clipper.AddPaths(std::forward(clip), ClipperLib::ptClip, true); // Perform the operation with the output to input_subject. // This pass does not generate a PolyTree, which is a very expensive operation with the current Clipper library // if there are overapping edges. + ClipperLib::Paths input_subject; clipper.Execute(clipType, input_subject, fillType, fillType); // Perform an additional Union operation to generate the PolyTree ordering. clipper.Clear(); @@ -611,101 +439,188 @@ inline ClipperLib::PolyTree _clipper_do_polytree2(const ClipperLib::ClipType cli clipper.Execute(ClipperLib::ctUnion, retval, fillType, fillType); return retval; } - -ClipperLib::PolyTree _clipper_do_pl(const ClipperLib::ClipType clipType, const Polylines &subject, - const Polygons &clip, const ClipperLib::PolyFillType fillType, - const bool safety_offset_) +template +inline ClipperLib::PolyTree _clipper_do_polytree2( + const ClipperLib::ClipType clipType, + PathProvider1 &&subject, + PathProvider2 &&clip, + const ClipperLib::PolyFillType fillType, + const ApplySafetyOffset do_safety_offset) +{ + assert(do_safety_offset == ApplySafetyOffset::No || clipType != ClipperLib::ctUnion); + return do_safety_offset == ApplySafetyOffset::Yes ? + _clipper_do_polytree2(clipType, std::forward(subject), safety_offset(std::forward(clip)), fillType) : + _clipper_do_polytree2(clipType, std::forward(subject), std::forward(clip), fillType); +} + +template +static inline Polygons _clipper(ClipperLib::ClipType clipType, TSubj &&subject, TClip &&clip, ApplySafetyOffset do_safety_offset) +{ + return to_polygons(_clipper_do(clipType, std::forward(subject), std::forward(clip), ClipperLib::pftNonZero, do_safety_offset)); +} + +Slic3r::Polygons diff(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctDifference, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctDifference, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctDifference, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons intersection(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctIntersection, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons intersection(const Slic3r::ExPolygon &subject, const Slic3r::ExPolygon &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctIntersection, ClipperUtils::ExPolygonProvider(subject), ClipperUtils::ExPolygonProvider(clip), do_safety_offset); } +Slic3r::Polygons intersection(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctIntersection, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons intersection(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctIntersection, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons intersection(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctIntersection, ClipperUtils::SurfacesProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons intersection(const Slic3r::Surfaces &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper(ClipperLib::ctIntersection, ClipperUtils::SurfacesProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::Polygons union_(const Slic3r::Polygons &subject) + { return _clipper(ClipperLib::ctUnion, ClipperUtils::PolygonsProvider(subject), ClipperUtils::EmptyPathsProvider(), ApplySafetyOffset::No); } +Slic3r::Polygons union_(const Slic3r::ExPolygons &subject) + { return _clipper(ClipperLib::ctUnion, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::EmptyPathsProvider(), ApplySafetyOffset::No); } +Slic3r::Polygons union_(const Slic3r::Polygons &subject, const Slic3r::Polygons &subject2) + { return _clipper(ClipperLib::ctUnion, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(subject2), ApplySafetyOffset::No); } + +template +static ExPolygons _clipper_ex(ClipperLib::ClipType clipType, TSubject &&subject, TClip &&clip, ApplySafetyOffset do_safety_offset) + { return PolyTreeToExPolygons(_clipper_do_polytree2(clipType, std::forward(subject), std::forward(clip), ClipperLib::pftNonZero, do_safety_offset)); } + +Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::PolygonsProvider(subject), ClipperUtils::SurfacesProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::PolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygon &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::ExPolygonProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::SurfacesProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::Surfaces &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::SurfacesProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygons &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::SurfacesProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::Surfaces &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::SurfacesProvider(subject), ClipperUtils::SurfacesProvider(clip), do_safety_offset); } +Slic3r::ExPolygons diff_ex(const Slic3r::SurfacesPtr &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctDifference, ClipperUtils::SurfacesPtrProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } + +Slic3r::ExPolygons intersection_ex(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::ExPolygon &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::ExPolygonProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::Polygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::PolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::SurfacesProvider(subject), ClipperUtils::PolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::Surfaces &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::SurfacesProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::Surfaces &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::SurfacesProvider(subject), ClipperUtils::SurfacesProvider(clip), do_safety_offset); } +Slic3r::ExPolygons intersection_ex(const Slic3r::SurfacesPtr &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset) + { return _clipper_ex(ClipperLib::ctIntersection, ClipperUtils::SurfacesPtrProvider(subject), ClipperUtils::ExPolygonsProvider(clip), do_safety_offset); } +Slic3r::ExPolygons union_ex(const Slic3r::Polygons &subject) + { return _clipper_ex(ClipperLib::ctUnion, ClipperUtils::PolygonsProvider(subject), ClipperUtils::EmptyPathsProvider(), ApplySafetyOffset::No); } +Slic3r::ExPolygons union_ex(const Slic3r::ExPolygons& subject) + { return PolyTreeToExPolygons(_clipper_do_polytree2(ClipperLib::ctUnion, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::EmptyPathsProvider(), ClipperLib::pftNonZero)); } +Slic3r::ExPolygons union_ex(const Slic3r::Surfaces& subject) + { return PolyTreeToExPolygons(_clipper_do_polytree2(ClipperLib::ctUnion, ClipperUtils::SurfacesProvider(subject), ClipperUtils::EmptyPathsProvider(), ClipperLib::pftNonZero)); } + +template +Polylines _clipper_pl_open(ClipperLib::ClipType clipType, PathsProvider1 &&subject, PathsProvider2 &&clip) { - // read input - ClipperLib::Paths input_subject = Slic3rMultiPoints_to_ClipperPaths(subject); - ClipperLib::Paths input_clip = Slic3rMultiPoints_to_ClipperPaths(clip); - - // perform safety offset - if (safety_offset_) safety_offset(&input_clip); - - // init Clipper ClipperLib::Clipper clipper; - clipper.Clear(); - - // add polygons - clipper.AddPaths(input_subject, ClipperLib::ptSubject, false); - clipper.AddPaths(input_clip, ClipperLib::ptClip, true); - - // perform operation + clipper.AddPaths(std::forward(subject), ClipperLib::ptSubject, false); + clipper.AddPaths(std::forward(clip), ClipperLib::ptClip, true); ClipperLib::PolyTree retval; - clipper.Execute(clipType, retval, fillType, fillType); - return retval; + clipper.Execute(clipType, retval, ClipperLib::pftNonZero, ClipperLib::pftNonZero); + return PolyTreeToPolylines(std::move(retval)); } -Polygons _clipper(ClipperLib::ClipType clipType, const Polygons &subject, const Polygons &clip, bool safety_offset_) +// If the split_at_first_point() call above happens to split the polygon inside the clipping area +// we would get two consecutive polylines instead of a single one, so we go through them in order +// to recombine continuous polylines. +static void _clipper_pl_recombine(Polylines &polylines) { - return ClipperPaths_to_Slic3rPolygons(_clipper_do(clipType, subject, clip, ClipperLib::pftNonZero, safety_offset_)); -} - -ExPolygons _clipper_ex(ClipperLib::ClipType clipType, const Polygons &subject, const Polygons &clip, bool safety_offset_) -{ - ClipperLib::PolyTree polytree = _clipper_do_polytree2(clipType, subject, clip, ClipperLib::pftNonZero, safety_offset_); - return PolyTreeToExPolygons(polytree); -} - -Polylines _clipper_pl(ClipperLib::ClipType clipType, const Polylines &subject, const Polygons &clip, bool safety_offset_) -{ - ClipperLib::Paths output; - ClipperLib::PolyTreeToPaths(_clipper_do_pl(clipType, subject, clip, ClipperLib::pftNonZero, safety_offset_), output); - return ClipperPaths_to_Slic3rPolylines(output); -} - -Polylines _clipper_pl(ClipperLib::ClipType clipType, const Polygons &subject, const Polygons &clip, bool safety_offset_) -{ - // transform input polygons into polylines - Polylines polylines; - polylines.reserve(subject.size()); - for (Polygons::const_iterator polygon = subject.begin(); polygon != subject.end(); ++polygon) - polylines.emplace_back(polygon->operator Polyline()); // implicit call to split_at_first_point() - - // perform clipping - Polylines retval = _clipper_pl(clipType, polylines, clip, safety_offset_); - - /* If the split_at_first_point() call above happens to split the polygon inside the clipping area - we would get two consecutive polylines instead of a single one, so we go through them in order - to recombine continuous polylines. */ - for (size_t i = 0; i < retval.size(); ++i) { - for (size_t j = i+1; j < retval.size(); ++j) { - if (retval[i].points.back() == retval[j].points.front()) { + for (size_t i = 0; i < polylines.size(); ++i) { + for (size_t j = i+1; j < polylines.size(); ++j) { + if (polylines[i].points.back() == polylines[j].points.front()) { /* If last point of i coincides with first point of j, append points of j to i and delete j */ - retval[i].points.insert(retval[i].points.end(), retval[j].points.begin()+1, retval[j].points.end()); - retval.erase(retval.begin() + j); + polylines[i].points.insert(polylines[i].points.end(), polylines[j].points.begin()+1, polylines[j].points.end()); + polylines.erase(polylines.begin() + j); --j; - } else if (retval[i].points.front() == retval[j].points.back()) { + } else if (polylines[i].points.front() == polylines[j].points.back()) { /* If first point of i coincides with last point of j, prepend points of j to i and delete j */ - retval[i].points.insert(retval[i].points.begin(), retval[j].points.begin(), retval[j].points.end()-1); - retval.erase(retval.begin() + j); + polylines[i].points.insert(polylines[i].points.begin(), polylines[j].points.begin(), polylines[j].points.end()-1); + polylines.erase(polylines.begin() + j); --j; - } else if (retval[i].points.front() == retval[j].points.front()) { + } else if (polylines[i].points.front() == polylines[j].points.front()) { /* Since Clipper does not preserve orientation of polylines, also check the case when first point of i coincides with first point of j. */ - retval[j].reverse(); - retval[i].points.insert(retval[i].points.begin(), retval[j].points.begin(), retval[j].points.end()-1); - retval.erase(retval.begin() + j); + polylines[j].reverse(); + polylines[i].points.insert(polylines[i].points.begin(), polylines[j].points.begin(), polylines[j].points.end()-1); + polylines.erase(polylines.begin() + j); --j; - } else if (retval[i].points.back() == retval[j].points.back()) { + } else if (polylines[i].points.back() == polylines[j].points.back()) { /* Since Clipper does not preserve orientation of polylines, also check the case when last point of i coincides with last point of j. */ - retval[j].reverse(); - retval[i].points.insert(retval[i].points.end(), retval[j].points.begin()+1, retval[j].points.end()); - retval.erase(retval.begin() + j); + polylines[j].reverse(); + polylines[i].points.insert(polylines[i].points.end(), polylines[j].points.begin()+1, polylines[j].points.end()); + polylines.erase(polylines.begin() + j); --j; } } } +} + +template +Polylines _clipper_pl_closed(ClipperLib::ClipType clipType, PathProvider1 &&subject, PathProvider2 &&clip) +{ + // Transform input polygons into open paths. + ClipperLib::Paths paths; + paths.reserve(subject.size()); + for (const Points &poly : subject) { + // Emplace polygon, duplicate the 1st point. + paths.push_back({}); + ClipperLib::Path &path = paths.back(); + path.reserve(poly.size() + 1); + path = poly; + path.emplace_back(poly.front()); + } + // perform clipping + Polylines retval = _clipper_pl_open(clipType, paths, std::forward(clip)); + _clipper_pl_recombine(retval); return retval; } -Lines -_clipper_ln(ClipperLib::ClipType clipType, const Lines &subject, const Polygons &clip, - bool safety_offset_) +Slic3r::Polylines diff_pl(const Slic3r::Polylines &subject, const Slic3r::Polygons &clip) + { return _clipper_pl_open(ClipperLib::ctDifference, ClipperUtils::PolylinesProvider(subject), ClipperUtils::PolygonsProvider(clip)); } +Slic3r::Polylines diff_pl(const Slic3r::Polylines &subject, const Slic3r::ExPolygon &clip) + { return _clipper_pl_open(ClipperLib::ctDifference, ClipperUtils::PolylinesProvider(subject), ClipperUtils::ExPolygonProvider(clip)); } +Slic3r::Polylines diff_pl(const Slic3r::Polylines &subject, const Slic3r::ExPolygons &clip) + { return _clipper_pl_open(ClipperLib::ctDifference, ClipperUtils::PolylinesProvider(subject), ClipperUtils::ExPolygonsProvider(clip)); } +Slic3r::Polylines diff_pl(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip) + { return _clipper_pl_closed(ClipperLib::ctDifference, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip)); } +Slic3r::Polylines intersection_pl(const Slic3r::Polylines &subject, const Slic3r::Polygons &clip) + { return _clipper_pl_open(ClipperLib::ctIntersection, ClipperUtils::PolylinesProvider(subject), ClipperUtils::PolygonsProvider(clip)); } +Slic3r::Polylines intersection_pl(const Slic3r::Polylines &subject, const Slic3r::ExPolygons &clip) + { return _clipper_pl_open(ClipperLib::ctIntersection, ClipperUtils::PolylinesProvider(subject), ClipperUtils::ExPolygonsProvider(clip)); } +Slic3r::Polylines intersection_pl(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip) + { return _clipper_pl_closed(ClipperLib::ctIntersection, ClipperUtils::PolygonsProvider(subject), ClipperUtils::PolygonsProvider(clip)); } + +Lines _clipper_ln(ClipperLib::ClipType clipType, const Lines &subject, const Polygons &clip) { // convert Lines to Polylines Polylines polylines; @@ -714,7 +629,7 @@ _clipper_ln(ClipperLib::ClipType clipType, const Lines &subject, const Polygons polylines.emplace_back(Polyline(line.a, line.b)); // perform operation - polylines = _clipper_pl(clipType, polylines, clip, safety_offset_); + polylines = _clipper_pl_open(clipType, ClipperUtils::PolylinesProvider(polylines), ClipperUtils::PolygonsProvider(clip)); // convert Polylines to Lines Lines retval; @@ -723,24 +638,14 @@ _clipper_ln(ClipperLib::ClipType clipType, const Lines &subject, const Polygons return retval; } -ClipperLib::PolyTree union_pt(const Polygons &subject, bool safety_offset_) +ClipperLib::PolyTree union_pt(const Polygons &subject) { - return _clipper_do(ClipperLib::ctUnion, subject, Polygons(), ClipperLib::pftEvenOdd, safety_offset_); + return _clipper_do(ClipperLib::ctUnion, ClipperUtils::PolygonsProvider(subject), ClipperUtils::EmptyPathsProvider(), ClipperLib::pftEvenOdd); } -ClipperLib::PolyTree union_pt(const ExPolygons &subject, bool safety_offset_) +ClipperLib::PolyTree union_pt(const ExPolygons &subject) { - return _clipper_do(ClipperLib::ctUnion, subject, Polygons(), ClipperLib::pftEvenOdd, safety_offset_); -} - -ClipperLib::PolyTree union_pt(Polygons &&subject, bool safety_offset_) -{ - return _clipper_do(ClipperLib::ctUnion, std::move(subject), Polygons(), ClipperLib::pftEvenOdd, safety_offset_); -} - -ClipperLib::PolyTree union_pt(ExPolygons &&subject, bool safety_offset_) -{ - return _clipper_do(ClipperLib::ctUnion, std::move(subject), Polygons(), ClipperLib::pftEvenOdd, safety_offset_); + return _clipper_do(ClipperLib::ctUnion, ClipperUtils::ExPolygonsProvider(subject), ClipperUtils::EmptyPathsProvider(), ClipperLib::pftEvenOdd); } // Simple spatial ordering of Polynodes @@ -752,7 +657,7 @@ ClipperLib::PolyNodes order_nodes(const ClipperLib::PolyNodes &nodes) for (const ClipperLib::PolyNode *node : nodes) ordering_points.emplace_back( - Point(node->Contour.front().X, node->Contour.front().Y)); + Point(node->Contour.front().x(), node->Contour.front().y())); // perform the ordering ClipperLib::PolyNodes ordered_nodes = @@ -766,7 +671,7 @@ static void traverse_pt_noholes(const ClipperLib::PolyNodes &nodes, Polygons *ou foreach_node(nodes, [&out](const ClipperLib::PolyNode *node) { traverse_pt_noholes(node->Childs, out); - out->emplace_back(ClipperPath_to_Slic3rPolygon(node->Contour)); + out->emplace_back(node->Contour); if (node->IsHole()) out->back().reverse(); // ccw }); } @@ -777,12 +682,12 @@ static void traverse_pt_outside_in(const ClipperLib::PolyNodes &nodes, Polygons Points ordering_points; ordering_points.reserve(nodes.size()); for (const ClipperLib::PolyNode *node : nodes) - ordering_points.emplace_back(node->Contour.front().X, node->Contour.front().Y); + ordering_points.emplace_back(node->Contour.front().x(), node->Contour.front().y()); // Perform the ordering, push results recursively. //FIXME pass the last point to chain_clipper_polynodes? for (const ClipperLib::PolyNode *node : chain_clipper_polynodes(ordering_points, nodes)) { - retval->emplace_back(ClipperPath_to_Slic3rPolygon(node->Contour)); + retval->emplace_back(node->Contour); if (node->IsHole()) // Orient a hole, which is clockwise oriented, to CCW. retval->back().reverse(); @@ -791,9 +696,9 @@ static void traverse_pt_outside_in(const ClipperLib::PolyNodes &nodes, Polygons } } -Polygons union_pt_chained_outside_in(const Polygons &subject, bool safety_offset_) +Polygons union_pt_chained_outside_in(const Polygons &subject) { - ClipperLib::PolyTree polytree = union_pt(subject, safety_offset_); + ClipperLib::PolyTree polytree = union_pt(subject); Polygons retval; traverse_pt_outside_in(polytree.Childs, &retval); @@ -802,22 +707,19 @@ Polygons union_pt_chained_outside_in(const Polygons &subject, bool safety_offset Polygons simplify_polygons(const Polygons &subject, bool preserve_collinear) { - // convert into Clipper polygons - ClipperLib::Paths input_subject = Slic3rMultiPoints_to_ClipperPaths(subject); - ClipperLib::Paths output; if (preserve_collinear) { ClipperLib::Clipper c; c.PreserveCollinear(true); c.StrictlySimple(true); - c.AddPaths(input_subject, ClipperLib::ptSubject, true); + c.AddPaths(ClipperUtils::PolygonsProvider(subject), ClipperLib::ptSubject, true); c.Execute(ClipperLib::ctUnion, output, ClipperLib::pftNonZero, ClipperLib::pftNonZero); } else { - ClipperLib::SimplifyPolygons(input_subject, output, ClipperLib::pftNonZero); + output = ClipperLib::SimplifyPolygons(ClipperUtils::PolygonsProvider(subject), ClipperLib::pftNonZero); } // convert into Slic3r polygons - return ClipperPaths_to_Slic3rPolygons(output); + return to_polygons(std::move(output)); } ExPolygons simplify_polygons_ex(const Polygons &subject, bool preserve_collinear) @@ -825,76 +727,15 @@ ExPolygons simplify_polygons_ex(const Polygons &subject, bool preserve_collinear if (! preserve_collinear) return union_ex(simplify_polygons(subject, false)); - // convert into Clipper polygons - ClipperLib::Paths input_subject = Slic3rMultiPoints_to_ClipperPaths(subject); - - ClipperLib::PolyTree polytree; - + ClipperLib::PolyTree polytree; ClipperLib::Clipper c; c.PreserveCollinear(true); c.StrictlySimple(true); - c.AddPaths(input_subject, ClipperLib::ptSubject, true); + c.AddPaths(ClipperUtils::PolygonsProvider(subject), ClipperLib::ptSubject, true); c.Execute(ClipperLib::ctUnion, polytree, ClipperLib::pftNonZero, ClipperLib::pftNonZero); // convert into ExPolygons - return PolyTreeToExPolygons(polytree); -} - -void safety_offset(ClipperLib::Paths* paths) -{ - CLIPPERUTILS_PROFILE_FUNC(); - -#ifdef CLIPPERUTILS_OFFSET_SCALE - // scale input - scaleClipperPolygons(*paths); -#endif // CLIPPERUTILS_OFFSET_SCALE - - // perform offset (delta = scale 1e-05) - ClipperLib::ClipperOffset co; -#ifdef CLIPPER_UTILS_DEBUG - if (clipper_export_enabled) { - static int iRun = 0; - export_clipper_input_polygons_bin(debug_out_path("safety_offset-polygons-%d", ++iRun).c_str(), *paths, ClipperLib::Paths()); - } -#endif /* CLIPPER_UTILS_DEBUG */ - ClipperLib::Paths out; - for (size_t i = 0; i < paths->size(); ++ i) { - ClipperLib::Path &path = (*paths)[i]; - co.Clear(); - co.MiterLimit = 2; - bool ccw = ClipperLib::Orientation(path); - if (! ccw) - std::reverse(path.begin(), path.end()); - { - CLIPPERUTILS_PROFILE_BLOCK(safety_offset_AddPaths); - co.AddPath((*paths)[i], ClipperLib::jtMiter, ClipperLib::etClosedPolygon); - } - { - CLIPPERUTILS_PROFILE_BLOCK(safety_offset_Execute); - // offset outside by 10um - ClipperLib::Paths out_this; -#ifdef CLIPPERUTILS_OFFSET_SCALE - co.Execute(out_this, ccw ? 10.f * float(CLIPPER_OFFSET_SCALE) : -10.f * float(CLIPPER_OFFSET_SCALE)); -#else // CLIPPERUTILS_OFFSET_SCALE - co.Execute(out_this, ccw ? 10.f : -10.f); -#endif // CLIPPERUTILS_OFFSET_SCALE - if (! ccw) { - // Reverse the resulting contours once again. - for (ClipperLib::Paths::iterator it = out_this.begin(); it != out_this.end(); ++ it) - std::reverse(it->begin(), it->end()); - } - if (out.empty()) - out = std::move(out_this); - else - std::move(std::begin(out_this), std::end(out_this), std::back_inserter(out)); - } - } - *paths = std::move(out); - -#ifdef CLIPPERUTILS_OFFSET_SCALE - // unscale output - unscaleClipperPolygons(*paths); -#endif // CLIPPERUTILS_OFFSET_SCALE + return PolyTreeToExPolygons(std::move(polytree)); } Polygons top_level_islands(const Slic3r::Polygons &polygons) @@ -903,14 +744,14 @@ Polygons top_level_islands(const Slic3r::Polygons &polygons) ClipperLib::Clipper clipper; clipper.Clear(); // perform union - clipper.AddPaths(Slic3rMultiPoints_to_ClipperPaths(polygons), ClipperLib::ptSubject, true); + clipper.AddPaths(ClipperUtils::PolygonsProvider(polygons), ClipperLib::ptSubject, true); ClipperLib::PolyTree polytree; clipper.Execute(ClipperLib::ctUnion, polytree, ClipperLib::pftEvenOdd, ClipperLib::pftEvenOdd); // Convert only the top level islands to the output. Polygons out; out.reserve(polytree.ChildCount()); for (int i = 0; i < polytree.ChildCount(); ++i) - out.emplace_back(ClipperPath_to_Slic3rPolygon(polytree.Childs[i]->Contour)); + out.emplace_back(std::move(polytree.Childs[i]->Contour)); return out; } @@ -988,9 +829,6 @@ ClipperLib::Path mittered_offset_path_scaled(const Points &contour, const std::v // Add a new point to the output, scale by CLIPPER_OFFSET_SCALE and round to ClipperLib::cInt. auto add_offset_point = [&out](Vec2d pt) { -#ifdef CLIPPERUTILS_OFFSET_SCALE - pt *= double(CLIPPER_OFFSET_SCALE); -#endif // CLIPPERUTILS_OFFSET_SCALE pt += Vec2d(0.5 - (pt.x() < 0), 0.5 - (pt.y() < 0)); out.emplace_back(ClipperLib::cInt(pt.x()), ClipperLib::cInt(pt.y())); }; @@ -1086,7 +924,7 @@ ClipperLib::Path mittered_offset_path_scaled(const Points &contour, const std::v { ClipperLib::Path polytmp(out); unscaleClipperPolygon(polytmp); - Slic3r::Polygon offsetted = ClipperPath_to_Slic3rPolygon(polytmp); + Slic3r::Polygon offsetted(std::move(polytmp)); BoundingBox bbox = get_extents(contour); bbox.merge(get_extents(offsetted)); static int iRun = 0; @@ -1140,11 +978,7 @@ Polygons variable_offset_inner(const ExPolygon &expoly, const std::vector> &deltas, double miter_limit) @@ -1186,11 +1020,7 @@ for (const std::vector& ds : deltas) clipper.Execute(ClipperLib::ctDifference, output, ClipperLib::pftNonZero, ClipperLib::pftNonZero); } -#ifdef CLIPPERUTILS_OFFSET_SCALE - // 4) Unscale the output. - unscaleClipperPolygons(output); -#endif // CLIPPERUTILS_OFFSET_SCALE - return ClipperPaths_to_Slic3rPolygons(output); + return to_polygons(std::move(output)); } ExPolygons variable_offset_outer_ex(const ExPolygon &expoly, const std::vector> &deltas, double miter_limit) @@ -1221,24 +1051,18 @@ for (const std::vector& ds : deltas) #endif /* NDEBUG */ // 3) Subtract holes from the contours. -#ifdef CLIPPERUTILS_OFFSET_SCALE - unscaleClipperPolygons(contours); -#endif // CLIPPERUTILS_OFFSET_SCALE ExPolygons output; if (holes.empty()) { output.reserve(contours.size()); for (ClipperLib::Path &path : contours) - output.emplace_back(ClipperPath_to_Slic3rPolygon(path)); + output.emplace_back(std::move(path)); } else { ClipperLib::Clipper clipper; -#ifdef CLIPPERUTILS_OFFSET_SCALE - unscaleClipperPolygons(holes); -#endif // CLIPPERUTILS_OFFSET_SCALE clipper.AddPaths(contours, ClipperLib::ptSubject, true); clipper.AddPaths(holes, ClipperLib::ptClip, true); ClipperLib::PolyTree polytree; clipper.Execute(ClipperLib::ctDifference, polytree, ClipperLib::pftNonZero, ClipperLib::pftNonZero); - output = PolyTreeToExPolygons(polytree); + output = PolyTreeToExPolygons(std::move(polytree)); } return output; @@ -1273,24 +1097,18 @@ ExPolygons variable_offset_inner_ex(const ExPolygon &expoly, const std::vectorcbegin(); } + iterator cend() const { return iterator(s_end); } + iterator end() const { return this->cend(); } + size_t size() const { return 1; } + + private: + const Points &m_points; + static Points s_end; + }; + + template + class MultiPointsProvider { + public: + MultiPointsProvider(const std::vector &multipoints) : m_multipoints(multipoints) {} + + struct iterator : public PathsProviderIteratorBase { + public: + explicit iterator(typename std::vector::const_iterator it) : m_it(it) {} + const Points& operator*() const { return m_it->points; } + bool operator==(const iterator &rhs) const { return m_it == rhs.m_it; } + bool operator!=(const iterator &rhs) const { return !(*this == rhs); } + const Points& operator++(int) { return (m_it ++)->points; } + iterator& operator++() { ++ m_it; return *this; } + private: + typename std::vector::const_iterator m_it; + }; + + iterator cbegin() const { return iterator(m_multipoints.begin()); } + iterator begin() const { return this->cbegin(); } + iterator cend() const { return iterator(m_multipoints.end()); } + iterator end() const { return this->cend(); } + size_t size() const { return m_multipoints.size(); } + + private: + const std::vector &m_multipoints; + }; + + using PolygonsProvider = MultiPointsProvider; + using PolylinesProvider = MultiPointsProvider; + + struct ExPolygonProvider { + ExPolygonProvider(const ExPolygon &expoly) : m_expoly(expoly) {} + + struct iterator : public PathsProviderIteratorBase { + public: + explicit iterator(const ExPolygon &expoly, int idx) : m_expoly(expoly), m_idx(idx) {} + const Points& operator*() const { return (m_idx == 0) ? m_expoly.contour.points : m_expoly.holes[m_idx - 1].points; } + bool operator==(const iterator &rhs) const { assert(m_expoly == rhs.m_expoly); return m_idx == rhs.m_idx; } + bool operator!=(const iterator &rhs) const { return !(*this == rhs); } + const Points& operator++(int) { const Points &out = **this; ++ m_idx; return out; } + iterator& operator++() { ++ m_idx; return *this; } + private: + const ExPolygon &m_expoly; + int m_idx; + }; + + iterator cbegin() const { return iterator(m_expoly, 0); } + iterator begin() const { return this->cbegin(); } + iterator cend() const { return iterator(m_expoly, m_expoly.holes.size() + 1); } + iterator end() const { return this->cend(); } + size_t size() const { return m_expoly.holes.size() + 1; } + + private: + const ExPolygon &m_expoly; + }; + + struct ExPolygonsProvider { + ExPolygonsProvider(const ExPolygons &expolygons) : m_expolygons(expolygons) { + m_size = 0; + for (const ExPolygon &expoly : expolygons) + m_size += expoly.holes.size() + 1; + } + + struct iterator : public PathsProviderIteratorBase { + public: + explicit iterator(ExPolygons::const_iterator it) : m_it_expolygon(it), m_idx_contour(0) {} + const Points& operator*() const { return (m_idx_contour == 0) ? m_it_expolygon->contour.points : m_it_expolygon->holes[m_idx_contour - 1].points; } + bool operator==(const iterator &rhs) const { return m_it_expolygon == rhs.m_it_expolygon && m_idx_contour == rhs.m_idx_contour; } + bool operator!=(const iterator &rhs) const { return !(*this == rhs); } + iterator& operator++() { + if (++ m_idx_contour == m_it_expolygon->holes.size() + 1) { + ++ m_it_expolygon; + m_idx_contour = 0; + } + return *this; + } + const Points& operator++(int) { + const Points &out = **this; + ++ (*this); + return out; + } + private: + ExPolygons::const_iterator m_it_expolygon; + size_t m_idx_contour; + }; + + iterator cbegin() const { return iterator(m_expolygons.cbegin()); } + iterator begin() const { return this->cbegin(); } + iterator cend() const { return iterator(m_expolygons.cend()); } + iterator end() const { return this->cend(); } + size_t size() const { return m_size; } + + private: + const ExPolygons &m_expolygons; + size_t m_size; + }; + + struct SurfacesProvider { + SurfacesProvider(const Surfaces &surfaces) : m_surfaces(surfaces) { + m_size = 0; + for (const Surface &surface : surfaces) + m_size += surface.expolygon.holes.size() + 1; + } + + struct iterator : public PathsProviderIteratorBase { + public: + explicit iterator(Surfaces::const_iterator it) : m_it_surface(it), m_idx_contour(0) {} + const Points& operator*() const { return (m_idx_contour == 0) ? m_it_surface->expolygon.contour.points : m_it_surface->expolygon.holes[m_idx_contour - 1].points; } + bool operator==(const iterator &rhs) const { return m_it_surface == rhs.m_it_surface && m_idx_contour == rhs.m_idx_contour; } + bool operator!=(const iterator &rhs) const { return !(*this == rhs); } + iterator& operator++() { + if (++ m_idx_contour == m_it_surface->expolygon.holes.size() + 1) { + ++ m_it_surface; + m_idx_contour = 0; + } + return *this; + } + const Points& operator++(int) { + const Points &out = **this; + ++ (*this); + return out; + } + private: + Surfaces::const_iterator m_it_surface; + size_t m_idx_contour; + }; + + iterator cbegin() const { return iterator(m_surfaces.cbegin()); } + iterator begin() const { return this->cbegin(); } + iterator cend() const { return iterator(m_surfaces.cend()); } + iterator end() const { return this->cend(); } + size_t size() const { return m_size; } + + private: + const Surfaces &m_surfaces; + size_t m_size; + }; + + struct SurfacesPtrProvider { + SurfacesPtrProvider(const SurfacesPtr &surfaces) : m_surfaces(surfaces) { + m_size = 0; + for (const Surface *surface : surfaces) + m_size += surface->expolygon.holes.size() + 1; + } + + struct iterator : public PathsProviderIteratorBase { + public: + explicit iterator(SurfacesPtr::const_iterator it) : m_it_surface(it), m_idx_contour(0) {} + const Points& operator*() const { return (m_idx_contour == 0) ? (*m_it_surface)->expolygon.contour.points : (*m_it_surface)->expolygon.holes[m_idx_contour - 1].points; } + bool operator==(const iterator &rhs) const { return m_it_surface == rhs.m_it_surface && m_idx_contour == rhs.m_idx_contour; } + bool operator!=(const iterator &rhs) const { return !(*this == rhs); } + iterator& operator++() { + if (++ m_idx_contour == (*m_it_surface)->expolygon.holes.size() + 1) { + ++ m_it_surface; + m_idx_contour = 0; + } + return *this; + } + const Points& operator++(int) { + const Points &out = **this; + ++ (*this); + return out; + } + private: + SurfacesPtr::const_iterator m_it_surface; + size_t m_idx_contour; + }; + + iterator cbegin() const { return iterator(m_surfaces.cbegin()); } + iterator begin() const { return this->cbegin(); } + iterator cend() const { return iterator(m_surfaces.cend()); } + iterator end() const { return this->cend(); } + size_t size() const { return m_size; } + + private: + const SurfacesPtr &m_surfaces; + size_t m_size; + }; +} + +ExPolygons ClipperPaths_to_Slic3rExPolygons(const ClipperLib::Paths &input); // offset Polygons -ClipperLib::Paths _offset(ClipperLib::Path &&input, ClipperLib::EndType endType, const float delta, ClipperLib::JoinType joinType, double miterLimit); -ClipperLib::Paths _offset(ClipperLib::Paths &&input, ClipperLib::EndType endType, const float delta, ClipperLib::JoinType joinType, double miterLimit); -inline Slic3r::Polygons offset(const Slic3r::Polygon &polygon, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rPolygons(_offset(Slic3rMultiPoint_to_ClipperPath(polygon), ClipperLib::etClosedPolygon, delta, joinType, miterLimit)); } - -#ifdef CLIPPERUTILS_UNSAFE_OFFSET -inline Slic3r::Polygons offset(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rPolygons(_offset(Slic3rMultiPoints_to_ClipperPaths(polygons), ClipperLib::etClosedPolygon, delta, joinType, miterLimit)); } -#endif // CLIPPERUTILS_UNSAFE_OFFSET +Slic3r::Polygons offset(const Slic3r::Polygon &polygon, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); // offset Polylines -inline Slic3r::Polygons offset(const Slic3r::Polyline &polyline, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtSquare, double miterLimit = 3) - { return ClipperPaths_to_Slic3rPolygons(_offset(Slic3rMultiPoint_to_ClipperPath(polyline), ClipperLib::etOpenButt, delta, joinType, miterLimit)); } -inline Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtSquare, double miterLimit = 3) - { return ClipperPaths_to_Slic3rPolygons(_offset(Slic3rMultiPoints_to_ClipperPaths(polylines), ClipperLib::etOpenButt, delta, joinType, miterLimit)); } +Slic3r::Polygons offset(const Slic3r::Polyline &polyline, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtSquare, double miterLimit = 3); +Slic3r::Polygons offset(const Slic3r::Polylines &polylines, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtSquare, double miterLimit = 3); +Slic3r::Polygons offset(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::Polygons offset(const Slic3r::ExPolygons &expolygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::Polygons offset(const Slic3r::Surfaces &surfaces, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::Polygons offset(const Slic3r::SurfacesPtr &surfaces, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::ExPolygons offset_ex(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::ExPolygons offset_ex(const Slic3r::ExPolygons &expolygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::ExPolygons offset_ex(const Slic3r::Surfaces &surfaces, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::Polygons union_safety_offset(const Slic3r::ExPolygons &expolygons); +Slic3r::ExPolygons union_safety_offset_ex(const Slic3r::ExPolygons &expolygons); -// offset expolygons and surfaces -ClipperLib::Paths _offset(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType, double miterLimit); -ClipperLib::Paths _offset(const Slic3r::ExPolygons &expolygons, const float delta, ClipperLib::JoinType joinType, double miterLimit); -inline Slic3r::Polygons offset(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rPolygons(_offset(expolygon, delta, joinType, miterLimit)); } -inline Slic3r::Polygons offset(const Slic3r::ExPolygons &expolygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rPolygons(_offset(expolygons, delta, joinType, miterLimit)); } -inline Slic3r::ExPolygons offset_ex(const Slic3r::Polygon &polygon, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rExPolygons(_offset(Slic3rMultiPoint_to_ClipperPath(polygon), ClipperLib::etClosedPolygon, delta, joinType, miterLimit)); } +Slic3r::Polygons offset2(const Slic3r::ExPolygons &expolygons, const float delta1, const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::ExPolygons offset2_ex(const Slic3r::ExPolygons &expolygons, const float delta1, const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); #ifdef CLIPPERUTILS_UNSAFE_OFFSET -inline Slic3r::ExPolygons offset_ex(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rExPolygons(_offset(Slic3rMultiPoints_to_ClipperPaths(polygons), ClipperLib::etClosedPolygon, delta, joinType, miterLimit)); } +Slic3r::Polygons offset(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::ExPolygons offset_ex(const Slic3r::Polygons &polygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +ClipperLib::Paths _offset2(const Slic3r::Polygons &polygons, const float delta1, const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::Polygons offset2(const Slic3r::Polygons &polygons, const float delta1, const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::ExPolygons offset2_ex(const Slic3r::Polygons &polygons, const float delta1, const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3); +Slic3r::Polygons union_safety_offset(const Slic3r::Polygons &expolygons); +Slic3r::ExPolygons union_safety_offset_ex(const Slic3r::Polygons &polygons); #endif // CLIPPERUTILS_UNSAFE_OFFSET -inline Slic3r::ExPolygons offset_ex(const Slic3r::ExPolygon &expolygon, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rExPolygons(_offset(expolygon, delta, joinType, miterLimit)); } -inline Slic3r::ExPolygons offset_ex(const Slic3r::ExPolygons &expolygons, const float delta, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miterLimit = 3) - { return ClipperPaths_to_Slic3rExPolygons(_offset(expolygons, delta, joinType, miterLimit)); } +Slic3r::Lines _clipper_ln(ClipperLib::ClipType clipType, const Slic3r::Lines &subject, const Slic3r::Polygons &clip); -#ifdef CLIPPERUTILS_UNSAFE_OFFSET -ClipperLib::Paths _offset2(const Slic3r::Polygons &polygons, const float delta1, - const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, - double miterLimit = 3); -Slic3r::Polygons offset2(const Slic3r::Polygons &polygons, const float delta1, - const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, - double miterLimit = 3); -Slic3r::ExPolygons offset2_ex(const Slic3r::Polygons &polygons, const float delta1, - const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, - double miterLimit = 3); -#endif // CLIPPERUTILS_UNSAFE_OFFSET +// Safety offset is applied to the clipping polygons only. +Slic3r::Polygons diff(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polygons diff(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::Polygons &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::Polygon &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygon &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::Surfaces &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::ExPolygons &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::Surfaces &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons diff_ex(const Slic3r::SurfacesPtr &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polylines diff_pl(const Slic3r::Polylines &subject, const Slic3r::Polygons &clip); +Slic3r::Polylines diff_pl(const Slic3r::Polylines &subject, const Slic3r::ExPolygon &clip); +Slic3r::Polylines diff_pl(const Slic3r::Polylines &subject, const Slic3r::ExPolygons &clip); +Slic3r::Polylines diff_pl(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip); -Slic3r::ExPolygons offset2_ex(const Slic3r::ExPolygons &expolygons, const float delta1, - const float delta2, ClipperLib::JoinType joinType = ClipperLib::jtMiter, - double miterLimit = 3); - -Slic3r::Polygons _clipper(ClipperLib::ClipType clipType, - const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false); -Slic3r::ExPolygons _clipper_ex(ClipperLib::ClipType clipType, - const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false); -Slic3r::Polylines _clipper_pl(ClipperLib::ClipType clipType, - const Slic3r::Polylines &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false); -Slic3r::Polylines _clipper_pl(ClipperLib::ClipType clipType, - const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false); -Slic3r::Lines _clipper_ln(ClipperLib::ClipType clipType, - const Slic3r::Lines &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false); - -// diff -inline Slic3r::Polygons -diff(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) +inline Slic3r::Lines diff_ln(const Slic3r::Lines &subject, const Slic3r::Polygons &clip) { - return _clipper(ClipperLib::ctDifference, subject, clip, safety_offset_); + return _clipper_ln(ClipperLib::ctDifference, subject, clip); } -inline Slic3r::ExPolygons -diff_ex(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) +// Safety offset is applied to the clipping polygons only. +Slic3r::Polygons intersection(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polygons intersection(const Slic3r::ExPolygon &subject, const Slic3r::ExPolygon &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polygons intersection(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polygons intersection(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polygons intersection(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polygons intersection(const Slic3r::Surfaces &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::ExPolygon &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::Polygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::ExPolygons &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::Surfaces &subject, const Slic3r::Polygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::Surfaces &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::Surfaces &subject, const Slic3r::Surfaces &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::ExPolygons intersection_ex(const Slic3r::SurfacesPtr &subject, const Slic3r::ExPolygons &clip, ApplySafetyOffset do_safety_offset = ApplySafetyOffset::No); +Slic3r::Polylines intersection_pl(const Slic3r::Polylines &subject, const Slic3r::Polygons &clip); +Slic3r::Polylines intersection_pl(const Slic3r::Polylines &subject, const Slic3r::ExPolygons &clip); +Slic3r::Polylines intersection_pl(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip); + +inline Slic3r::Lines intersection_ln(const Slic3r::Lines &subject, const Slic3r::Polygons &clip) { - return _clipper_ex(ClipperLib::ctDifference, subject, clip, safety_offset_); + return _clipper_ln(ClipperLib::ctIntersection, subject, clip); } -inline Slic3r::ExPolygons -diff_ex(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, bool safety_offset_ = false) -{ - return _clipper_ex(ClipperLib::ctDifference, to_polygons(subject), to_polygons(clip), safety_offset_); -} - -inline Slic3r::Polygons -diff(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, bool safety_offset_ = false) -{ - return _clipper(ClipperLib::ctDifference, to_polygons(subject), to_polygons(clip), safety_offset_); -} - -inline Slic3r::Polylines -diff_pl(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper_pl(ClipperLib::ctDifference, subject, clip, safety_offset_); -} - -inline Slic3r::Polylines -diff_pl(const Slic3r::Polylines &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper_pl(ClipperLib::ctDifference, subject, clip, safety_offset_); -} - -inline Slic3r::Lines -diff_ln(const Slic3r::Lines &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper_ln(ClipperLib::ctDifference, subject, clip, safety_offset_); -} - -// intersection -inline Slic3r::Polygons -intersection(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper(ClipperLib::ctIntersection, subject, clip, safety_offset_); -} - -inline Slic3r::ExPolygons -intersection_ex(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper_ex(ClipperLib::ctIntersection, subject, clip, safety_offset_); -} - -inline Slic3r::ExPolygons -intersection_ex(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, bool safety_offset_ = false) -{ - return _clipper_ex(ClipperLib::ctIntersection, to_polygons(subject), to_polygons(clip), safety_offset_); -} - -inline Slic3r::Polygons -intersection(const Slic3r::ExPolygons &subject, const Slic3r::ExPolygons &clip, bool safety_offset_ = false) -{ - return _clipper(ClipperLib::ctIntersection, to_polygons(subject), to_polygons(clip), safety_offset_); -} - -inline Slic3r::Polylines -intersection_pl(const Slic3r::Polygons &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper_pl(ClipperLib::ctIntersection, subject, clip, safety_offset_); -} - -inline Slic3r::Polylines -intersection_pl(const Slic3r::Polylines &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper_pl(ClipperLib::ctIntersection, subject, clip, safety_offset_); -} - -inline Slic3r::Lines intersection_ln(const Slic3r::Lines &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) -{ - return _clipper_ln(ClipperLib::ctIntersection, subject, clip, safety_offset_); -} - -inline Slic3r::Lines intersection_ln(const Slic3r::Line &subject, const Slic3r::Polygons &clip, bool safety_offset_ = false) +inline Slic3r::Lines intersection_ln(const Slic3r::Line &subject, const Slic3r::Polygons &clip) { Slic3r::Lines lines; lines.emplace_back(subject); - return _clipper_ln(ClipperLib::ctIntersection, lines, clip, safety_offset_); + return _clipper_ln(ClipperLib::ctIntersection, lines, clip); } -// union -inline Slic3r::Polygons union_(const Slic3r::Polygons &subject, bool safety_offset_ = false) -{ - return _clipper(ClipperLib::ctUnion, subject, Slic3r::Polygons(), safety_offset_); -} +Slic3r::Polygons union_(const Slic3r::Polygons &subject); +Slic3r::Polygons union_(const Slic3r::ExPolygons &subject); +Slic3r::Polygons union_(const Slic3r::Polygons &subject, const Slic3r::Polygons &subject2); +Slic3r::ExPolygons union_ex(const Slic3r::Polygons &subject); +Slic3r::ExPolygons union_ex(const Slic3r::ExPolygons &subject); +Slic3r::ExPolygons union_ex(const Slic3r::Surfaces &subject); -inline Slic3r::Polygons union_(const Slic3r::Polygons &subject, const Slic3r::Polygons &subject2, bool safety_offset_ = false) -{ - return _clipper(ClipperLib::ctUnion, subject, subject2, safety_offset_); -} +ClipperLib::PolyTree union_pt(const Slic3r::Polygons &subject); +ClipperLib::PolyTree union_pt(const Slic3r::ExPolygons &subject); -inline Slic3r::ExPolygons union_ex(const Slic3r::Polygons &subject, bool safety_offset_ = false) -{ - return _clipper_ex(ClipperLib::ctUnion, subject, Slic3r::Polygons(), safety_offset_); -} - -inline Slic3r::ExPolygons union_ex(const Slic3r::ExPolygons &subject, bool safety_offset_ = false) -{ - return _clipper_ex(ClipperLib::ctUnion, to_polygons(subject), Slic3r::Polygons(), safety_offset_); -} - -inline Slic3r::ExPolygons union_ex(const Slic3r::Surfaces &subject, bool safety_offset_ = false) -{ - return _clipper_ex(ClipperLib::ctUnion, to_polygons(subject), Slic3r::Polygons(), safety_offset_); -} - -ClipperLib::PolyTree union_pt(const Slic3r::Polygons &subject, bool safety_offset_ = false); -ClipperLib::PolyTree union_pt(const Slic3r::ExPolygons &subject, bool safety_offset_ = false); -ClipperLib::PolyTree union_pt(Slic3r::Polygons &&subject, bool safety_offset_ = false); -ClipperLib::PolyTree union_pt(Slic3r::ExPolygons &&subject, bool safety_offset_ = false); - -Slic3r::Polygons union_pt_chained_outside_in(const Slic3r::Polygons &subject, bool safety_offset_ = false); +Slic3r::Polygons union_pt_chained_outside_in(const Slic3r::Polygons &subject); ClipperLib::PolyNodes order_nodes(const ClipperLib::PolyNodes &nodes); @@ -283,7 +410,7 @@ void traverse_pt(const ClipperLib::PolyNode *tree, Polygons *out) if (!tree) return; // terminates recursion // Push the contour of the current level - out->emplace_back(ClipperPath_to_Slic3rPolygon(tree->Contour)); + out->emplace_back(tree->Contour); // Do the recursion for all the children. traverse_pt(tree->Childs, out); @@ -302,13 +429,13 @@ void traverse_pt(const ClipperLib::PolyNode *tree, ExPolygons *out) } ExPolygon level; - level.contour = ClipperPath_to_Slic3rPolygon(tree->Contour); + level.contour.points = tree->Contour; foreach_node(tree->Childs, [out, &level] (const ClipperLib::PolyNode *node) { // Holes are collected here. - level.holes.emplace_back(ClipperPath_to_Slic3rPolygon(node->Contour)); + level.holes.emplace_back(node->Contour); // By doing a recursion, a new level expoly is created with the contour // and holes of the lower level. Doing this for all the childs. @@ -331,8 +458,6 @@ void traverse_pt(const ClipperLib::PolyNodes &nodes, ExOrJustPolygons *retval) Slic3r::Polygons simplify_polygons(const Slic3r::Polygons &subject, bool preserve_collinear = false); Slic3r::ExPolygons simplify_polygons_ex(const Slic3r::Polygons &subject, bool preserve_collinear = false); -void safety_offset(ClipperLib::Paths* paths); - Polygons top_level_islands(const Slic3r::Polygons &polygons); ClipperLib::Path mittered_offset_path_scaled(const Points &contour, const std::vector &deltas, double miter_limit); diff --git a/src/libslic3r/Config.cpp b/src/libslic3r/Config.cpp index 6755a6378..5db1d8179 100644 --- a/src/libslic3r/Config.cpp +++ b/src/libslic3r/Config.cpp @@ -471,8 +471,8 @@ bool ConfigBase::set_deserialize_nothrow(const t_config_option_key &opt_key_src, { t_config_option_key opt_key = opt_key_src; std::string value = value_src; - // Both opt_key and value may be modified by _handle_legacy(). - // If the opt_key is no more valid in this version of Slic3r, opt_key is cleared by _handle_legacy(). + // Both opt_key and value may be modified by handle_legacy(). + // If the opt_key is no more valid in this version of Slic3r, opt_key is cleared by handle_legacy(). this->handle_legacy(opt_key, value); if (opt_key.empty()) // Ignore the option. diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp index 9aab435ed..adda2654e 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -18,11 +18,53 @@ #include #include +#include #include #include #include +namespace Slic3r { + struct FloatOrPercent + { + double value; + bool percent; + + private: + friend class cereal::access; + template void serialize(Archive& ar) { ar(this->value); ar(this->percent); } + }; + + inline bool operator==(const FloatOrPercent& l, const FloatOrPercent& r) throw() { return l.value == r.value && l.percent == r.percent; } + inline bool operator!=(const FloatOrPercent& l, const FloatOrPercent& r) throw() { return !(l == r); } +} + +namespace std { + template<> struct hash { + std::size_t operator()(const Slic3r::FloatOrPercent& v) const noexcept { + std::size_t seed = std::hash{}(v.value); + return v.percent ? seed ^ 0x9e3779b9 : seed; + } + }; + + template<> struct hash { + std::size_t operator()(const Slic3r::Vec2d& v) const noexcept { + std::size_t seed = std::hash{}(v.x()); + boost::hash_combine(seed, std::hash{}(v.y())); + return seed; + } + }; + + template<> struct hash { + std::size_t operator()(const Slic3r::Vec3d& v) const noexcept { + std::size_t seed = std::hash{}(v.x()); + boost::hash_combine(seed, std::hash{}(v.y())); + boost::hash_combine(seed, std::hash{}(v.z())); + return seed; + } + }; +} + namespace Slic3r { // Name of the configuration option. @@ -137,6 +179,7 @@ public: virtual void setInt(int /* val */) { throw BadOptionTypeException("Calling ConfigOption::setInt on a non-int ConfigOption"); } virtual bool operator==(const ConfigOption &rhs) const = 0; bool operator!=(const ConfigOption &rhs) const { return ! (*this == rhs); } + virtual size_t hash() const throw() = 0; bool is_scalar() const { return (int(this->type()) & int(coVectorType)) == 0; } bool is_vector() const { return ! this->is_scalar(); } // If this option is nullable, then it may have its value or values set to nil. @@ -185,8 +228,10 @@ public: return this->value == static_cast*>(&rhs)->value; } - bool operator==(const T &rhs) const { return this->value == rhs; } - bool operator!=(const T &rhs) const { return this->value != rhs; } + bool operator==(const T &rhs) const throw() { return this->value == rhs; } + bool operator!=(const T &rhs) const throw() { return this->value != rhs; } + + size_t hash() const throw() override { return std::hash{}(this->value); } private: friend class cereal::access; @@ -339,8 +384,16 @@ public: return this->values == static_cast*>(&rhs)->values; } - bool operator==(const std::vector &rhs) const { return this->values == rhs; } - bool operator!=(const std::vector &rhs) const { return this->values != rhs; } + bool operator==(const std::vector &rhs) const throw() { return this->values == rhs; } + bool operator!=(const std::vector &rhs) const throw() { return this->values != rhs; } + + size_t hash() const throw() override { + std::hash hasher; + size_t seed = 0; + for (const auto &v : this->values) + boost::hash_combine(seed, hasher(v)); + return seed; + } // Is this option overridden by another option? // An option overrides another option if it is not nil and not equal. @@ -413,7 +466,7 @@ public: ConfigOptionType type() const override { return static_type(); } double getFloat() const override { return this->value; } ConfigOption* clone() const override { return new ConfigOptionFloat(*this); } - bool operator==(const ConfigOptionFloat &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionFloat &rhs) const throw() { return this->value == rhs.value; } std::string serialize() const override { @@ -454,7 +507,7 @@ public: static ConfigOptionType static_type() { return coFloats; } ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionFloatsTempl(*this); } - bool operator==(const ConfigOptionFloatsTempl &rhs) const { return vectors_equal(this->values, rhs.values); } + bool operator==(const ConfigOptionFloatsTempl &rhs) const throw() { return vectors_equal(this->values, rhs.values); } bool operator==(const ConfigOption &rhs) const override { if (rhs.type() != this->type()) throw Slic3r::RuntimeError("ConfigOptionFloatsTempl: Comparing incompatible types"); @@ -566,7 +619,7 @@ public: int getInt() const override { return this->value; } void setInt(int val) override { this->value = val; } ConfigOption* clone() const override { return new ConfigOptionInt(*this); } - bool operator==(const ConfigOptionInt &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionInt &rhs) const throw() { return this->value == rhs.value; } std::string serialize() const override { @@ -606,7 +659,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionIntsTempl(*this); } ConfigOptionIntsTempl& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionIntsTempl &rhs) const { return this->values == rhs.values; } + bool operator==(const ConfigOptionIntsTempl &rhs) const throw() { return this->values == rhs.values; } // Could a special "nil" value be stored inside the vector, indicating undefined value? bool nullable() const override { return NULLABLE; } // Special "nil" value to be stored into the vector if this->supports_nil(). @@ -689,7 +742,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionString(*this); } ConfigOptionString& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionString &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionString &rhs) const throw() { return this->value == rhs.value; } bool empty() const { return this->value.empty(); } std::string serialize() const override @@ -722,7 +775,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionStrings(*this); } ConfigOptionStrings& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionStrings &rhs) const { return this->values == rhs.values; } + bool operator==(const ConfigOptionStrings &rhs) const throw() { return this->values == rhs.values; } bool is_nil(size_t) const override { return false; } std::string serialize() const override @@ -757,7 +810,8 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionPercent(*this); } ConfigOptionPercent& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionPercent &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionPercent &rhs) const throw() { return this->value == rhs.value; } + double get_abs_value(double ratio_over) const { return ratio_over * this->value / 100; } std::string serialize() const override @@ -796,8 +850,8 @@ public: static ConfigOptionType static_type() { return coPercents; } ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionPercentsTempl(*this); } - ConfigOptionPercentsTempl& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionPercentsTempl &rhs) const { return this->values == rhs.values; } + ConfigOptionPercentsTempl& operator=(const ConfigOption *opt) { this->set(opt); return *this; } + bool operator==(const ConfigOptionPercentsTempl &rhs) const throw() { return this->values == rhs.values; } std::string serialize() const override { @@ -856,8 +910,12 @@ public: assert(dynamic_cast(&rhs)); return *this == *static_cast(&rhs); } - bool operator==(const ConfigOptionFloatOrPercent &rhs) const + bool operator==(const ConfigOptionFloatOrPercent &rhs) const throw() { return this->value == rhs.value && this->percent == rhs.percent; } + size_t hash() const throw() override { + size_t seed = std::hash{}(this->value); + return this->percent ? seed ^ 0x9e3779b9 : seed; + } double get_abs_value(double ratio_over) const { return this->percent ? (ratio_over * this->value / 100) : this->value; } @@ -891,27 +949,6 @@ private: template void serialize(Archive &ar) { ar(cereal::base_class(this), percent); } }; - -struct FloatOrPercent -{ - double value; - bool percent; - -private: - friend class cereal::access; - template void serialize(Archive & ar) { ar(this->value); ar(this->percent); } -}; - -inline bool operator==(const FloatOrPercent &l, const FloatOrPercent &r) -{ - return l.value == r.value && l.percent == r.percent; -} - -inline bool operator!=(const FloatOrPercent& l, const FloatOrPercent& r) -{ - return !(l == r); -} - template class ConfigOptionFloatsOrPercentsTempl : public ConfigOptionVector { @@ -925,13 +962,14 @@ public: static ConfigOptionType static_type() { return coFloatsOrPercents; } ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionFloatsOrPercentsTempl(*this); } - bool operator==(const ConfigOptionFloatsOrPercentsTempl &rhs) const { return vectors_equal(this->values, rhs.values); } + bool operator==(const ConfigOptionFloatsOrPercentsTempl &rhs) const throw() { return vectors_equal(this->values, rhs.values); } bool operator==(const ConfigOption &rhs) const override { if (rhs.type() != this->type()) throw Slic3r::RuntimeError("ConfigOptionFloatsOrPercentsTempl: Comparing incompatible types"); assert(dynamic_cast*>(&rhs)); return vectors_equal(this->values, static_cast*>(&rhs)->values); } + // Could a special "nil" value be stored inside the vector, indicating undefined value? bool nullable() const override { return NULLABLE; } // Special "nil" value to be stored into the vector if this->supports_nil(). @@ -1038,7 +1076,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionPoint(*this); } ConfigOptionPoint& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionPoint &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionPoint &rhs) const throw() { return this->value == rhs.value; } std::string serialize() const override { @@ -1074,7 +1112,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionPoints(*this); } ConfigOptionPoints& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionPoints &rhs) const { return this->values == rhs.values; } + bool operator==(const ConfigOptionPoints &rhs) const throw() { return this->values == rhs.values; } bool is_nil(size_t) const override { return false; } std::string serialize() const override @@ -1146,7 +1184,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionPoint3(*this); } ConfigOptionPoint3& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionPoint3 &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionPoint3 &rhs) const throw() { return this->value == rhs.value; } std::string serialize() const override { @@ -1183,7 +1221,7 @@ public: bool getBool() const override { return this->value; } ConfigOption* clone() const override { return new ConfigOptionBool(*this); } ConfigOptionBool& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionBool &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionBool &rhs) const throw() { return this->value == rhs.value; } std::string serialize() const override { @@ -1217,7 +1255,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionBoolsTempl(*this); } ConfigOptionBoolsTempl& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionBoolsTempl &rhs) const { return this->values == rhs.values; } + bool operator==(const ConfigOptionBoolsTempl &rhs) const throw() { return this->values == rhs.values; } // Could a special "nil" value be stored inside the vector, indicating undefined value? bool nullable() const override { return NULLABLE; } // Special "nil" value to be stored into the vector if this->supports_nil(). @@ -1311,7 +1349,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionEnum(*this); } ConfigOptionEnum& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionEnum &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionEnum &rhs) const throw() { return this->value == rhs.value; } int getInt() const override { return (int)this->value; } void setInt(int val) override { this->value = T(val); } @@ -1352,22 +1390,7 @@ public: } // Map from an enum name to an enum integer value. - static const t_config_enum_names& get_enum_names() - { - static t_config_enum_names names; - if (names.empty()) { - // Initialize the map. - const t_config_enum_values &enum_keys_map = ConfigOptionEnum::get_enum_values(); - int cnt = 0; - for (const auto& kvp : enum_keys_map) - cnt = std::max(cnt, kvp.second); - cnt += 1; - names.assign(cnt, ""); - for (const auto& kvp : enum_keys_map) - names[kvp.second] = kvp.first; - } - return names; - } + static const t_config_enum_names& get_enum_names(); // Map from an enum name to an enum integer value. static const t_config_enum_values& get_enum_values(); @@ -1397,7 +1420,7 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionEnumGeneric(*this); } ConfigOptionEnumGeneric& operator=(const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionEnumGeneric &rhs) const { return this->value == rhs.value; } + bool operator==(const ConfigOptionEnumGeneric &rhs) const throw() { return this->value == rhs.value; } bool operator==(const ConfigOption &rhs) const override { diff --git a/src/libslic3r/EdgeGrid.cpp b/src/libslic3r/EdgeGrid.cpp index b9e9ec3dd..1385a51d8 100644 --- a/src/libslic3r/EdgeGrid.cpp +++ b/src/libslic3r/EdgeGrid.cpp @@ -546,7 +546,7 @@ bool EdgeGrid::Grid::inside(const Point &pt_src) return false; coord_t ix = p(0) / m_resolution; coord_t iy = p(1) / m_resolution; - if (ix >= this->m_cols || iy >= this->m_rows) + if (ix >= m_cols || iy >= m_rows) return false; size_t i_closest = (size_t)-1; diff --git a/src/libslic3r/ExPolygon.hpp b/src/libslic3r/ExPolygon.hpp index 73770bb18..04b84f767 100644 --- a/src/libslic3r/ExPolygon.hpp +++ b/src/libslic3r/ExPolygon.hpp @@ -83,8 +83,8 @@ inline bool operator!=(const ExPolygon &lhs, const ExPolygon &rhs) { return lhs. inline size_t number_polygons(const ExPolygons &expolys) { size_t n_polygons = 0; - for (ExPolygons::const_iterator it = expolys.begin(); it != expolys.end(); ++ it) - n_polygons += it->holes.size() + 1; + for (const ExPolygon &ex : expolys) + n_polygons += ex.holes.size() + 1; return n_polygons; } @@ -360,6 +360,8 @@ extern std::vector get_extents_vector(const ExPolygons &polygons); extern bool remove_sticks(ExPolygon &poly); extern void keep_largest_contour_only(ExPolygons &polygons); +inline double area(const ExPolygon &poly) { return poly.area(); } + inline double area(const ExPolygons &polys) { double s = 0.; diff --git a/src/libslic3r/Execution/Execution.hpp b/src/libslic3r/Execution/Execution.hpp index e4bad9f23..62e49cfeb 100644 --- a/src/libslic3r/Execution/Execution.hpp +++ b/src/libslic3r/Execution/Execution.hpp @@ -10,10 +10,6 @@ namespace Slic3r { -// Borrowed from C++20 -template -using remove_cvref_t = std::remove_reference_t>; - // Override for valid execution policies template struct IsExecutionPolicy_ : public std::false_type {}; diff --git a/src/libslic3r/ExtrusionEntity.cpp b/src/libslic3r/ExtrusionEntity.cpp index 3284bc39e..d9320373f 100644 --- a/src/libslic3r/ExtrusionEntity.cpp +++ b/src/libslic3r/ExtrusionEntity.cpp @@ -14,12 +14,12 @@ namespace Slic3r { void ExtrusionPath::intersect_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const { - this->_inflate_collection(intersection_pl((Polylines)polyline, to_polygons(collection.expolygons)), retval); + this->_inflate_collection(intersection_pl(Polylines{ polyline }, collection.expolygons), retval); } void ExtrusionPath::subtract_expolygons(const ExPolygonCollection &collection, ExtrusionEntityCollection* retval) const { - this->_inflate_collection(diff_pl((Polylines)this->polyline, to_polygons(collection.expolygons)), retval); + this->_inflate_collection(diff_pl(Polylines{ this->polyline }, collection.expolygons), retval); } void ExtrusionPath::clip_end(double distance) @@ -318,7 +318,7 @@ std::string ExtrusionEntity::role_to_string(ExtrusionRole role) case erIroning : return L("Ironing"); case erBridgeInfill : return L("Bridge infill"); case erGapFill : return L("Gap fill"); - case erSkirt : return L("Skirt"); + case erSkirt : return L("Skirt/Brim"); case erSupportMaterial : return L("Support material"); case erSupportMaterialInterface : return L("Support material interface"); case erWipeTower : return L("Wipe tower"); @@ -349,7 +349,7 @@ ExtrusionRole ExtrusionEntity::string_to_role(const std::string_view role) return erBridgeInfill; else if (role == L("Gap fill")) return erGapFill; - else if (role == L("Skirt")) + else if (role == L("Skirt") || role == L("Skirt/Brim")) // "Skirt" is for backward compatibility with 2.3.1 and earlier return erSkirt; else if (role == L("Support material")) return erSupportMaterial; diff --git a/src/libslic3r/Fill/Fill.cpp b/src/libslic3r/Fill/Fill.cpp index 579259a5f..7ba6de7d4 100644 --- a/src/libslic3r/Fill/Fill.cpp +++ b/src/libslic3r/Fill/Fill.cpp @@ -122,10 +122,10 @@ std::vector group_fills(const Layer &layer) if (surface.surface_type == stInternalVoid) has_internal_voids = true; else { - const PrintRegionConfig ®ion_config = layerm.region()->config(); + const PrintRegionConfig ®ion_config = layerm.region().config(); FlowRole extrusion_role = surface.is_top() ? frTopSolidInfill : (surface.is_solid() ? frSolidInfill : frInfill); bool is_bridge = layer.id() > 0 && surface.is_bridge(); - params.extruder = layerm.region()->extruder(extrusion_role); + params.extruder = layerm.region().extruder(extrusion_role); params.pattern = region_config.fill_pattern.value; params.density = float(region_config.fill_density); @@ -160,11 +160,9 @@ std::vector group_fills(const Layer &layer) params.anchor_length = 1000.f; params.anchor_length_max = 1000.f; } else { - // it's internal infill, so we can calculate a generic flow spacing - // for all layers, for avoiding the ugly effect of - // misaligned infill on first layer because of different extrusion width and - // layer height - params.spacing = layerm.flow(frInfill, layer.object()->config().layer_height).spacing(); + // Internal infill. Calculating infill line spacing independent of the current layer height and 1st layer status, + // so that internall infill will be aligned over all layers of the current region. + params.spacing = layerm.region().flow(*layer.object(), frInfill, layer.object()->config().layer_height, false).spacing(); // Anchor a sparse infill to inner perimeters with the following anchor length: params.anchor_length = float(region_config.infill_anchor); if (region_config.infill_anchor.percent) @@ -213,7 +211,7 @@ std::vector group_fills(const Layer &layer) Polygons polys = to_polygons(std::move(fill.expolygons)); // Make a union of polygons, use a safety offset, subtract the preceding polygons. // Bridges are processed first (see SurfaceFill::operator<()) - fill.expolygons = all_polygons.empty() ? union_ex(polys, true) : diff_ex(polys, all_polygons, true); + fill.expolygons = all_polygons.empty() ? union_safety_offset_ex(polys) : diff_ex(polys, all_polygons, ApplySafetyOffset::Yes); append(all_polygons, std::move(polys)); } else if (&fill != &surface_fills.back()) append(all_polygons, to_polygons(fill.expolygons)); @@ -254,12 +252,11 @@ std::vector group_fills(const Layer &layer) // Corners of infill regions, which would not be filled with an extrusion path with a radius of distance_between_surfaces/2 Polygons collapsed = diff( surfaces_polygons, - offset2(surfaces_polygons, (float)-distance_between_surfaces/2, (float)+distance_between_surfaces/2), - true); + offset2(surfaces_polygons, (float)-distance_between_surfaces/2, (float)+distance_between_surfaces/2 + ClipperSafetyOffset)); //FIXME why the voids are added to collapsed here? First it is expensive, second the result may lead to some unwanted regions being // added if two offsetted void regions merge. // polygons_append(voids, collapsed); - ExPolygons extensions = intersection_ex(offset(collapsed, (float)distance_between_surfaces), voids, true); + ExPolygons extensions = intersection_ex(offset(collapsed, (float)distance_between_surfaces), voids, ApplySafetyOffset::Yes); // Now find an internal infill SurfaceFill to add these extrusions to. SurfaceFill *internal_solid_fill = nullptr; unsigned int region_id = 0; @@ -277,11 +274,11 @@ std::vector group_fills(const Layer &layer) } if (internal_solid_fill == nullptr) { // Produce another solid fill. - params.extruder = layerm.region()->extruder(frSolidInfill); - params.pattern = layerm.region()->config().top_fill_pattern == ipMonotonic ? ipMonotonic : ipRectilinear; + params.extruder = layerm.region().extruder(frSolidInfill); + params.pattern = layerm.region().config().top_fill_pattern == ipMonotonic ? ipMonotonic : ipRectilinear; params.density = 100.f; params.extrusion_role = erInternalInfill; - params.angle = float(Geometry::deg2rad(layerm.region()->config().fill_angle.value)); + params.angle = float(Geometry::deg2rad(layerm.region().config().fill_angle.value)); // calculate the actual flow we'll be using for this infill params.flow = layerm.flow(frSolidInfill); params.spacing = params.flow.spacing(); @@ -504,7 +501,7 @@ void Layer::make_ironing() for (LayerRegion *layerm : m_regions) if (! layerm->slices.empty()) { IroningParams ironing_params; - const PrintRegionConfig &config = layerm->region()->config(); + const PrintRegionConfig &config = layerm->region().config(); if (config.ironing && (config.ironing_type == IroningType::AllSolid || (config.top_solid_layers > 0 && @@ -559,7 +556,7 @@ void Layer::make_ironing() Polygons infills; for (size_t k = i; k < j; ++ k) { const IroningParams &ironing_params = by_extruder[k]; - const PrintRegionConfig ®ion_config = ironing_params.layerm->region()->config(); + const PrintRegionConfig ®ion_config = ironing_params.layerm->region().config(); bool iron_everything = region_config.ironing_type == IroningType::AllSolid; bool iron_completely = iron_everything; if (iron_everything) { @@ -596,7 +593,7 @@ void Layer::make_ironing() // For IroningType::AllSolid only: // Add solid infill areas for layers, that contain some non-ironable infil (sparse infill, bridge infill). append(infills, to_polygons(std::move(ironing_areas))); - ironing_areas = union_ex(infills, true); + ironing_areas = union_safety_offset_ex(infills); } } diff --git a/src/libslic3r/Fill/Fill3DHoneycomb.cpp b/src/libslic3r/Fill/Fill3DHoneycomb.cpp index 95c26fbad..0dec8004b 100644 --- a/src/libslic3r/Fill/Fill3DHoneycomb.cpp +++ b/src/libslic3r/Fill/Fill3DHoneycomb.cpp @@ -162,7 +162,7 @@ void Fill3DHoneycomb::_fill_surface_single( pl.translate(bb.min); // clip pattern to boundaries, chain the clipped polylines - polylines = intersection_pl(polylines, to_polygons(expolygon)); + polylines = intersection_pl(polylines, expolygon); // connect lines if needed if (params.dont_connect() || polylines.size() <= 1) diff --git a/src/libslic3r/Fill/FillAdaptive.cpp b/src/libslic3r/Fill/FillAdaptive.cpp index d8c05887e..3eabc6106 100644 --- a/src/libslic3r/Fill/FillAdaptive.cpp +++ b/src/libslic3r/Fill/FillAdaptive.cpp @@ -291,13 +291,13 @@ std::pair adaptive_fill_line_spacing(const PrintObject &print_ob double extrusion_width; }; std::vector region_fill_data; - region_fill_data.reserve(print_object.print()->regions().size()); + region_fill_data.reserve(print_object.num_printing_regions()); bool build_octree = false; const std::vector &nozzle_diameters = print_object.print()->config().nozzle_diameter.values; double max_nozzle_diameter = *std::max_element(nozzle_diameters.begin(), nozzle_diameters.end()); double default_infill_extrusion_width = Flow::auto_extrusion_width(FlowRole::frInfill, float(max_nozzle_diameter)); - for (const PrintRegion *region : print_object.print()->regions()) { - const PrintRegionConfig &config = region->config(); + for (size_t region_id = 0; region_id < print_object.num_printing_regions(); ++ region_id) { + const PrintRegionConfig &config = print_object.printing_region(region_id).config(); bool nonempty = config.fill_density > 0; bool has_adaptive_infill = nonempty && config.fill_pattern == ipAdaptiveCubic; bool has_support_infill = nonempty && config.fill_pattern == ipSupportCubic; @@ -1368,7 +1368,7 @@ void Filler::_fill_surface_single( all_polylines.reserve(lines.size()); std::transform(lines.begin(), lines.end(), std::back_inserter(all_polylines), [](const Line& l) { return Polyline{ l.a, l.b }; }); // Crop all polylines - all_polylines = intersection_pl(std::move(all_polylines), to_polygons(expolygon)); + all_polylines = intersection_pl(std::move(all_polylines), expolygon); #endif } diff --git a/src/libslic3r/Fill/FillBase.cpp b/src/libslic3r/Fill/FillBase.cpp index 6d1d94ff8..a41a11cb7 100644 --- a/src/libslic3r/Fill/FillBase.cpp +++ b/src/libslic3r/Fill/FillBase.cpp @@ -595,7 +595,6 @@ static inline bool line_rounded_thick_segment_collision( // Very short line vector. Just test whether the center point is inside the offset line. Vec2d lpt = 0.5 * (line_a + line_b); if (segment_l > SCALED_EPSILON) { - struct Linef { Vec2d a, b; }; intersects = line_alg::distance_to_squared(Linef{ segment_a, segment_b }, lpt) < offset2; } else intersects = (0.5 * (segment_a + segment_b) - lpt).squaredNorm() < offset2; @@ -1196,8 +1195,6 @@ static inline void mark_boundary_segments_overlapping_infill( // Spacing (width) of the infill lines. const double spacing) { - struct Linef { Vec2d a; Vec2d b; }; - for (ContourIntersectionPoint &cp : graph.map_infill_end_point_to_boundary) { const Points &contour = graph.boundary[cp.contour_idx]; const std::vector &contour_params = graph.boundary_params[cp.contour_idx]; @@ -2003,9 +2000,8 @@ static double evaluate_support_arch_cost(const Polyline &pl) double dmax = 0; // Maximum distance in Y axis out of the (ymin, ymax) band and from the (front, back) line. - struct Linef { Vec2d a, b; }; Linef line { front.cast(), back.cast() }; - for (const Point pt : pl.points) + for (const Point &pt : pl.points) dmax = std::max(std::max(dmax, line_alg::distance_to(line, Vec2d(pt.cast()))), std::max(pt.y() - ymax, ymin - pt.y())); return dmax; } diff --git a/src/libslic3r/Fill/FillConcentric.cpp b/src/libslic3r/Fill/FillConcentric.cpp index 785c93be3..d5997552b 100644 --- a/src/libslic3r/Fill/FillConcentric.cpp +++ b/src/libslic3r/Fill/FillConcentric.cpp @@ -33,7 +33,7 @@ void FillConcentric::_fill_surface_single( // generate paths from the outermost to the innermost, to avoid // adhesion problems of the first central tiny loops - loops = union_pt_chained_outside_in(loops, false); + loops = union_pt_chained_outside_in(loops); // split paths using a nearest neighbor search size_t iPathFirst = polylines_out.size(); diff --git a/src/libslic3r/Fill/FillGyroid.cpp b/src/libslic3r/Fill/FillGyroid.cpp index ff2d049cf..c6510daa2 100644 --- a/src/libslic3r/Fill/FillGyroid.cpp +++ b/src/libslic3r/Fill/FillGyroid.cpp @@ -180,7 +180,7 @@ void FillGyroid::_fill_surface_single( for (Polyline &pl : polylines) pl.translate(bb.min); - polylines = intersection_pl(polylines, to_polygons(expolygon)); + polylines = intersection_pl(polylines, expolygon); if (! polylines.empty()) { // Remove very small bits, but be careful to not remove infill lines connecting thin walls! diff --git a/src/libslic3r/Fill/FillHoneycomb.cpp b/src/libslic3r/Fill/FillHoneycomb.cpp index f7f79ae83..5dc2ed501 100644 --- a/src/libslic3r/Fill/FillHoneycomb.cpp +++ b/src/libslic3r/Fill/FillHoneycomb.cpp @@ -73,7 +73,7 @@ void FillHoneycomb::_fill_surface_single( } } - all_polylines = intersection_pl(std::move(all_polylines), to_polygons(expolygon)); + all_polylines = intersection_pl(std::move(all_polylines), expolygon); if (params.dont_connect() || all_polylines.size() <= 1) append(polylines_out, chain_polylines(std::move(all_polylines))); else diff --git a/src/libslic3r/Fill/FillLine.cpp b/src/libslic3r/Fill/FillLine.cpp index f6431a333..b7ab5430e 100644 --- a/src/libslic3r/Fill/FillLine.cpp +++ b/src/libslic3r/Fill/FillLine.cpp @@ -58,7 +58,7 @@ void FillLine::_fill_surface_single( pts.push_back(it->a); pts.push_back(it->b); } - Polylines polylines = intersection_pl(polylines_src, offset(expolygon, scale_(0.02)), false); + Polylines polylines = intersection_pl(polylines_src, offset(expolygon, scale_(0.02))); // FIXME Vojtech: This is only performed for horizontal lines, not for the vertical lines! const float INFILL_OVERLAP_OVER_SPACING = 0.3f; diff --git a/src/libslic3r/Fill/FillPlanePath.cpp b/src/libslic3r/Fill/FillPlanePath.cpp index 7beaf2f08..f1e3884bc 100644 --- a/src/libslic3r/Fill/FillPlanePath.cpp +++ b/src/libslic3r/Fill/FillPlanePath.cpp @@ -33,18 +33,16 @@ void FillPlanePath::_fill_surface_single( coord_t(ceil(coordf_t(bounding_box.max.x()) / distance_between_lines)), coord_t(ceil(coordf_t(bounding_box.max.y()) / distance_between_lines))); - Polylines polylines; if (pts.size() >= 2) { // Convert points to a polyline, upscale. - polylines.push_back(Polyline()); - Polyline &polyline = polylines.back(); + Polylines polylines(1, Polyline()); + Polyline &polyline = polylines.front(); polyline.points.reserve(pts.size()); for (const Vec2d &pt : pts) - polyline.points.push_back(Point( - coord_t(floor(pt.x() * distance_between_lines + 0.5)), - coord_t(floor(pt.y() * distance_between_lines + 0.5)))); -// intersection(polylines_src, offset((Polygons)expolygon, scale_(0.02)), &polylines); - polylines = intersection_pl(std::move(polylines), to_polygons(expolygon)); + polyline.points.emplace_back( + coord_t(floor(pt.x() * distance_between_lines + 0.5)), + coord_t(floor(pt.y() * distance_between_lines + 0.5))); + polylines = intersection_pl(polylines, expolygon); Polylines chained; if (params.dont_connect() || params.density > 0.5 || polylines.size() <= 1) chained = chain_polylines(std::move(polylines)); diff --git a/src/libslic3r/Flow.cpp b/src/libslic3r/Flow.cpp index 1645bf683..9f4730261 100644 --- a/src/libslic3r/Flow.cpp +++ b/src/libslic3r/Flow.cpp @@ -89,18 +89,11 @@ double Flow::extrusion_width(const std::string& opt_key, const ConfigOptionFloat if (opt->percent) { auto opt_key_layer_height = first_layer ? "first_layer_height" : "layer_height"; - auto opt_layer_height = config.option(opt_key_layer_height); + auto opt_layer_height = config.option(opt_key_layer_height); if (opt_layer_height == nullptr) throw_on_missing_variable(opt_key, opt_key_layer_height); - double layer_height = opt_layer_height->getFloat(); - if (first_layer && static_cast(opt_layer_height)->percent) { - // first_layer_height depends on layer_height. - opt_layer_height = config.option("layer_height"); - if (opt_layer_height == nullptr) - throw_on_missing_variable(opt_key, "layer_height"); - layer_height *= 0.01 * opt_layer_height->getFloat(); - } - return opt->get_abs_value(layer_height); + assert(! first_layer || ! static_cast(opt_layer_height)->percent); + return opt->get_abs_value(opt_layer_height->getFloat()); } if (opt->value == 0.) { @@ -238,13 +231,14 @@ Flow support_material_flow(const PrintObject *object, float layer_height) Flow support_material_1st_layer_flow(const PrintObject *object, float layer_height) { - const auto &width = (object->print()->config().first_layer_extrusion_width.value > 0) ? object->print()->config().first_layer_extrusion_width : object->config().support_material_extrusion_width; + const PrintConfig &print_config = object->print()->config(); + const auto &width = (print_config.first_layer_extrusion_width.value > 0) ? print_config.first_layer_extrusion_width : object->config().support_material_extrusion_width; return Flow::new_from_config_width( frSupportMaterial, // The width parameter accepted by new_from_config_width is of type ConfigOptionFloatOrPercent, the Flow class takes care of the percent to value substitution. (width.value > 0) ? width : object->config().extrusion_width, - float(object->print()->config().nozzle_diameter.get_at(object->config().support_material_extruder-1)), - (layer_height > 0.f) ? layer_height : float(object->config().first_layer_height.get_abs_value(object->config().layer_height.value))); + float(print_config.nozzle_diameter.get_at(object->config().support_material_extruder-1)), + (layer_height > 0.f) ? layer_height : float(print_config.first_layer_height.get_abs_value(object->config().layer_height.value))); } Flow support_material_interface_flow(const PrintObject *object, float layer_height) diff --git a/src/libslic3r/Format/SL1.cpp b/src/libslic3r/Format/SL1.cpp index 64cb8b815..4038cb046 100644 --- a/src/libslic3r/Format/SL1.cpp +++ b/src/libslic3r/Format/SL1.cpp @@ -248,7 +248,7 @@ std::vector extract_slices_from_sla_archive( { double incr, val, prev; bool stop = false; - tbb::spin_mutex mutex; + tbb::spin_mutex mutex = {}; } st {100. / slices.size(), 0., 0.}; tbb::parallel_for(size_t(0), arch.images.size(), @@ -371,6 +371,13 @@ void fill_iniconf(ConfMap &m, const SLAPrint &print) m["numSlow"] = std::to_string(stats.slow_layers_count); m["numFast"] = std::to_string(stats.fast_layers_count); m["printTime"] = std::to_string(stats.estimated_print_time); + + bool hollow_en = false; + auto it = print.objects().begin(); + while (!hollow_en && it != print.objects().end()) + hollow_en = (*it++)->config().hollowing_enable; + + m["hollow"] = hollow_en ? "1" : "0"; m["action"] = "print"; } diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index a79940810..d47d185a0 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -611,12 +611,47 @@ std::vector>> GCode::collec // free functions called by GCode::do_export() namespace DoExport { - static void update_print_estimated_times_stats(const GCodeProcessor& processor, PrintStatistics& print_statistics) +// static void update_print_estimated_times_stats(const GCodeProcessor& processor, PrintStatistics& print_statistics) +// { +// const GCodeProcessor::Result& result = processor.get_result(); +// print_statistics.estimated_normal_print_time = get_time_dhms(result.print_statistics.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].time); +// print_statistics.estimated_silent_print_time = processor.is_stealth_time_estimator_enabled() ? +// get_time_dhms(result.print_statistics.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].time) : "N/A"; +// } + + static void update_print_estimated_stats(const GCodeProcessor& processor, const std::vector& extruders, PrintStatistics& print_statistics) { const GCodeProcessor::Result& result = processor.get_result(); - print_statistics.estimated_normal_print_time = get_time_dhms(result.time_statistics.modes[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Normal)].time); + print_statistics.estimated_normal_print_time = get_time_dhms(result.print_statistics.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].time); print_statistics.estimated_silent_print_time = processor.is_stealth_time_estimator_enabled() ? - get_time_dhms(result.time_statistics.modes[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].time) : "N/A"; + get_time_dhms(result.print_statistics.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].time) : "N/A"; + + // update filament statictics + double total_extruded_volume = 0.0; + double total_used_filament = 0.0; + double total_weight = 0.0; + double total_cost = 0.0; + for (auto volume : result.print_statistics.volumes_per_extruder) { + total_extruded_volume += volume.second; + + size_t extruder_id = volume.first; + auto extruder = std::find_if(extruders.begin(), extruders.end(), [extruder_id](const Extruder& extr) { return extr.id() == extruder_id; }); + if (extruder == extruders.end()) + continue; + + double s = PI * sqr(0.5* extruder->filament_diameter()); + double weight = volume.second * extruder->filament_density() * 0.001; + total_used_filament += volume.second/s; + total_weight += weight; + total_cost += weight * extruder->filament_cost() * 0.001; + } + + print_statistics.total_extruded_volume = total_extruded_volume; + print_statistics.total_used_filament = total_used_filament; + print_statistics.total_weight = total_weight; + print_statistics.total_cost = total_cost; + + print_statistics.filament_stats = result.print_statistics.volumes_per_extruder; } #if ENABLE_VALIDATE_CUSTOM_GCODE @@ -754,7 +789,8 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessor::Result* re BOOST_LOG_TRIVIAL(debug) << "Start processing gcode, " << log_memory_info(); m_processor.process_file(path_tmp, true, [print]() { print->throw_if_canceled(); }); - DoExport::update_print_estimated_times_stats(m_processor, print->m_print_statistics); +// DoExport::update_print_estimated_times_stats(m_processor, print->m_print_statistics); + DoExport::update_print_estimated_stats(m_processor, m_writer.extruders(), print->m_print_statistics); #if ENABLE_GCODE_WINDOW if (result != nullptr) { *result = std::move(m_processor.extract_result()); @@ -796,19 +832,19 @@ namespace DoExport { // get the minimum cross-section used in the print std::vector mm3_per_mm; for (auto object : print.objects()) { - for (size_t region_id = 0; region_id < object->region_volumes.size(); ++ region_id) { - const PrintRegion* region = print.regions()[region_id]; + for (size_t region_id = 0; region_id < object->num_printing_regions(); ++ region_id) { + const PrintRegion ®ion = object->printing_region(region_id); for (auto layer : object->layers()) { const LayerRegion* layerm = layer->regions()[region_id]; - if (region->config().get_abs_value("perimeter_speed") == 0 || - region->config().get_abs_value("small_perimeter_speed") == 0 || - region->config().get_abs_value("external_perimeter_speed") == 0 || - region->config().get_abs_value("bridge_speed") == 0) + if (region.config().get_abs_value("perimeter_speed") == 0 || + region.config().get_abs_value("small_perimeter_speed") == 0 || + region.config().get_abs_value("external_perimeter_speed") == 0 || + region.config().get_abs_value("bridge_speed") == 0) mm3_per_mm.push_back(layerm->perimeters.min_mm3_per_mm()); - if (region->config().get_abs_value("infill_speed") == 0 || - region->config().get_abs_value("solid_infill_speed") == 0 || - region->config().get_abs_value("top_solid_infill_speed") == 0 || - region->config().get_abs_value("bridge_speed") == 0) + if (region.config().get_abs_value("infill_speed") == 0 || + region.config().get_abs_value("solid_infill_speed") == 0 || + region.config().get_abs_value("top_solid_infill_speed") == 0 || + region.config().get_abs_value("bridge_speed") == 0) { // Minimal volumetric flow should not be calculated over ironing extrusions. // Use following lambda instead of the built-it method. @@ -887,8 +923,7 @@ namespace DoExport { if (thumbnail_cb != nullptr) { const size_t max_row_length = 78; - ThumbnailsList thumbnails; - thumbnail_cb(thumbnails, sizes, true, true, true, true); + ThumbnailsList thumbnails = thumbnail_cb(ThumbnailsParams{ sizes, true, true, true, true }); for (const ThumbnailData& data : thumbnails) { if (data.is_valid()) @@ -958,7 +993,6 @@ namespace DoExport { dst.first += buf; ++ dst.second; }; - print_statistics.filament_stats.insert(std::pair{extruder.id(), (float)used_filament}); append(out_filament_used_mm, "%.2lf", used_filament); append(out_filament_used_cm3, "%.2lf", extruded_volume * 0.001); if (filament_weight > 0.) { @@ -1111,17 +1145,19 @@ void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thu // Write some terse information on the slicing parameters. const PrintObject *first_object = print.objects().front(); const double layer_height = first_object->config().layer_height.value; - const double first_layer_height = first_object->config().first_layer_height.get_abs_value(layer_height); - for (const PrintRegion* region : print.regions()) { - _write_format(file, "; external perimeters extrusion width = %.2fmm\n", region->flow(*first_object, frExternalPerimeter, layer_height).width()); - _write_format(file, "; perimeters extrusion width = %.2fmm\n", region->flow(*first_object, frPerimeter, layer_height).width()); - _write_format(file, "; infill extrusion width = %.2fmm\n", region->flow(*first_object, frInfill, layer_height).width()); - _write_format(file, "; solid infill extrusion width = %.2fmm\n", region->flow(*first_object, frSolidInfill, layer_height).width()); - _write_format(file, "; top infill extrusion width = %.2fmm\n", region->flow(*first_object, frTopSolidInfill, layer_height).width()); + assert(! print.config().first_layer_height.percent); + const double first_layer_height = print.config().first_layer_height.value; + for (size_t region_id = 0; region_id < print.num_print_regions(); ++ region_id) { + const PrintRegion ®ion = print.get_print_region(region_id); + _write_format(file, "; external perimeters extrusion width = %.2fmm\n", region.flow(*first_object, frExternalPerimeter, layer_height).width()); + _write_format(file, "; perimeters extrusion width = %.2fmm\n", region.flow(*first_object, frPerimeter, layer_height).width()); + _write_format(file, "; infill extrusion width = %.2fmm\n", region.flow(*first_object, frInfill, layer_height).width()); + _write_format(file, "; solid infill extrusion width = %.2fmm\n", region.flow(*first_object, frSolidInfill, layer_height).width()); + _write_format(file, "; top infill extrusion width = %.2fmm\n", region.flow(*first_object, frTopSolidInfill, layer_height).width()); if (print.has_support_material()) _write_format(file, "; support material extrusion width = %.2fmm\n", support_material_flow(first_object).width()); if (print.config().first_layer_extrusion_width.value > 0) - _write_format(file, "; first layer extrusion width = %.2fmm\n", region->flow(*first_object, frPerimeter, first_layer_height, true).width()); + _write_format(file, "; first layer extrusion width = %.2fmm\n", region.flow(*first_object, frPerimeter, first_layer_height, true).width()); _write_format(file, "\n"); } print.throw_if_canceled(); @@ -1935,7 +1971,7 @@ void GCode::process_layer( bool enable = (layer.id() > 0 || !print.has_brim()) && (layer.id() >= (size_t)print.config().skirt_height.value && ! print.has_infinite_skirt()); if (enable) { for (const LayerRegion *layer_region : layer.regions()) - if (size_t(layer_region->region()->config().bottom_solid_layers.value) > layer.id() || + if (size_t(layer_region->region().config().bottom_solid_layers.value) > layer.id() || layer_region->perimeters.items_count() > 1u || layer_region->fills.items_count() > 0) { enable = false; @@ -2109,7 +2145,9 @@ void GCode::process_layer( const LayerRegion *layerm = layer.regions()[region_id]; if (layerm == nullptr) continue; - const PrintRegion ®ion = *print.regions()[region_id]; + // PrintObjects own the PrintRegions, thus the pointer to PrintRegion would be unique to a PrintObject, they would not + // identify the content of PrintRegion accross the whole print uniquely. Translate to a Print specific PrintRegion. + const PrintRegion ®ion = print.get_print_region(layerm->region().print_region_id()); // Now we must process perimeters and infills and create islands of extrusions in by_region std::map. // It is also necessary to save which extrusions are part of MM wiping and which are not. @@ -2167,8 +2205,8 @@ void GCode::process_layer( // extrusions->first_point fits inside ith slice point_inside_surface(island_idx, extrusions->first_point())) { if (islands[island_idx].by_region.empty()) - islands[island_idx].by_region.assign(print.regions().size(), ObjectByExtruder::Island::Region()); - islands[island_idx].by_region[region_id].append(entity_type, extrusions, entity_overrides); + islands[island_idx].by_region.assign(print.num_print_regions(), ObjectByExtruder::Island::Region()); + islands[island_idx].by_region[region.print_region_id()].append(entity_type, extrusions, entity_overrides); break; } } @@ -2570,7 +2608,7 @@ std::string GCode::extrude_perimeters(const Print &print, const std::vectorconfig()); + m_config.apply(print.get_print_region(®ion - &by_region.front()).config()); for (const ExtrusionEntity *ee : region.perimeters) gcode += this->extrude_entity(*ee, "perimeter", -1., &lower_layer_edge_grid); } @@ -2591,7 +2629,7 @@ std::string GCode::extrude_infill(const Print &print, const std::vectorrole() == erIroning) == ironing) extrusions.emplace_back(ee); if (! extrusions.empty()) { - m_config.apply(print.regions()[®ion - &by_region.front()]->config()); + m_config.apply(print.get_print_region(®ion - &by_region.front()).config()); chain_and_reorder_extrusion_entities(extrusions, &m_last_pos); for (const ExtrusionEntity *fill : extrusions) { auto *eec = dynamic_cast(fill); diff --git a/src/libslic3r/GCode/CoolingBuffer.cpp b/src/libslic3r/GCode/CoolingBuffer.cpp index 7f48aae80..07b9b07bb 100644 --- a/src/libslic3r/GCode/CoolingBuffer.cpp +++ b/src/libslic3r/GCode/CoolingBuffer.cpp @@ -326,7 +326,7 @@ std::vector CoolingBuffer::parse_layer_gcode(const std:: PerExtruderAdjustments *adjustment = &per_extruder_adjustments[map_extruder_to_per_extruder_adjustment[current_extruder]]; const char *line_start = gcode.c_str(); const char *line_end = line_start; - const char extrusion_axis = config.get_extrusion_axis()[0]; + const char extrusion_axis = get_extrusion_axis(config)[0]; // Index of an existing CoolingLine of the current adjustment, which holds the feedrate setting command // for a sequence of extrusion moves. size_t active_speed_modifier = size_t(-1); diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 7a1790971..917f84f40 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -186,6 +186,72 @@ void GCodeProcessor::TimeMachine::CustomGCodeTime::reset() times = std::vector>(); } +void GCodeProcessor::UsedFilaments::reset() +{ + color_change_cache = 0.0f; + volumes_per_color_change = std::vector(); + + tool_change_cache = 0.0f; + volumes_per_extruder.clear(); + + role_cache = 0.0f; + filaments_per_role.clear(); +} + +void GCodeProcessor::UsedFilaments::increase_caches(double extruded_volume) +{ + color_change_cache += extruded_volume; + tool_change_cache += extruded_volume; + role_cache += extruded_volume; +} + +void GCodeProcessor::UsedFilaments::process_color_change_cache() +{ + if (color_change_cache != 0.0f) { + volumes_per_color_change.push_back(color_change_cache); + color_change_cache = 0.0f; + } +} + +void GCodeProcessor::UsedFilaments::process_extruder_cache(GCodeProcessor* processor) +{ + size_t active_extruder_id = processor->m_extruder_id; + if (tool_change_cache != 0.0f) { + if (volumes_per_extruder.find(active_extruder_id) != volumes_per_extruder.end()) + volumes_per_extruder[active_extruder_id] += tool_change_cache; + else + volumes_per_extruder[active_extruder_id] = tool_change_cache; + tool_change_cache = 0.0f; + } +} + +void GCodeProcessor::UsedFilaments::process_role_cache(GCodeProcessor* processor) +{ + if (role_cache != 0.0f) { + std::pair filament = { 0.0f, 0.0f }; + + double s = PI * sqr(0.5 * processor->m_filament_diameters[processor->m_extruder_id]); + filament.first = role_cache/s * 0.001; + filament.second = role_cache * processor->m_filament_densities[processor->m_extruder_id] * 0.001; + + ExtrusionRole active_role = processor->m_extrusion_role; + if (filaments_per_role.find(active_role) != filaments_per_role.end()) { + filaments_per_role[active_role].first += filament.first; + filaments_per_role[active_role].second += filament.second; + } + else + filaments_per_role[active_role] = filament; + role_cache = 0.0f; + } +} + +void GCodeProcessor::UsedFilaments::process_caches(GCodeProcessor* processor) +{ + process_color_change_cache(); + process_extruder_cache(processor); + process_role_cache(processor); +} + void GCodeProcessor::TimeMachine::reset() { enabled = false; @@ -348,10 +414,10 @@ void GCodeProcessor::TimeProcessor::reset() machine_limits = MachineEnvelopeConfig(); filament_load_times = std::vector(); filament_unload_times = std::vector(); - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { machines[i].reset(); } - machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Normal)].enabled = true; + machines[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].enabled = true; } #if ENABLE_GCODE_LINES_ID_IN_H_SLIDER @@ -416,19 +482,19 @@ void GCodeProcessor::TimeProcessor::post_process(const std::string& filename) size_t g1_lines_counter = 0; // keeps track of last exported pair #if ENABLE_EXTENDED_M73_LINES - std::array, static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count)> last_exported_main; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + std::array, static_cast(PrintEstimatedStatistics::ETimeMode::Count)> last_exported_main; + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { last_exported_main[i] = { 0, time_in_minutes(machines[i].time) }; } // keeps track of last exported remaining time to next printer stop - std::array(PrintEstimatedTimeStatistics::ETimeMode::Count)> last_exported_stop; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + std::array(PrintEstimatedStatistics::ETimeMode::Count)> last_exported_stop; + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { last_exported_stop[i] = time_in_minutes(machines[i].time); } #else - std::array, static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count)> last_exported; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + std::array, static_cast(PrintEstimatedStatistics::ETimeMode::Count)> last_exported; + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { last_exported[i] = { 0, time_in_minutes(machines[i].time) }; } #endif // ENABLE_EXTENDED_M73_LINES @@ -451,7 +517,7 @@ void GCodeProcessor::TimeProcessor::post_process(const std::string& filename) line = line.substr(1); if (export_remaining_time_enabled && (line == reserved_tag(ETags::First_Line_M73_Placeholder) || line == reserved_tag(ETags::Last_Line_M73_Placeholder))) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { const TimeMachine& machine = machines[i]; if (machine.enabled) { #if ENABLE_EXTENDED_M73_LINES @@ -486,7 +552,7 @@ void GCodeProcessor::TimeProcessor::post_process(const std::string& filename) else if (line == reserved_tag(ETags::Estimated_Printing_Time_Placeholder)) { #else if (export_remaining_time_enabled && (line == First_Line_M73_Placeholder_Tag || line == Last_Line_M73_Placeholder_Tag)) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { const TimeMachine& machine = machines[i]; if (machine.enabled) { ret += format_line_M73(machine.line_m73_mask.c_str(), @@ -497,13 +563,13 @@ void GCodeProcessor::TimeProcessor::post_process(const std::string& filename) } else if (line == Estimated_Printing_Time_Placeholder_Tag) { #endif // ENABLE_VALIDATE_CUSTOM_GCODE - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { const TimeMachine& machine = machines[i]; - PrintEstimatedTimeStatistics::ETimeMode mode = static_cast(i); - if (mode == PrintEstimatedTimeStatistics::ETimeMode::Normal || machine.enabled) { + PrintEstimatedStatistics::ETimeMode mode = static_cast(i); + if (mode == PrintEstimatedStatistics::ETimeMode::Normal || machine.enabled) { char buf[128]; sprintf(buf, "; estimated printing time (%s mode) = %s\n", - (mode == PrintEstimatedTimeStatistics::ETimeMode::Normal) ? "normal" : "silent", + (mode == PrintEstimatedStatistics::ETimeMode::Normal) ? "normal" : "silent", get_time_dhms(machine.time).c_str()); ret += buf; } @@ -545,7 +611,7 @@ void GCodeProcessor::TimeProcessor::post_process(const std::string& filename) unsigned int exported_lines_count = 0; #endif // ENABLE_GCODE_LINES_ID_IN_H_SLIDER if (export_remaining_time_enabled) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { const TimeMachine& machine = machines[i]; if (machine.enabled) { // export pair @@ -789,13 +855,13 @@ GCodeProcessor::GCodeProcessor() { reset(); #if ENABLE_EXTENDED_M73_LINES - m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Normal)].line_m73_main_mask = "M73 P%s R%s\n"; - m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Normal)].line_m73_stop_mask = "M73 C%s\n"; - m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].line_m73_main_mask = "M73 Q%s S%s\n"; - m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].line_m73_stop_mask = "M73 D%s\n"; + m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].line_m73_main_mask = "M73 P%s R%s\n"; + m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].line_m73_stop_mask = "M73 C%s\n"; + m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].line_m73_main_mask = "M73 Q%s S%s\n"; + m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].line_m73_stop_mask = "M73 D%s\n"; #else - m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Normal)].line_m73_mask = "M73 P%s R%s\n"; - m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].line_m73_mask = "M73 Q%s S%s\n"; + m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].line_m73_mask = "M73 P%s R%s\n"; + m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].line_m73_mask = "M73 Q%s S%s\n"; #endif // ENABLE_EXTENDED_M73_LINES } @@ -826,6 +892,11 @@ void GCodeProcessor::apply_config(const PrintConfig& config) m_filament_diameters[i] = static_cast(config.filament_diameter.values[i]); } + m_filament_densities.resize(config.filament_density.values.size()); + for (size_t i = 0; i < config.filament_density.values.size(); ++i) { + m_filament_densities[i] = static_cast(config.filament_density.values[i]); + } + if ((m_flavor == gcfMarlinLegacy || m_flavor == gcfMarlinFirmware) && config.machine_limits_usage.value != MachineLimitsUsage::Ignore) { m_time_processor.machine_limits = reinterpret_cast(config); if (m_flavor == gcfMarlinLegacy) { @@ -846,7 +917,7 @@ void GCodeProcessor::apply_config(const PrintConfig& config) m_time_processor.filament_unload_times[i] = static_cast(config.filament_unload_time.values[i]); } - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { float max_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_extruding, i); m_time_processor.machines[i].max_acceleration = max_acceleration; m_time_processor.machines[i].acceleration = (max_acceleration > 0.0f) ? max_acceleration : DEFAULT_ACCELERATION; @@ -857,6 +928,12 @@ void GCodeProcessor::apply_config(const PrintConfig& config) m_time_processor.export_remaining_time_enabled = config.remaining_times.value; m_use_volumetric_e = config.use_volumetric_e; + +#if ENABLE_START_GCODE_VISUALIZATION + const ConfigOptionFloatOrPercent* first_layer_height = config.option("first_layer_height"); + if (first_layer_height != nullptr) + m_first_layer_height = std::abs(first_layer_height->value); +#endif // ENABLE_START_GCODE_VISUALIZATION } void GCodeProcessor::apply_config(const DynamicPrintConfig& config) @@ -890,6 +967,13 @@ void GCodeProcessor::apply_config(const DynamicPrintConfig& config) } } + const ConfigOptionFloats* filament_densities = config.option("filament_density"); + if (filament_densities != nullptr) { + for (double dens : filament_densities->values) { + m_filament_densities.push_back(static_cast(dens)); + } + } + m_result.extruders_count = config.option("nozzle_diameter")->values.size(); const ConfigOptionPoints* extruder_offset = config.option("extruder_offset"); @@ -1020,7 +1104,7 @@ void GCodeProcessor::apply_config(const DynamicPrintConfig& config) m_time_processor.machine_limits.machine_min_travel_rate.values = machine_min_travel_rate->values; } - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { float max_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_extruding, i); m_time_processor.machines[i].max_acceleration = max_acceleration; m_time_processor.machines[i].acceleration = (max_acceleration > 0.0f) ? max_acceleration : DEFAULT_ACCELERATION; @@ -1035,11 +1119,17 @@ void GCodeProcessor::apply_config(const DynamicPrintConfig& config) const ConfigOptionBool* use_volumetric_e = config.option("use_volumetric_e"); if (use_volumetric_e != nullptr) m_use_volumetric_e = use_volumetric_e->value; + +#if ENABLE_START_GCODE_VISUALIZATION + const ConfigOptionFloatOrPercent* first_layer_height = config.option("first_layer_height"); + if (first_layer_height != nullptr) + m_first_layer_height = std::abs(first_layer_height->value); +#endif // ENABLE_START_GCODE_VISUALIZATION } void GCodeProcessor::enable_stealth_time_estimator(bool enabled) { - m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].enabled = enabled; + m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].enabled = enabled; } void GCodeProcessor::reset() @@ -1060,6 +1150,9 @@ void GCodeProcessor::reset() #if ENABLE_GCODE_LINES_ID_IN_H_SLIDER m_line_id = 0; +#if ENABLE_SEAMS_VISUALIZATION + m_last_line_id = 0; +#endif // ENABLE_SEAMS_VISUALIZATION #endif // ENABLE_GCODE_LINES_ID_IN_H_SLIDER m_feedrate = 0.0f; m_width = 0.0f; @@ -1081,7 +1174,12 @@ void GCodeProcessor::reset() } m_filament_diameters = std::vector(Min_Extruder_Count, 1.75f); + m_filament_densities = std::vector(Min_Extruder_Count, 1.245f); m_extruded_last_z = 0.0f; +#if ENABLE_START_GCODE_VISUALIZATION + m_first_layer_height = 0.0f; + m_processing_start_custom_gcode = false; +#endif // ENABLE_START_GCODE_VISUALIZATION m_g1_line_id = 0; m_layer_id = 0; m_cp_color.reset(); @@ -1090,6 +1188,7 @@ void GCodeProcessor::reset() m_producers_enabled = false; m_time_processor.reset(); + m_used_filaments.reset(); m_result.reset(); m_result.id = ++s_result_id; @@ -1167,7 +1266,7 @@ void GCodeProcessor::process_file(const std::string& filename, bool apply_postpr } // process the time blocks - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { TimeMachine& machine = m_time_processor.machines[i]; TimeMachine::CustomGCodeTime& gcode_time = machine.gcode_time; machine.calculate_time(); @@ -1175,6 +1274,8 @@ void GCodeProcessor::process_file(const std::string& filename, bool apply_postpr gcode_time.times.push_back({ CustomGCode::ColorChange, gcode_time.cache }); } + m_used_filaments.process_caches(this); + update_estimated_times_stats(); // post-process to add M73 lines into the gcode @@ -1197,20 +1298,20 @@ void GCodeProcessor::process_file(const std::string& filename, bool apply_postpr #endif // ENABLE_GCODE_VIEWER_STATISTICS } -float GCodeProcessor::get_time(PrintEstimatedTimeStatistics::ETimeMode mode) const +float GCodeProcessor::get_time(PrintEstimatedStatistics::ETimeMode mode) const { - return (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) ? m_time_processor.machines[static_cast(mode)].time : 0.0f; + return (mode < PrintEstimatedStatistics::ETimeMode::Count) ? m_time_processor.machines[static_cast(mode)].time : 0.0f; } -std::string GCodeProcessor::get_time_dhm(PrintEstimatedTimeStatistics::ETimeMode mode) const +std::string GCodeProcessor::get_time_dhm(PrintEstimatedStatistics::ETimeMode mode) const { - return (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) ? short_time(get_time_dhms(m_time_processor.machines[static_cast(mode)].time)) : std::string("N/A"); + return (mode < PrintEstimatedStatistics::ETimeMode::Count) ? short_time(get_time_dhms(m_time_processor.machines[static_cast(mode)].time)) : std::string("N/A"); } -std::vector>> GCodeProcessor::get_custom_gcode_times(PrintEstimatedTimeStatistics::ETimeMode mode, bool include_remaining) const +std::vector>> GCodeProcessor::get_custom_gcode_times(PrintEstimatedStatistics::ETimeMode mode, bool include_remaining) const { std::vector>> ret; - if (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) { + if (mode < PrintEstimatedStatistics::ETimeMode::Count) { const TimeMachine& machine = m_time_processor.machines[static_cast(mode)]; float total_time = 0.0f; for (const auto& [type, time] : machine.gcode_time.times) { @@ -1222,10 +1323,10 @@ std::vector>> GCodeProcesso return ret; } -std::vector> GCodeProcessor::get_moves_time(PrintEstimatedTimeStatistics::ETimeMode mode) const +std::vector> GCodeProcessor::get_moves_time(PrintEstimatedStatistics::ETimeMode mode) const { std::vector> ret; - if (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) { + if (mode < PrintEstimatedStatistics::ETimeMode::Count) { for (size_t i = 0; i < m_time_processor.machines[static_cast(mode)].moves_time.size(); ++i) { float time = m_time_processor.machines[static_cast(mode)].moves_time[i]; if (time > 0.0f) @@ -1235,10 +1336,10 @@ std::vector> GCodeProcessor::get_moves_time(PrintEst return ret; } -std::vector> GCodeProcessor::get_roles_time(PrintEstimatedTimeStatistics::ETimeMode mode) const +std::vector> GCodeProcessor::get_roles_time(PrintEstimatedStatistics::ETimeMode mode) const { std::vector> ret; - if (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) { + if (mode < PrintEstimatedStatistics::ETimeMode::Count) { for (size_t i = 0; i < m_time_processor.machines[static_cast(mode)].roles_time.size(); ++i) { float time = m_time_processor.machines[static_cast(mode)].roles_time[i]; if (time > 0.0f) @@ -1248,9 +1349,9 @@ std::vector> GCodeProcessor::get_roles_time(Prin return ret; } -std::vector GCodeProcessor::get_layers_time(PrintEstimatedTimeStatistics::ETimeMode mode) const +std::vector GCodeProcessor::get_layers_time(PrintEstimatedStatistics::ETimeMode mode) const { - return (mode < PrintEstimatedTimeStatistics::ETimeMode::Count) ? + return (mode < PrintEstimatedStatistics::ETimeMode::Count) ? m_time_processor.machines[static_cast(mode)].layers_time : std::vector(); } @@ -1442,7 +1543,15 @@ void GCodeProcessor::process_tags(const std::string_view comment) #if ENABLE_VALIDATE_CUSTOM_GCODE // extrusion role tag if (boost::starts_with(comment, reserved_tag(ETags::Role))) { + m_used_filaments.process_role_cache(this); m_extrusion_role = ExtrusionEntity::string_to_role(comment.substr(reserved_tag(ETags::Role).length())); +#if ENABLE_SEAMS_VISUALIZATION + if (m_extrusion_role == erExternalPerimeter) + m_seams_detector.activate(true); +#endif // ENABLE_SEAMS_VISUALIZATION +#if ENABLE_START_GCODE_VISUALIZATION + m_processing_start_custom_gcode = (m_extrusion_role == erCustom && m_g1_line_id == 0); +#endif // ENABLE_START_GCODE_VISUALIZATION return; } @@ -1520,7 +1629,8 @@ void GCodeProcessor::process_tags(const std::string_view comment) extruder_id = static_cast(eid); } - m_extruder_colors[extruder_id] = static_cast(m_extruder_offsets.size()) + m_cp_color.counter; // color_change position in list of color for preview + if (extruder_id < m_extruder_colors.size()) + m_extruder_colors[extruder_id] = static_cast(m_extruder_offsets.size()) + m_cp_color.counter; // color_change position in list of color for preview ++m_cp_color.counter; if (m_cp_color.counter == UCHAR_MAX) m_cp_color.counter = 0; @@ -1531,6 +1641,7 @@ void GCodeProcessor::process_tags(const std::string_view comment) } process_custom_gcode_time(CustomGCode::ColorChange); + process_filaments(CustomGCode::ColorChange); return; } @@ -1660,6 +1771,10 @@ bool GCodeProcessor::process_cura_tags(const std::string_view comment) BOOST_LOG_TRIVIAL(warning) << "GCodeProcessor found unknown extrusion role: " << type; } +#if ENABLE_SEAMS_VISUALIZATION + if (m_extrusion_role == erExternalPerimeter) + m_seams_detector.activate(true); +#endif // ENABLE_SEAMS_VISUALIZATION return true; } @@ -1724,6 +1839,9 @@ bool GCodeProcessor::process_simplify3d_tags(const std::string_view comment) pos = cmt.find(" outer perimeter"); if (pos == 0) { m_extrusion_role = erExternalPerimeter; +#if ENABLE_SEAMS_VISUALIZATION + m_seams_detector.activate(true); +#endif // ENABLE_SEAMS_VISUALIZATION return true; } @@ -1878,6 +1996,11 @@ bool GCodeProcessor::process_craftware_tags(const std::string_view comment) BOOST_LOG_TRIVIAL(warning) << "GCodeProcessor found unknown extrusion role: " << type; } +#if ENABLE_SEAMS_VISUALIZATION + if (m_extrusion_role == erExternalPerimeter) + m_seams_detector.activate(true); +#endif // ENABLE_SEAMS_VISUALIZATION + return true; } @@ -1916,6 +2039,11 @@ bool GCodeProcessor::process_ideamaker_tags(const std::string_view comment) m_extrusion_role = erNone; BOOST_LOG_TRIVIAL(warning) << "GCodeProcessor found unknown extrusion role: " << type; } + +#if ENABLE_SEAMS_VISUALIZATION + if (m_extrusion_role == erExternalPerimeter) + m_seams_detector.activate(true); +#endif // ENABLE_SEAMS_VISUALIZATION return true; } @@ -1984,6 +2112,9 @@ bool GCodeProcessor::process_kissslicer_tags(const std::string_view comment) pos = comment.find(" 'Perimeter Path'"); if (pos == 0) { m_extrusion_role = erExternalPerimeter; +#if ENABLE_SEAMS_VISUALIZATION + m_seams_detector.activate(true); +#endif // ENABLE_SEAMS_VISUALIZATION return true; } @@ -2148,6 +2279,9 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) float volume_extruded_filament = area_filament_cross_section * delta_pos[E]; float area_toolpath_cross_section = volume_extruded_filament / delta_xyz; + // save extruded volume to the cache + m_used_filaments.increase_caches(volume_extruded_filament); + // volume extruded filament / tool displacement = area toolpath cross section m_mm3_per_mm = area_toolpath_cross_section; #if ENABLE_GCODE_VIEWER_DATA_CHECKING @@ -2187,7 +2321,11 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) #endif // ENABLE_GCODE_VIEWER_DATA_CHECKING } +#if ENABLE_START_GCODE_VISUALIZATION + if (type == EMoveType::Extrude && (m_width == 0.0f || m_height == 0.0f)) +#else if (type == EMoveType::Extrude && (m_extrusion_role == erCustom || m_width == 0.0f || m_height == 0.0f)) +#endif // ENABLE_START_GCODE_VISUALIZATION type = EMoveType::Travel; // time estimate section @@ -2204,7 +2342,7 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) assert(distance != 0.0f); float inv_distance = 1.0f / distance; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { TimeMachine& machine = m_time_processor.machines[i]; if (!machine.enabled) continue; @@ -2214,8 +2352,8 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) std::vector& blocks = machine.blocks; curr.feedrate = (delta_pos[E] == 0.0f) ? - minimum_travel_feedrate(static_cast(i), m_feedrate) : - minimum_feedrate(static_cast(i), m_feedrate); + minimum_travel_feedrate(static_cast(i), m_feedrate) : + minimum_feedrate(static_cast(i), m_feedrate); TimeBlock block; block.move_type = type; @@ -2233,7 +2371,7 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) curr.abs_axis_feedrate[a] = std::abs(curr.axis_feedrate[a]); if (curr.abs_axis_feedrate[a] != 0.0f) { - float axis_max_feedrate = get_axis_max_feedrate(static_cast(i), static_cast(a)); + float axis_max_feedrate = get_axis_max_feedrate(static_cast(i), static_cast(a)); if (axis_max_feedrate != 0.0f) min_feedrate_factor = std::min(min_feedrate_factor, axis_max_feedrate / curr.abs_axis_feedrate[a]); } @@ -2250,13 +2388,13 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) // calculates block acceleration float acceleration = - (type == EMoveType::Travel) ? get_travel_acceleration(static_cast(i)) : + (type == EMoveType::Travel) ? get_travel_acceleration(static_cast(i)) : (is_extrusion_only_move(delta_pos) ? - get_retract_acceleration(static_cast(i)) : - get_acceleration(static_cast(i))); + get_retract_acceleration(static_cast(i)) : + get_acceleration(static_cast(i))); for (unsigned char a = X; a <= E; ++a) { - float axis_max_acceleration = get_axis_max_acceleration(static_cast(i), static_cast(a)); + float axis_max_acceleration = get_axis_max_acceleration(static_cast(i), static_cast(a)); if (acceleration * std::abs(delta_pos[a]) * inv_distance > axis_max_acceleration) acceleration = axis_max_acceleration; } @@ -2267,7 +2405,7 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) curr.safe_feedrate = block.feedrate_profile.cruise; for (unsigned char a = X; a <= E; ++a) { - float axis_max_jerk = get_axis_max_jerk(static_cast(i), static_cast(a)); + float axis_max_jerk = get_axis_max_jerk(static_cast(i), static_cast(a)); if (curr.abs_axis_feedrate[a] > axis_max_jerk) curr.safe_feedrate = std::min(curr.safe_feedrate, axis_max_jerk); } @@ -2303,19 +2441,19 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) // Calculate the jerk depending on whether the axis is coasting in the same direction or reversing a direction. float jerk = (v_exit > v_entry) ? - (((v_entry > 0.0f) || (v_exit < 0.0f)) ? + ((v_entry > 0.0f || v_exit < 0.0f) ? // coasting (v_exit - v_entry) : // axis reversal std::max(v_exit, -v_entry)) : // v_exit <= v_entry - (((v_entry < 0.0f) || (v_exit > 0.0f)) ? + ((v_entry < 0.0f || v_exit > 0.0f) ? // coasting (v_entry - v_exit) : // axis reversal std::max(-v_exit, v_entry)); - float axis_max_jerk = get_axis_max_jerk(static_cast(i), static_cast(a)); + float axis_max_jerk = get_axis_max_jerk(static_cast(i), static_cast(a)); if (jerk > axis_max_jerk) { v_factor *= axis_max_jerk / jerk; limited = true; @@ -2330,7 +2468,7 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) float vmax_junction_threshold = vmax_junction * 0.99f; // Not coasting. The machine will stop and start the movements anyway, better to start the segment from start. - if ((prev.safe_feedrate > vmax_junction_threshold) && (curr.safe_feedrate > vmax_junction_threshold)) + if (prev.safe_feedrate > vmax_junction_threshold && curr.safe_feedrate > vmax_junction_threshold) vmax_junction = curr.safe_feedrate; } @@ -2354,6 +2492,32 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line) machine.calculate_time(TimeProcessor::Planner::queue_size); } +#if ENABLE_SEAMS_VISUALIZATION + if (m_seams_detector.is_active()) { + // check for seam starting vertex + if (type == EMoveType::Extrude && m_extrusion_role == erExternalPerimeter && !m_seams_detector.has_first_vertex()) + m_seams_detector.set_first_vertex(m_result.moves.back().position - m_extruder_offsets[m_extruder_id]); + // check for seam ending vertex and store the resulting move + else if ((type != EMoveType::Extrude || m_extrusion_role != erExternalPerimeter) && m_seams_detector.has_first_vertex()) { + auto set_end_position = [this](const Vec3f& pos) { + m_end_position[X] = pos.x(); m_end_position[Y] = pos.y(); m_end_position[Z] = pos.z(); + }; + + const Vec3f curr_pos(m_end_position[X], m_end_position[Y], m_end_position[Z]); + const Vec3f new_pos = m_result.moves.back().position - m_extruder_offsets[m_extruder_id]; + const std::optional first_vertex = m_seams_detector.get_first_vertex(); + // the threshold value = 0.0625f == 0.25 * 0.25 is arbitrary, we may find some smarter condition later + if ((new_pos - *first_vertex).squaredNorm() < 0.0625f) { + set_end_position(0.5f * (new_pos + *first_vertex)); + store_move_vertex(EMoveType::Seam); + set_end_position(curr_pos); + } + + m_seams_detector.activate(false); + } + } +#endif // ENABLE_SEAMS_VISUALIZATION + // store move store_move_vertex(type); } @@ -2574,8 +2738,8 @@ void GCodeProcessor::process_M201(const GCodeReader::GCodeLine& line) // see http://reprap.org/wiki/G-code#M201:_Set_max_printing_acceleration float factor = ((m_flavor != gcfRepRapSprinter && m_flavor != gcfRepRapFirmware) && m_units == EUnits::Inches) ? INCHES_TO_MM : 1.0f; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { - if (static_cast(i) == PrintEstimatedTimeStatistics::ETimeMode::Normal || + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { + if (static_cast(i) == PrintEstimatedStatistics::ETimeMode::Normal || m_time_processor.machine_envelope_processing_enabled) { if (line.has_x()) set_option_value(m_time_processor.machine_limits.machine_max_acceleration_x, i, line.x() * factor); @@ -2602,8 +2766,8 @@ void GCodeProcessor::process_M203(const GCodeReader::GCodeLine& line) // http://smoothieware.org/supported-g-codes float factor = (m_flavor == gcfMarlinLegacy || m_flavor == gcfMarlinFirmware || m_flavor == gcfSmoothie) ? 1.0f : MMMIN_TO_MMSEC; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { - if (static_cast(i) == PrintEstimatedTimeStatistics::ETimeMode::Normal || + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { + if (static_cast(i) == PrintEstimatedStatistics::ETimeMode::Normal || m_time_processor.machine_envelope_processing_enabled) { if (line.has_x()) set_option_value(m_time_processor.machine_limits.machine_max_feedrate_x, i, line.x() * factor); @@ -2623,27 +2787,27 @@ void GCodeProcessor::process_M203(const GCodeReader::GCodeLine& line) void GCodeProcessor::process_M204(const GCodeReader::GCodeLine& line) { float value; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { - if (static_cast(i) == PrintEstimatedTimeStatistics::ETimeMode::Normal || + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { + if (static_cast(i) == PrintEstimatedStatistics::ETimeMode::Normal || m_time_processor.machine_envelope_processing_enabled) { if (line.has_value('S', value)) { // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware // It is also generated by PrusaSlicer to control acceleration per extrusion type // (perimeters, first layer etc) when 'Marlin (legacy)' flavor is used. - set_acceleration(static_cast(i), value); - set_travel_acceleration(static_cast(i), value); + set_acceleration(static_cast(i), value); + set_travel_acceleration(static_cast(i), value); if (line.has_value('T', value)) set_option_value(m_time_processor.machine_limits.machine_max_acceleration_retracting, i, value); } else { // New acceleration format, compatible with the upstream Marlin. if (line.has_value('P', value)) - set_acceleration(static_cast(i), value); + set_acceleration(static_cast(i), value); if (line.has_value('R', value)) set_option_value(m_time_processor.machine_limits.machine_max_acceleration_retracting, i, value); if (line.has_value('T', value)) // Interpret the T value as the travel acceleration in the new Marlin format. - set_travel_acceleration(static_cast(i), value); + set_travel_acceleration(static_cast(i), value); } } } @@ -2651,8 +2815,8 @@ void GCodeProcessor::process_M204(const GCodeReader::GCodeLine& line) void GCodeProcessor::process_M205(const GCodeReader::GCodeLine& line) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { - if (static_cast(i) == PrintEstimatedTimeStatistics::ETimeMode::Normal || + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { + if (static_cast(i) == PrintEstimatedStatistics::ETimeMode::Normal || m_time_processor.machine_envelope_processing_enabled) { if (line.has_x()) { float max_jerk = line.x(); @@ -2685,7 +2849,7 @@ void GCodeProcessor::process_M221(const GCodeReader::GCodeLine& line) float value_t; if (line.has_value('S', value_s) && !line.has_value('T', value_t)) { value_s *= 0.01f; - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { m_time_processor.machines[i].extrude_factor_override_percentage = value_s; } } @@ -2736,7 +2900,7 @@ void GCodeProcessor::process_M402(const GCodeReader::GCodeLine& line) void GCodeProcessor::process_M566(const GCodeReader::GCodeLine& line) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { if (line.has_x()) set_option_value(m_time_processor.machine_limits.machine_max_jerk_x, i, line.x() * MMMIN_TO_MMSEC); @@ -2787,6 +2951,7 @@ void GCodeProcessor::process_T(const std::string_view command) BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid toolchange, maybe from a custom gcode."; else { unsigned char old_extruder_id = m_extruder_id; + process_filaments(CustomGCode::ToolChange); m_extruder_id = id; m_cp_color.current = m_extruder_colors[id]; // Specific to the MK3 MMU2: @@ -2807,15 +2972,29 @@ void GCodeProcessor::process_T(const std::string_view command) void GCodeProcessor::store_move_vertex(EMoveType type) { +#if ENABLE_SEAMS_VISUALIZATION + m_last_line_id = (type == EMoveType::Color_change || type == EMoveType::Pause_Print || type == EMoveType::Custom_GCode) ? + m_line_id + 1 : + ((type == EMoveType::Seam) ? m_last_line_id : m_line_id); +#endif // ENABLE_SEAMS_VISUALIZATION + MoveVertex vertex = { #if ENABLE_GCODE_LINES_ID_IN_H_SLIDER +#if ENABLE_SEAMS_VISUALIZATION + m_last_line_id, +#else (type == EMoveType::Color_change || type == EMoveType::Pause_Print || type == EMoveType::Custom_GCode) ? m_line_id + 1 : m_line_id, +#endif // ENABLE_SEAMS_VISUALIZATION #endif // ENABLE_GCODE_LINES_ID_IN_H_SLIDER type, m_extrusion_role, m_extruder_id, m_cp_color.current, +#if ENABLE_START_GCODE_VISUALIZATION + Vec3f(m_end_position[X], m_end_position[Y], m_processing_start_custom_gcode ? m_first_layer_height : m_end_position[Z]) + m_extruder_offsets[m_extruder_id], +#else Vec3f(m_end_position[X], m_end_position[Y], m_end_position[Z]) + m_extruder_offsets[m_extruder_id], +#endif // ENABLE_START_GCODE_VISUALIZATION m_end_position[E] - m_start_position[E], m_feedrate, m_width, @@ -2830,7 +3009,7 @@ void GCodeProcessor::store_move_vertex(EMoveType type) #if ENABLE_EXTENDED_M73_LINES // stores stop time placeholders for later use if (type == EMoveType::Color_change || type == EMoveType::Pause_Print) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { TimeMachine& machine = m_time_processor.machines[i]; if (!machine.enabled) continue; @@ -2841,7 +3020,7 @@ void GCodeProcessor::store_move_vertex(EMoveType type) #endif // ENABLE_EXTENDED_M73_LINES } -float GCodeProcessor::minimum_feedrate(PrintEstimatedTimeStatistics::ETimeMode mode, float feedrate) const +float GCodeProcessor::minimum_feedrate(PrintEstimatedStatistics::ETimeMode mode, float feedrate) const { if (m_time_processor.machine_limits.machine_min_extruding_rate.empty()) return feedrate; @@ -2849,7 +3028,7 @@ float GCodeProcessor::minimum_feedrate(PrintEstimatedTimeStatistics::ETimeMode m return std::max(feedrate, get_option_value(m_time_processor.machine_limits.machine_min_extruding_rate, static_cast(mode))); } -float GCodeProcessor::minimum_travel_feedrate(PrintEstimatedTimeStatistics::ETimeMode mode, float feedrate) const +float GCodeProcessor::minimum_travel_feedrate(PrintEstimatedStatistics::ETimeMode mode, float feedrate) const { if (m_time_processor.machine_limits.machine_min_travel_rate.empty()) return feedrate; @@ -2857,7 +3036,7 @@ float GCodeProcessor::minimum_travel_feedrate(PrintEstimatedTimeStatistics::ETim return std::max(feedrate, get_option_value(m_time_processor.machine_limits.machine_min_travel_rate, static_cast(mode))); } -float GCodeProcessor::get_axis_max_feedrate(PrintEstimatedTimeStatistics::ETimeMode mode, Axis axis) const +float GCodeProcessor::get_axis_max_feedrate(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const { switch (axis) { @@ -2869,7 +3048,7 @@ float GCodeProcessor::get_axis_max_feedrate(PrintEstimatedTimeStatistics::ETimeM } } -float GCodeProcessor::get_axis_max_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode, Axis axis) const +float GCodeProcessor::get_axis_max_acceleration(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const { switch (axis) { @@ -2881,7 +3060,7 @@ float GCodeProcessor::get_axis_max_acceleration(PrintEstimatedTimeStatistics::ET } } -float GCodeProcessor::get_axis_max_jerk(PrintEstimatedTimeStatistics::ETimeMode mode, Axis axis) const +float GCodeProcessor::get_axis_max_jerk(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const { switch (axis) { @@ -2893,18 +3072,18 @@ float GCodeProcessor::get_axis_max_jerk(PrintEstimatedTimeStatistics::ETimeMode } } -float GCodeProcessor::get_retract_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode) const +float GCodeProcessor::get_retract_acceleration(PrintEstimatedStatistics::ETimeMode mode) const { return get_option_value(m_time_processor.machine_limits.machine_max_acceleration_retracting, static_cast(mode)); } -float GCodeProcessor::get_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode) const +float GCodeProcessor::get_acceleration(PrintEstimatedStatistics::ETimeMode mode) const { size_t id = static_cast(mode); return (id < m_time_processor.machines.size()) ? m_time_processor.machines[id].acceleration : DEFAULT_ACCELERATION; } -void GCodeProcessor::set_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode, float value) +void GCodeProcessor::set_acceleration(PrintEstimatedStatistics::ETimeMode mode, float value) { size_t id = static_cast(mode); if (id < m_time_processor.machines.size()) { @@ -2914,13 +3093,13 @@ void GCodeProcessor::set_acceleration(PrintEstimatedTimeStatistics::ETimeMode mo } } -float GCodeProcessor::get_travel_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode) const +float GCodeProcessor::get_travel_acceleration(PrintEstimatedStatistics::ETimeMode mode) const { size_t id = static_cast(mode); return (id < m_time_processor.machines.size()) ? m_time_processor.machines[id].travel_acceleration : DEFAULT_TRAVEL_ACCELERATION; } -void GCodeProcessor::set_travel_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode, float value) +void GCodeProcessor::set_travel_acceleration(PrintEstimatedStatistics::ETimeMode mode, float value) { size_t id = static_cast(mode); if (id < m_time_processor.machines.size()) { @@ -2948,7 +3127,7 @@ float GCodeProcessor::get_filament_unload_time(size_t extruder_id) void GCodeProcessor::process_custom_gcode_time(CustomGCode::Type code) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { TimeMachine& machine = m_time_processor.machines[i]; if (!machine.enabled) continue; @@ -2965,17 +3144,26 @@ void GCodeProcessor::process_custom_gcode_time(CustomGCode::Type code) } } +void GCodeProcessor::process_filaments(CustomGCode::Type code) +{ + if (code == CustomGCode::ColorChange) + m_used_filaments.process_color_change_cache(); + + if (code == CustomGCode::ToolChange) + m_used_filaments.process_extruder_cache(this); +} + void GCodeProcessor::simulate_st_synchronize(float additional_time) { - for (size_t i = 0; i < static_cast(PrintEstimatedTimeStatistics::ETimeMode::Count); ++i) { + for (size_t i = 0; i < static_cast(PrintEstimatedStatistics::ETimeMode::Count); ++i) { m_time_processor.machines[i].simulate_st_synchronize(additional_time); } } void GCodeProcessor::update_estimated_times_stats() { - auto update_mode = [this](PrintEstimatedTimeStatistics::ETimeMode mode) { - PrintEstimatedTimeStatistics::Mode& data = m_result.time_statistics.modes[static_cast(mode)]; + auto update_mode = [this](PrintEstimatedStatistics::ETimeMode mode) { + PrintEstimatedStatistics::Mode& data = m_result.print_statistics.modes[static_cast(mode)]; data.time = get_time(mode); data.custom_gcode_times = get_custom_gcode_times(mode, true); data.moves_times = get_moves_time(mode); @@ -2983,11 +3171,15 @@ void GCodeProcessor::update_estimated_times_stats() data.layers_times = get_layers_time(mode); }; - update_mode(PrintEstimatedTimeStatistics::ETimeMode::Normal); - if (m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].enabled) - update_mode(PrintEstimatedTimeStatistics::ETimeMode::Stealth); + update_mode(PrintEstimatedStatistics::ETimeMode::Normal); + if (m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].enabled) + update_mode(PrintEstimatedStatistics::ETimeMode::Stealth); else - m_result.time_statistics.modes[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].reset(); + m_result.print_statistics.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].reset(); + + m_result.print_statistics.volumes_per_color_change = m_used_filaments.volumes_per_color_change; + m_result.print_statistics.volumes_per_extruder = m_used_filaments.volumes_per_extruder; + m_result.print_statistics.used_filaments_per_role = m_used_filaments.filaments_per_role; } } /* namespace Slic3r */ diff --git a/src/libslic3r/GCode/GCodeProcessor.hpp b/src/libslic3r/GCode/GCodeProcessor.hpp index cf55bf86e..8975255ec 100644 --- a/src/libslic3r/GCode/GCodeProcessor.hpp +++ b/src/libslic3r/GCode/GCodeProcessor.hpp @@ -12,6 +12,9 @@ #include #include #include +#if ENABLE_SEAMS_VISUALIZATION +#include +#endif // ENABLE_SEAMS_VISUALIZATION namespace Slic3r { @@ -20,6 +23,9 @@ namespace Slic3r { Noop, Retract, Unretract, +#if ENABLE_SEAMS_VISUALIZATION + Seam, +#endif // ENABLE_SEAMS_VISUALIZATION Tool_change, Color_change, Pause_Print, @@ -30,7 +36,7 @@ namespace Slic3r { Count }; - struct PrintEstimatedTimeStatistics + struct PrintEstimatedStatistics { enum class ETimeMode : unsigned char { @@ -56,14 +62,21 @@ namespace Slic3r { } }; + std::vector volumes_per_color_change; + std::map volumes_per_extruder; + std::map> used_filaments_per_role; + std::array(ETimeMode::Count)> modes; - PrintEstimatedTimeStatistics() { reset(); } + PrintEstimatedStatistics() { reset(); } void reset() { for (auto m : modes) { m.reset(); } + volumes_per_color_change.clear(); + volumes_per_extruder.clear(); + used_filaments_per_role.clear(); } }; @@ -308,7 +321,7 @@ namespace Slic3r { // Additional load / unload times for a filament exchange sequence. std::vector filament_load_times; std::vector filament_unload_times; - std::array(PrintEstimatedTimeStatistics::ETimeMode::Count)> machines; + std::array(PrintEstimatedStatistics::ETimeMode::Count)> machines; void reset(); @@ -321,6 +334,30 @@ namespace Slic3r { #endif // ENABLE_GCODE_LINES_ID_IN_H_SLIDER }; + struct UsedFilaments // filaments per ColorChange + { + double color_change_cache; + std::vector volumes_per_color_change; + + double tool_change_cache; + std::map volumes_per_extruder; + + double role_cache; + // ExtrusionRole : + std::map> filaments_per_role; + + void reset(); + + void increase_caches(double extruded_volume); + + void process_color_change_cache(); + void process_extruder_cache(GCodeProcessor* processor); + void process_role_cache(GCodeProcessor* processor); + void process_caches(GCodeProcessor* processor); + + friend class GCodeProcessor; + }; + public: #if !ENABLE_GCODE_LINES_ID_IN_H_SLIDER struct MoveVertex @@ -366,12 +403,11 @@ namespace Slic3r { SettingsIds settings_ids; size_t extruders_count; std::vector extruder_colors; - PrintEstimatedTimeStatistics time_statistics; + PrintEstimatedStatistics print_statistics; #if ENABLE_GCODE_VIEWER_STATISTICS int64_t time{ 0 }; - void reset() - { + void reset() { time = 0; moves = std::vector(); bed_shape = Pointfs(); @@ -380,8 +416,7 @@ namespace Slic3r { settings_ids.reset(); } #else - void reset() - { + void reset() { moves = std::vector(); bed_shape = Pointfs(); extruder_colors = std::vector(); @@ -391,6 +426,29 @@ namespace Slic3r { #endif // ENABLE_GCODE_VIEWER_STATISTICS }; +#if ENABLE_SEAMS_VISUALIZATION + class SeamsDetector + { + bool m_active{ false }; + std::optional m_first_vertex; + + public: + void activate(bool active) { + if (m_active != active) { + m_active = active; + if (m_active) + m_first_vertex.reset(); + } + } + + std::optional get_first_vertex() const { return m_first_vertex; } + void set_first_vertex(const Vec3f& vertex) { m_first_vertex = vertex; } + + bool is_active() const { return m_active; } + bool has_first_vertex() const { return m_first_vertex.has_value(); } + }; +#endif // ENABLE_SEAMS_VISUALIZATION + #if ENABLE_GCODE_VIEWER_DATA_CHECKING struct DataChecker { @@ -476,6 +534,9 @@ namespace Slic3r { #if ENABLE_GCODE_LINES_ID_IN_H_SLIDER unsigned int m_line_id; +#if ENABLE_SEAMS_VISUALIZATION + unsigned int m_last_line_id; +#endif // ENABLE_SEAMS_VISUALIZATION #endif // ENABLE_GCODE_LINES_ID_IN_H_SLIDER float m_feedrate; // mm/s float m_width; // mm @@ -489,11 +550,19 @@ namespace Slic3r { ExtruderColors m_extruder_colors; ExtruderTemps m_extruder_temps; std::vector m_filament_diameters; + std::vector m_filament_densities; float m_extruded_last_z; +#if ENABLE_START_GCODE_VISUALIZATION + float m_first_layer_height; // mm + bool m_processing_start_custom_gcode; +#endif // ENABLE_START_GCODE_VISUALIZATION unsigned int m_g1_line_id; unsigned int m_layer_id; CpColor m_cp_color; bool m_use_volumetric_e; +#if ENABLE_SEAMS_VISUALIZATION + SeamsDetector m_seams_detector; +#endif // ENABLE_SEAMS_VISUALIZATION enum class EProducer { @@ -513,6 +582,7 @@ namespace Slic3r { bool m_producers_enabled; TimeProcessor m_time_processor; + UsedFilaments m_used_filaments; Result m_result; static unsigned int s_result_id; @@ -529,7 +599,7 @@ namespace Slic3r { void apply_config(const PrintConfig& config); void enable_stealth_time_estimator(bool enabled); bool is_stealth_time_estimator_enabled() const { - return m_time_processor.machines[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Stealth)].enabled; + return m_time_processor.machines[static_cast(PrintEstimatedStatistics::ETimeMode::Stealth)].enabled; } void enable_machine_envelope_processing(bool enabled) { m_time_processor.machine_envelope_processing_enabled = enabled; } void enable_producers(bool enabled) { m_producers_enabled = enabled; } @@ -542,13 +612,13 @@ namespace Slic3r { // throws CanceledException through print->throw_if_canceled() (sent by the caller as callback). void process_file(const std::string& filename, bool apply_postprocess, std::function cancel_callback = nullptr); - float get_time(PrintEstimatedTimeStatistics::ETimeMode mode) const; - std::string get_time_dhm(PrintEstimatedTimeStatistics::ETimeMode mode) const; - std::vector>> get_custom_gcode_times(PrintEstimatedTimeStatistics::ETimeMode mode, bool include_remaining) const; + float get_time(PrintEstimatedStatistics::ETimeMode mode) const; + std::string get_time_dhm(PrintEstimatedStatistics::ETimeMode mode) const; + std::vector>> get_custom_gcode_times(PrintEstimatedStatistics::ETimeMode mode, bool include_remaining) const; - std::vector> get_moves_time(PrintEstimatedTimeStatistics::ETimeMode mode) const; - std::vector> get_roles_time(PrintEstimatedTimeStatistics::ETimeMode mode) const; - std::vector get_layers_time(PrintEstimatedTimeStatistics::ETimeMode mode) const; + std::vector> get_moves_time(PrintEstimatedStatistics::ETimeMode mode) const; + std::vector> get_roles_time(PrintEstimatedStatistics::ETimeMode mode) const; + std::vector get_layers_time(PrintEstimatedStatistics::ETimeMode mode) const; private: void apply_config(const DynamicPrintConfig& config); @@ -664,20 +734,21 @@ namespace Slic3r { void store_move_vertex(EMoveType type); - float minimum_feedrate(PrintEstimatedTimeStatistics::ETimeMode mode, float feedrate) const; - float minimum_travel_feedrate(PrintEstimatedTimeStatistics::ETimeMode mode, float feedrate) const; - float get_axis_max_feedrate(PrintEstimatedTimeStatistics::ETimeMode mode, Axis axis) const; - float get_axis_max_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode, Axis axis) const; - float get_axis_max_jerk(PrintEstimatedTimeStatistics::ETimeMode mode, Axis axis) const; - float get_retract_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode) const; - float get_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode) const; - void set_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode, float value); - float get_travel_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode) const; - void set_travel_acceleration(PrintEstimatedTimeStatistics::ETimeMode mode, float value); + float minimum_feedrate(PrintEstimatedStatistics::ETimeMode mode, float feedrate) const; + float minimum_travel_feedrate(PrintEstimatedStatistics::ETimeMode mode, float feedrate) const; + float get_axis_max_feedrate(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const; + float get_axis_max_acceleration(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const; + float get_axis_max_jerk(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const; + float get_retract_acceleration(PrintEstimatedStatistics::ETimeMode mode) const; + float get_acceleration(PrintEstimatedStatistics::ETimeMode mode) const; + void set_acceleration(PrintEstimatedStatistics::ETimeMode mode, float value); + float get_travel_acceleration(PrintEstimatedStatistics::ETimeMode mode) const; + void set_travel_acceleration(PrintEstimatedStatistics::ETimeMode mode, float value); float get_filament_load_time(size_t extruder_id); float get_filament_unload_time(size_t extruder_id); void process_custom_gcode_time(CustomGCode::Type code); + void process_filaments(CustomGCode::Type code); // Simulates firmware st_synchronize() call void simulate_st_synchronize(float additional_time = 0.0f); diff --git a/src/libslic3r/GCode/ThumbnailData.hpp b/src/libslic3r/GCode/ThumbnailData.hpp index 2a302ed85..195dfe633 100644 --- a/src/libslic3r/GCode/ThumbnailData.hpp +++ b/src/libslic3r/GCode/ThumbnailData.hpp @@ -19,8 +19,18 @@ struct ThumbnailData bool is_valid() const; }; -typedef std::vector ThumbnailsList; -typedef std::function ThumbnailsGeneratorCallback; +using ThumbnailsList = std::vector; + +struct ThumbnailsParams +{ + const Vec2ds sizes; + bool printable_only; + bool parts_only; + bool show_bed; + bool transparent_background; +}; + +typedef std::function ThumbnailsGeneratorCallback; } // namespace Slic3r diff --git a/src/libslic3r/GCode/ToolOrdering.cpp b/src/libslic3r/GCode/ToolOrdering.cpp index c45e26015..9dc9f3f96 100644 --- a/src/libslic3r/GCode/ToolOrdering.cpp +++ b/src/libslic3r/GCode/ToolOrdering.cpp @@ -223,11 +223,8 @@ void ToolOrdering::collect_extruders(const PrintObject &object, const std::vecto layer_tools.extruder_override = extruder_override; // What extruders are required to print this object layer? - for (size_t region_id = 0; region_id < object.region_volumes.size(); ++ region_id) { - const LayerRegion *layerm = (region_id < layer->regions().size()) ? layer->regions()[region_id] : nullptr; - if (layerm == nullptr) - continue; - const PrintRegion ®ion = *object.print()->regions()[region_id]; + for (const LayerRegion *layerm : layer->regions()) { + const PrintRegion ®ion = layerm->region(); if (! layerm->perimeters.entities.empty()) { bool something_nonoverriddable = true; @@ -688,16 +685,14 @@ float WipingExtrusions::mark_wiping_extrusions(const Print& print, unsigned int // iterate through copies (aka PrintObject instances) first, so that we mark neighbouring infills to minimize travel moves for (unsigned int copy = 0; copy < num_of_copies; ++copy) { - - for (size_t region_id = 0; region_id < object->region_volumes.size(); ++ region_id) { - const auto& region = *object->print()->regions()[region_id]; - + for (const LayerRegion *layerm : this_layer->regions()) { + const auto ®ion = layerm->region(); if (!region.config().wipe_into_infill && !object->config().wipe_into_objects) continue; bool wipe_into_infill_only = ! object->config().wipe_into_objects && region.config().wipe_into_infill; if (print.config().infill_first != perimeters_done || wipe_into_infill_only) { - for (const ExtrusionEntity* ee : this_layer->regions()[region_id]->fills.entities) { // iterate through all infill Collections + for (const ExtrusionEntity* ee : layerm->fills.entities) { // iterate through all infill Collections auto* fill = dynamic_cast(ee); if (!is_overriddable(*fill, print.config(), *object, region)) @@ -721,7 +716,7 @@ float WipingExtrusions::mark_wiping_extrusions(const Print& print, unsigned int // Now the same for perimeters - see comments above for explanation: if (object->config().wipe_into_objects && print.config().infill_first == perimeters_done) { - for (const ExtrusionEntity* ee : this_layer->regions()[region_id]->perimeters.entities) { + for (const ExtrusionEntity* ee : layerm->perimeters.entities) { auto* fill = dynamic_cast(ee); if (is_overriddable(*fill, print.config(), *object, region) && !is_entity_overridden(fill, copy) && fill->total_volume() > min_infill_volume) { set_extruder_override(fill, copy, new_extruder, num_of_copies); @@ -762,13 +757,12 @@ void WipingExtrusions::ensure_perimeters_infills_order(const Print& print) size_t num_of_copies = object->instances().size(); for (size_t copy = 0; copy < num_of_copies; ++copy) { // iterate through copies first, so that we mark neighbouring infills to minimize travel moves - for (size_t region_id = 0; region_id < object->region_volumes.size(); ++ region_id) { - const auto& region = *object->print()->regions()[region_id]; - + for (const LayerRegion *layerm : this_layer->regions()) { + const auto ®ion = layerm->region(); if (!region.config().wipe_into_infill && !object->config().wipe_into_objects) continue; - for (const ExtrusionEntity* ee : this_layer->regions()[region_id]->fills.entities) { // iterate through all infill Collections + for (const ExtrusionEntity* ee : layerm->fills.entities) { // iterate through all infill Collections auto* fill = dynamic_cast(ee); if (!is_overriddable(*fill, print.config(), *object, region) @@ -791,7 +785,7 @@ void WipingExtrusions::ensure_perimeters_infills_order(const Print& print) } // Now the same for perimeters - see comments above for explanation: - for (const ExtrusionEntity* ee : this_layer->regions()[region_id]->perimeters.entities) { // iterate through all perimeter Collections + for (const ExtrusionEntity* ee : layerm->perimeters.entities) { // iterate through all perimeter Collections auto* fill = dynamic_cast(ee); if (is_overriddable(*fill, print.config(), *object, region) && ! is_entity_overridden(fill, copy)) set_extruder_override(fill, copy, (print.config().infill_first ? last_nonsoluble_extruder : first_nonsoluble_extruder), num_of_copies); diff --git a/src/libslic3r/GCode/WipeTower.cpp b/src/libslic3r/GCode/WipeTower.cpp index 10c68d076..fc6a15b65 100644 --- a/src/libslic3r/GCode/WipeTower.cpp +++ b/src/libslic3r/GCode/WipeTower.cpp @@ -500,9 +500,9 @@ WipeTower::ToolChangeResult WipeTower::construct_tcr(WipeTowerWriter& writer, ToolChangeResult result; result.priming = priming; result.initial_tool = int(old_tool); - result.new_tool = int(this->m_current_tool); - result.print_z = this->m_z_pos; - result.layer_height = this->m_layer_height; + result.new_tool = int(m_current_tool); + result.print_z = m_z_pos; + result.layer_height = m_layer_height; result.elapsed_time = writer.elapsed_time(); result.start_pos = writer.start_pos_rotated(); result.end_pos = priming ? writer.pos() : writer.pos_rotated(); @@ -546,10 +546,24 @@ WipeTower::WipeTower(const PrintConfig& config, const std::vector& bed_points = config.bed_shape.values; + BoundingBoxf bb(bed_points); + m_bed_width = float(bb.size().x()); m_bed_shape = (bed_points.size() == 4 ? RectangularBed : CircularBed); - m_bed_width = float(BoundingBoxf(bed_points).size().x()); + + if (m_bed_shape == CircularBed) { + // this may still be a custom bed, check that the points are roughly on a circle + double r2 = std::pow(m_bed_width/2., 2.); + double lim2 = std::pow(m_bed_width/10., 2.); + Vec2d center = bb.center(); + for (const Vec2d& pt : bed_points) + if (std::abs(std::pow(pt.x()-center.x(), 2.) + std::pow(pt.y()-center.y(), 2.) - r2) > lim2) { + m_bed_shape = CustomBed; + break; + } + } + m_bed_bottom_left = m_bed_shape == RectangularBed ? Vec2f(bed_points.front().x(), bed_points.front().y()) : Vec2f::Zero(); @@ -616,7 +630,7 @@ std::vector WipeTower::prime( bool /*last_wipe_inside_wipe_tower*/) { this->set_layer(first_layer_height, first_layer_height, tools.size(), true, false); - this->m_current_tool = tools.front(); + m_current_tool = tools.front(); // The Prusa i3 MK2 has a working space of [0, -2.2] to [250, 210]. // Due to the XYZ calibration, this working space may shrink slightly from all directions, @@ -625,10 +639,12 @@ std::vector WipeTower::prime( float prime_section_width = std::min(0.9f * m_bed_width / tools.size(), 60.f); box_coordinates cleaning_box(Vec2f(0.02f * m_bed_width, 0.01f + m_perimeter_width/2.f), prime_section_width, 100.f); - // In case of a circular bed, place it so it goes across the diameter and hope it will fit - if (m_bed_shape == CircularBed) - cleaning_box.translate(-m_bed_width/2 + m_bed_width * 0.03f, -m_bed_width * 0.12f); - if (m_bed_shape == RectangularBed) + if (m_bed_shape == CircularBed) { + cleaning_box = box_coordinates(Vec2f(0.f, 0.f), prime_section_width, 100.f); + float total_width_half = tools.size() * prime_section_width / 2.f; + cleaning_box.translate(-total_width_half, -std::sqrt(std::max(0.f, std::pow(m_bed_width/2, 2.f) - std::pow(1.05f * total_width_half, 2.f)))); + } + else cleaning_box.translate(m_bed_bottom_left); std::vector results; diff --git a/src/libslic3r/GCode/WipeTower.hpp b/src/libslic3r/GCode/WipeTower.hpp index c3b2770b7..b0c5111aa 100644 --- a/src/libslic3r/GCode/WipeTower.hpp +++ b/src/libslic3r/GCode/WipeTower.hpp @@ -164,10 +164,9 @@ public: m_current_layer_finished = false; m_current_shape = (! is_first_layer && m_current_shape == SHAPE_NORMAL) ? SHAPE_REVERSED : SHAPE_NORMAL; if (is_first_layer) { - this->m_num_layer_changes = 0; - this->m_num_tool_changes = 0; - } - else + m_num_layer_changes = 0; + m_num_tool_changes = 0; + } else ++ m_num_layer_changes; // Calculate extrusion flow from desired line width, nozzle diameter, filament diameter and layer_height: @@ -277,7 +276,8 @@ private: // Bed properties enum { RectangularBed, - CircularBed + CircularBed, + CustomBed } m_bed_shape; float m_bed_width; // width of the bed bounding box Vec2f m_bed_bottom_left; // bottom-left corner coordinates (for rectangular beds) diff --git a/src/libslic3r/GCodeReader.cpp b/src/libslic3r/GCodeReader.cpp index fb493fcb7..9753e4820 100644 --- a/src/libslic3r/GCodeReader.cpp +++ b/src/libslic3r/GCodeReader.cpp @@ -13,13 +13,13 @@ namespace Slic3r { void GCodeReader::apply_config(const GCodeConfig &config) { m_config = config; - m_extrusion_axis = m_config.get_extrusion_axis()[0]; + m_extrusion_axis = get_extrusion_axis(m_config)[0]; } void GCodeReader::apply_config(const DynamicPrintConfig &config) { m_config.apply(config, true); - m_extrusion_axis = m_config.get_extrusion_axis()[0]; + m_extrusion_axis = get_extrusion_axis(m_config)[0]; } const char* GCodeReader::parse_line_internal(const char *ptr, GCodeLine &gline, std::pair &command) diff --git a/src/libslic3r/GCodeWriter.cpp b/src/libslic3r/GCodeWriter.cpp index bc8533113..c84c7b09e 100644 --- a/src/libslic3r/GCodeWriter.cpp +++ b/src/libslic3r/GCodeWriter.cpp @@ -18,7 +18,7 @@ namespace Slic3r { void GCodeWriter::apply_print_config(const PrintConfig &print_config) { this->config.apply(print_config, true); - m_extrusion_axis = this->config.get_extrusion_axis(); + m_extrusion_axis = get_extrusion_axis(this->config); m_single_extruder_multi_material = print_config.single_extruder_multi_material.value; bool is_marlin = print_config.gcode_flavor.value == gcfMarlinLegacy || print_config.gcode_flavor.value == gcfMarlinFirmware; m_max_acceleration = std::lrint((is_marlin && print_config.machine_limits_usage.value == MachineLimitsUsage::EmitToGCode) ? diff --git a/src/libslic3r/Geometry.cpp b/src/libslic3r/Geometry.cpp index d5ef41125..e60eb01b6 100644 --- a/src/libslic3r/Geometry.cpp +++ b/src/libslic3r/Geometry.cpp @@ -1083,8 +1083,7 @@ MedialAxis::process_edge_neighbors(const VD::edge_type* edge, ThickPolyline* pol } } -bool -MedialAxis::validate_edge(const VD::edge_type* edge) +bool MedialAxis::validate_edge(const VD::edge_type* edge) { // prevent overflows and detect almost-infinite edges #ifndef CLIPPERLIB_INT32 diff --git a/src/libslic3r/Geometry.hpp b/src/libslic3r/Geometry.hpp index f6f4f5618..c6af515c8 100644 --- a/src/libslic3r/Geometry.hpp +++ b/src/libslic3r/Geometry.hpp @@ -22,12 +22,14 @@ #pragma warning(pop) #endif // _MSC_VER -namespace ClipperLib { -class PolyNode; -using PolyNodes = std::vector; -} +namespace Slic3r { -namespace Slic3r { namespace Geometry { + namespace ClipperLib { + class PolyNode; + using PolyNodes = std::vector; + } + +namespace Geometry { // Generic result of an orientation predicate. enum Orientation @@ -530,6 +532,6 @@ inline bool is_rotation_ninety_degrees(const Vec3d &rotation) return is_rotation_ninety_degrees(rotation.x()) && is_rotation_ninety_degrees(rotation.y()) && is_rotation_ninety_degrees(rotation.z()); } -} } +} } // namespace Slicer::Geometry #endif diff --git a/src/libslic3r/Layer.cpp b/src/libslic3r/Layer.cpp index b974ff217..3f2327686 100644 --- a/src/libslic3r/Layer.cpp +++ b/src/libslic3r/Layer.cpp @@ -27,7 +27,7 @@ bool Layer::empty() const return true; } -LayerRegion* Layer::add_region(PrintRegion* print_region) +LayerRegion* Layer::add_region(const PrintRegion *print_region) { m_regions.emplace_back(new LayerRegion(this, print_region)); return m_regions.back(); @@ -39,11 +39,11 @@ void Layer::make_slices() ExPolygons slices; if (m_regions.size() == 1) { // optimization: if we only have one region, take its slices - slices = m_regions.front()->slices; + slices = to_expolygons(m_regions.front()->slices.surfaces); } else { Polygons slices_p; for (LayerRegion *layerm : m_regions) - polygons_append(slices_p, to_polygons(layerm->slices)); + polygons_append(slices_p, to_polygons(layerm->slices.surfaces)); slices = union_ex(slices_p); } @@ -102,10 +102,10 @@ ExPolygons Layer::merged(float offset_scaled) const } Polygons polygons; for (LayerRegion *layerm : m_regions) { - const PrintRegionConfig &config = layerm->region()->config(); + const PrintRegionConfig &config = layerm->region().config(); // Our users learned to bend Slic3r to produce empty volumes to act as subtracters. Only add the region if it is non-empty. if (config.bottom_solid_layers > 0 || config.top_solid_layers > 0 || config.fill_density > 0. || config.perimeters > 0) - append(polygons, offset(to_expolygons(layerm->slices.surfaces), offset_scaled)); + append(polygons, offset(layerm->slices.surfaces, offset_scaled)); } ExPolygons out = union_ex(polygons); if (offset_scaled2 != 0.f) @@ -134,7 +134,7 @@ void Layer::make_perimeters() continue; BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id() << ", region " << region_id; done[region_id] = true; - const PrintRegionConfig &config = (*layerm)->region()->config(); + const PrintRegionConfig &config = (*layerm)->region().config(); // find compatible regions LayerRegionPtrs layerms; @@ -142,7 +142,7 @@ void Layer::make_perimeters() for (LayerRegionPtrs::const_iterator it = layerm + 1; it != m_regions.end(); ++it) if (! (*it)->slices.empty()) { LayerRegion* other_layerm = *it; - const PrintRegionConfig &other_config = other_layerm->region()->config(); + const PrintRegionConfig &other_config = other_layerm->region().config(); if (config.perimeter_extruder == other_config.perimeter_extruder && config.perimeters == other_config.perimeters && config.perimeter_speed == other_config.perimeter_speed @@ -180,12 +180,12 @@ void Layer::make_perimeters() for (LayerRegion *layerm : layerms) { for (Surface &surface : layerm->slices.surfaces) slices[surface.extra_perimeters].emplace_back(surface); - if (layerm->region()->config().fill_density > layerm_config->region()->config().fill_density) + if (layerm->region().config().fill_density > layerm_config->region().config().fill_density) layerm_config = layerm; } // merge the surfaces assigned to each group for (std::pair &surfaces_with_extra_perimeters : slices) - new_slices.append(union_ex(surfaces_with_extra_perimeters.second, true), surfaces_with_extra_perimeters.second.front()); + new_slices.append(offset_ex(surfaces_with_extra_perimeters.second, ClipperSafetyOffset), surfaces_with_extra_perimeters.second.front()); } // make perimeters @@ -196,7 +196,7 @@ void Layer::make_perimeters() if (!fill_surfaces.surfaces.empty()) { for (LayerRegionPtrs::iterator l = layerms.begin(); l != layerms.end(); ++l) { // Separate the fill surfaces. - ExPolygons expp = intersection_ex(to_polygons(fill_surfaces), (*l)->slices); + ExPolygons expp = intersection_ex(fill_surfaces.surfaces, (*l)->slices.surfaces); (*l)->fill_expolygons = expp; (*l)->fill_surfaces.set(std::move(expp), fill_surfaces.surfaces.front()); } diff --git a/src/libslic3r/Layer.hpp b/src/libslic3r/Layer.hpp index 87296f8f1..102a991ca 100644 --- a/src/libslic3r/Layer.hpp +++ b/src/libslic3r/Layer.hpp @@ -22,8 +22,7 @@ class LayerRegion public: Layer* layer() { return m_layer; } const Layer* layer() const { return m_layer; } - PrintRegion* region() { return m_region; } - const PrintRegion* region() const { return m_region; } + const PrintRegion& region() const { return *m_region; } // collection of surfaces generated by slicing the original geometry // divided by type top/bottom/internal @@ -86,12 +85,12 @@ public: protected: friend class Layer; - LayerRegion(Layer *layer, PrintRegion *region) : m_layer(layer), m_region(region) {} + LayerRegion(Layer *layer, const PrintRegion *region) : m_layer(layer), m_region(region) {} ~LayerRegion() {} private: - Layer *m_layer; - PrintRegion *m_region; + Layer *m_layer; + const PrintRegion *m_region; }; @@ -126,9 +125,9 @@ public: std::vector lslices_bboxes; size_t region_count() const { return m_regions.size(); } - const LayerRegion* get_region(int idx) const { return m_regions.at(idx); } + const LayerRegion* get_region(int idx) const { return m_regions[idx]; } LayerRegion* get_region(int idx) { return m_regions[idx]; } - LayerRegion* add_region(PrintRegion* print_region); + LayerRegion* add_region(const PrintRegion *print_region); const LayerRegionPtrs& regions() const { return m_regions; } // Test whether whether there are any slices assigned to this layer. bool empty() const; @@ -196,7 +195,7 @@ protected: // between the raft and the object first layer. SupportLayer(size_t id, PrintObject *object, coordf_t height, coordf_t print_z, coordf_t slice_z) : Layer(id, object, height, print_z, slice_z) {} - virtual ~SupportLayer() {} + virtual ~SupportLayer() = default; }; } diff --git a/src/libslic3r/LayerRegion.cpp b/src/libslic3r/LayerRegion.cpp index 059d94e25..356811b74 100644 --- a/src/libslic3r/LayerRegion.cpp +++ b/src/libslic3r/LayerRegion.cpp @@ -27,13 +27,14 @@ Flow LayerRegion::flow(FlowRole role, double layer_height) const Flow LayerRegion::bridging_flow(FlowRole role) const { - const PrintRegion ®ion = *this->region(); + const PrintRegion ®ion = this->region(); const PrintRegionConfig ®ion_config = region.config(); - if (this->layer()->object()->config().thick_bridges) { + const PrintObject &print_object = *this->layer()->object(); + if (print_object.config().thick_bridges) { // The old Slic3r way (different from all other slicers): Use rounded extrusions. // Get the configured nozzle_diameter for the extruder associated to the flow role requested. // Here this->extruder(role) - 1 may underflow to MAX_INT, but then the get_at() will follback to zero'th element, so everything is all right. - auto nozzle_diameter = float(region.print()->config().nozzle_diameter.get_at(region.extruder(role) - 1)); + auto nozzle_diameter = float(print_object.print()->config().nozzle_diameter.get_at(region.extruder(role) - 1)); // Applies default bridge spacing. return Flow::bridging_flow(float(sqrt(region_config.bridge_flow_ratio)) * nozzle_diameter, nozzle_diameter); } else { @@ -49,19 +50,17 @@ void LayerRegion::slices_to_fill_surfaces_clipped() // in place. However we're now only using its boundaries (which are invariant) // so we're safe. This guarantees idempotence of prepare_infill() also in case // that combine_infill() turns some fill_surface into VOID surfaces. -// Polygons fill_boundaries = to_polygons(std::move(this->fill_surfaces)); - Polygons fill_boundaries = to_polygons(this->fill_expolygons); // Collect polygons per surface type. - std::vector polygons_by_surface; - polygons_by_surface.assign(size_t(stCount), Polygons()); + std::vector by_surface; + by_surface.assign(size_t(stCount), SurfacesPtr()); for (Surface &surface : this->slices.surfaces) - polygons_append(polygons_by_surface[(size_t)surface.surface_type], surface.expolygon); + by_surface[size_t(surface.surface_type)].emplace_back(&surface); // Trim surfaces by the fill_boundaries. this->fill_surfaces.surfaces.clear(); for (size_t surface_type = 0; surface_type < size_t(stCount); ++ surface_type) { - const Polygons &polygons = polygons_by_surface[surface_type]; - if (! polygons.empty()) - this->fill_surfaces.append(intersection_ex(polygons, fill_boundaries), SurfaceType(surface_type)); + const SurfacesPtr &this_surfaces = by_surface[surface_type]; + if (! this_surfaces.empty()) + this->fill_surfaces.append(intersection_ex(this_surfaces, this->fill_expolygons), SurfaceType(surface_type)); } } @@ -71,7 +70,7 @@ void LayerRegion::make_perimeters(const SurfaceCollection &slices, SurfaceCollec this->thin_fills.clear(); const PrintConfig &print_config = this->layer()->object()->print()->config(); - const PrintRegionConfig ®ion_config = this->region()->config(); + const PrintRegionConfig ®ion_config = this->region().config(); // This needs to be in sync with PrintObject::_slice() slicing_mode_normal_below_layer! bool spiral_vase = print_config.spiral_vase && //FIXME account for raft layers. @@ -112,7 +111,7 @@ void LayerRegion::make_perimeters(const SurfaceCollection &slices, SurfaceCollec void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Polygons *lower_layer_covered) { - const bool has_infill = this->region()->config().fill_density.value > 0.; + const bool has_infill = this->region().config().fill_density.value > 0.; const float margin = float(scale_(EXTERNAL_INFILL_MARGIN)); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING @@ -180,11 +179,11 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly if (bridges.empty()) { - fill_boundaries = union_(fill_boundaries, true); + fill_boundaries = union_safety_offset(fill_boundaries); } else { // 1) Calculate the inflated bridge regions, each constrained to its island. - ExPolygons fill_boundaries_ex = union_ex(fill_boundaries, true); + ExPolygons fill_boundaries_ex = union_safety_offset_ex(fill_boundaries); std::vector bridges_grown; std::vector bridge_bboxes; @@ -221,7 +220,7 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly BOOST_LOG_TRIVIAL(trace) << "Bridge did not fall into the source region!"; } else { // Found an island, to which this bridge region belongs. Trim it, - polys = intersection(polys, to_polygons(fill_boundaries_ex[idx_island])); + polys = intersection(polys, fill_boundaries_ex[idx_island]); } bridge_bboxes.push_back(get_extents(polys)); bridges_grown.push_back(std::move(polys)); @@ -239,7 +238,7 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly for (size_t j = i + 1; j < bridges.size(); ++ j) { if (! bridge_bboxes[i].overlap(bridge_bboxes[j])) continue; - if (intersection(bridges_grown[i], bridges_grown[j], false).empty()) + if (intersection(bridges_grown[i], bridges_grown[j]).empty()) continue; // The two bridge regions intersect. Give them the same group id. if (bridge_group[j] != size_t(-1)) { @@ -286,7 +285,7 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly #ifdef SLIC3R_DEBUG printf("Processing bridge at layer %zu:\n", this->layer()->id()); #endif - double custom_angle = Geometry::deg2rad(this->region()->config().bridge_angle.value); + double custom_angle = Geometry::deg2rad(this->region().config().bridge_angle.value); if (bd.detect_angle(custom_angle)) { bridges[idx_last].bridge_angle = bd.angle; if (this->layer()->object()->has_support()) { @@ -299,7 +298,7 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly bridges[idx_last].bridge_angle = custom_angle; } // without safety offset, artifacts are generated (GH #2494) - surfaces_append(bottom, union_ex(grown, true), bridges[idx_last]); + surfaces_append(bottom, union_safety_offset_ex(grown), bridges[idx_last]); } fill_boundaries = to_polygons(fill_boundaries_ex); @@ -325,11 +324,11 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly if (s1.empty()) continue; Polygons polys; - polygons_append(polys, std::move(s1)); + polygons_append(polys, to_polygons(std::move(s1))); for (size_t j = i + 1; j < top.size(); ++ j) { Surface &s2 = top[j]; if (! s2.empty() && surfaces_could_merge(s1, s2)) { - polygons_append(polys, std::move(s2)); + polygons_append(polys, to_polygons(std::move(s2))); s2.clear(); } } @@ -339,7 +338,7 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly surfaces_append( new_surfaces, // Don't use a safety offset as fill_boundaries were already united using the safety offset. - intersection_ex(polys, fill_boundaries, false), + intersection_ex(polys, fill_boundaries), s1); } } @@ -351,11 +350,11 @@ void LayerRegion::process_external_surfaces(const Layer *lower_layer, const Poly if (s1.empty()) continue; Polygons polys; - polygons_append(polys, std::move(s1)); + polygons_append(polys, to_polygons(std::move(s1))); for (size_t j = i + 1; j < internal.size(); ++ j) { Surface &s2 = internal[j]; if (! s2.empty() && surfaces_could_merge(s1, s2)) { - polygons_append(polys, std::move(s2)); + polygons_append(polys, to_polygons(std::move(s2))); s2.clear(); } } @@ -385,21 +384,21 @@ void LayerRegion::prepare_fill_surfaces() bool spiral_vase = this->layer()->object()->print()->config().spiral_vase; // if no solid layers are requested, turn top/bottom surfaces to internal - if (! spiral_vase && this->region()->config().top_solid_layers == 0) { + if (! spiral_vase && this->region().config().top_solid_layers == 0) { for (Surface &surface : this->fill_surfaces.surfaces) if (surface.is_top()) surface.surface_type = this->layer()->object()->config().infill_only_where_needed ? stInternalVoid : stInternal; } - if (this->region()->config().bottom_solid_layers == 0) { + if (this->region().config().bottom_solid_layers == 0) { for (Surface &surface : this->fill_surfaces.surfaces) if (surface.is_bottom()) // (surface.surface_type == stBottom) surface.surface_type = stInternal; } // turn too small internal regions into solid regions according to the user setting - if (! spiral_vase && this->region()->config().fill_density.value > 0) { + if (! spiral_vase && this->region().config().fill_density.value > 0) { // scaling an area requires two calls! - double min_area = scale_(scale_(this->region()->config().solid_infill_below_area.value)); + double min_area = scale_(scale_(this->region().config().solid_infill_below_area.value)); for (Surface &surface : this->fill_surfaces.surfaces) if (surface.surface_type == stInternal && surface.area() <= min_area) surface.surface_type = stInternalSolid; @@ -423,7 +422,7 @@ void LayerRegion::trim_surfaces(const Polygons &trimming_polygons) for (const Surface &surface : this->slices.surfaces) assert(surface.surface_type == stInternal); #endif /* NDEBUG */ - this->slices.set(intersection_ex(to_polygons(std::move(this->slices.surfaces)), trimming_polygons, false), stInternal); + this->slices.set(intersection_ex(this->slices.surfaces, trimming_polygons), stInternal); } void LayerRegion::elephant_foot_compensation_step(const float elephant_foot_compensation_perimeter_step, const Polygons &trimming_polygons) @@ -432,10 +431,9 @@ void LayerRegion::elephant_foot_compensation_step(const float elephant_foot_comp for (const Surface &surface : this->slices.surfaces) assert(surface.surface_type == stInternal); #endif /* NDEBUG */ - ExPolygons slices_expolygons = to_expolygons(std::move(this->slices.surfaces)); - Polygons slices_polygons = to_polygons(slices_expolygons); - Polygons tmp = intersection(slices_polygons, trimming_polygons, false); - append(tmp, diff(slices_polygons, offset(offset_ex(slices_expolygons, -elephant_foot_compensation_perimeter_step), elephant_foot_compensation_perimeter_step))); + ExPolygons surfaces = to_expolygons(std::move(this->slices.surfaces)); + Polygons tmp = intersection(surfaces, trimming_polygons); + append(tmp, diff(surfaces, offset(offset_ex(surfaces, -elephant_foot_compensation_perimeter_step), elephant_foot_compensation_perimeter_step))); this->slices.set(union_ex(tmp), stInternal); } diff --git a/src/libslic3r/Line.hpp b/src/libslic3r/Line.hpp index 72532b4e3..b62775bfe 100644 --- a/src/libslic3r/Line.hpp +++ b/src/libslic3r/Line.hpp @@ -4,6 +4,8 @@ #include "libslic3r.h" #include "Point.hpp" +#include + namespace Slic3r { class BoundingBox; @@ -20,12 +22,28 @@ Linef3 transform(const Linef3& line, const Transform3d& t); namespace line_alg { +template struct Traits { + static constexpr int Dim = L::Dim; + using Scalar = typename L::Scalar; + + static Vec& get_a(L &l) { return l.a; } + static Vec& get_b(L &l) { return l.b; } + static const Vec& get_a(const L &l) { return l.a; } + static const Vec& get_b(const L &l) { return l.b; } +}; + +template const constexpr int Dim = Traits>::Dim; +template using Scalar = typename Traits>::Scalar; + +template auto get_a(L &&l) { return Traits>::get_a(l); } +template auto get_b(L &&l) { return Traits>::get_b(l); } + // Distance to the closest point of line. -template -double distance_to_squared(const L &line, const Vec &point) +template +double distance_to_squared(const L &line, const Vec, Scalar> &point) { - const Vec v = (line.b - line.a).template cast(); - const Vec va = (point - line.a).template cast(); + const Vec, double> v = (get_b(line) - get_a(line)).template cast(); + const Vec, double> va = (point - get_a(line)).template cast(); const double l2 = v.squaredNorm(); // avoid a sqrt if (l2 == 0.0) // a == b case @@ -35,12 +53,12 @@ double distance_to_squared(const L &line, const Vec &point) // It falls where t = [(this-a) . (b-a)] / |b-a|^2 const double t = va.dot(v) / l2; if (t < 0.0) return va.squaredNorm(); // beyond the 'a' end of the segment - else if (t > 1.0) return (point - line.b).template cast().squaredNorm(); // beyond the 'b' end of the segment + else if (t > 1.0) return (point - get_b(line)).template cast().squaredNorm(); // beyond the 'b' end of the segment return (t * v - va).squaredNorm(); } -template -double distance_to(const L &line, const Vec &point) +template +double distance_to(const L &line, const Vec, Scalar> &point) { return std::sqrt(distance_to_squared(line, point)); } @@ -84,6 +102,9 @@ public: Point a; Point b; + + static const constexpr int Dim = 2; + using Scalar = Point::Scalar; }; class ThickLine : public Line @@ -107,6 +128,9 @@ public: Vec3crd a; Vec3crd b; + + static const constexpr int Dim = 3; + using Scalar = Vec3crd::Scalar; }; class Linef @@ -117,6 +141,9 @@ public: Vec2d a; Vec2d b; + + static const constexpr int Dim = 2; + using Scalar = Vec2d::Scalar; }; class Linef3 @@ -133,6 +160,9 @@ public: Vec3d a; Vec3d b; + + static const constexpr int Dim = 3; + using Scalar = Vec3d::Scalar; }; BoundingBox get_extents(const Lines &lines); diff --git a/src/libslic3r/MTUtils.hpp b/src/libslic3r/MTUtils.hpp index 7b903f66c..9e77aa90a 100644 --- a/src/libslic3r/MTUtils.hpp +++ b/src/libslic3r/MTUtils.hpp @@ -106,8 +106,8 @@ template bool all_of(const C &container) }); } -template -using remove_cvref_t = std::remove_reference_t>; +//template +//using remove_cvref_t = std::remove_reference_t>; /// Exactly like Matlab https://www.mathworks.com/help/matlab/ref/linspace.html template> diff --git a/src/libslic3r/MinAreaBoundingBox.cpp b/src/libslic3r/MinAreaBoundingBox.cpp index 15c04517d..51fd8a45e 100644 --- a/src/libslic3r/MinAreaBoundingBox.cpp +++ b/src/libslic3r/MinAreaBoundingBox.cpp @@ -14,55 +14,9 @@ #include #endif -#include +#include #include -namespace libnest2d { - -template<> struct PointType { using Type = Slic3r::Point; }; -template<> struct CoordType { using Type = coord_t; }; -template<> struct ShapeTag { using Type = PolygonTag; }; -template<> struct ShapeTag { using Type = PolygonTag; }; -template<> struct ShapeTag { using Type = PathTag; }; -template<> struct ShapeTag { using Type = PointTag; }; -template<> struct ContourType { using Type = Slic3r::Points; }; -template<> struct ContourType { using Type = Slic3r::Points; }; - -namespace pointlike { - -template<> inline coord_t x(const Slic3r::Point& p) { return p.x(); } -template<> inline coord_t y(const Slic3r::Point& p) { return p.y(); } -template<> inline coord_t& x(Slic3r::Point& p) { return p.x(); } -template<> inline coord_t& y(Slic3r::Point& p) { return p.y(); } - -} // pointlike - -namespace shapelike { -template<> inline Slic3r::Points& contour(Slic3r::ExPolygon& sh) { return sh.contour.points; } -template<> inline const Slic3r::Points& contour(const Slic3r::ExPolygon& sh) { return sh.contour.points; } -template<> inline Slic3r::Points& contour(Slic3r::Polygon& sh) { return sh.points; } -template<> inline const Slic3r::Points& contour(const Slic3r::Polygon& sh) { return sh.points; } - -template<> Slic3r::Points::iterator begin(Slic3r::Points& pts, const PathTag&) { return pts.begin();} -template<> Slic3r::Points::const_iterator cbegin(const Slic3r::Points& pts, const PathTag&) { return pts.cbegin(); } -template<> Slic3r::Points::iterator end(Slic3r::Points& pts, const PathTag&) { return pts.end();} -template<> Slic3r::Points::const_iterator cend(const Slic3r::Points& pts, const PathTag&) { return pts.cend(); } - -template<> inline Slic3r::ExPolygon create(Slic3r::Points&& contour) -{ - Slic3r::ExPolygon expoly; expoly.contour.points.swap(contour); - return expoly; -} - -template<> inline Slic3r::Polygon create(Slic3r::Points&& contour) -{ - Slic3r::Polygon poly; poly.points.swap(contour); - return poly; -} - -} // shapelike -} // libnest2d - namespace Slic3r { // Used as compute type. @@ -74,13 +28,22 @@ using Rational = boost::rational; using Rational = boost::rational<__int128>; #endif +template +libnest2d::RotatedBox minAreaBoundigBox_( + const P &p, MinAreaBoundigBox::PolygonLevel lvl) +{ + P chull = lvl == MinAreaBoundigBox::pcConvex ? + p : + libnest2d::sl::convexHull(p); + + libnest2d::removeCollinearPoints(chull); + + return libnest2d::minAreaBoundingBox(chull); +} + MinAreaBoundigBox::MinAreaBoundigBox(const Polygon &p, PolygonLevel pc) { - const Polygon &chull = pc == pcConvex ? p : - libnest2d::sl::convexHull(p); - - libnest2d::RotatedBox box = - libnest2d::minAreaBoundingBox(chull); + libnest2d::RotatedBox box = minAreaBoundigBox_(p, pc); m_right = libnest2d::cast(box.right_extent()); m_bottom = libnest2d::cast(box.bottom_extent()); @@ -89,11 +52,7 @@ MinAreaBoundigBox::MinAreaBoundigBox(const Polygon &p, PolygonLevel pc) MinAreaBoundigBox::MinAreaBoundigBox(const ExPolygon &p, PolygonLevel pc) { - const ExPolygon &chull = pc == pcConvex ? p : - libnest2d::sl::convexHull(p); - - libnest2d::RotatedBox box = - libnest2d::minAreaBoundingBox(chull); + libnest2d::RotatedBox box = minAreaBoundigBox_(p, pc); m_right = libnest2d::cast(box.right_extent()); m_bottom = libnest2d::cast(box.bottom_extent()); @@ -102,11 +61,7 @@ MinAreaBoundigBox::MinAreaBoundigBox(const ExPolygon &p, PolygonLevel pc) MinAreaBoundigBox::MinAreaBoundigBox(const Points &pts, PolygonLevel pc) { - const Points &chull = pc == pcConvex ? pts : - libnest2d::sl::convexHull(pts); - - libnest2d::RotatedBox box = - libnest2d::minAreaBoundingBox(chull); + libnest2d::RotatedBox box = minAreaBoundigBox_(pts, pc); m_right = libnest2d::cast(box.right_extent()); m_bottom = libnest2d::cast(box.bottom_extent()); diff --git a/src/libslic3r/MinAreaBoundingBox.hpp b/src/libslic3r/MinAreaBoundingBox.hpp index 30d0e9799..242fc9611 100644 --- a/src/libslic3r/MinAreaBoundingBox.hpp +++ b/src/libslic3r/MinAreaBoundingBox.hpp @@ -26,12 +26,8 @@ public: }; // Constructors with various types of geometry data used in Slic3r. - // If the convexity is known apriory, pcConvex can be used to skip - // convex hull calculation. It is very important that the input polygons - // do NOT have any collinear points (except for the first and the last - // vertex being the same -- meaning a closed polygon for boost) - // To make sure this constraint is satisfied, you can call - // remove_collinear_points on the input polygon before handing over here) + // If the convexity is known apriory, pcConvex can be used to skip + // convex hull calculation. explicit MinAreaBoundigBox(const Polygon&, PolygonLevel = pcSimple); explicit MinAreaBoundigBox(const ExPolygon&, PolygonLevel = pcSimple); explicit MinAreaBoundigBox(const Points&, PolygonLevel = pcSimple); diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index c82627b38..a02eb738b 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -833,18 +833,6 @@ indexed_triangle_set ModelObject::raw_indexed_triangle_set() const return out; } -// Non-transformed (non-rotated, non-scaled, non-translated) sum of all object volumes. -TriangleMesh ModelObject::full_raw_mesh() const -{ - TriangleMesh mesh; - for (const ModelVolume *v : this->volumes) - { - TriangleMesh vol_mesh(v->mesh()); - vol_mesh.transform(v->get_matrix()); - mesh.merge(vol_mesh); - } - return mesh; -} const BoundingBoxf3& ModelObject::raw_mesh_bounding_box() const { @@ -1822,7 +1810,7 @@ void ModelVolume::transform_this_mesh(const Transform3d &mesh_trafo, bool fix_le this->set_mesh(std::move(mesh)); TriangleMesh convex_hull = this->get_convex_hull(); convex_hull.transform(mesh_trafo, fix_left_handed); - this->m_convex_hull = std::make_shared(std::move(convex_hull)); + m_convex_hull = std::make_shared(std::move(convex_hull)); // Let the rest of the application know that the geometry changed, so the meshes have to be reloaded. this->set_new_unique_id(); } @@ -1834,7 +1822,7 @@ void ModelVolume::transform_this_mesh(const Matrix3d &matrix, bool fix_left_hand this->set_mesh(std::move(mesh)); TriangleMesh convex_hull = this->get_convex_hull(); convex_hull.transform(matrix, fix_left_handed); - this->m_convex_hull = std::make_shared(std::move(convex_hull)); + m_convex_hull = std::make_shared(std::move(convex_hull)); // Let the rest of the application know that the geometry changed, so the meshes have to be reloaded. this->set_new_unique_id(); } diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index 3e2c9a3c5..ffb6dc718 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -180,8 +180,8 @@ private: class LayerHeightProfile final : public ObjectWithTimestamp { public: // Assign the content if the timestamp differs, don't assign an ObjectID. - void assign(const LayerHeightProfile &rhs) { if (! this->timestamp_matches(rhs)) { this->m_data = rhs.m_data; this->copy_timestamp(rhs); } } - void assign(LayerHeightProfile &&rhs) { if (! this->timestamp_matches(rhs)) { this->m_data = std::move(rhs.m_data); this->copy_timestamp(rhs); } } + void assign(const LayerHeightProfile &rhs) { if (! this->timestamp_matches(rhs)) { m_data = rhs.m_data; this->copy_timestamp(rhs); } } + void assign(LayerHeightProfile &&rhs) { if (! this->timestamp_matches(rhs)) { m_data = std::move(rhs.m_data); this->copy_timestamp(rhs); } } std::vector get() const throw() { return m_data; } bool empty() const throw() { return m_data.empty(); } @@ -289,8 +289,6 @@ public: TriangleMesh raw_mesh() const; // The same as above, but producing a lightweight indexed_triangle_set. indexed_triangle_set raw_indexed_triangle_set() const; - // Non-transformed (non-rotated, non-scaled, non-translated) sum of all object volumes. - TriangleMesh full_raw_mesh() const; // A transformed snug bounding box around the non-modifier object volumes, without the translation applied. // This bounding box is only used for the actual slicing. const BoundingBoxf3& raw_bounding_box() const; @@ -510,8 +508,8 @@ enum class ConversionType : int { class FacetsAnnotation final : public ObjectWithTimestamp { public: // Assign the content if the timestamp differs, don't assign an ObjectID. - void assign(const FacetsAnnotation& rhs) { if (! this->timestamp_matches(rhs)) { this->m_data = rhs.m_data; this->copy_timestamp(rhs); } } - void assign(FacetsAnnotation&& rhs) { if (! this->timestamp_matches(rhs)) { this->m_data = std::move(rhs.m_data); this->copy_timestamp(rhs); } } + void assign(const FacetsAnnotation& rhs) { if (! this->timestamp_matches(rhs)) { m_data = rhs.m_data; this->copy_timestamp(rhs); } } + void assign(FacetsAnnotation&& rhs) { if (! this->timestamp_matches(rhs)) { m_data = std::move(rhs.m_data); this->copy_timestamp(rhs); } } const std::map>& get_data() const throw() { return m_data; } bool set(const TriangleSelector& selector); indexed_triangle_set get_facets(const ModelVolume& mv, EnforcerBlockerType type) const; @@ -686,6 +684,7 @@ protected: friend class SLAPrint; friend class Model; friend class ModelObject; + friend void model_volume_list_update_supports(ModelObject& model_object_dst, const ModelObject& model_object_new); // Copies IDs of both the ModelVolume and its config. explicit ModelVolume(const ModelVolume &rhs) = default; diff --git a/src/libslic3r/MultiPoint.hpp b/src/libslic3r/MultiPoint.hpp index d17142bb2..46b47832a 100644 --- a/src/libslic3r/MultiPoint.hpp +++ b/src/libslic3r/MultiPoint.hpp @@ -84,6 +84,13 @@ public: static Points _douglas_peucker(const Points &points, const double tolerance); static Points visivalingam(const Points& pts, const double& tolerance); + + inline auto begin() { return points.begin(); } + inline auto begin() const { return points.begin(); } + inline auto end() { return points.end(); } + inline auto end() const { return points.end(); } + inline auto cbegin() const { return points.begin(); } + inline auto cend() const { return points.end(); } }; class MultiPoint3 diff --git a/src/libslic3r/MutablePolygon.hpp b/src/libslic3r/MutablePolygon.hpp index ef2b61221..14d7787cf 100644 --- a/src/libslic3r/MutablePolygon.hpp +++ b/src/libslic3r/MutablePolygon.hpp @@ -52,7 +52,7 @@ public: PointType* operator->() const { return &m_data->at(m_idx).point; } MutablePolygon& polygon() const { assert(this->valid()); return *m_data; } IndexType size() const { assert(this->valid()); return m_data->size(); } - iterator& remove() { this->m_idx = m_data->remove(*this).m_idx; return *this; } + iterator& remove() { m_idx = m_data->remove(*this).m_idx; return *this; } iterator insert(const PointType pt) const { return m_data->insert(*this, pt); } private: iterator(MutablePolygon *data, IndexType idx) : m_data(data), m_idx(idx) {} @@ -162,10 +162,10 @@ public: return out; }; - bool empty() const { return this->m_size == 0; } - size_t size() const { return this->m_size; } - size_t capacity() const { return this->m_data.capacity(); } - bool valid() const { return this->m_size >= 3; } + bool empty() const { return m_size == 0; } + size_t size() const { return m_size; } + size_t capacity() const { return m_data.capacity(); } + bool valid() const { return m_size >= 3; } void clear() { m_data.clear(); m_size = 0; m_head = IndexType(-1); m_head_free = IndexType(-1); } iterator begin() { return { this, m_head }; } diff --git a/src/libslic3r/Optimize/NLoptOptimizer.hpp b/src/libslic3r/Optimize/NLoptOptimizer.hpp index 826b1632a..f5d314046 100644 --- a/src/libslic3r/Optimize/NLoptOptimizer.hpp +++ b/src/libslic3r/Optimize/NLoptOptimizer.hpp @@ -121,8 +121,8 @@ protected: if(!std::isnan(rel_diff)) nlopt_set_ftol_rel(nl.ptr, rel_diff); if(!std::isnan(stopval)) nlopt_set_stopval(nl.ptr, stopval); - if(this->m_stopcr.max_iterations() > 0) - nlopt_set_maxeval(nl.ptr, this->m_stopcr.max_iterations()); + if(m_stopcr.max_iterations() > 0) + nlopt_set_maxeval(nl.ptr, m_stopcr.max_iterations()); } template diff --git a/src/libslic3r/Optimize/Optimizer.hpp b/src/libslic3r/Optimize/Optimizer.hpp index 05191eba2..8ae55c61c 100644 --- a/src/libslic3r/Optimize/Optimizer.hpp +++ b/src/libslic3r/Optimize/Optimizer.hpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace Slic3r { namespace opt { diff --git a/src/libslic3r/PNGReadWrite.cpp b/src/libslic3r/PNGReadWrite.cpp index 3308f1fd4..51bf7de7c 100644 --- a/src/libslic3r/PNGReadWrite.cpp +++ b/src/libslic3r/PNGReadWrite.cpp @@ -103,6 +103,7 @@ bool decode_png(IStream &in_buf, ImageGreyscale &out_img) // Down to earth function to store a packed RGB image to file. Mostly useful for debugging purposes. // Based on https://www.lemoda.net/c/write-png/ // png_color_type is PNG_COLOR_TYPE_RGB or PNG_COLOR_TYPE_GRAY +//FIXME maybe better to use tdefl_write_image_to_png_file_in_memory() instead? static bool write_rgb_or_gray_to_file(const char *file_name_utf8, size_t width, size_t height, int png_color_type, const uint8_t *data) { bool result = false; diff --git a/src/libslic3r/PerimeterGenerator.cpp b/src/libslic3r/PerimeterGenerator.cpp index 6ec4dbf6b..3190845bd 100644 --- a/src/libslic3r/PerimeterGenerator.cpp +++ b/src/libslic3r/PerimeterGenerator.cpp @@ -349,9 +349,7 @@ void PerimeterGenerator::process() coord_t min_width = coord_t(scale_(this->ext_perimeter_flow.nozzle_diameter() / 3)); ExPolygons expp = offset2_ex( // medial axis requires non-overlapping geometry - diff_ex(to_polygons(last), - offset(offsets, float(ext_perimeter_width / 2.)), - true), + diff_ex(last, offset(offsets, float(ext_perimeter_width / 2.) + ClipperSafetyOffset)), - float(min_width / 2.), float(min_width / 2.)); // the maximum thickness of our thin wall area is equal to the minimum thickness of a single loop for (ExPolygon &ex : expp) @@ -498,8 +496,7 @@ void PerimeterGenerator::process() ExPolygons gaps_ex = diff_ex( //FIXME offset2 would be enough and cheaper. offset2_ex(gaps, - float(min / 2.), float(min / 2.)), - offset2_ex(gaps, - float(max / 2.), float(max / 2.)), - true); + offset2_ex(gaps, - float(max / 2.), float(max / 2. + ClipperSafetyOffset))); ThickPolylines polylines; for (const ExPolygon &ex : gaps_ex) ex.medial_axis(max, min, &polylines); @@ -514,7 +511,7 @@ void PerimeterGenerator::process() and use zigzag). */ //FIXME Vojtech: This grows by a rounded extrusion width, not by line spacing, // therefore it may cover the area, but no the volume. - last = diff_ex(to_polygons(last), gap_fill.polygons_covered_by_width(10.f)); + last = diff_ex(last, gap_fill.polygons_covered_by_width(10.f)); this->gap_fill->append(std::move(gap_fill.entities)); } } diff --git a/src/libslic3r/Point.hpp b/src/libslic3r/Point.hpp index f38a7066b..12870b713 100644 --- a/src/libslic3r/Point.hpp +++ b/src/libslic3r/Point.hpp @@ -17,42 +17,42 @@ class BoundingBox; class Line; class MultiPoint; class Point; -typedef Point Vector; +using Vector = Point; // Eigen types, to replace the Slic3r's own types in the future. // Vector types with a fixed point coordinate base type. -typedef Eigen::Matrix Vec2crd; -typedef Eigen::Matrix Vec3crd; -typedef Eigen::Matrix Vec2i; -typedef Eigen::Matrix Vec3i; -typedef Eigen::Matrix Vec2i32; -typedef Eigen::Matrix Vec2i64; -typedef Eigen::Matrix Vec3i32; -typedef Eigen::Matrix Vec3i64; +using Vec2crd = Eigen::Matrix; +using Vec3crd = Eigen::Matrix; +using Vec2i = Eigen::Matrix; +using Vec3i = Eigen::Matrix; +using Vec2i32 = Eigen::Matrix; +using Vec2i64 = Eigen::Matrix; +using Vec3i32 = Eigen::Matrix; +using Vec3i64 = Eigen::Matrix; // Vector types with a double coordinate base type. -typedef Eigen::Matrix Vec2f; -typedef Eigen::Matrix Vec3f; -typedef Eigen::Matrix Vec2d; -typedef Eigen::Matrix Vec3d; +using Vec2f = Eigen::Matrix; +using Vec3f = Eigen::Matrix; +using Vec2d = Eigen::Matrix; +using Vec3d = Eigen::Matrix; -typedef std::vector Points; -typedef std::vector PointPtrs; -typedef std::vector PointConstPtrs; -typedef std::vector Points3; -typedef std::vector Pointfs; -typedef std::vector Vec2ds; -typedef std::vector Pointf3s; +using Points = std::vector; +using PointPtrs = std::vector; +using PointConstPtrs = std::vector; +using Points3 = std::vector; +using Pointfs = std::vector; +using Vec2ds = std::vector; +using Pointf3s = std::vector; -typedef Eigen::Matrix Matrix2f; -typedef Eigen::Matrix Matrix2d; -typedef Eigen::Matrix Matrix3f; -typedef Eigen::Matrix Matrix3d; +using Matrix2f = Eigen::Matrix; +using Matrix2d = Eigen::Matrix; +using Matrix3f = Eigen::Matrix; +using Matrix3d = Eigen::Matrix; -typedef Eigen::Transform Transform2f; -typedef Eigen::Transform Transform2d; -typedef Eigen::Transform Transform3f; -typedef Eigen::Transform Transform3d; +using Transform2f = Eigen::Transform; +using Transform2d = Eigen::Transform; +using Transform3f = Eigen::Transform; +using Transform3d = Eigen::Transform; inline bool operator<(const Vec2d &lhs, const Vec2d &rhs) { return lhs(0) < rhs(0) || (lhs(0) == rhs(0) && lhs(1) < rhs(1)); } @@ -101,7 +101,7 @@ template using Vec = Eigen::Matrix map_type; + using map_type = typename std::unordered_multimap; PointAccessor m_point_accessor; map_type m_map; coord_t m_search_radius; @@ -439,11 +439,11 @@ inline Point align_to_grid(Point coord, Point spacing, Point base) #include namespace boost { namespace polygon { template <> - struct geometry_concept { typedef point_concept type; }; + struct geometry_concept { using type = point_concept; }; template <> struct point_traits { - typedef coord_t coordinate_type; + using coordinate_type = coord_t; static inline coordinate_type get(const Slic3r::Point& point, orientation_2d orient) { return static_cast(point((orient == HORIZONTAL) ? 0 : 1)); @@ -452,7 +452,7 @@ namespace boost { namespace polygon { template <> struct point_mutable_traits { - typedef coord_t coordinate_type; + using coordinate_type = coord_t; static inline void set(Slic3r::Point& point, orientation_2d orient, coord_t value) { point((orient == HORIZONTAL) ? 0 : 1) = value; } diff --git a/src/libslic3r/Polygon.cpp b/src/libslic3r/Polygon.cpp index 7c588c67c..5b180afca 100644 --- a/src/libslic3r/Polygon.cpp +++ b/src/libslic3r/Polygon.cpp @@ -33,32 +33,16 @@ Polyline Polygon::split_at_index(int index) const return polyline; } -/* -int64_t Polygon::area2x() const -{ - size_t n = poly.size(); - if (n < 3) - return 0; - - int64_t a = 0; - for (size_t i = 0, j = n - 1; i < n; ++i) - a += int64_t(poly[j](0) + poly[i](0)) * int64_t(poly[j](1) - poly[i](1)); - j = i; - } - return -a * 0.5; -} -*/ - double Polygon::area(const Points &points) { - size_t n = points.size(); - if (n < 3) - return 0.; - double a = 0.; - for (size_t i = 0, j = n - 1; i < n; ++i) { - a += ((double)points[j](0) + (double)points[i](0)) * ((double)points[i](1) - (double)points[j](1)); - j = i; + if (points.size() >= 3) { + Vec2d p1 = points.back().cast(); + for (const Point &p : points) { + Vec2d p2 = p.cast(); + a += cross2(p1, p2); + p1 = p2; + } } return 0.5 * a; } @@ -70,7 +54,7 @@ double Polygon::area() const bool Polygon::is_counter_clockwise() const { - return ClipperLib::Orientation(Slic3rMultiPoint_to_ClipperPath(*this)); + return ClipperLib::Orientation(this->points); } bool Polygon::is_clockwise() const @@ -169,19 +153,22 @@ void Polygon::triangulate_convex(Polygons* polygons) const } // center of mass +// source: https://en.wikipedia.org/wiki/Centroid Point Polygon::centroid() const { - double area_temp = this->area(); - double x_temp = 0; - double y_temp = 0; - - Polyline polyline = this->split_at_first_point(); - for (Points::const_iterator point = polyline.points.begin(); point != polyline.points.end() - 1; ++point) { - x_temp += (double)( point->x() + (point+1)->x() ) * ( (double)point->x()*(point+1)->y() - (double)(point+1)->x()*point->y() ); - y_temp += (double)( point->y() + (point+1)->y() ) * ( (double)point->x()*(point+1)->y() - (double)(point+1)->x()*point->y() ); + double area_sum = 0.; + Vec2d c(0., 0.); + if (points.size() >= 3) { + Vec2d p1 = points.back().cast(); + for (const Point &p : points) { + Vec2d p2 = p.cast(); + double a = cross2(p1, p2); + area_sum += a; + c += (p1 + p2) * a; + p1 = p2; + } } - - return Point(x_temp/(6*area_temp), y_temp/(6*area_temp)); + return Point(Vec2d(c / (3. * area_sum))); } // find all concave vertices (i.e. having an internal angle greater than the supplied angle) diff --git a/src/libslic3r/Polygon.hpp b/src/libslic3r/Polygon.hpp index dd2d68d46..333f1e6b1 100644 --- a/src/libslic3r/Polygon.hpp +++ b/src/libslic3r/Polygon.hpp @@ -72,6 +72,9 @@ public: // Projection of a point onto the polygon. Point point_projection(const Point &point) const; std::vector parameter_by_length() const; + + using iterator = Points::iterator; + using const_iterator = Points::const_iterator; }; inline bool operator==(const Polygon &lhs, const Polygon &rhs) { return lhs.points == rhs.points; } @@ -90,6 +93,8 @@ inline double total_length(const Polygons &polylines) { return total; } +inline double area(const Polygon &poly) { return poly.area(); } + inline double area(const Polygons &polys) { double s = 0.; @@ -217,6 +222,24 @@ inline Polylines to_polylines(Polygons &&polys) return polylines; } +inline Polygons to_polygons(const std::vector &paths) +{ + Polygons out; + out.reserve(paths.size()); + for (const Points &path : paths) + out.emplace_back(path); + return out; +} + +inline Polygons to_polygons(std::vector &&paths) +{ + Polygons out; + out.reserve(paths.size()); + for (const Points &path : paths) + out.emplace_back(std::move(path)); + return out; +} + } // Slic3r // start Boost diff --git a/src/libslic3r/Polyline.hpp b/src/libslic3r/Polyline.hpp index 9c70522bf..51dcf9d36 100644 --- a/src/libslic3r/Polyline.hpp +++ b/src/libslic3r/Polyline.hpp @@ -78,6 +78,9 @@ public: bool is_closed() const { return this->points.front() == this->points.back(); } }; +inline bool operator==(const Polyline &lhs, const Polyline &rhs) { return lhs.points == rhs.points; } +inline bool operator!=(const Polyline &lhs, const Polyline &rhs) { return lhs.points != rhs.points; } + // Don't use this class in production code, it is used exclusively by the Perl binding for unit tests! #ifdef PERL_UCHAR_MIN class PolylineCollection @@ -124,6 +127,24 @@ inline Lines to_lines(const Polylines &polys) return lines; } +inline Polylines to_polylines(const std::vector &paths) +{ + Polylines out; + out.reserve(paths.size()); + for (const Points &path : paths) + out.emplace_back(path); + return out; +} + +inline Polylines to_polylines(std::vector &&paths) +{ + Polylines out; + out.reserve(paths.size()); + for (const Points &path : paths) + out.emplace_back(std::move(path)); + return out; +} + inline void polylines_append(Polylines &dst, const Polylines &src) { dst.insert(dst.end(), src.begin(), src.end()); diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index 7db61a20f..7a258182e 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -296,6 +296,13 @@ void Preset::normalize(DynamicPrintConfig &config) if (auto *gap_fill_enabled = config.option("gap_fill_enabled", false); gap_fill_enabled) gap_fill_enabled->value = false; } + if (auto *first_layer_height = config.option("first_layer_height", false); first_layer_height && first_layer_height->percent) + if (const auto *layer_height = config.option("layer_height", false); layer_height) { + // Legacy conversion - first_layer_height moved from PrintObject setting to a Print setting, thus we are getting rid of the dependency + // of first_layer_height on PrintObject specific layer_height. Covert the first layer heigth to an absolute value. + first_layer_height->value = first_layer_height->get_abs_value(layer_height->value); + first_layer_height->percent = false; + } } std::string Preset::remove_invalid_keys(DynamicPrintConfig &config, const DynamicPrintConfig &default_config) @@ -617,11 +624,17 @@ const std::vector& Preset::sla_printer_options() PresetCollection::PresetCollection(Preset::Type type, const std::vector &keys, const Slic3r::StaticPrintConfig &defaults, const std::string &default_name) : m_type(type), m_edited_preset(type, "", false), +#if ENABLE_PROJECT_DIRTY_STATE + m_saved_preset(type, "", false), +#endif // ENABLE_PROJECT_DIRTY_STATE m_idx_selected(0) { // Insert just the default preset. this->add_default_preset(keys, defaults, default_name); m_edited_preset.config.apply(m_presets.front().config); +#if ENABLE_PROJECT_DIRTY_STATE + update_saved_preset_from_current_preset(); +#endif // ENABLE_PROJECT_DIRTY_STATE } void PresetCollection::reset(bool delete_files) @@ -798,7 +811,10 @@ std::pair PresetCollection::load_external_preset( // The source config may contain keys from many possible preset types. Just copy those that relate to this preset. this->get_edited_preset().config.apply_only(combined_config, keys, true); this->update_dirty(); - assert(this->get_edited_preset().is_dirty); +#if ENABLE_PROJECT_DIRTY_STATE + update_saved_preset_from_current_preset(); +#endif // ENABLE_PROJECT_DIRTY_STATE + assert(this->get_edited_preset().is_dirty); return std::make_pair(&(*it), this->get_edited_preset().is_dirty); } if (inherits.empty()) { @@ -1063,7 +1079,7 @@ Preset* PresetCollection::find_preset(const std::string &name, bool first_visibl size_t PresetCollection::first_visible_idx() const { size_t idx = m_default_suppressed ? m_num_default_presets : 0; - for (; idx < this->m_presets.size(); ++ idx) + for (; idx < m_presets.size(); ++ idx) if (m_presets[idx].is_visible) break; if (idx == m_presets.size()) @@ -1208,6 +1224,9 @@ Preset& PresetCollection::select_preset(size_t idx) idx = first_visible_idx(); m_idx_selected = idx; m_edited_preset = m_presets[idx]; +#if ENABLE_PROJECT_DIRTY_STATE + update_saved_preset_from_current_preset(); +#endif // ENABLE_PROJECT_DIRTY_STATE bool default_visible = ! m_default_suppressed || m_idx_selected < m_num_default_presets; for (size_t i = 0; i < m_num_default_presets; ++i) m_presets[i].is_visible = default_visible; @@ -1275,7 +1294,7 @@ std::vector PresetCollection::merge_presets(PresetCollection &&othe assert(it != new_vendors.end()); preset.vendor = &it->second; } - this->m_presets.emplace(it, std::move(preset)); + m_presets.emplace(it, std::move(preset)); } else duplicates.emplace_back(std::move(preset.name)); } diff --git a/src/libslic3r/Preset.hpp b/src/libslic3r/Preset.hpp index 6e56ad911..8d407fb64 100644 --- a/src/libslic3r/Preset.hpp +++ b/src/libslic3r/Preset.hpp @@ -346,6 +346,11 @@ public: Preset& get_edited_preset() { return m_edited_preset; } const Preset& get_edited_preset() const { return m_edited_preset; } +#if ENABLE_PROJECT_DIRTY_STATE + // Return the last saved preset. + const Preset& get_saved_preset() const { return m_saved_preset; } +#endif // ENABLE_PROJECT_DIRTY_STATE + // Return vendor of the first parent profile, for which the vendor is defined, or null if such profile does not exist. PresetWithVendorProfile get_preset_with_vendor_profile(const Preset &preset) const; PresetWithVendorProfile get_edited_preset_with_vendor_profile() const { return this->get_preset_with_vendor_profile(this->get_edited_preset()); } @@ -365,8 +370,16 @@ public: // Return a preset by an index. If the preset is active, a temporary copy is returned. Preset& preset(size_t idx) { return (idx == m_idx_selected) ? m_edited_preset : m_presets[idx]; } const Preset& preset(size_t idx) const { return const_cast(this)->preset(idx); } +#if ENABLE_PROJECT_DIRTY_STATE + void discard_current_changes() { + m_presets[m_idx_selected].reset_dirty(); + m_edited_preset = m_presets[m_idx_selected]; + update_saved_preset_from_current_preset(); + } +#else void discard_current_changes() { m_presets[m_idx_selected].reset_dirty(); m_edited_preset = m_presets[m_idx_selected]; } - +#endif // ENABLE_PROJECT_DIRTY_STATE + // Return a preset by its name. If the preset is active, a temporary copy is returned. // If a preset is not found by its name, null is returned. Preset* find_preset(const std::string &name, bool first_visible_if_not_found = false); @@ -440,6 +453,16 @@ public: std::vector current_different_from_parent_options(const bool deep_compare = false) const { return dirty_options(&this->get_edited_preset(), this->get_selected_preset_parent(), deep_compare); } +#if ENABLE_PROJECT_DIRTY_STATE + // Compare the content of get_saved_preset() with get_edited_preset() configs, return true if they differ. + bool saved_is_dirty() const { return !this->saved_dirty_options().empty(); } + // Compare the content of get_saved_preset() with get_edited_preset() configs, return the list of keys where they differ. + std::vector saved_dirty_options(const bool deep_compare = false) const + { return dirty_options(&this->get_edited_preset(), &this->get_saved_preset(), deep_compare); } + // Copy edited preset into saved preset. + void update_saved_preset_from_current_preset() { m_saved_preset = m_edited_preset; } +#endif // ENABLE_PROJECT_DIRTY_STATE + // Return a sorted list of system preset names. // Used for validating the "inherits" flag when importing user's config bundles. // Returns names of all system presets including the former names of these presets. @@ -527,6 +550,11 @@ private: std::map m_map_system_profile_renamed; // Initially this preset contains a copy of the selected preset. Later on, this copy may be modified by the user. Preset m_edited_preset; +#if ENABLE_PROJECT_DIRTY_STATE + // Contains a copy of the last saved selected preset. + Preset m_saved_preset; +#endif // ENABLE_PROJECT_DIRTY_STATE + // Selected preset. size_t m_idx_selected; // Is the "- default -" preset suppressed? diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index ce5bf1b29..538ee6009 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -31,6 +31,9 @@ namespace Slic3r { template class PrintState; template class PrintState; +PrintRegion::PrintRegion(const PrintRegionConfig &config) : PrintRegion(config, config.hash()) {} +PrintRegion::PrintRegion(PrintRegionConfig &&config) : PrintRegion(std::move(config), config.hash()) {} + void Print::clear() { tbb::mutex::scoped_lock lock(this->state_mutex()); @@ -39,24 +42,10 @@ void Print::clear() for (PrintObject *object : m_objects) delete object; m_objects.clear(); - for (PrintRegion *region : m_regions) - delete region; - m_regions.clear(); + m_print_regions.clear(); m_model.clear_objects(); } -PrintRegion* Print::add_region() -{ - m_regions.emplace_back(new PrintRegion(this)); - return m_regions.back(); -} - -PrintRegion* Print::add_region(const PrintRegionConfig &config) -{ - m_regions.emplace_back(new PrintRegion(this, config)); - return m_regions.back(); -} - // Called by Print::apply(). // This method only accepts PrintConfig option keys. bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* new_config */, const std::vector &opt_keys) @@ -273,15 +262,10 @@ bool Print::is_step_done(PrintObjectStep step) const std::vector Print::object_extruders() const { std::vector extruders; - extruders.reserve(m_regions.size() * 3); - std::vector region_used(m_regions.size(), false); + extruders.reserve(m_print_regions.size() * m_objects.size() * 3); for (const PrintObject *object : m_objects) - for (const std::vector> &volumes_per_region : object->region_volumes) - if (! volumes_per_region.empty()) - region_used[&volumes_per_region - &object->region_volumes.front()] = true; - for (size_t idx_region = 0; idx_region < m_regions.size(); ++ idx_region) - if (region_used[idx_region]) - m_regions[idx_region]->collect_object_printing_extruders(extruders); + for (const PrintRegion ®ion : object->all_regions()) + region.collect_object_printing_extruders(*this, extruders); sort_remove_duplicates(extruders); return extruders; } @@ -345,242 +329,6 @@ double Print::max_allowed_layer_height() const return nozzle_diameter_max; } -// Add or remove support modifier ModelVolumes from model_object_dst to match the ModelVolumes of model_object_new -// in the exact order and with the same IDs. -// It is expected, that the model_object_dst already contains the non-support volumes of model_object_new in the correct order. -void Print::model_volume_list_update_supports(ModelObject &model_object_dst, const ModelObject &model_object_new) -{ - typedef std::pair ModelVolumeWithStatus; - std::vector old_volumes; - old_volumes.reserve(model_object_dst.volumes.size()); - for (const ModelVolume *model_volume : model_object_dst.volumes) - old_volumes.emplace_back(ModelVolumeWithStatus(model_volume, false)); - auto model_volume_lower = [](const ModelVolumeWithStatus &mv1, const ModelVolumeWithStatus &mv2){ return mv1.first->id() < mv2.first->id(); }; - auto model_volume_equal = [](const ModelVolumeWithStatus &mv1, const ModelVolumeWithStatus &mv2){ return mv1.first->id() == mv2.first->id(); }; - std::sort(old_volumes.begin(), old_volumes.end(), model_volume_lower); - model_object_dst.volumes.clear(); - model_object_dst.volumes.reserve(model_object_new.volumes.size()); - for (const ModelVolume *model_volume_src : model_object_new.volumes) { - ModelVolumeWithStatus key(model_volume_src, false); - auto it = std::lower_bound(old_volumes.begin(), old_volumes.end(), key, model_volume_lower); - if (it != old_volumes.end() && model_volume_equal(*it, key)) { - // The volume was found in the old list. Just copy it. - assert(! it->second); // not consumed yet - it->second = true; - ModelVolume *model_volume_dst = const_cast(it->first); - // For support modifiers, the type may have been switched from blocker to enforcer and vice versa. - assert((model_volume_dst->is_support_modifier() && model_volume_src->is_support_modifier()) || model_volume_dst->type() == model_volume_src->type()); - model_object_dst.volumes.emplace_back(model_volume_dst); - if (model_volume_dst->is_support_modifier()) { - // For support modifiers, the type may have been switched from blocker to enforcer and vice versa. - model_volume_dst->set_type(model_volume_src->type()); - model_volume_dst->set_transformation(model_volume_src->get_transformation()); - } - assert(model_volume_dst->get_matrix().isApprox(model_volume_src->get_matrix())); - } else { - // The volume was not found in the old list. Create a new copy. - assert(model_volume_src->is_support_modifier()); - model_object_dst.volumes.emplace_back(new ModelVolume(*model_volume_src)); - model_object_dst.volumes.back()->set_model_object(&model_object_dst); - } - } - // Release the non-consumed old volumes (those were deleted from the new list). - for (ModelVolumeWithStatus &mv_with_status : old_volumes) - if (! mv_with_status.second) - delete mv_with_status.first; -} - -static inline void model_volume_list_copy_configs(ModelObject &model_object_dst, const ModelObject &model_object_src, const ModelVolumeType type) -{ - size_t i_src, i_dst; - for (i_src = 0, i_dst = 0; i_src < model_object_src.volumes.size() && i_dst < model_object_dst.volumes.size();) { - const ModelVolume &mv_src = *model_object_src.volumes[i_src]; - ModelVolume &mv_dst = *model_object_dst.volumes[i_dst]; - if (mv_src.type() != type) { - ++ i_src; - continue; - } - if (mv_dst.type() != type) { - ++ i_dst; - continue; - } - assert(mv_src.id() == mv_dst.id()); - // Copy the ModelVolume data. - mv_dst.name = mv_src.name; - mv_dst.config.assign_config(mv_src.config); - assert(mv_dst.supported_facets.id() == mv_src.supported_facets.id()); - mv_dst.supported_facets.assign(mv_src.supported_facets); - assert(mv_dst.seam_facets.id() == mv_src.seam_facets.id()); - mv_dst.seam_facets.assign(mv_src.seam_facets); - //FIXME what to do with the materials? - // mv_dst.m_material_id = mv_src.m_material_id; - ++ i_src; - ++ i_dst; - } -} - -static inline void layer_height_ranges_copy_configs(t_layer_config_ranges &lr_dst, const t_layer_config_ranges &lr_src) -{ - assert(lr_dst.size() == lr_src.size()); - auto it_src = lr_src.cbegin(); - for (auto &kvp_dst : lr_dst) { - const auto &kvp_src = *it_src ++; - assert(std::abs(kvp_dst.first.first - kvp_src.first.first ) <= EPSILON); - assert(std::abs(kvp_dst.first.second - kvp_src.first.second) <= EPSILON); - // Layer heights are allowed do differ in case the layer height table is being overriden by the smooth profile. - // assert(std::abs(kvp_dst.second.option("layer_height")->getFloat() - kvp_src.second.option("layer_height")->getFloat()) <= EPSILON); - kvp_dst.second = kvp_src.second; - } -} - -static inline bool transform3d_lower(const Transform3d &lhs, const Transform3d &rhs) -{ - typedef Transform3d::Scalar T; - const T *lv = lhs.data(); - const T *rv = rhs.data(); - for (size_t i = 0; i < 16; ++ i, ++ lv, ++ rv) { - if (*lv < *rv) - return true; - else if (*lv > *rv) - return false; - } - return false; -} - -static inline bool transform3d_equal(const Transform3d &lhs, const Transform3d &rhs) -{ - typedef Transform3d::Scalar T; - const T *lv = lhs.data(); - const T *rv = rhs.data(); - for (size_t i = 0; i < 16; ++ i, ++ lv, ++ rv) - if (*lv != *rv) - return false; - return true; -} - -struct PrintObjectTrafoAndInstances -{ - Transform3d trafo; - PrintInstances instances; - bool operator<(const PrintObjectTrafoAndInstances &rhs) const { return transform3d_lower(this->trafo, rhs.trafo); } -}; - -// Generate a list of trafos and XY offsets for instances of a ModelObject -static std::vector print_objects_from_model_object(const ModelObject &model_object) -{ - std::set trafos; - PrintObjectTrafoAndInstances trafo; - for (ModelInstance *model_instance : model_object.instances) - if (model_instance->is_printable()) { - trafo.trafo = model_instance->get_matrix(); - auto shift = Point::new_scale(trafo.trafo.data()[12], trafo.trafo.data()[13]); - // Reset the XY axes of the transformation. - trafo.trafo.data()[12] = 0; - trafo.trafo.data()[13] = 0; - // Search or insert a trafo. - auto it = trafos.emplace(trafo).first; - const_cast(*it).instances.emplace_back(PrintInstance{ nullptr, model_instance, shift }); - } - return std::vector(trafos.begin(), trafos.end()); -} - -// Compare just the layer ranges and their layer heights, not the associated configs. -// Ignore the layer heights if check_layer_heights is false. -static bool layer_height_ranges_equal(const t_layer_config_ranges &lr1, const t_layer_config_ranges &lr2, bool check_layer_height) -{ - if (lr1.size() != lr2.size()) - return false; - auto it2 = lr2.begin(); - for (const auto &kvp1 : lr1) { - const auto &kvp2 = *it2 ++; - if (std::abs(kvp1.first.first - kvp2.first.first ) > EPSILON || - std::abs(kvp1.first.second - kvp2.first.second) > EPSILON || - (check_layer_height && std::abs(kvp1.second.option("layer_height")->getFloat() - kvp2.second.option("layer_height")->getFloat()) > EPSILON)) - return false; - } - return true; -} - -// Returns true if va == vb when all CustomGCode items that are not ToolChangeCode are ignored. -static bool custom_per_printz_gcodes_tool_changes_differ(const std::vector &va, const std::vector &vb) -{ - auto it_a = va.begin(); - auto it_b = vb.begin(); - while (it_a != va.end() || it_b != vb.end()) { - if (it_a != va.end() && it_a->type != CustomGCode::ToolChange) { - // Skip any CustomGCode items, which are not tool changes. - ++ it_a; - continue; - } - if (it_b != vb.end() && it_b->type != CustomGCode::ToolChange) { - // Skip any CustomGCode items, which are not tool changes. - ++ it_b; - continue; - } - if (it_a == va.end() || it_b == vb.end()) - // va or vb contains more Tool Changes than the other. - return true; - assert(it_a->type == CustomGCode::ToolChange); - assert(it_b->type == CustomGCode::ToolChange); - if (*it_a != *it_b) - // The two Tool Changes differ. - return true; - ++ it_a; - ++ it_b; - } - // There is no change in custom Tool Changes. - return false; -} - -// Collect diffs of configuration values at various containers, -// resolve the filament rectract overrides of extruder retract values. -void Print::config_diffs( - const DynamicPrintConfig &new_full_config, - t_config_option_keys &print_diff, t_config_option_keys &object_diff, t_config_option_keys ®ion_diff, - t_config_option_keys &full_config_diff, - DynamicPrintConfig &filament_overrides) const -{ - // Collect changes to print config, account for overrides of extruder retract values by filament presets. - { - const std::vector &extruder_retract_keys = print_config_def.extruder_retract_keys(); - const std::string filament_prefix = "filament_"; - for (const t_config_option_key &opt_key : m_config.keys()) { - const ConfigOption *opt_old = m_config.option(opt_key); - assert(opt_old != nullptr); - const ConfigOption *opt_new = new_full_config.option(opt_key); - // assert(opt_new != nullptr); - if (opt_new == nullptr) - //FIXME This may happen when executing some test cases. - continue; - const ConfigOption *opt_new_filament = std::binary_search(extruder_retract_keys.begin(), extruder_retract_keys.end(), opt_key) ? new_full_config.option(filament_prefix + opt_key) : nullptr; - if (opt_new_filament != nullptr && ! opt_new_filament->is_nil()) { - // An extruder retract override is available at some of the filament presets. - if (*opt_old != *opt_new || opt_new->overriden_by(opt_new_filament)) { - auto opt_copy = opt_new->clone(); - opt_copy->apply_override(opt_new_filament); - if (*opt_old == *opt_copy) - delete opt_copy; - else { - filament_overrides.set_key_value(opt_key, opt_copy); - print_diff.emplace_back(opt_key); - } - } - } else if (*opt_new != *opt_old) - print_diff.emplace_back(opt_key); - } - } - // Collect changes to object and region configs. - object_diff = m_default_object_config.diff(new_full_config); - region_diff = m_default_region_config.diff(new_full_config); - // Prepare for storing of the full print config into new_full_config to be exported into the G-code and to be used by the PlaceholderParser. - for (const t_config_option_key &opt_key : new_full_config.keys()) { - const ConfigOption *opt_old = m_full_print_config.option(opt_key); - const ConfigOption *opt_new = new_full_config.option(opt_key); - if (opt_old == nullptr || *opt_new != *opt_old) - full_config_diff.emplace_back(opt_key); - } -} - std::vector Print::print_object_ids() const { std::vector out; @@ -591,594 +339,6 @@ std::vector Print::print_object_ids() const return out; } -Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_config) -{ -#ifdef _DEBUG - check_model_ids_validity(model); -#endif /* _DEBUG */ - - // Normalize the config. - new_full_config.option("print_settings_id", true); - new_full_config.option("filament_settings_id", true); - new_full_config.option("printer_settings_id", true); - new_full_config.option("physical_printer_settings_id", true); - new_full_config.normalize_fdm(); - - // Find modified keys of the various configs. Resolve overrides extruder retract values by filament profiles. - t_config_option_keys print_diff, object_diff, region_diff, full_config_diff; - DynamicPrintConfig filament_overrides; - this->config_diffs(new_full_config, print_diff, object_diff, region_diff, full_config_diff, filament_overrides); - - // Do not use the ApplyStatus as we will use the max function when updating apply_status. - unsigned int apply_status = APPLY_STATUS_UNCHANGED; - auto update_apply_status = [&apply_status](bool invalidated) - { apply_status = std::max(apply_status, invalidated ? APPLY_STATUS_INVALIDATED : APPLY_STATUS_CHANGED); }; - if (! (print_diff.empty() && object_diff.empty() && region_diff.empty())) - update_apply_status(false); - - // Grab the lock for the Print / PrintObject milestones. - tbb::mutex::scoped_lock lock(this->state_mutex()); - - // The following call may stop the background processing. - if (! print_diff.empty()) - update_apply_status(this->invalidate_state_by_config_options(new_full_config, print_diff)); - - // Apply variables to placeholder parser. The placeholder parser is used by G-code export, - // which should be stopped if print_diff is not empty. - size_t num_extruders = m_config.nozzle_diameter.size(); - bool num_extruders_changed = false; - if (! full_config_diff.empty()) { - update_apply_status(this->invalidate_step(psGCodeExport)); - // Set the profile aliases for the PrintBase::output_filename() - m_placeholder_parser.set("print_preset", new_full_config.option("print_settings_id")->clone()); - m_placeholder_parser.set("filament_preset", new_full_config.option("filament_settings_id")->clone()); - m_placeholder_parser.set("printer_preset", new_full_config.option("printer_settings_id")->clone()); - m_placeholder_parser.set("physical_printer_preset", new_full_config.option("physical_printer_settings_id")->clone()); - // We want the filament overrides to be applied over their respective extruder parameters by the PlaceholderParser. - // see "Placeholders do not respect filament overrides." GH issue #3649 - m_placeholder_parser.apply_config(filament_overrides); - // It is also safe to change m_config now after this->invalidate_state_by_config_options() call. - m_config.apply_only(new_full_config, print_diff, true); - //FIXME use move semantics once ConfigBase supports it. - m_config.apply(filament_overrides); - // Handle changes to object config defaults - m_default_object_config.apply_only(new_full_config, object_diff, true); - // Handle changes to regions config defaults - m_default_region_config.apply_only(new_full_config, region_diff, true); - m_full_print_config = std::move(new_full_config); - if (num_extruders != m_config.nozzle_diameter.size()) { - num_extruders = m_config.nozzle_diameter.size(); - num_extruders_changed = true; - } - } - - class LayerRanges - { - public: - LayerRanges() {} - // Convert input config ranges into continuous non-overlapping sorted vector of intervals and their configs. - void assign(const t_layer_config_ranges &in) { - m_ranges.clear(); - m_ranges.reserve(in.size()); - // Input ranges are sorted lexicographically. First range trims the other ranges. - coordf_t last_z = 0; - for (const std::pair &range : in) - if (range.first.second > last_z) { - coordf_t min_z = std::max(range.first.first, 0.); - if (min_z > last_z + EPSILON) { - m_ranges.emplace_back(t_layer_height_range(last_z, min_z), nullptr); - last_z = min_z; - } - if (range.first.second > last_z + EPSILON) { - const DynamicPrintConfig *cfg = &range.second.get(); - m_ranges.emplace_back(t_layer_height_range(last_z, range.first.second), cfg); - last_z = range.first.second; - } - } - if (m_ranges.empty()) - m_ranges.emplace_back(t_layer_height_range(0, DBL_MAX), nullptr); - else if (m_ranges.back().second == nullptr) - m_ranges.back().first.second = DBL_MAX; - else - m_ranges.emplace_back(t_layer_height_range(m_ranges.back().first.second, DBL_MAX), nullptr); - } - - const DynamicPrintConfig* config(const t_layer_height_range &range) const { - auto it = std::lower_bound(m_ranges.begin(), m_ranges.end(), std::make_pair< t_layer_height_range, const DynamicPrintConfig*>(t_layer_height_range(range.first - EPSILON, range.second - EPSILON), nullptr)); - // #ys_FIXME_COLOR - // assert(it != m_ranges.end()); - // assert(it == m_ranges.end() || std::abs(it->first.first - range.first ) < EPSILON); - // assert(it == m_ranges.end() || std::abs(it->first.second - range.second) < EPSILON); - if (it == m_ranges.end() || - std::abs(it->first.first - range.first) > EPSILON || - std::abs(it->first.second - range.second) > EPSILON ) - return nullptr; // desired range doesn't found - return (it == m_ranges.end()) ? nullptr : it->second; - } - std::vector>::const_iterator begin() const { return m_ranges.cbegin(); } - std::vector>::const_iterator end() const { return m_ranges.cend(); } - private: - std::vector> m_ranges; - }; - struct ModelObjectStatus { - enum Status { - Unknown, - Old, - New, - Moved, - Deleted, - }; - ModelObjectStatus(ObjectID id, Status status = Unknown) : id(id), status(status) {} - ObjectID id; - Status status; - LayerRanges layer_ranges; - // Search by id. - bool operator<(const ModelObjectStatus &rhs) const { return id < rhs.id; } - }; - std::set model_object_status; - - // 1) Synchronize model objects. - if (model.id() != m_model.id()) { - // Kill everything, initialize from scratch. - // Stop background processing. - this->call_cancel_callback(); - update_apply_status(this->invalidate_all_steps()); - for (PrintObject *object : m_objects) { - model_object_status.emplace(object->model_object()->id(), ModelObjectStatus::Deleted); - update_apply_status(object->invalidate_all_steps()); - delete object; - } - m_objects.clear(); - for (PrintRegion *region : m_regions) - delete region; - m_regions.clear(); - m_model.assign_copy(model); - for (const ModelObject *model_object : m_model.objects) - model_object_status.emplace(model_object->id(), ModelObjectStatus::New); - } else { - if (m_model.custom_gcode_per_print_z != model.custom_gcode_per_print_z) { - update_apply_status(num_extruders_changed || - // Tool change G-codes are applied as color changes for a single extruder printer, no need to invalidate tool ordering. - //FIXME The tool ordering may be invalidated unnecessarily if the custom_gcode_per_print_z.mode is not applicable - // to the active print / model state, and then it is reset, so it is being applicable, but empty, thus the effect is the same. - (num_extruders > 1 && custom_per_printz_gcodes_tool_changes_differ(m_model.custom_gcode_per_print_z.gcodes, model.custom_gcode_per_print_z.gcodes)) ? - // The Tool Ordering and the Wipe Tower are no more valid. - this->invalidate_steps({ psWipeTower, psGCodeExport }) : - // There is no change in Tool Changes stored in custom_gcode_per_print_z, therefore there is no need to update Tool Ordering. - this->invalidate_step(psGCodeExport)); - m_model.custom_gcode_per_print_z = model.custom_gcode_per_print_z; - } - if (model_object_list_equal(m_model, model)) { - // The object list did not change. - for (const ModelObject *model_object : m_model.objects) - model_object_status.emplace(model_object->id(), ModelObjectStatus::Old); - } else if (model_object_list_extended(m_model, model)) { - // Add new objects. Their volumes and configs will be synchronized later. - update_apply_status(this->invalidate_step(psGCodeExport)); - for (const ModelObject *model_object : m_model.objects) - model_object_status.emplace(model_object->id(), ModelObjectStatus::Old); - for (size_t i = m_model.objects.size(); i < model.objects.size(); ++ i) { - model_object_status.emplace(model.objects[i]->id(), ModelObjectStatus::New); - m_model.objects.emplace_back(ModelObject::new_copy(*model.objects[i])); - m_model.objects.back()->set_model(&m_model); - } - } else { - // Reorder the objects, add new objects. - // First stop background processing before shuffling or deleting the PrintObjects in the object list. - this->call_cancel_callback(); - update_apply_status(this->invalidate_step(psGCodeExport)); - // Second create a new list of objects. - std::vector model_objects_old(std::move(m_model.objects)); - m_model.objects.clear(); - m_model.objects.reserve(model.objects.size()); - auto by_id_lower = [](const ModelObject *lhs, const ModelObject *rhs){ return lhs->id() < rhs->id(); }; - std::sort(model_objects_old.begin(), model_objects_old.end(), by_id_lower); - for (const ModelObject *mobj : model.objects) { - auto it = std::lower_bound(model_objects_old.begin(), model_objects_old.end(), mobj, by_id_lower); - if (it == model_objects_old.end() || (*it)->id() != mobj->id()) { - // New ModelObject added. - m_model.objects.emplace_back(ModelObject::new_copy(*mobj)); - m_model.objects.back()->set_model(&m_model); - model_object_status.emplace(mobj->id(), ModelObjectStatus::New); - } else { - // Existing ModelObject re-added (possibly moved in the list). - m_model.objects.emplace_back(*it); - model_object_status.emplace(mobj->id(), ModelObjectStatus::Moved); - } - } - bool deleted_any = false; - for (ModelObject *&model_object : model_objects_old) { - if (model_object_status.find(ModelObjectStatus(model_object->id())) == model_object_status.end()) { - model_object_status.emplace(model_object->id(), ModelObjectStatus::Deleted); - deleted_any = true; - } else - // Do not delete this ModelObject instance. - model_object = nullptr; - } - if (deleted_any) { - // Delete PrintObjects of the deleted ModelObjects. - PrintObjectPtrs print_objects_old = std::move(m_objects); - m_objects.clear(); - m_objects.reserve(print_objects_old.size()); - for (PrintObject *print_object : print_objects_old) { - auto it_status = model_object_status.find(ModelObjectStatus(print_object->model_object()->id())); - assert(it_status != model_object_status.end()); - if (it_status->status == ModelObjectStatus::Deleted) { - update_apply_status(print_object->invalidate_all_steps()); - delete print_object; - } else - m_objects.emplace_back(print_object); - } - for (ModelObject *model_object : model_objects_old) - delete model_object; - } - } - } - - // 2) Map print objects including their transformation matrices. - struct PrintObjectStatus { - enum Status { - Unknown, - Deleted, - Reused, - New - }; - PrintObjectStatus(PrintObject *print_object, Status status = Unknown) : - id(print_object->model_object()->id()), - print_object(print_object), - trafo(print_object->trafo()), - status(status) {} - PrintObjectStatus(ObjectID id) : id(id), print_object(nullptr), trafo(Transform3d::Identity()), status(Unknown) {} - // ID of the ModelObject & PrintObject - ObjectID id; - // Pointer to the old PrintObject - PrintObject *print_object; - // Trafo generated with model_object->world_matrix(true) - Transform3d trafo; - Status status; - // Search by id. - bool operator<(const PrintObjectStatus &rhs) const { return id < rhs.id; } - }; - std::multiset print_object_status; - for (PrintObject *print_object : m_objects) - print_object_status.emplace(PrintObjectStatus(print_object)); - - // 3) Synchronize ModelObjects & PrintObjects. - for (size_t idx_model_object = 0; idx_model_object < model.objects.size(); ++ idx_model_object) { - ModelObject &model_object = *m_model.objects[idx_model_object]; - auto it_status = model_object_status.find(ModelObjectStatus(model_object.id())); - assert(it_status != model_object_status.end()); - assert(it_status->status != ModelObjectStatus::Deleted); - const ModelObject& model_object_new = *model.objects[idx_model_object]; - const_cast(*it_status).layer_ranges.assign(model_object_new.layer_config_ranges); - if (it_status->status == ModelObjectStatus::New) - // PrintObject instances will be added in the next loop. - continue; - // Update the ModelObject instance, possibly invalidate the linked PrintObjects. - assert(it_status->status == ModelObjectStatus::Old || it_status->status == ModelObjectStatus::Moved); - // Check whether a model part volume was added or removed, their transformations or order changed. - // Only volume IDs, volume types, transformation matrices and their order are checked, configuration and other parameters are NOT checked. - bool model_parts_differ = model_volume_list_changed(model_object, model_object_new, ModelVolumeType::MODEL_PART); - bool modifiers_differ = model_volume_list_changed(model_object, model_object_new, ModelVolumeType::PARAMETER_MODIFIER); - bool supports_differ = model_volume_list_changed(model_object, model_object_new, ModelVolumeType::SUPPORT_BLOCKER) || - model_volume_list_changed(model_object, model_object_new, ModelVolumeType::SUPPORT_ENFORCER); - if (model_parts_differ || modifiers_differ || - model_object.origin_translation != model_object_new.origin_translation || - ! model_object.layer_height_profile.timestamp_matches(model_object_new.layer_height_profile) || - ! layer_height_ranges_equal(model_object.layer_config_ranges, model_object_new.layer_config_ranges, model_object_new.layer_height_profile.empty())) { - // The very first step (the slicing step) is invalidated. One may freely remove all associated PrintObjects. - auto range = print_object_status.equal_range(PrintObjectStatus(model_object.id())); - for (auto it = range.first; it != range.second; ++ it) { - update_apply_status(it->print_object->invalidate_all_steps()); - const_cast(*it).status = PrintObjectStatus::Deleted; - } - // Copy content of the ModelObject including its ID, do not change the parent. - model_object.assign_copy(model_object_new); - } else if (supports_differ || model_custom_supports_data_changed(model_object, model_object_new)) { - // First stop background processing before shuffling or deleting the ModelVolumes in the ModelObject's list. - if (supports_differ) { - this->call_cancel_callback(); - update_apply_status(false); - } - // Invalidate just the supports step. - auto range = print_object_status.equal_range(PrintObjectStatus(model_object.id())); - for (auto it = range.first; it != range.second; ++ it) - update_apply_status(it->print_object->invalidate_step(posSupportMaterial)); - if (supports_differ) { - // Copy just the support volumes. - model_volume_list_update_supports(model_object, model_object_new); - } - } else if (model_custom_seam_data_changed(model_object, model_object_new)) { - update_apply_status(this->invalidate_step(psGCodeExport)); - } - if (! model_parts_differ && ! modifiers_differ) { - // Synchronize Object's config. - bool object_config_changed = ! model_object.config.timestamp_matches(model_object_new.config); - if (object_config_changed) - model_object.config.assign_config(model_object_new.config); - if (! object_diff.empty() || object_config_changed || num_extruders_changed) { - PrintObjectConfig new_config = PrintObject::object_config_from_model_object(m_default_object_config, model_object, num_extruders); - auto range = print_object_status.equal_range(PrintObjectStatus(model_object.id())); - for (auto it = range.first; it != range.second; ++ it) { - t_config_option_keys diff = it->print_object->config().diff(new_config); - if (! diff.empty()) { - update_apply_status(it->print_object->invalidate_state_by_config_options(it->print_object->config(), new_config, diff)); - it->print_object->config_apply_only(new_config, diff, true); - } - } - } - // Synchronize (just copy) the remaining data of ModelVolumes (name, config, custom supports data). - //FIXME What to do with m_material_id? - model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, ModelVolumeType::MODEL_PART); - model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, ModelVolumeType::PARAMETER_MODIFIER); - layer_height_ranges_copy_configs(model_object.layer_config_ranges /* dst */, model_object_new.layer_config_ranges /* src */); - // Copy the ModelObject name, input_file and instances. The instances will be compared against PrintObject instances in the next step. - model_object.name = model_object_new.name; - model_object.input_file = model_object_new.input_file; - // Only refresh ModelInstances if there is any change. - if (model_object.instances.size() != model_object_new.instances.size() || - ! std::equal(model_object.instances.begin(), model_object.instances.end(), model_object_new.instances.begin(), [](auto l, auto r){ return l->id() == r->id(); })) { - // G-code generator accesses model_object.instances to generate sequential print ordering matching the Plater object list. - update_apply_status(this->invalidate_step(psGCodeExport)); - model_object.clear_instances(); - model_object.instances.reserve(model_object_new.instances.size()); - for (const ModelInstance *model_instance : model_object_new.instances) { - model_object.instances.emplace_back(new ModelInstance(*model_instance)); - model_object.instances.back()->set_model_object(&model_object); - } - } else if (! std::equal(model_object.instances.begin(), model_object.instances.end(), model_object_new.instances.begin(), - [](auto l, auto r){ return l->print_volume_state == r->print_volume_state && l->printable == r->printable && - l->get_transformation().get_matrix().isApprox(r->get_transformation().get_matrix()); })) { - // If some of the instances changed, the bounding box of the updated ModelObject is likely no more valid. - // This is safe as the ModelObject's bounding box is only accessed from this function, which is called from the main thread only. - model_object.invalidate_bounding_box(); - // Synchronize the content of instances. - auto new_instance = model_object_new.instances.begin(); - for (auto old_instance = model_object.instances.begin(); old_instance != model_object.instances.end(); ++ old_instance, ++ new_instance) { - (*old_instance)->set_transformation((*new_instance)->get_transformation()); - (*old_instance)->print_volume_state = (*new_instance)->print_volume_state; - (*old_instance)->printable = (*new_instance)->printable; - } - } - } - } - - // 4) Generate PrintObjects from ModelObjects and their instances. - { - PrintObjectPtrs print_objects_new; - print_objects_new.reserve(std::max(m_objects.size(), m_model.objects.size())); - bool new_objects = false; - // Walk over all new model objects and check, whether there are matching PrintObjects. - for (ModelObject *model_object : m_model.objects) { - auto range = print_object_status.equal_range(PrintObjectStatus(model_object->id())); - std::vector old; - if (range.first != range.second) { - old.reserve(print_object_status.count(PrintObjectStatus(model_object->id()))); - for (auto it = range.first; it != range.second; ++ it) - if (it->status != PrintObjectStatus::Deleted) - old.emplace_back(&(*it)); - } - // Generate a list of trafos and XY offsets for instances of a ModelObject - // Producing the config for PrintObject on demand, caching it at print_object_last. - const PrintObject *print_object_last = nullptr; - auto print_object_apply_config = [this, &print_object_last, model_object, num_extruders](PrintObject* print_object) { - print_object->config_apply(print_object_last ? - print_object_last->config() : - PrintObject::object_config_from_model_object(m_default_object_config, *model_object, num_extruders)); - print_object_last = print_object; - }; - std::vector new_print_instances = print_objects_from_model_object(*model_object); - if (old.empty()) { - // Simple case, just generate new instances. - for (PrintObjectTrafoAndInstances &print_instances : new_print_instances) { - PrintObject *print_object = new PrintObject(this, model_object, print_instances.trafo, std::move(print_instances.instances)); - print_object_apply_config(print_object); - print_objects_new.emplace_back(print_object); - // print_object_status.emplace(PrintObjectStatus(print_object, PrintObjectStatus::New)); - new_objects = true; - } - continue; - } - // Complex case, try to merge the two lists. - // Sort the old lexicographically by their trafos. - std::sort(old.begin(), old.end(), [](const PrintObjectStatus *lhs, const PrintObjectStatus *rhs){ return transform3d_lower(lhs->trafo, rhs->trafo); }); - // Merge the old / new lists. - auto it_old = old.begin(); - for (PrintObjectTrafoAndInstances &new_instances : new_print_instances) { - for (; it_old != old.end() && transform3d_lower((*it_old)->trafo, new_instances.trafo); ++ it_old); - if (it_old == old.end() || ! transform3d_equal((*it_old)->trafo, new_instances.trafo)) { - // This is a new instance (or a set of instances with the same trafo). Just add it. - PrintObject *print_object = new PrintObject(this, model_object, new_instances.trafo, std::move(new_instances.instances)); - print_object_apply_config(print_object); - print_objects_new.emplace_back(print_object); - // print_object_status.emplace(PrintObjectStatus(print_object, PrintObjectStatus::New)); - new_objects = true; - if (it_old != old.end()) - const_cast(*it_old)->status = PrintObjectStatus::Deleted; - } else { - // The PrintObject already exists and the copies differ. - PrintBase::ApplyStatus status = (*it_old)->print_object->set_instances(std::move(new_instances.instances)); - if (status != PrintBase::APPLY_STATUS_UNCHANGED) - update_apply_status(status == PrintBase::APPLY_STATUS_INVALIDATED); - print_objects_new.emplace_back((*it_old)->print_object); - const_cast(*it_old)->status = PrintObjectStatus::Reused; - } - } - } - if (m_objects != print_objects_new) { - this->call_cancel_callback(); - update_apply_status(this->invalidate_all_steps()); - m_objects = print_objects_new; - // Delete the PrintObjects marked as Unknown or Deleted. - bool deleted_objects = false; - for (auto &pos : print_object_status) - if (pos.status == PrintObjectStatus::Unknown || pos.status == PrintObjectStatus::Deleted) { - update_apply_status(pos.print_object->invalidate_all_steps()); - delete pos.print_object; - deleted_objects = true; - } - if (new_objects || deleted_objects) - update_apply_status(this->invalidate_steps({ psSkirt, psBrim, psWipeTower, psGCodeExport })); - if (new_objects) - update_apply_status(false); - } - print_object_status.clear(); - } - - // 5) Synchronize configs of ModelVolumes, synchronize AMF / 3MF materials (and their configs), refresh PrintRegions. - // Update reference counts of regions from the remaining PrintObjects and their volumes. - // Regions with zero references could and should be reused. - for (PrintRegion *region : m_regions) - region->m_refcnt = 0; - for (PrintObject *print_object : m_objects) { - int idx_region = 0; - for (const auto &volumes : print_object->region_volumes) { - if (! volumes.empty()) - ++ m_regions[idx_region]->m_refcnt; - ++ idx_region; - } - } - - // All regions now have distinct settings. - // Check whether applying the new region config defaults we'd get different regions. - for (size_t region_id = 0; region_id < m_regions.size(); ++ region_id) { - PrintRegion ®ion = *m_regions[region_id]; - PrintRegionConfig this_region_config; - bool this_region_config_set = false; - for (PrintObject *print_object : m_objects) { - const LayerRanges *layer_ranges; - { - auto it_status = model_object_status.find(ModelObjectStatus(print_object->model_object()->id())); - assert(it_status != model_object_status.end()); - assert(it_status->status != ModelObjectStatus::Deleted); - layer_ranges = &it_status->layer_ranges; - } - if (region_id < print_object->region_volumes.size()) { - for (const std::pair &volume_and_range : print_object->region_volumes[region_id]) { - const ModelVolume &volume = *print_object->model_object()->volumes[volume_and_range.second]; - const DynamicPrintConfig *layer_range_config = layer_ranges->config(volume_and_range.first); - if (this_region_config_set) { - // If the new config for this volume differs from the other - // volume configs currently associated to this region, it means - // the region subdivision does not make sense anymore. - if (! this_region_config.equals(PrintObject::region_config_from_model_volume(m_default_region_config, layer_range_config, volume, num_extruders))) - // Regions were split. Reset this print_object. - goto print_object_end; - } else { - this_region_config = PrintObject::region_config_from_model_volume(m_default_region_config, layer_range_config, volume, num_extruders); - for (size_t i = 0; i < region_id; ++ i) { - const PrintRegion ®ion_other = *m_regions[i]; - if (region_other.m_refcnt != 0 && region_other.config().equals(this_region_config)) - // Regions were merged. Reset this print_object. - goto print_object_end; - } - this_region_config_set = true; - } - } - } - continue; - print_object_end: - update_apply_status(print_object->invalidate_all_steps()); - // Decrease the references to regions from this volume. - int ireg = 0; - for (const std::vector> &volumes : print_object->region_volumes) { - if (! volumes.empty()) - -- m_regions[ireg]->m_refcnt; - ++ ireg; - } - print_object->region_volumes.clear(); - } - if (this_region_config_set) { - t_config_option_keys diff = region.config().diff(this_region_config); - if (! diff.empty()) { - // Stop the background process before assigning new configuration to the regions. - for (PrintObject *print_object : m_objects) - if (region_id < print_object->region_volumes.size() && ! print_object->region_volumes[region_id].empty()) - update_apply_status(print_object->invalidate_state_by_config_options(region.config(), this_region_config, diff)); - region.config_apply_only(this_region_config, diff, false); - } - } - } - - // Possibly add new regions for the newly added or resetted PrintObjects. - for (size_t idx_print_object = 0; idx_print_object < m_objects.size(); ++ idx_print_object) { - PrintObject &print_object0 = *m_objects[idx_print_object]; - const ModelObject &model_object = *print_object0.model_object(); - const LayerRanges *layer_ranges; - { - auto it_status = model_object_status.find(ModelObjectStatus(model_object.id())); - assert(it_status != model_object_status.end()); - assert(it_status->status != ModelObjectStatus::Deleted); - layer_ranges = &it_status->layer_ranges; - } - std::vector regions_in_object; - regions_in_object.reserve(64); - for (size_t i = idx_print_object; i < m_objects.size() && m_objects[i]->model_object() == &model_object; ++ i) { - PrintObject &print_object = *m_objects[i]; - bool fresh = print_object.region_volumes.empty(); - unsigned int volume_id = 0; - unsigned int idx_region_in_object = 0; - for (const ModelVolume *volume : model_object.volumes) { - if (! volume->is_model_part() && ! volume->is_modifier()) { - ++ volume_id; - continue; - } - // Filter the layer ranges, so they do not overlap and they contain at least a single layer. - // Now insert a volume with a layer range to its own region. - for (auto it_range = layer_ranges->begin(); it_range != layer_ranges->end(); ++ it_range) { - int region_id = -1; - if (&print_object == &print_object0) { - // Get the config applied to this volume. - PrintRegionConfig config = PrintObject::region_config_from_model_volume(m_default_region_config, it_range->second, *volume, num_extruders); - // Find an existing print region with the same config. - int idx_empty_slot = -1; - for (int i = 0; i < (int)m_regions.size(); ++ i) { - if (m_regions[i]->m_refcnt == 0) { - if (idx_empty_slot == -1) - idx_empty_slot = i; - } else if (config.equals(m_regions[i]->config())) { - region_id = i; - break; - } - } - // If no region exists with the same config, create a new one. - if (region_id == -1) { - if (idx_empty_slot == -1) { - region_id = (int)m_regions.size(); - this->add_region(config); - } else { - region_id = idx_empty_slot; - m_regions[region_id]->set_config(std::move(config)); - } - } - regions_in_object.emplace_back(region_id); - } else - region_id = regions_in_object[idx_region_in_object ++]; - // Assign volume to a region. - if (fresh) { - if ((size_t)region_id >= print_object.region_volumes.size() || print_object.region_volumes[region_id].empty()) - ++ m_regions[region_id]->m_refcnt; - print_object.add_region_volume(region_id, volume_id, it_range->first); - } - } - ++ volume_id; - } - } - } - - // Update SlicingParameters for each object where the SlicingParameters is not valid. - // If it is not valid, then it is ensured that PrintObject.m_slicing_params is not in use - // (posSlicing and posSupportMaterial was invalidated). - for (PrintObject *object : m_objects) - object->update_slicing_parameters(); - -#ifdef _DEBUG - check_model_ids_equal(m_model, model); -#endif /* _DEBUG */ - - return static_cast(apply_status); -} - bool Print::has_infinite_skirt() const { return (m_config.draft_shield && m_config.skirts > 0) || (m_config.ooze_prevention && this->extruders().size() > 1); @@ -1253,10 +413,12 @@ static inline bool sequential_print_vertical_clearance_valid(const Print &print) // Precondition: Print::validate() requires the Print::apply() to be called its invocation. std::string Print::validate(std::string* warning) const { + std::vector extruders = this->extruders(); + if (m_objects.empty()) return L("All objects are outside of the print volume."); - if (extruders().empty()) + if (extruders.empty()) return L("The supplied settings will cause an empty print."); if (m_config.complete_objects) { @@ -1275,20 +437,16 @@ std::string Print::validate(std::string* warning) const return L("Only a single object may be printed at a time in Spiral Vase mode. " "Either remove all but the last object, or enable sequential mode by \"complete_objects\"."); assert(m_objects.size() == 1); - size_t num_regions = 0; - for (const std::vector> &volumes_per_region : m_objects.front()->region_volumes) - if (! volumes_per_region.empty()) - ++ num_regions; - if (num_regions > 1) + if (m_objects.front()->all_regions().size() > 1) return L("The Spiral Vase option can only be used when printing single material objects."); } if (this->has_wipe_tower() && ! m_objects.empty()) { // Make sure all extruders use same diameter filament and have the same nozzle diameter // EPSILON comparison is used for nozzles and 10 % tolerance is used for filaments - double first_nozzle_diam = m_config.nozzle_diameter.get_at(extruders().front()); - double first_filament_diam = m_config.filament_diameter.get_at(extruders().front()); - for (const auto& extruder_idx : extruders()) { + double first_nozzle_diam = m_config.nozzle_diameter.get_at(extruders.front()); + double first_filament_diam = m_config.filament_diameter.get_at(extruders.front()); + for (const auto& extruder_idx : extruders) { double nozzle_diam = m_config.nozzle_diameter.get_at(extruder_idx); double filament_diam = m_config.filament_diameter.get_at(extruder_idx); if (nozzle_diam - EPSILON > first_nozzle_diam || nozzle_diam + EPSILON < first_nozzle_diam @@ -1306,7 +464,7 @@ std::string Print::validate(std::string* warning) const return L("Ooze prevention is currently not supported with the wipe tower enabled."); if (m_config.use_volumetric_e) return L("The Wipe Tower currently does not support volumetric E (use_volumetric_e=0)."); - if (m_config.complete_objects && extruders().size() > 1) + if (m_config.complete_objects && extruders.size() > 1) return L("The Wipe Tower is currently not supported for multimaterial sequential prints."); if (m_objects.size() > 1) { @@ -1386,8 +544,6 @@ std::string Print::validate(std::string* warning) const } { - std::vector extruders = this->extruders(); - // Find the smallest used nozzle diameter and the number of unique nozzle diameters. double min_nozzle_diameter = std::numeric_limits::max(); double max_nozzle_diameter = 0; @@ -1464,7 +620,8 @@ std::string Print::validate(std::string* warning) const } // validate first_layer_height - double first_layer_height = object->config().get_abs_value("first_layer_height"); + assert(! m_config.first_layer_height.percent); + double first_layer_height = m_config.first_layer_height.value; double first_layer_min_nozzle_diameter; if (object->has_raft()) { // if we have raft layers, only support material extruder is used on first layer @@ -1493,8 +650,8 @@ std::string Print::validate(std::string* warning) const if ((object->has_support() || object->has_raft()) && ! validate_extrusion_width(object->config(), "support_material_extrusion_width", layer_height, err_msg)) return err_msg; for (const char *opt_key : { "perimeter_extrusion_width", "external_perimeter_extrusion_width", "infill_extrusion_width", "solid_infill_extrusion_width", "top_infill_extrusion_width" }) - for (size_t i = 0; i < object->region_volumes.size(); ++ i) - if (! object->region_volumes[i].empty() && ! validate_extrusion_width(this->get_region(i)->config(), opt_key, layer_height, err_msg)) + for (const PrintRegion ®ion : object->all_regions()) + if (! validate_extrusion_width(region.config(), opt_key, layer_height, err_msg)) return err_msg; } } @@ -1561,16 +718,15 @@ BoundingBox Print::total_bounding_box() const double Print::skirt_first_layer_height() const { - if (m_objects.empty()) - throw Slic3r::InvalidArgument("skirt_first_layer_height() can't be called without PrintObjects"); - return m_objects.front()->config().get_abs_value("first_layer_height"); + assert(! m_config.first_layer_height.percent); + return m_config.first_layer_height.value; } Flow Print::brim_flow() const { ConfigOptionFloatOrPercent width = m_config.first_layer_extrusion_width; if (width.value == 0) - width = m_regions.front()->config().perimeter_extrusion_width; + width = m_print_regions.front()->config().perimeter_extrusion_width; if (width.value == 0) width = m_objects.front()->config().extrusion_width; @@ -1582,7 +738,7 @@ Flow Print::brim_flow() const return Flow::new_from_config_width( frPerimeter, width, - (float)m_config.nozzle_diameter.get_at(m_regions.front()->config().perimeter_extruder-1), + (float)m_config.nozzle_diameter.get_at(m_print_regions.front()->config().perimeter_extruder-1), (float)this->skirt_first_layer_height()); } @@ -1590,7 +746,7 @@ Flow Print::skirt_flow() const { ConfigOptionFloatOrPercent width = m_config.first_layer_extrusion_width; if (width.value == 0) - width = m_regions.front()->config().perimeter_extrusion_width; + width = m_print_regions.front()->config().perimeter_extrusion_width; if (width.value == 0) width = m_objects.front()->config().extrusion_width; diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index 91f86d010..3fdc49db8 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -15,6 +15,9 @@ #include "libslic3r.h" +#include +#include + namespace Slic3r { class Print; @@ -57,12 +60,20 @@ enum PrintObjectStep { // sharing the same config (including the same assigned extruder(s)) class PrintRegion { - friend class Print; +public: + PrintRegion() = default; + PrintRegion(const PrintRegionConfig &config); + PrintRegion(const PrintRegionConfig &config, const size_t config_hash) : m_config(config), m_config_hash(config_hash) {} + PrintRegion(PrintRegionConfig &&config); + PrintRegion(PrintRegionConfig &&config, const size_t config_hash) : m_config(std::move(config)), m_config_hash(config_hash) {} + ~PrintRegion() = default; // Methods NOT modifying the PrintRegion's state: public: - const Print* print() const { return m_print; } - const PrintRegionConfig& config() const { return m_config; } + const PrintRegionConfig& config() const throw() { return m_config; } + size_t config_hash() const throw() { return m_config_hash; } + // Identifier of this PrintRegion in the list of Print::m_print_regions. + int print_region_id() const throw() { return m_print_region_id; } // 1-based extruder identifier for this region and role. unsigned int extruder(FlowRole role) const; Flow flow(const PrintObject &object, FlowRole role, double layer_height, bool first_layer = false) const; @@ -72,29 +83,25 @@ public: coordf_t bridging_height_avg(const PrintConfig &print_config) const; // Collect 0-based extruder indices used to print this region's object. - void collect_object_printing_extruders(std::vector &object_extruders) const; + void collect_object_printing_extruders(const Print &print, std::vector &object_extruders) const; static void collect_object_printing_extruders(const PrintConfig &print_config, const PrintRegionConfig ®ion_config, const bool has_brim, std::vector &object_extruders); // Methods modifying the PrintRegion's state: public: - Print* print() { return m_print; } - void set_config(const PrintRegionConfig &config) { m_config = config; } - void set_config(PrintRegionConfig &&config) { m_config = std::move(config); } + void set_config(const PrintRegionConfig &config) { m_config = config; m_config_hash = m_config.hash(); } + void set_config(PrintRegionConfig &&config) { m_config = std::move(config); m_config_hash = m_config.hash(); } void config_apply_only(const ConfigBase &other, const t_config_option_keys &keys, bool ignore_nonexistent = false) - { this->m_config.apply_only(other, keys, ignore_nonexistent); } - -protected: - size_t m_refcnt; - + { m_config.apply_only(other, keys, ignore_nonexistent); m_config_hash = m_config.hash(); } private: - Print *m_print; + friend Print; PrintRegionConfig m_config; - - PrintRegion(Print* print) : m_refcnt(0), m_print(print) {} - PrintRegion(Print* print, const PrintRegionConfig &config) : m_refcnt(0), m_print(print), m_config(config) {} - ~PrintRegion() = default; + size_t m_config_hash; + int m_print_region_id = -1; }; +inline bool operator==(const PrintRegion &lhs, const PrintRegion &rhs) { return lhs.config_hash() == rhs.config_hash() && lhs.config() == rhs.config(); } +inline bool operator!=(const PrintRegion &lhs, const PrintRegion &rhs) { return ! (lhs == rhs); } + template class ConstVectorOfPtrsAdaptor { public: @@ -145,15 +152,40 @@ struct PrintInstance typedef std::vector PrintInstances; +// Region and its volumes (printing volumes or modifier volumes) +struct PrintRegionVolumes +{ + // Single volume + Z range assigned to a region. + struct VolumeWithZRange { + // Z range to slice this ModelVolume over. + t_layer_height_range layer_height_range; + // Index of a ModelVolume inside its parent ModelObject. + int volume_idx; + }; + + // Overriding one region with some other extruder, producing another region. + // The region is owned by PrintObject::m_all_regions. + struct ExtruderOverride { + unsigned int extruder; +// const PrintRegion *region; + }; + + // The region is owned by PrintObject::m_all_regions. +// const PrintRegion *region; + // Possible overrides of the default region extruder. + std::vector overrides; + // List of ModelVolume indices and layer ranges of thereof. + std::vector volumes; + // Is this region printing in any layer? +// bool printing { false }; +}; + class PrintObject : public PrintObjectBaseWithState { private: // Prevents erroneous use by other classes. typedef PrintObjectBaseWithState Inherited; public: - // vector of (layer height ranges and vectors of volume ids), indexed by region_id - std::vector>> region_volumes; - // Size of an object: XYZ in scaled coordinates. The size might not be quite snug in XY plane. const Vec3crd& size() const { return m_size; } const PrintObjectConfig& config() const { return m_config; } @@ -180,9 +212,9 @@ public: // adds region_id, too, if necessary void add_region_volume(unsigned int region_id, int volume_id, const t_layer_height_range &layer_range) { - if (region_id >= region_volumes.size()) - region_volumes.resize(region_id + 1); - region_volumes[region_id].emplace_back(layer_range, volume_id); + if (region_id >= m_region_volumes.size()) + m_region_volumes.resize(region_id + 1); + m_region_volumes[region_id].volumes.push_back({ layer_range, volume_id }); } // This is the *total* layer count (including support layers) // this value is not supposed to be compared with Layer::id @@ -213,7 +245,7 @@ public: // Initialize the layer_height_profile from the model_object's layer_height_profile, from model_object's layer height table, or from slicing parameters. // Returns true, if the layer_height_profile was changed. - static bool update_layer_height_profile(const ModelObject &model_object, const SlicingParameters &slicing_parameters, std::vector &layer_height_profile); + static bool update_layer_height_profile(const ModelObject &model_object, const SlicingParameters &slicing_parameters, std::vector &layer_height_profile); // Collect the slicing parameters, to be used by variable layer thickness algorithm, // by the interactive layer height editor and by the printing process itself. @@ -222,6 +254,11 @@ public: const SlicingParameters& slicing_parameters() const { return m_slicing_params; } static SlicingParameters slicing_parameters(const DynamicPrintConfig &full_config, const ModelObject &model_object, float object_max_z); + size_t num_printing_regions() const throw() { return m_all_regions.size(); } + const PrintRegion& printing_region(size_t idx) const throw() { return *m_all_regions[idx]; } + //FIXME returing all possible regions before slicing, thus some of the regions may not be slicing at the end. + std::vector> all_regions() const; + bool has_support() const { return m_config.support_material || m_config.support_material_enforce_layers > 0; } bool has_raft() const { return m_config.raft_layers > 0; } bool has_support_material() const { return this->has_support() || this->has_raft(); } @@ -247,8 +284,8 @@ private: PrintObject(Print* print, ModelObject* model_object, const Transform3d& trafo, PrintInstances&& instances); ~PrintObject() = default; - void config_apply(const ConfigBase &other, bool ignore_nonexistent = false) { this->m_config.apply(other, ignore_nonexistent); } - void config_apply_only(const ConfigBase &other, const t_config_option_keys &keys, bool ignore_nonexistent = false) { this->m_config.apply_only(other, keys, ignore_nonexistent); } + void config_apply(const ConfigBase &other, bool ignore_nonexistent = false) { m_config.apply(other, ignore_nonexistent); } + void config_apply_only(const ConfigBase &other, const t_config_option_keys &keys, bool ignore_nonexistent = false) { m_config.apply_only(other, keys, ignore_nonexistent); } PrintBase::ApplyStatus set_instances(PrintInstances &&instances); // Invalidates the step, and its depending steps in PrintObject and Print. bool invalidate_step(PrintObjectStep step); @@ -296,6 +333,10 @@ private: // This is the adjustment of the the Object's coordinate system towards PrintObject's coordinate system. Point m_center_offset; + std::vector> m_all_regions; + // vector of (layer height ranges and vectors of volume ids), indexed by region_id + std::vector m_region_volumes; + SlicingParameters m_slicing_params; LayerPtrs m_layers; SupportLayerPtrs m_support_layers; @@ -366,7 +407,7 @@ struct PrintStatistics double total_weight; double total_wipe_tower_cost; double total_wipe_tower_filament; - std::map filament_stats; + std::map filament_stats; // Config with the filled in print statistics. DynamicConfig config() const; @@ -395,11 +436,13 @@ class ConstPrintObjectPtrsAdaptor : public ConstVectorOfPtrsAdaptor }; typedef std::vector PrintRegionPtrs; +/* typedef std::vector ConstPrintRegionPtrs; class ConstPrintRegionPtrsAdaptor : public ConstVectorOfPtrsAdaptor { friend Print; ConstPrintRegionPtrsAdaptor(const PrintRegionPtrs *data) : ConstVectorOfPtrsAdaptor(data) {} }; +*/ // The complete print tray with possibly multiple objects. class Print : public PrintBaseWithState @@ -470,14 +513,14 @@ public: [object_id](const PrintObject *obj) { return obj->id() == object_id; }); return (it == m_objects.end()) ? nullptr : *it; } - ConstPrintRegionPtrsAdaptor regions() const { return ConstPrintRegionPtrsAdaptor(&m_regions); } +// ConstPrintRegionPtrsAdaptor regions() const { return ConstPrintRegionPtrsAdaptor(&m_regions); } // How many of PrintObject::copies() over all print objects are there? // If zero, then the print is empty and the print shall not be executed. unsigned int num_object_instances() const; // For Perl bindings. PrintObjectPtrs& objects_mutable() { return m_objects; } - PrintRegionPtrs& regions_mutable() { return m_regions; } + PrintRegionPtrs& print_regions_mutable() { return m_print_regions; } const ExtrusionEntityCollection& skirt() const { return m_skirt; } const ExtrusionEntityCollection& brim() const { return m_brim; } @@ -498,26 +541,15 @@ public: std::string output_filename(const std::string &filename_base = std::string()) const override; - // Accessed by SupportMaterial - const PrintRegion* get_region(size_t idx) const { return m_regions[idx]; } - const ToolOrdering& get_tool_ordering() const { return m_wipe_tower_data.tool_ordering; } // #ys_FIXME just for testing + size_t num_print_regions() const throw() { return m_print_regions.size(); } + const PrintRegion& get_print_region(size_t idx) const { return *m_print_regions[idx]; } + const ToolOrdering& get_tool_ordering() const { return m_wipe_tower_data.tool_ordering; } protected: - // methods for handling regions - PrintRegion* get_region(size_t idx) { return m_regions[idx]; } - PrintRegion* add_region(); - PrintRegion* add_region(const PrintRegionConfig &config); - // Invalidates the step, and its depending steps in Print. bool invalidate_step(PrintStep step); private: - void config_diffs( - const DynamicPrintConfig &new_full_config, - t_config_option_keys &print_diff, t_config_option_keys &object_diff, t_config_option_keys ®ion_diff, - t_config_option_keys &full_config_diff, - DynamicPrintConfig &filament_overrides) const; - bool invalidate_state_by_config_options(const ConfigOptionResolver &new_config, const std::vector &opt_keys); void _make_skirt(); @@ -529,14 +561,11 @@ private: // Return 4 wipe tower corners in the world coordinates (shifted and rotated), including the wipe tower brim. std::vector first_layer_wipe_tower_corners() const; - // Declared here to have access to Model / ModelObject / ModelInstance - static void model_volume_list_update_supports(ModelObject &model_object_dst, const ModelObject &model_object_src); - PrintConfig m_config; PrintObjectConfig m_default_object_config; PrintRegionConfig m_default_region_config; PrintObjectPtrs m_objects; - PrintRegionPtrs m_regions; + PrintRegionPtrs m_print_regions; // Ordered collections of extrusion paths to build skirt loops and brim. ExtrusionEntityCollection m_skirt; diff --git a/src/libslic3r/PrintApply.cpp b/src/libslic3r/PrintApply.cpp new file mode 100644 index 000000000..f0e262fdc --- /dev/null +++ b/src/libslic3r/PrintApply.cpp @@ -0,0 +1,824 @@ +#include "Model.hpp" +#include "Print.hpp" + +namespace Slic3r { + +// Add or remove support modifier ModelVolumes from model_object_dst to match the ModelVolumes of model_object_new +// in the exact order and with the same IDs. +// It is expected, that the model_object_dst already contains the non-support volumes of model_object_new in the correct order. +// Friend to ModelVolume to allow copying. +// static is not accepted by gcc if declared as a friend of ModelObject. +/* static */ void model_volume_list_update_supports(ModelObject &model_object_dst, const ModelObject &model_object_new) +{ + typedef std::pair ModelVolumeWithStatus; + std::vector old_volumes; + old_volumes.reserve(model_object_dst.volumes.size()); + for (const ModelVolume *model_volume : model_object_dst.volumes) + old_volumes.emplace_back(ModelVolumeWithStatus(model_volume, false)); + auto model_volume_lower = [](const ModelVolumeWithStatus &mv1, const ModelVolumeWithStatus &mv2){ return mv1.first->id() < mv2.first->id(); }; + auto model_volume_equal = [](const ModelVolumeWithStatus &mv1, const ModelVolumeWithStatus &mv2){ return mv1.first->id() == mv2.first->id(); }; + std::sort(old_volumes.begin(), old_volumes.end(), model_volume_lower); + model_object_dst.volumes.clear(); + model_object_dst.volumes.reserve(model_object_new.volumes.size()); + for (const ModelVolume *model_volume_src : model_object_new.volumes) { + ModelVolumeWithStatus key(model_volume_src, false); + auto it = std::lower_bound(old_volumes.begin(), old_volumes.end(), key, model_volume_lower); + if (it != old_volumes.end() && model_volume_equal(*it, key)) { + // The volume was found in the old list. Just copy it. + assert(! it->second); // not consumed yet + it->second = true; + ModelVolume *model_volume_dst = const_cast(it->first); + // For support modifiers, the type may have been switched from blocker to enforcer and vice versa. + assert((model_volume_dst->is_support_modifier() && model_volume_src->is_support_modifier()) || model_volume_dst->type() == model_volume_src->type()); + model_object_dst.volumes.emplace_back(model_volume_dst); + if (model_volume_dst->is_support_modifier()) { + // For support modifiers, the type may have been switched from blocker to enforcer and vice versa. + model_volume_dst->set_type(model_volume_src->type()); + model_volume_dst->set_transformation(model_volume_src->get_transformation()); + } + assert(model_volume_dst->get_matrix().isApprox(model_volume_src->get_matrix())); + } else { + // The volume was not found in the old list. Create a new copy. + assert(model_volume_src->is_support_modifier()); + model_object_dst.volumes.emplace_back(new ModelVolume(*model_volume_src)); + model_object_dst.volumes.back()->set_model_object(&model_object_dst); + } + } + // Release the non-consumed old volumes (those were deleted from the new list). + for (ModelVolumeWithStatus &mv_with_status : old_volumes) + if (! mv_with_status.second) + delete mv_with_status.first; +} + +static inline void model_volume_list_copy_configs(ModelObject &model_object_dst, const ModelObject &model_object_src, const ModelVolumeType type) +{ + size_t i_src, i_dst; + for (i_src = 0, i_dst = 0; i_src < model_object_src.volumes.size() && i_dst < model_object_dst.volumes.size();) { + const ModelVolume &mv_src = *model_object_src.volumes[i_src]; + ModelVolume &mv_dst = *model_object_dst.volumes[i_dst]; + if (mv_src.type() != type) { + ++ i_src; + continue; + } + if (mv_dst.type() != type) { + ++ i_dst; + continue; + } + assert(mv_src.id() == mv_dst.id()); + // Copy the ModelVolume data. + mv_dst.name = mv_src.name; + mv_dst.config.assign_config(mv_src.config); + assert(mv_dst.supported_facets.id() == mv_src.supported_facets.id()); + mv_dst.supported_facets.assign(mv_src.supported_facets); + assert(mv_dst.seam_facets.id() == mv_src.seam_facets.id()); + mv_dst.seam_facets.assign(mv_src.seam_facets); + //FIXME what to do with the materials? + // mv_dst.m_material_id = mv_src.m_material_id; + ++ i_src; + ++ i_dst; + } +} + +static inline void layer_height_ranges_copy_configs(t_layer_config_ranges &lr_dst, const t_layer_config_ranges &lr_src) +{ + assert(lr_dst.size() == lr_src.size()); + auto it_src = lr_src.cbegin(); + for (auto &kvp_dst : lr_dst) { + const auto &kvp_src = *it_src ++; + assert(std::abs(kvp_dst.first.first - kvp_src.first.first ) <= EPSILON); + assert(std::abs(kvp_dst.first.second - kvp_src.first.second) <= EPSILON); + // Layer heights are allowed do differ in case the layer height table is being overriden by the smooth profile. + // assert(std::abs(kvp_dst.second.option("layer_height")->getFloat() - kvp_src.second.option("layer_height")->getFloat()) <= EPSILON); + kvp_dst.second = kvp_src.second; + } +} + +static inline bool transform3d_lower(const Transform3d &lhs, const Transform3d &rhs) +{ + typedef Transform3d::Scalar T; + const T *lv = lhs.data(); + const T *rv = rhs.data(); + for (size_t i = 0; i < 16; ++ i, ++ lv, ++ rv) { + if (*lv < *rv) + return true; + else if (*lv > *rv) + return false; + } + return false; +} + +static inline bool transform3d_equal(const Transform3d &lhs, const Transform3d &rhs) +{ + typedef Transform3d::Scalar T; + const T *lv = lhs.data(); + const T *rv = rhs.data(); + for (size_t i = 0; i < 16; ++ i, ++ lv, ++ rv) + if (*lv != *rv) + return false; + return true; +} + +struct PrintObjectTrafoAndInstances +{ + Transform3d trafo; + PrintInstances instances; + bool operator<(const PrintObjectTrafoAndInstances &rhs) const { return transform3d_lower(this->trafo, rhs.trafo); } +}; + +// Generate a list of trafos and XY offsets for instances of a ModelObject +static std::vector print_objects_from_model_object(const ModelObject &model_object) +{ + std::set trafos; + PrintObjectTrafoAndInstances trafo; + for (ModelInstance *model_instance : model_object.instances) + if (model_instance->is_printable()) { + trafo.trafo = model_instance->get_matrix(); + auto shift = Point::new_scale(trafo.trafo.data()[12], trafo.trafo.data()[13]); + // Reset the XY axes of the transformation. + trafo.trafo.data()[12] = 0; + trafo.trafo.data()[13] = 0; + // Search or insert a trafo. + auto it = trafos.emplace(trafo).first; + const_cast(*it).instances.emplace_back(PrintInstance{ nullptr, model_instance, shift }); + } + return std::vector(trafos.begin(), trafos.end()); +} + +// Compare just the layer ranges and their layer heights, not the associated configs. +// Ignore the layer heights if check_layer_heights is false. +static bool layer_height_ranges_equal(const t_layer_config_ranges &lr1, const t_layer_config_ranges &lr2, bool check_layer_height) +{ + if (lr1.size() != lr2.size()) + return false; + auto it2 = lr2.begin(); + for (const auto &kvp1 : lr1) { + const auto &kvp2 = *it2 ++; + if (std::abs(kvp1.first.first - kvp2.first.first ) > EPSILON || + std::abs(kvp1.first.second - kvp2.first.second) > EPSILON || + (check_layer_height && std::abs(kvp1.second.option("layer_height")->getFloat() - kvp2.second.option("layer_height")->getFloat()) > EPSILON)) + return false; + } + return true; +} + +// Returns true if va == vb when all CustomGCode items that are not ToolChangeCode are ignored. +static bool custom_per_printz_gcodes_tool_changes_differ(const std::vector &va, const std::vector &vb) +{ + auto it_a = va.begin(); + auto it_b = vb.begin(); + while (it_a != va.end() || it_b != vb.end()) { + if (it_a != va.end() && it_a->type != CustomGCode::ToolChange) { + // Skip any CustomGCode items, which are not tool changes. + ++ it_a; + continue; + } + if (it_b != vb.end() && it_b->type != CustomGCode::ToolChange) { + // Skip any CustomGCode items, which are not tool changes. + ++ it_b; + continue; + } + if (it_a == va.end() || it_b == vb.end()) + // va or vb contains more Tool Changes than the other. + return true; + assert(it_a->type == CustomGCode::ToolChange); + assert(it_b->type == CustomGCode::ToolChange); + if (*it_a != *it_b) + // The two Tool Changes differ. + return true; + ++ it_a; + ++ it_b; + } + // There is no change in custom Tool Changes. + return false; +} + +// Collect changes to print config, account for overrides of extruder retract values by filament presets. +static t_config_option_keys print_config_diffs( + const PrintConfig ¤t_config, + const DynamicPrintConfig &new_full_config, + DynamicPrintConfig &filament_overrides) +{ + const std::vector &extruder_retract_keys = print_config_def.extruder_retract_keys(); + const std::string filament_prefix = "filament_"; + t_config_option_keys print_diff; + for (const t_config_option_key &opt_key : current_config.keys()) { + const ConfigOption *opt_old = current_config.option(opt_key); + assert(opt_old != nullptr); + const ConfigOption *opt_new = new_full_config.option(opt_key); + // assert(opt_new != nullptr); + if (opt_new == nullptr) + //FIXME This may happen when executing some test cases. + continue; + const ConfigOption *opt_new_filament = std::binary_search(extruder_retract_keys.begin(), extruder_retract_keys.end(), opt_key) ? new_full_config.option(filament_prefix + opt_key) : nullptr; + if (opt_new_filament != nullptr && ! opt_new_filament->is_nil()) { + // An extruder retract override is available at some of the filament presets. + if (*opt_old != *opt_new || opt_new->overriden_by(opt_new_filament)) { + auto opt_copy = opt_new->clone(); + opt_copy->apply_override(opt_new_filament); + if (*opt_old == *opt_copy) + delete opt_copy; + else { + filament_overrides.set_key_value(opt_key, opt_copy); + print_diff.emplace_back(opt_key); + } + } + } else if (*opt_new != *opt_old) + print_diff.emplace_back(opt_key); + } + + return print_diff; + } + +// Prepare for storing of the full print config into new_full_config to be exported into the G-code and to be used by the PlaceholderParser. +static t_config_option_keys full_print_config_diffs(const DynamicPrintConfig ¤t_full_config, const DynamicPrintConfig &new_full_config) +{ + t_config_option_keys full_config_diff; + for (const t_config_option_key &opt_key : new_full_config.keys()) { + const ConfigOption *opt_old = current_full_config.option(opt_key); + const ConfigOption *opt_new = new_full_config.option(opt_key); + if (opt_old == nullptr || *opt_new != *opt_old) + full_config_diff.emplace_back(opt_key); + } + return full_config_diff; +} + +Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_config) +{ +#ifdef _DEBUG + check_model_ids_validity(model); +#endif /* _DEBUG */ + + // Normalize the config. + new_full_config.option("print_settings_id", true); + new_full_config.option("filament_settings_id", true); + new_full_config.option("printer_settings_id", true); + new_full_config.option("physical_printer_settings_id", true); + new_full_config.normalize_fdm(); + + // Find modified keys of the various configs. Resolve overrides extruder retract values by filament profiles. + DynamicPrintConfig filament_overrides; + t_config_option_keys print_diff = print_config_diffs(m_config, new_full_config, filament_overrides); + t_config_option_keys full_config_diff = full_print_config_diffs(m_full_print_config, new_full_config); + // Collect changes to object and region configs. + t_config_option_keys object_diff = m_default_object_config.diff(new_full_config); + t_config_option_keys region_diff = m_default_region_config.diff(new_full_config); + + // Do not use the ApplyStatus as we will use the max function when updating apply_status. + unsigned int apply_status = APPLY_STATUS_UNCHANGED; + auto update_apply_status = [&apply_status](bool invalidated) + { apply_status = std::max(apply_status, invalidated ? APPLY_STATUS_INVALIDATED : APPLY_STATUS_CHANGED); }; + if (! (print_diff.empty() && object_diff.empty() && region_diff.empty())) + update_apply_status(false); + + // Grab the lock for the Print / PrintObject milestones. + tbb::mutex::scoped_lock lock(this->state_mutex()); + + // The following call may stop the background processing. + if (! print_diff.empty()) + update_apply_status(this->invalidate_state_by_config_options(new_full_config, print_diff)); + + // Apply variables to placeholder parser. The placeholder parser is used by G-code export, + // which should be stopped if print_diff is not empty. + size_t num_extruders = m_config.nozzle_diameter.size(); + bool num_extruders_changed = false; + if (! full_config_diff.empty()) { + update_apply_status(this->invalidate_step(psGCodeExport)); + // Set the profile aliases for the PrintBase::output_filename() + m_placeholder_parser.set("print_preset", new_full_config.option("print_settings_id")->clone()); + m_placeholder_parser.set("filament_preset", new_full_config.option("filament_settings_id")->clone()); + m_placeholder_parser.set("printer_preset", new_full_config.option("printer_settings_id")->clone()); + m_placeholder_parser.set("physical_printer_preset", new_full_config.option("physical_printer_settings_id")->clone()); + // We want the filament overrides to be applied over their respective extruder parameters by the PlaceholderParser. + // see "Placeholders do not respect filament overrides." GH issue #3649 + m_placeholder_parser.apply_config(filament_overrides); + // It is also safe to change m_config now after this->invalidate_state_by_config_options() call. + m_config.apply_only(new_full_config, print_diff, true); + //FIXME use move semantics once ConfigBase supports it. + m_config.apply(filament_overrides); + // Handle changes to object config defaults + m_default_object_config.apply_only(new_full_config, object_diff, true); + // Handle changes to regions config defaults + m_default_region_config.apply_only(new_full_config, region_diff, true); + m_full_print_config = std::move(new_full_config); + if (num_extruders != m_config.nozzle_diameter.size()) { + num_extruders = m_config.nozzle_diameter.size(); + num_extruders_changed = true; + } + } + + class LayerRanges + { + public: + LayerRanges() {} + // Convert input config ranges into continuous non-overlapping sorted vector of intervals and their configs. + void assign(const t_layer_config_ranges &in) { + m_ranges.clear(); + m_ranges.reserve(in.size()); + // Input ranges are sorted lexicographically. First range trims the other ranges. + coordf_t last_z = 0; + for (const std::pair &range : in) + if (range.first.second > last_z) { + coordf_t min_z = std::max(range.first.first, 0.); + if (min_z > last_z + EPSILON) { + m_ranges.emplace_back(t_layer_height_range(last_z, min_z), nullptr); + last_z = min_z; + } + if (range.first.second > last_z + EPSILON) { + const DynamicPrintConfig *cfg = &range.second.get(); + m_ranges.emplace_back(t_layer_height_range(last_z, range.first.second), cfg); + last_z = range.first.second; + } + } + if (m_ranges.empty()) + m_ranges.emplace_back(t_layer_height_range(0, DBL_MAX), nullptr); + else if (m_ranges.back().second == nullptr) + m_ranges.back().first.second = DBL_MAX; + else + m_ranges.emplace_back(t_layer_height_range(m_ranges.back().first.second, DBL_MAX), nullptr); + } + + const DynamicPrintConfig* config(const t_layer_height_range &range) const { + auto it = std::lower_bound(m_ranges.begin(), m_ranges.end(), std::make_pair< t_layer_height_range, const DynamicPrintConfig*>(t_layer_height_range(range.first - EPSILON, range.second - EPSILON), nullptr)); + // #ys_FIXME_COLOR + // assert(it != m_ranges.end()); + // assert(it == m_ranges.end() || std::abs(it->first.first - range.first ) < EPSILON); + // assert(it == m_ranges.end() || std::abs(it->first.second - range.second) < EPSILON); + if (it == m_ranges.end() || + std::abs(it->first.first - range.first) > EPSILON || + std::abs(it->first.second - range.second) > EPSILON ) + return nullptr; // desired range doesn't found + return (it == m_ranges.end()) ? nullptr : it->second; + } + std::vector>::const_iterator begin() const { return m_ranges.cbegin(); } + std::vector>::const_iterator end() const { return m_ranges.cend(); } + private: + std::vector> m_ranges; + }; + struct ModelObjectStatus { + enum Status { + Unknown, + Old, + New, + Moved, + Deleted, + }; + ModelObjectStatus(ObjectID id, Status status = Unknown) : id(id), status(status) {} + ObjectID id; + Status status; + LayerRanges layer_ranges; + // Search by id. + bool operator<(const ModelObjectStatus &rhs) const { return id < rhs.id; } + }; + std::set model_object_status; + + // 1) Synchronize model objects. + if (model.id() != m_model.id()) { + // Kill everything, initialize from scratch. + // Stop background processing. + this->call_cancel_callback(); + update_apply_status(this->invalidate_all_steps()); + for (PrintObject *object : m_objects) { + model_object_status.emplace(object->model_object()->id(), ModelObjectStatus::Deleted); + update_apply_status(object->invalidate_all_steps()); + delete object; + } + m_objects.clear(); + m_model.assign_copy(model); + for (const ModelObject *model_object : m_model.objects) + model_object_status.emplace(model_object->id(), ModelObjectStatus::New); + } else { + if (m_model.custom_gcode_per_print_z != model.custom_gcode_per_print_z) { + update_apply_status(num_extruders_changed || + // Tool change G-codes are applied as color changes for a single extruder printer, no need to invalidate tool ordering. + //FIXME The tool ordering may be invalidated unnecessarily if the custom_gcode_per_print_z.mode is not applicable + // to the active print / model state, and then it is reset, so it is being applicable, but empty, thus the effect is the same. + (num_extruders > 1 && custom_per_printz_gcodes_tool_changes_differ(m_model.custom_gcode_per_print_z.gcodes, model.custom_gcode_per_print_z.gcodes)) ? + // The Tool Ordering and the Wipe Tower are no more valid. + this->invalidate_steps({ psWipeTower, psGCodeExport }) : + // There is no change in Tool Changes stored in custom_gcode_per_print_z, therefore there is no need to update Tool Ordering. + this->invalidate_step(psGCodeExport)); + m_model.custom_gcode_per_print_z = model.custom_gcode_per_print_z; + } + if (model_object_list_equal(m_model, model)) { + // The object list did not change. + for (const ModelObject *model_object : m_model.objects) + model_object_status.emplace(model_object->id(), ModelObjectStatus::Old); + } else if (model_object_list_extended(m_model, model)) { + // Add new objects. Their volumes and configs will be synchronized later. + update_apply_status(this->invalidate_step(psGCodeExport)); + for (const ModelObject *model_object : m_model.objects) + model_object_status.emplace(model_object->id(), ModelObjectStatus::Old); + for (size_t i = m_model.objects.size(); i < model.objects.size(); ++ i) { + model_object_status.emplace(model.objects[i]->id(), ModelObjectStatus::New); + m_model.objects.emplace_back(ModelObject::new_copy(*model.objects[i])); + m_model.objects.back()->set_model(&m_model); + } + } else { + // Reorder the objects, add new objects. + // First stop background processing before shuffling or deleting the PrintObjects in the object list. + this->call_cancel_callback(); + update_apply_status(this->invalidate_step(psGCodeExport)); + // Second create a new list of objects. + std::vector model_objects_old(std::move(m_model.objects)); + m_model.objects.clear(); + m_model.objects.reserve(model.objects.size()); + auto by_id_lower = [](const ModelObject *lhs, const ModelObject *rhs){ return lhs->id() < rhs->id(); }; + std::sort(model_objects_old.begin(), model_objects_old.end(), by_id_lower); + for (const ModelObject *mobj : model.objects) { + auto it = std::lower_bound(model_objects_old.begin(), model_objects_old.end(), mobj, by_id_lower); + if (it == model_objects_old.end() || (*it)->id() != mobj->id()) { + // New ModelObject added. + m_model.objects.emplace_back(ModelObject::new_copy(*mobj)); + m_model.objects.back()->set_model(&m_model); + model_object_status.emplace(mobj->id(), ModelObjectStatus::New); + } else { + // Existing ModelObject re-added (possibly moved in the list). + m_model.objects.emplace_back(*it); + model_object_status.emplace(mobj->id(), ModelObjectStatus::Moved); + } + } + bool deleted_any = false; + for (ModelObject *&model_object : model_objects_old) { + if (model_object_status.find(ModelObjectStatus(model_object->id())) == model_object_status.end()) { + model_object_status.emplace(model_object->id(), ModelObjectStatus::Deleted); + deleted_any = true; + } else + // Do not delete this ModelObject instance. + model_object = nullptr; + } + if (deleted_any) { + // Delete PrintObjects of the deleted ModelObjects. + PrintObjectPtrs print_objects_old = std::move(m_objects); + m_objects.clear(); + m_objects.reserve(print_objects_old.size()); + for (PrintObject *print_object : print_objects_old) { + auto it_status = model_object_status.find(ModelObjectStatus(print_object->model_object()->id())); + assert(it_status != model_object_status.end()); + if (it_status->status == ModelObjectStatus::Deleted) { + update_apply_status(print_object->invalidate_all_steps()); + delete print_object; + } else + m_objects.emplace_back(print_object); + } + for (ModelObject *model_object : model_objects_old) + delete model_object; + } + } + } + + // 2) Map print objects including their transformation matrices. + struct PrintObjectStatus { + enum Status { + Unknown, + Deleted, + Reused, + New + }; + PrintObjectStatus(PrintObject *print_object, Status status = Unknown) : + id(print_object->model_object()->id()), + print_object(print_object), + trafo(print_object->trafo()), + status(status) {} + PrintObjectStatus(ObjectID id) : id(id), print_object(nullptr), trafo(Transform3d::Identity()), status(Unknown) {} + // ID of the ModelObject & PrintObject + ObjectID id; + // Pointer to the old PrintObject + PrintObject *print_object; + // Trafo generated with model_object->world_matrix(true) + Transform3d trafo; + Status status; + // Search by id. + bool operator<(const PrintObjectStatus &rhs) const { return id < rhs.id; } + }; + std::multiset print_object_status; + for (PrintObject *print_object : m_objects) + print_object_status.emplace(PrintObjectStatus(print_object)); + + // 3) Synchronize ModelObjects & PrintObjects. + for (size_t idx_model_object = 0; idx_model_object < model.objects.size(); ++ idx_model_object) { + ModelObject &model_object = *m_model.objects[idx_model_object]; + auto it_status = model_object_status.find(ModelObjectStatus(model_object.id())); + assert(it_status != model_object_status.end()); + assert(it_status->status != ModelObjectStatus::Deleted); + const ModelObject& model_object_new = *model.objects[idx_model_object]; + const_cast(*it_status).layer_ranges.assign(model_object_new.layer_config_ranges); + if (it_status->status == ModelObjectStatus::New) + // PrintObject instances will be added in the next loop. + continue; + // Update the ModelObject instance, possibly invalidate the linked PrintObjects. + assert(it_status->status == ModelObjectStatus::Old || it_status->status == ModelObjectStatus::Moved); + // Check whether a model part volume was added or removed, their transformations or order changed. + // Only volume IDs, volume types, transformation matrices and their order are checked, configuration and other parameters are NOT checked. + bool model_parts_differ = model_volume_list_changed(model_object, model_object_new, ModelVolumeType::MODEL_PART); + bool modifiers_differ = model_volume_list_changed(model_object, model_object_new, ModelVolumeType::PARAMETER_MODIFIER); + bool supports_differ = model_volume_list_changed(model_object, model_object_new, ModelVolumeType::SUPPORT_BLOCKER) || + model_volume_list_changed(model_object, model_object_new, ModelVolumeType::SUPPORT_ENFORCER); + if (model_parts_differ || modifiers_differ || + model_object.origin_translation != model_object_new.origin_translation || + ! model_object.layer_height_profile.timestamp_matches(model_object_new.layer_height_profile) || + ! layer_height_ranges_equal(model_object.layer_config_ranges, model_object_new.layer_config_ranges, model_object_new.layer_height_profile.empty())) { + // The very first step (the slicing step) is invalidated. One may freely remove all associated PrintObjects. + auto range = print_object_status.equal_range(PrintObjectStatus(model_object.id())); + for (auto it = range.first; it != range.second; ++ it) { + update_apply_status(it->print_object->invalidate_all_steps()); + const_cast(*it).status = PrintObjectStatus::Deleted; + } + // Copy content of the ModelObject including its ID, do not change the parent. + model_object.assign_copy(model_object_new); + } else if (supports_differ || model_custom_supports_data_changed(model_object, model_object_new)) { + // First stop background processing before shuffling or deleting the ModelVolumes in the ModelObject's list. + if (supports_differ) { + this->call_cancel_callback(); + update_apply_status(false); + } + // Invalidate just the supports step. + auto range = print_object_status.equal_range(PrintObjectStatus(model_object.id())); + for (auto it = range.first; it != range.second; ++ it) + update_apply_status(it->print_object->invalidate_step(posSupportMaterial)); + if (supports_differ) { + // Copy just the support volumes. + model_volume_list_update_supports(model_object, model_object_new); + } + } else if (model_custom_seam_data_changed(model_object, model_object_new)) { + update_apply_status(this->invalidate_step(psGCodeExport)); + } + if (! model_parts_differ && ! modifiers_differ) { + // Synchronize Object's config. + bool object_config_changed = ! model_object.config.timestamp_matches(model_object_new.config); + if (object_config_changed) + model_object.config.assign_config(model_object_new.config); + if (! object_diff.empty() || object_config_changed || num_extruders_changed) { + PrintObjectConfig new_config = PrintObject::object_config_from_model_object(m_default_object_config, model_object, num_extruders); + auto range = print_object_status.equal_range(PrintObjectStatus(model_object.id())); + for (auto it = range.first; it != range.second; ++ it) { + t_config_option_keys diff = it->print_object->config().diff(new_config); + if (! diff.empty()) { + update_apply_status(it->print_object->invalidate_state_by_config_options(it->print_object->config(), new_config, diff)); + it->print_object->config_apply_only(new_config, diff, true); + } + } + } + // Synchronize (just copy) the remaining data of ModelVolumes (name, config, custom supports data). + //FIXME What to do with m_material_id? + model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, ModelVolumeType::MODEL_PART); + model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, ModelVolumeType::PARAMETER_MODIFIER); + layer_height_ranges_copy_configs(model_object.layer_config_ranges /* dst */, model_object_new.layer_config_ranges /* src */); + // Copy the ModelObject name, input_file and instances. The instances will be compared against PrintObject instances in the next step. + model_object.name = model_object_new.name; + model_object.input_file = model_object_new.input_file; + // Only refresh ModelInstances if there is any change. + if (model_object.instances.size() != model_object_new.instances.size() || + ! std::equal(model_object.instances.begin(), model_object.instances.end(), model_object_new.instances.begin(), [](auto l, auto r){ return l->id() == r->id(); })) { + // G-code generator accesses model_object.instances to generate sequential print ordering matching the Plater object list. + update_apply_status(this->invalidate_step(psGCodeExport)); + model_object.clear_instances(); + model_object.instances.reserve(model_object_new.instances.size()); + for (const ModelInstance *model_instance : model_object_new.instances) { + model_object.instances.emplace_back(new ModelInstance(*model_instance)); + model_object.instances.back()->set_model_object(&model_object); + } + } else if (! std::equal(model_object.instances.begin(), model_object.instances.end(), model_object_new.instances.begin(), + [](auto l, auto r){ return l->print_volume_state == r->print_volume_state && l->printable == r->printable && + l->get_transformation().get_matrix().isApprox(r->get_transformation().get_matrix()); })) { + // If some of the instances changed, the bounding box of the updated ModelObject is likely no more valid. + // This is safe as the ModelObject's bounding box is only accessed from this function, which is called from the main thread only. + model_object.invalidate_bounding_box(); + // Synchronize the content of instances. + auto new_instance = model_object_new.instances.begin(); + for (auto old_instance = model_object.instances.begin(); old_instance != model_object.instances.end(); ++ old_instance, ++ new_instance) { + (*old_instance)->set_transformation((*new_instance)->get_transformation()); + (*old_instance)->print_volume_state = (*new_instance)->print_volume_state; + (*old_instance)->printable = (*new_instance)->printable; + } + } + } + } + + // 4) Generate PrintObjects from ModelObjects and their instances. + bool print_regions_reshuffled = false; + { + PrintObjectPtrs print_objects_new; + print_objects_new.reserve(std::max(m_objects.size(), m_model.objects.size())); + bool new_objects = false; + // Walk over all new model objects and check, whether there are matching PrintObjects. + for (ModelObject *model_object : m_model.objects) { + auto range = print_object_status.equal_range(PrintObjectStatus(model_object->id())); + std::vector old; + if (range.first != range.second) { + old.reserve(print_object_status.count(PrintObjectStatus(model_object->id()))); + for (auto it = range.first; it != range.second; ++ it) + if (it->status != PrintObjectStatus::Deleted) + old.emplace_back(&(*it)); + } + // Generate a list of trafos and XY offsets for instances of a ModelObject + // Producing the config for PrintObject on demand, caching it at print_object_last. + const PrintObject *print_object_last = nullptr; + auto print_object_apply_config = [this, &print_object_last, model_object, num_extruders](PrintObject* print_object) { + print_object->config_apply(print_object_last ? + print_object_last->config() : + PrintObject::object_config_from_model_object(m_default_object_config, *model_object, num_extruders)); + print_object_last = print_object; + }; + std::vector new_print_instances = print_objects_from_model_object(*model_object); + if (old.empty()) { + // Simple case, just generate new instances. + for (PrintObjectTrafoAndInstances &print_instances : new_print_instances) { + PrintObject *print_object = new PrintObject(this, model_object, print_instances.trafo, std::move(print_instances.instances)); + print_object_apply_config(print_object); + print_objects_new.emplace_back(print_object); + // print_object_status.emplace(PrintObjectStatus(print_object, PrintObjectStatus::New)); + new_objects = true; + } + continue; + } + // Complex case, try to merge the two lists. + // Sort the old lexicographically by their trafos. + std::sort(old.begin(), old.end(), [](const PrintObjectStatus *lhs, const PrintObjectStatus *rhs){ return transform3d_lower(lhs->trafo, rhs->trafo); }); + // Merge the old / new lists. + auto it_old = old.begin(); + for (PrintObjectTrafoAndInstances &new_instances : new_print_instances) { + for (; it_old != old.end() && transform3d_lower((*it_old)->trafo, new_instances.trafo); ++ it_old); + if (it_old == old.end() || ! transform3d_equal((*it_old)->trafo, new_instances.trafo)) { + // This is a new instance (or a set of instances with the same trafo). Just add it. + PrintObject *print_object = new PrintObject(this, model_object, new_instances.trafo, std::move(new_instances.instances)); + print_object_apply_config(print_object); + print_objects_new.emplace_back(print_object); + // print_object_status.emplace(PrintObjectStatus(print_object, PrintObjectStatus::New)); + new_objects = true; + if (it_old != old.end()) + const_cast(*it_old)->status = PrintObjectStatus::Deleted; + } else { + // The PrintObject already exists and the copies differ. + PrintBase::ApplyStatus status = (*it_old)->print_object->set_instances(std::move(new_instances.instances)); + if (status != PrintBase::APPLY_STATUS_UNCHANGED) + update_apply_status(status == PrintBase::APPLY_STATUS_INVALIDATED); + print_objects_new.emplace_back((*it_old)->print_object); + const_cast(*it_old)->status = PrintObjectStatus::Reused; + } + } + } + if (m_objects != print_objects_new) { + this->call_cancel_callback(); + update_apply_status(this->invalidate_all_steps()); + m_objects = print_objects_new; + // Delete the PrintObjects marked as Unknown or Deleted. + bool deleted_objects = false; + for (auto &pos : print_object_status) + if (pos.status == PrintObjectStatus::Unknown || pos.status == PrintObjectStatus::Deleted) { + update_apply_status(pos.print_object->invalidate_all_steps()); + delete pos.print_object; + deleted_objects = true; + } + if (new_objects || deleted_objects) + update_apply_status(this->invalidate_steps({ psSkirt, psBrim, psWipeTower, psGCodeExport })); + if (new_objects) + update_apply_status(false); + print_regions_reshuffled = true; + } + print_object_status.clear(); + } + + // All regions now have distinct settings. + // Check whether applying the new region config defaults we'd get different regions. + for (PrintObject *print_object : m_objects) { + const LayerRanges *layer_ranges; + { + auto it_status = model_object_status.find(ModelObjectStatus(print_object->model_object()->id())); + assert(it_status != model_object_status.end()); + assert(it_status->status != ModelObjectStatus::Deleted); + layer_ranges = &it_status->layer_ranges; + } + bool some_object_region_modified = false; + bool regions_merged = false; + for (size_t region_id = 0; region_id < print_object->m_region_volumes.size(); ++ region_id) { + PrintRegion ®ion = *print_object->m_all_regions[region_id]; + PrintRegionConfig region_config; + bool region_config_set = false; + for (const PrintRegionVolumes::VolumeWithZRange &volume_w_zrange : print_object->m_region_volumes[region_id].volumes) { + const ModelVolume &volume = *print_object->model_object()->volumes[volume_w_zrange.volume_idx]; + const DynamicPrintConfig *layer_range_config = layer_ranges->config(volume_w_zrange.layer_height_range); + PrintRegionConfig this_region_config = PrintObject::region_config_from_model_volume(m_default_region_config, layer_range_config, volume, num_extruders); + if (region_config_set) { + if (this_region_config != region_config) { + regions_merged = true; + break; + } + } else { + region_config = std::move(this_region_config); + region_config_set = true; + } + } + if (regions_merged) + break; + size_t region_config_hash = region_config.hash(); + bool modified = region.config_hash() != region_config_hash || region.config() != region_config; + some_object_region_modified |= modified; + if (some_object_region_modified) + // Verify whether this region was not merged with some other region. + for (size_t i = 0; i < region_id; ++ i) { + const PrintRegion ®ion_other = *print_object->m_all_regions[i]; + if (region_other.config_hash() == region_config_hash && region_other.config() == region_config) { + // Regions were merged. Reset this print_object. + regions_merged = true; + break; + } + } + if (modified) { + // Stop the background process before assigning new configuration to the regions. + t_config_option_keys diff = region.config().diff(region_config); + update_apply_status(print_object->invalidate_state_by_config_options(region.config(), region_config, diff)); + region.config_apply_only(region_config, diff, false); + } + } + if (regions_merged) { + // Two regions of a single object were either split or merged. This invalidates the whole slicing. + update_apply_status(print_object->invalidate_all_steps()); + print_object->m_region_volumes.clear(); + } + } + + // Possibly add new regions for the newly added or resetted PrintObjects. + for (size_t idx_print_object = 0; idx_print_object < m_objects.size();) { + PrintObject &print_object0 = *m_objects[idx_print_object]; + const ModelObject &model_object = *print_object0.model_object(); + const LayerRanges *layer_ranges; + { + auto it_status = model_object_status.find(ModelObjectStatus(model_object.id())); + assert(it_status != model_object_status.end()); + assert(it_status->status != ModelObjectStatus::Deleted); + layer_ranges = &it_status->layer_ranges; + } + if (print_object0.m_region_volumes.empty()) { + // Fresh or completely invalidated print_object. Assign regions. + unsigned int volume_id = 0; + for (const ModelVolume *volume : model_object.volumes) { + if (! volume->is_model_part() && ! volume->is_modifier()) { + ++ volume_id; + continue; + } + // Filter the layer ranges, so they do not overlap and they contain at least a single layer. + // Now insert a volume with a layer range to its own region. + for (auto it_range = layer_ranges->begin(); it_range != layer_ranges->end(); ++ it_range) { + int region_id = -1; + // Get the config applied to this volume. + PrintRegionConfig config = PrintObject::region_config_from_model_volume(m_default_region_config, it_range->second, *volume, num_extruders); + size_t hash = config.hash(); + for (size_t i = 0; i < print_object0.m_all_regions.size(); ++ i) + if (hash == print_object0.m_all_regions[i]->config_hash() && config == *print_object0.m_all_regions[i]) { + region_id = int(i); + break; + } + // If no region exists with the same config, create a new one. + if (region_id == -1) { + region_id = int(print_object0.m_all_regions.size()); + print_object0.m_all_regions.emplace_back(std::make_unique(std::move(config), hash)); + } + print_object0.add_region_volume(region_id, volume_id, it_range->first); + } + ++ volume_id; + } + print_regions_reshuffled = true; + } + for (++ idx_print_object; idx_print_object < m_objects.size() && m_objects[idx_print_object]->model_object() == &model_object; ++ idx_print_object) { + PrintObject &print_object = *m_objects[idx_print_object]; + if (print_object.m_region_volumes.empty()) { + // Copy region volumes and regions from print_object0. + print_object.m_region_volumes = print_object0.m_region_volumes; + print_object.m_all_regions.reserve(print_object0.m_all_regions.size()); + for (const std::unique_ptr ®ion : print_object0.m_all_regions) + print_object.m_all_regions.emplace_back(std::make_unique(*region)); + print_regions_reshuffled = true; + } + } + } + + if (print_regions_reshuffled) { + // Update Print::m_print_regions from objects. + struct cmp { bool operator() (const PrintRegion *l, const PrintRegion *r) const { return l->config_hash() == r->config_hash() && l->config() == r->config(); } }; + std::set region_set; + m_print_regions.clear(); + for (PrintObject *print_object : m_objects) + for (std::unique_ptr &print_region : print_object->m_all_regions) + if (auto it = region_set.find(print_region.get()); it == region_set.end()) { + int print_region_id = int(m_print_regions.size()); + m_print_regions.emplace_back(print_region.get()); + print_region->m_print_region_id = print_region_id; + } else { + print_region->m_print_region_id = (*it)->print_region_id(); + } + } + + // Update SlicingParameters for each object where the SlicingParameters is not valid. + // If it is not valid, then it is ensured that PrintObject.m_slicing_params is not in use + // (posSlicing and posSupportMaterial was invalidated). + for (PrintObject *object : m_objects) + object->update_slicing_parameters(); + +#ifdef _DEBUG + check_model_ids_equal(m_model, model); +#endif /* _DEBUG */ + + return static_cast(apply_status); +} + +} // namespace Slic3r diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 5516b298d..72722e6fc 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -18,6 +19,152 @@ namespace Slic3r { #define L(s) (s) #define _(s) Slic3r::I18N::translate(s) +static t_config_enum_names enum_names_from_keys_map(const t_config_enum_values &enum_keys_map) +{ + t_config_enum_names names; + int cnt = 0; + for (const auto& kvp : enum_keys_map) + cnt = std::max(cnt, kvp.second); + cnt += 1; + names.assign(cnt, ""); + for (const auto& kvp : enum_keys_map) + names[kvp.second] = kvp.first; + return names; +} + +#define CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(NAME) \ + static t_config_enum_names s_keys_names_##NAME = enum_names_from_keys_map(s_keys_map_##NAME); \ + template<> const t_config_enum_values& ConfigOptionEnum::get_enum_values() { return s_keys_map_##NAME; } \ + template<> const t_config_enum_names& ConfigOptionEnum::get_enum_names() { return s_keys_names_##NAME; } + +static t_config_enum_values s_keys_map_PrinterTechnology { + { "FFF", ptFFF }, + { "SLA", ptSLA } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(PrinterTechnology) + +static t_config_enum_values s_keys_map_GCodeFlavor { + { "reprap", gcfRepRapSprinter }, + { "reprapfirmware", gcfRepRapFirmware }, + { "repetier", gcfRepetier }, + { "teacup", gcfTeacup }, + { "makerware", gcfMakerWare }, + { "marlin", gcfMarlinLegacy }, + { "marlinfirmware", gcfMarlinFirmware }, + { "sailfish", gcfSailfish }, + { "smoothie", gcfSmoothie }, + { "mach3", gcfMach3 }, + { "machinekit", gcfMachinekit }, + { "no-extrusion", gcfNoExtrusion } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(GCodeFlavor) + +static t_config_enum_values s_keys_map_MachineLimitsUsage { + { "emit_to_gcode", int(MachineLimitsUsage::EmitToGCode) }, + { "time_estimate_only", int(MachineLimitsUsage::TimeEstimateOnly) }, + { "ignore", int(MachineLimitsUsage::Ignore) } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(MachineLimitsUsage) + +static t_config_enum_values s_keys_map_PrintHostType { + { "octoprint", htOctoPrint }, + { "duet", htDuet }, + { "flashair", htFlashAir }, + { "astrobox", htAstroBox }, + { "repetier", htRepetier } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(PrintHostType) + +static t_config_enum_values s_keys_map_AuthorizationType { + { "key", atKeyPassword }, + { "user", atUserPassword } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(AuthorizationType) + +static t_config_enum_values s_keys_map_FuzzySkinType { + { "none", int(FuzzySkinType::None) }, + { "external", int(FuzzySkinType::External) }, + { "all", int(FuzzySkinType::All) } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(FuzzySkinType) + +static t_config_enum_values s_keys_map_InfillPattern { + { "rectilinear", ipRectilinear }, + { "monotonic", ipMonotonic }, + { "alignedrectilinear", ipAlignedRectilinear }, + { "grid", ipGrid }, + { "triangles", ipTriangles }, + { "stars", ipStars }, + { "cubic", ipCubic }, + { "line", ipLine }, + { "concentric", ipConcentric }, + { "honeycomb", ipHoneycomb }, + { "3dhoneycomb", ip3DHoneycomb }, + { "gyroid", ipGyroid }, + { "hilbertcurve", ipHilbertCurve }, + { "archimedeanchords", ipArchimedeanChords }, + { "octagramspiral", ipOctagramSpiral }, + { "adaptivecubic", ipAdaptiveCubic }, + { "supportcubic", ipSupportCubic } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(InfillPattern) + +static t_config_enum_values s_keys_map_IroningType { + { "top", int(IroningType::TopSurfaces) }, + { "topmost", int(IroningType::TopmostOnly) }, + { "solid", int(IroningType::AllSolid) } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(IroningType) + +static t_config_enum_values s_keys_map_SupportMaterialPattern { + { "rectilinear", smpRectilinear }, + { "rectilinear-grid", smpRectilinearGrid }, + { "honeycomb", smpHoneycomb } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(SupportMaterialPattern) + +static t_config_enum_values s_keys_map_SupportMaterialStyle { + { "grid", smsGrid }, + { "snug", smsSnug } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(SupportMaterialStyle) + +static t_config_enum_values s_keys_map_SupportMaterialInterfacePattern { + { "auto", smipAuto }, + { "rectilinear", smipRectilinear }, + { "concentric", smipConcentric } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(SupportMaterialInterfacePattern) + +static t_config_enum_values s_keys_map_SeamPosition { + { "random", spRandom }, + { "nearest", spNearest }, + { "aligned", spAligned }, + { "rear", spRear } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(SeamPosition) + +static const t_config_enum_values s_keys_map_SLADisplayOrientation = { + { "landscape", sladoLandscape}, + { "portrait", sladoPortrait} +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(SLADisplayOrientation) + +static const t_config_enum_values s_keys_map_SLAPillarConnectionMode = { + {"zigzag", slapcmZigZag}, + {"cross", slapcmCross}, + {"dynamic", slapcmDynamic} +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(SLAPillarConnectionMode) + +static const t_config_enum_values s_keys_map_BrimType = { + {"no_brim", btNoBrim}, + {"outer_only", btOuterOnly}, + {"inner_only", btInnerOnly}, + {"outer_and_inner", btOuterAndInner} +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(BrimType) + static void assign_printer_technology_to_unknown(t_optiondef_map &options, PrinterTechnology printer_technology) { for (std::pair &kvp : options) @@ -995,10 +1142,8 @@ void PrintConfigDef::init_fff_params() def->label = L("First layer height"); def->category = L("Layers and Perimeters"); def->tooltip = L("When printing with very low layer heights, you might still want to print a thicker " - "bottom layer to improve adhesion and tolerance for non perfect build plates. " - "This can be expressed as an absolute value or as a percentage (for example: 150%) " - "over the default layer height."); - def->sidetext = L("mm or %"); + "bottom layer to improve adhesion and tolerance for non perfect build plates."); + def->sidetext = L("mm"); def->ratio_over = "layer_height"; def->set_default_value(new ConfigOptionFloatOrPercent(0.35, false)); @@ -3610,7 +3755,7 @@ std::string DynamicPrintConfig::validate() FullPrintConfig fpc; fpc.apply(*this, true); // Verify this print options through the FullPrintConfig. - return fpc.validate(); + return Slic3r::validate(fpc); } default: //FIXME no validation on SLA data? @@ -3619,135 +3764,135 @@ std::string DynamicPrintConfig::validate() } //FIXME localize this function. -std::string FullPrintConfig::validate() +std::string validate(const FullPrintConfig &cfg) { // --layer-height - if (this->get_abs_value("layer_height") <= 0) + if (cfg.get_abs_value("layer_height") <= 0) return "Invalid value for --layer-height"; - if (fabs(fmod(this->get_abs_value("layer_height"), SCALING_FACTOR)) > 1e-4) + if (fabs(fmod(cfg.get_abs_value("layer_height"), SCALING_FACTOR)) > 1e-4) return "--layer-height must be a multiple of print resolution"; // --first-layer-height - if (this->get_abs_value("first_layer_height") <= 0) + if (cfg.first_layer_height.value <= 0) return "Invalid value for --first-layer-height"; // --filament-diameter - for (double fd : this->filament_diameter.values) + for (double fd : cfg.filament_diameter.values) if (fd < 1) return "Invalid value for --filament-diameter"; // --nozzle-diameter - for (double nd : this->nozzle_diameter.values) + for (double nd : cfg.nozzle_diameter.values) if (nd < 0.005) return "Invalid value for --nozzle-diameter"; // --perimeters - if (this->perimeters.value < 0) + if (cfg.perimeters.value < 0) return "Invalid value for --perimeters"; // --solid-layers - if (this->top_solid_layers < 0) + if (cfg.top_solid_layers < 0) return "Invalid value for --top-solid-layers"; - if (this->bottom_solid_layers < 0) + if (cfg.bottom_solid_layers < 0) return "Invalid value for --bottom-solid-layers"; - if (this->use_firmware_retraction.value && - this->gcode_flavor.value != gcfSmoothie && - this->gcode_flavor.value != gcfRepRapSprinter && - this->gcode_flavor.value != gcfRepRapFirmware && - this->gcode_flavor.value != gcfMarlinLegacy && - this->gcode_flavor.value != gcfMarlinFirmware && - this->gcode_flavor.value != gcfMachinekit && - this->gcode_flavor.value != gcfRepetier) + if (cfg.use_firmware_retraction.value && + cfg.gcode_flavor.value != gcfSmoothie && + cfg.gcode_flavor.value != gcfRepRapSprinter && + cfg.gcode_flavor.value != gcfRepRapFirmware && + cfg.gcode_flavor.value != gcfMarlinLegacy && + cfg.gcode_flavor.value != gcfMarlinFirmware && + cfg.gcode_flavor.value != gcfMachinekit && + cfg.gcode_flavor.value != gcfRepetier) return "--use-firmware-retraction is only supported by Marlin, Smoothie, RepRapFirmware, Repetier and Machinekit firmware"; - if (this->use_firmware_retraction.value) - for (unsigned char wipe : this->wipe.values) + if (cfg.use_firmware_retraction.value) + for (unsigned char wipe : cfg.wipe.values) if (wipe) return "--use-firmware-retraction is not compatible with --wipe"; // --gcode-flavor - if (! print_config_def.get("gcode_flavor")->has_enum_value(this->gcode_flavor.serialize())) + if (! print_config_def.get("gcode_flavor")->has_enum_value(cfg.gcode_flavor.serialize())) return "Invalid value for --gcode-flavor"; // --fill-pattern - if (! print_config_def.get("fill_pattern")->has_enum_value(this->fill_pattern.serialize())) + if (! print_config_def.get("fill_pattern")->has_enum_value(cfg.fill_pattern.serialize())) return "Invalid value for --fill-pattern"; // --top-fill-pattern - if (! print_config_def.get("top_fill_pattern")->has_enum_value(this->top_fill_pattern.serialize())) + if (! print_config_def.get("top_fill_pattern")->has_enum_value(cfg.top_fill_pattern.serialize())) return "Invalid value for --top-fill-pattern"; // --bottom-fill-pattern - if (! print_config_def.get("bottom_fill_pattern")->has_enum_value(this->bottom_fill_pattern.serialize())) + if (! print_config_def.get("bottom_fill_pattern")->has_enum_value(cfg.bottom_fill_pattern.serialize())) return "Invalid value for --bottom-fill-pattern"; // --fill-density - if (fabs(this->fill_density.value - 100.) < EPSILON && - ! print_config_def.get("top_fill_pattern")->has_enum_value(this->fill_pattern.serialize())) + if (fabs(cfg.fill_density.value - 100.) < EPSILON && + ! print_config_def.get("top_fill_pattern")->has_enum_value(cfg.fill_pattern.serialize())) return "The selected fill pattern is not supposed to work at 100% density"; // --infill-every-layers - if (this->infill_every_layers < 1) + if (cfg.infill_every_layers < 1) return "Invalid value for --infill-every-layers"; // --skirt-height - if (this->skirt_height < 0) + if (cfg.skirt_height < 0) return "Invalid value for --skirt-height"; // --bridge-flow-ratio - if (this->bridge_flow_ratio <= 0) + if (cfg.bridge_flow_ratio <= 0) return "Invalid value for --bridge-flow-ratio"; // extruder clearance - if (this->extruder_clearance_radius <= 0) + if (cfg.extruder_clearance_radius <= 0) return "Invalid value for --extruder-clearance-radius"; - if (this->extruder_clearance_height <= 0) + if (cfg.extruder_clearance_height <= 0) return "Invalid value for --extruder-clearance-height"; // --extrusion-multiplier - for (double em : this->extrusion_multiplier.values) + for (double em : cfg.extrusion_multiplier.values) if (em <= 0) return "Invalid value for --extrusion-multiplier"; // --default-acceleration - if ((this->perimeter_acceleration != 0. || this->infill_acceleration != 0. || this->bridge_acceleration != 0. || this->first_layer_acceleration != 0.) && - this->default_acceleration == 0.) + if ((cfg.perimeter_acceleration != 0. || cfg.infill_acceleration != 0. || cfg.bridge_acceleration != 0. || cfg.first_layer_acceleration != 0.) && + cfg.default_acceleration == 0.) return "Invalid zero value for --default-acceleration when using other acceleration settings"; // --spiral-vase - if (this->spiral_vase) { + if (cfg.spiral_vase) { // Note that we might want to have more than one perimeter on the bottom // solid layers. - if (this->perimeters > 1) + if (cfg.perimeters > 1) return "Can't make more than one perimeter when spiral vase mode is enabled"; - else if (this->perimeters < 1) + else if (cfg.perimeters < 1) return "Can't make less than one perimeter when spiral vase mode is enabled"; - if (this->fill_density > 0) + if (cfg.fill_density > 0) return "Spiral vase mode can only print hollow objects, so you need to set Fill density to 0"; - if (this->top_solid_layers > 0) + if (cfg.top_solid_layers > 0) return "Spiral vase mode is not compatible with top solid layers"; - if (this->support_material || this->support_material_enforce_layers > 0) + if (cfg.support_material || cfg.support_material_enforce_layers > 0) return "Spiral vase mode is not compatible with support material"; } // extrusion widths { double max_nozzle_diameter = 0.; - for (double dmr : this->nozzle_diameter.values) + for (double dmr : cfg.nozzle_diameter.values) max_nozzle_diameter = std::max(max_nozzle_diameter, dmr); const char *widths[] = { "external_perimeter", "perimeter", "infill", "solid_infill", "top_infill", "support_material", "first_layer" }; for (size_t i = 0; i < sizeof(widths) / sizeof(widths[i]); ++ i) { std::string key(widths[i]); key += "_extrusion_width"; - if (this->get_abs_value(key, max_nozzle_diameter) > 10. * max_nozzle_diameter) + if (cfg.get_abs_value(key, max_nozzle_diameter) > 10. * max_nozzle_diameter) return std::string("Invalid extrusion width (too large): ") + key; } } // Out of range validation of numeric values. - for (const std::string &opt_key : this->keys()) { - const ConfigOption *opt = this->optptr(opt_key); + for (const std::string &opt_key : cfg.keys()) { + const ConfigOption *opt = cfg.optptr(opt_key); assert(opt != nullptr); const ConfigOptionDef *optdef = print_config_def.get(opt_key); assert(optdef != nullptr); @@ -3792,19 +3937,21 @@ std::string FullPrintConfig::validate() return ""; } -// Declare the static caches for each StaticPrintConfig derived class. -StaticPrintConfig::StaticCache PrintObjectConfig::s_cache_PrintObjectConfig; -StaticPrintConfig::StaticCache PrintRegionConfig::s_cache_PrintRegionConfig; -StaticPrintConfig::StaticCache MachineEnvelopeConfig::s_cache_MachineEnvelopeConfig; -StaticPrintConfig::StaticCache GCodeConfig::s_cache_GCodeConfig; -StaticPrintConfig::StaticCache PrintConfig::s_cache_PrintConfig; -StaticPrintConfig::StaticCache FullPrintConfig::s_cache_FullPrintConfig; - -StaticPrintConfig::StaticCache SLAMaterialConfig::s_cache_SLAMaterialConfig; -StaticPrintConfig::StaticCache SLAPrintConfig::s_cache_SLAPrintConfig; -StaticPrintConfig::StaticCache SLAPrintObjectConfig::s_cache_SLAPrintObjectConfig; -StaticPrintConfig::StaticCache SLAPrinterConfig::s_cache_SLAPrinterConfig; -StaticPrintConfig::StaticCache SLAFullPrintConfig::s_cache_SLAFullPrintConfig; +// Declare and initialize static caches of StaticPrintConfig derived classes. +#define PRINT_CONFIG_CACHE_ELEMENT_DEFINITION(r, data, CLASS_NAME) StaticPrintConfig::StaticCache BOOST_PP_CAT(CLASS_NAME::s_cache_, CLASS_NAME); +#define PRINT_CONFIG_CACHE_ELEMENT_INITIALIZATION(r, data, CLASS_NAME) Slic3r::CLASS_NAME::initialize_cache(); +#define PRINT_CONFIG_CACHE_INITIALIZE(CLASSES_SEQ) \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CACHE_ELEMENT_DEFINITION, _, BOOST_PP_TUPLE_TO_SEQ(CLASSES_SEQ)) \ + int print_config_static_initializer() { \ + /* Putting a trace here to avoid the compiler to optimize out this function. */ \ + BOOST_LOG_TRIVIAL(trace) << "Initializing StaticPrintConfigs"; \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CACHE_ELEMENT_INITIALIZATION, _, BOOST_PP_TUPLE_TO_SEQ(CLASSES_SEQ)) \ + return 1; \ + } +PRINT_CONFIG_CACHE_INITIALIZE(( + PrintObjectConfig, PrintRegionConfig, MachineEnvelopeConfig, GCodeConfig, PrintConfig, FullPrintConfig, + SLAMaterialConfig, SLAPrintConfig, SLAPrintObjectConfig, SLAPrinterConfig, SLAFullPrintConfig)) +static int print_config_static_initialized = print_config_static_initializer(); CLIActionsConfigDef::CLIActionsConfigDef() { diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index aab509662..2ba6d4cbd 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -19,6 +19,14 @@ #include "libslic3r.h" #include "Config.hpp" +#include +#include +#include +#include +#include +#include +#include + // #define HAS_PRESSURE_EQUALIZER namespace Slic3r { @@ -29,10 +37,10 @@ enum GCodeFlavor : unsigned char { }; enum class MachineLimitsUsage { - EmitToGCode, - TimeEstimateOnly, - Ignore, - Count, + EmitToGCode, + TimeEstimateOnly, + Ignore, + Count, }; enum PrintHostType { @@ -55,10 +63,10 @@ enum InfillPattern : int { }; enum class IroningType { - TopSurfaces, - TopmostOnly, - AllSolid, - Count, + TopSurfaces, + TopmostOnly, + AllSolid, + Count, }; enum SupportMaterialPattern { @@ -103,178 +111,27 @@ enum BrimType { btOuterAndInner, }; -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["FFF"] = ptFFF; - keys_map["SLA"] = ptSLA; - } - return keys_map; -} +#define CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(NAME) \ + template<> const t_config_enum_names& ConfigOptionEnum::get_enum_names(); \ + template<> const t_config_enum_values& ConfigOptionEnum::get_enum_values(); -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["reprap"] = gcfRepRapSprinter; - keys_map["reprapfirmware"] = gcfRepRapFirmware; - keys_map["repetier"] = gcfRepetier; - keys_map["teacup"] = gcfTeacup; - keys_map["makerware"] = gcfMakerWare; - keys_map["marlin"] = gcfMarlinLegacy; - keys_map["marlinfirmware"] = gcfMarlinFirmware; - keys_map["sailfish"] = gcfSailfish; - keys_map["smoothie"] = gcfSmoothie; - keys_map["mach3"] = gcfMach3; - keys_map["machinekit"] = gcfMachinekit; - keys_map["no-extrusion"] = gcfNoExtrusion; - } - return keys_map; -} +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(PrinterTechnology) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(GCodeFlavor) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(MachineLimitsUsage) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(PrintHostType) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(AuthorizationType) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(FuzzySkinType) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(InfillPattern) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(IroningType) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(SupportMaterialPattern) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(SupportMaterialStyle) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(SupportMaterialInterfacePattern) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(SeamPosition) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(SLADisplayOrientation) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(SLAPillarConnectionMode) +CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS(BrimType) -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["emit_to_gcode"] = int(MachineLimitsUsage::EmitToGCode); - keys_map["time_estimate_only"] = int(MachineLimitsUsage::TimeEstimateOnly); - keys_map["ignore"] = int(MachineLimitsUsage::Ignore); - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["octoprint"] = htOctoPrint; - keys_map["duet"] = htDuet; - keys_map["flashair"] = htFlashAir; - keys_map["astrobox"] = htAstroBox; - keys_map["repetier"] = htRepetier; - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["key"] = atKeyPassword; - keys_map["user"] = atUserPassword; - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["none"] = int(FuzzySkinType::None); - keys_map["external"] = int(FuzzySkinType::External); - keys_map["all"] = int(FuzzySkinType::All); - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["rectilinear"] = ipRectilinear; - keys_map["monotonic"] = ipMonotonic; - keys_map["alignedrectilinear"] = ipAlignedRectilinear; - keys_map["grid"] = ipGrid; - keys_map["triangles"] = ipTriangles; - keys_map["stars"] = ipStars; - keys_map["cubic"] = ipCubic; - keys_map["line"] = ipLine; - keys_map["concentric"] = ipConcentric; - keys_map["honeycomb"] = ipHoneycomb; - keys_map["3dhoneycomb"] = ip3DHoneycomb; - keys_map["gyroid"] = ipGyroid; - keys_map["hilbertcurve"] = ipHilbertCurve; - keys_map["archimedeanchords"] = ipArchimedeanChords; - keys_map["octagramspiral"] = ipOctagramSpiral; - keys_map["adaptivecubic"] = ipAdaptiveCubic; - keys_map["supportcubic"] = ipSupportCubic; - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["top"] = int(IroningType::TopSurfaces); - keys_map["topmost"] = int(IroningType::TopmostOnly); - keys_map["solid"] = int(IroningType::AllSolid); - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["rectilinear"] = smpRectilinear; - keys_map["rectilinear-grid"] = smpRectilinearGrid; - keys_map["honeycomb"] = smpHoneycomb; - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["grid"] = smsGrid; - keys_map["snug"] = smsSnug; - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["auto"] = smipAuto; - keys_map["rectilinear"] = smipRectilinear; - keys_map["concentric"] = smipConcentric; - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static t_config_enum_values keys_map; - if (keys_map.empty()) { - keys_map["random"] = spRandom; - keys_map["nearest"] = spNearest; - keys_map["aligned"] = spAligned; - keys_map["rear"] = spRear; - } - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static const t_config_enum_values keys_map = { - { "landscape", sladoLandscape}, - { "portrait", sladoPortrait} - }; - - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static const t_config_enum_values keys_map = { - {"zigzag", slapcmZigZag}, - {"cross", slapcmCross}, - {"dynamic", slapcmDynamic} - }; - - return keys_map; -} - -template<> inline const t_config_enum_values& ConfigOptionEnum::get_enum_values() { - static const t_config_enum_values keys_map = { - {"no_brim", btNoBrim}, - {"outer_only", btOuterOnly}, - {"inner_only", btInnerOnly}, - {"outer_and_inner", btOuterAndInner} - }; - - return keys_map; -} +#undef CONFIG_OPTION_ENUM_DECLARE_STATIC_MAPS // Defines each and every confiuration option of Slic3r, including the properties of the GUI dialogs. // Does not store the actual values, but defines default values. @@ -298,8 +155,8 @@ private: void init_extruder_option_keys(); void init_sla_params(); - std::vector m_extruder_option_keys; - std::vector m_extruder_retract_keys; + std::vector m_extruder_option_keys; + std::vector m_extruder_retract_keys; }; // The one and only global definition of SLic3r configuration options. @@ -337,7 +194,7 @@ public: void normalize_fdm(); - void set_num_extruders(unsigned int num_extruders); + void set_num_extruders(unsigned int num_extruders); // Validate the PrintConfig. Returns an empty string on success, otherwise an error message is returned. std::string validate(); @@ -358,7 +215,7 @@ public: // Overrides ConfigBase::def(). Static configuration definition. Any value stored into this ConfigBase shall have its definition here. const ConfigDef* def() const override { return &print_config_def; } // Reference to the cached list of keys. - virtual const t_config_option_keys& keys_ref() const = 0; + virtual const t_config_option_keys& keys_ref() const = 0; protected: // Verify whether the opt_key has not been obsoleted or renamed. @@ -451,10 +308,12 @@ public: \ /* Overrides ConfigBase::keys(). Collect names of all configuration values maintained by this configuration store. */ \ t_config_option_keys keys() const override { return s_cache_##CLASS_NAME.keys(); } \ const t_config_option_keys& keys_ref() const override { return s_cache_##CLASS_NAME.keys(); } \ - static const CLASS_NAME& defaults() { initialize_cache(); return s_cache_##CLASS_NAME.defaults(); } \ + static const CLASS_NAME& defaults() { assert(s_cache_##CLASS_NAME.initialized()); return s_cache_##CLASS_NAME.defaults(); } \ private: \ + friend int print_config_static_initializer(); \ static void initialize_cache() \ { \ + assert(! s_cache_##CLASS_NAME.initialized()); \ if (! s_cache_##CLASS_NAME.initialized()) { \ CLASS_NAME *inst = new CLASS_NAME(1); \ inst->initialize(s_cache_##CLASS_NAME, (const char*)inst); \ @@ -468,7 +327,7 @@ private: \ STATIC_PRINT_CONFIG_CACHE_BASE(CLASS_NAME) \ public: \ /* Public default constructor will initialize the key/option cache and the default object copy if needed. */ \ - CLASS_NAME() { initialize_cache(); *this = s_cache_##CLASS_NAME.defaults(); } \ + CLASS_NAME() { assert(s_cache_##CLASS_NAME.initialized()); *this = s_cache_##CLASS_NAME.defaults(); } \ protected: \ /* Protected constructor to be called when compounded. */ \ CLASS_NAME(int) {} @@ -482,729 +341,498 @@ public: \ void handle_legacy(t_config_option_key &opt_key, std::string &value) const override \ { PrintConfigDef::handle_legacy(opt_key, value); } -#define OPT_PTR(KEY) cache.opt_add(#KEY, base_ptr, this->KEY) +#define PRINT_CONFIG_CLASS_ELEMENT_DEFINITION(r, data, elem) BOOST_PP_TUPLE_ELEM(0, elem) BOOST_PP_TUPLE_ELEM(1, elem); +#define PRINT_CONFIG_CLASS_ELEMENT_INITIALIZATION2(KEY) cache.opt_add(BOOST_PP_STRINGIZE(KEY), base_ptr, this->KEY); +#define PRINT_CONFIG_CLASS_ELEMENT_INITIALIZATION(r, data, elem) PRINT_CONFIG_CLASS_ELEMENT_INITIALIZATION2(BOOST_PP_TUPLE_ELEM(1, elem)) +#define PRINT_CONFIG_CLASS_ELEMENT_HASH(r, data, elem) boost::hash_combine(seed, BOOST_PP_TUPLE_ELEM(1, elem).hash()); +#define PRINT_CONFIG_CLASS_ELEMENT_EQUAL(r, data, elem) if (! (BOOST_PP_TUPLE_ELEM(1, elem) == rhs.BOOST_PP_TUPLE_ELEM(1, elem))) return false; + +#define PRINT_CONFIG_CLASS_DEFINE(CLASS_NAME, PARAMETER_DEFINITION_SEQ) \ +class CLASS_NAME : public StaticPrintConfig { \ + STATIC_PRINT_CONFIG_CACHE(CLASS_NAME) \ +public: \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_DEFINITION, _, PARAMETER_DEFINITION_SEQ) \ + size_t hash() const throw() \ + { \ + size_t seed = 0; \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_HASH, _, PARAMETER_DEFINITION_SEQ) \ + return seed; \ + } \ + bool operator==(const CLASS_NAME &rhs) const throw() \ + { \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_EQUAL, _, PARAMETER_DEFINITION_SEQ) \ + return true; \ + } \ + bool operator!=(const CLASS_NAME &rhs) const throw() { return ! (*this == rhs); } \ +protected: \ + void initialize(StaticCacheBase &cache, const char *base_ptr) \ + { \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_INITIALIZATION, _, PARAMETER_DEFINITION_SEQ) \ + } \ +}; + +#define PRINT_CONFIG_CLASS_DERIVED_CLASS_LIST_ITEM(r, data, i, elem) BOOST_PP_COMMA_IF(i) public elem +#define PRINT_CONFIG_CLASS_DERIVED_CLASS_LIST(CLASSES_PARENTS_TUPLE) BOOST_PP_SEQ_FOR_EACH_I(PRINT_CONFIG_CLASS_DERIVED_CLASS_LIST_ITEM, _, BOOST_PP_TUPLE_TO_SEQ(CLASSES_PARENTS_TUPLE)) +#define PRINT_CONFIG_CLASS_DERIVED_INITIALIZER_ITEM(r, VALUE, i, elem) BOOST_PP_COMMA_IF(i) elem(VALUE) +#define PRINT_CONFIG_CLASS_DERIVED_INITIALIZER(CLASSES_PARENTS_TUPLE, VALUE) BOOST_PP_SEQ_FOR_EACH_I(PRINT_CONFIG_CLASS_DERIVED_INITIALIZER_ITEM, VALUE, BOOST_PP_TUPLE_TO_SEQ(CLASSES_PARENTS_TUPLE)) +#define PRINT_CONFIG_CLASS_DERIVED_INITCACHE_ITEM(r, data, elem) this->elem::initialize(cache, base_ptr); +#define PRINT_CONFIG_CLASS_DERIVED_INITCACHE(CLASSES_PARENTS_TUPLE) BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_DERIVED_INITCACHE_ITEM, _, BOOST_PP_TUPLE_TO_SEQ(CLASSES_PARENTS_TUPLE)) +#define PRINT_CONFIG_CLASS_DERIVED_HASH(r, data, elem) boost::hash_combine(seed, static_cast(this)->hash()); +#define PRINT_CONFIG_CLASS_DERIVED_EQUAL(r, data, elem) \ + if (! (*static_cast(this) == static_cast(rhs))) return false; + +// Generic version, with or without new parameters. Don't use this directly. +#define PRINT_CONFIG_CLASS_DERIVED_DEFINE1(CLASS_NAME, CLASSES_PARENTS_TUPLE, PARAMETER_DEFINITION, PARAMETER_REGISTRATION, PARAMETER_HASHES, PARAMETER_EQUALS) \ +class CLASS_NAME : PRINT_CONFIG_CLASS_DERIVED_CLASS_LIST(CLASSES_PARENTS_TUPLE) { \ + STATIC_PRINT_CONFIG_CACHE_DERIVED(CLASS_NAME) \ + CLASS_NAME() : PRINT_CONFIG_CLASS_DERIVED_INITIALIZER(CLASSES_PARENTS_TUPLE, 0) { assert(s_cache_##CLASS_NAME.initialized()); *this = s_cache_##CLASS_NAME.defaults(); } \ +public: \ + PARAMETER_DEFINITION \ + size_t hash() const throw() \ + { \ + size_t seed = 0; \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_DERIVED_HASH, _, BOOST_PP_TUPLE_TO_SEQ(CLASSES_PARENTS_TUPLE)) \ + PARAMETER_HASHES \ + return seed; \ + } \ + bool operator==(const CLASS_NAME &rhs) const throw() \ + { \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_DERIVED_EQUAL, _, BOOST_PP_TUPLE_TO_SEQ(CLASSES_PARENTS_TUPLE)) \ + PARAMETER_EQUALS \ + return true; \ + } \ + bool operator!=(const CLASS_NAME &rhs) const throw() { return ! (*this == rhs); } \ +protected: \ + CLASS_NAME(int) : PRINT_CONFIG_CLASS_DERIVED_INITIALIZER(CLASSES_PARENTS_TUPLE, 1) {} \ + void initialize(StaticCacheBase &cache, const char* base_ptr) { \ + PRINT_CONFIG_CLASS_DERIVED_INITCACHE(CLASSES_PARENTS_TUPLE) \ + PARAMETER_REGISTRATION \ + } \ +}; +// Variant without adding new parameters. +#define PRINT_CONFIG_CLASS_DERIVED_DEFINE0(CLASS_NAME, CLASSES_PARENTS_TUPLE) \ + PRINT_CONFIG_CLASS_DERIVED_DEFINE1(CLASS_NAME, CLASSES_PARENTS_TUPLE, BOOST_PP_EMPTY(), BOOST_PP_EMPTY(), BOOST_PP_EMPTY(), BOOST_PP_EMPTY()) +// Variant with adding new parameters. +#define PRINT_CONFIG_CLASS_DERIVED_DEFINE(CLASS_NAME, CLASSES_PARENTS_TUPLE, PARAMETER_DEFINITION_SEQ) \ + PRINT_CONFIG_CLASS_DERIVED_DEFINE1(CLASS_NAME, CLASSES_PARENTS_TUPLE, \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_DEFINITION, _, PARAMETER_DEFINITION_SEQ), \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_INITIALIZATION, _, PARAMETER_DEFINITION_SEQ), \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_HASH, _, PARAMETER_DEFINITION_SEQ), \ + BOOST_PP_SEQ_FOR_EACH(PRINT_CONFIG_CLASS_ELEMENT_EQUAL, _, PARAMETER_DEFINITION_SEQ)) // This object is mapped to Perl as Slic3r::Config::PrintObject. -class PrintObjectConfig : public StaticPrintConfig -{ - STATIC_PRINT_CONFIG_CACHE(PrintObjectConfig) -public: - ConfigOptionFloat brim_offset; - ConfigOptionEnum brim_type; - ConfigOptionFloat brim_width; - ConfigOptionBool clip_multipart_objects; - ConfigOptionBool dont_support_bridges; - ConfigOptionFloat elefant_foot_compensation; - ConfigOptionFloatOrPercent extrusion_width; - ConfigOptionFloatOrPercent first_layer_height; - ConfigOptionBool infill_only_where_needed; - // Force the generation of solid shells between adjacent materials/volumes. - ConfigOptionBool interface_shells; - ConfigOptionFloat layer_height; - ConfigOptionFloat raft_contact_distance; - ConfigOptionFloat raft_expansion; - ConfigOptionPercent raft_first_layer_density; - ConfigOptionFloat raft_first_layer_expansion; - ConfigOptionInt raft_layers; - ConfigOptionEnum seam_position; -// ConfigOptionFloat seam_preferred_direction; -// ConfigOptionFloat seam_preferred_direction_jitter; - ConfigOptionFloat slice_closing_radius; - ConfigOptionBool support_material; - // Automatic supports (generated based on support_material_threshold). - ConfigOptionBool support_material_auto; - // Direction of the support pattern (in XY plane). - ConfigOptionFloat support_material_angle; - ConfigOptionBool support_material_buildplate_only; - ConfigOptionFloat support_material_contact_distance; - ConfigOptionFloat support_material_bottom_contact_distance; - ConfigOptionInt support_material_enforce_layers; - ConfigOptionInt support_material_extruder; - ConfigOptionFloatOrPercent support_material_extrusion_width; - ConfigOptionBool support_material_interface_contact_loops; - ConfigOptionInt support_material_interface_extruder; - ConfigOptionInt support_material_interface_layers; - ConfigOptionInt support_material_bottom_interface_layers; - // Spacing between interface lines (the hatching distance). Set zero to get a solid interface. - ConfigOptionFloat support_material_interface_spacing; - ConfigOptionFloatOrPercent support_material_interface_speed; - ConfigOptionEnum support_material_pattern; - ConfigOptionEnum support_material_interface_pattern; - // Morphological closing of support areas. Only used for "sung" supports. - ConfigOptionFloat support_material_closing_radius; - // Spacing between support material lines (the hatching distance). - ConfigOptionFloat support_material_spacing; - ConfigOptionFloat support_material_speed; - ConfigOptionEnum support_material_style; - ConfigOptionBool support_material_synchronize_layers; - // Overhang angle threshold. - ConfigOptionInt support_material_threshold; - ConfigOptionBool support_material_with_sheath; - ConfigOptionFloatOrPercent support_material_xy_spacing; - ConfigOptionBool thick_bridges; - ConfigOptionFloat xy_size_compensation; - ConfigOptionBool wipe_into_objects; +PRINT_CONFIG_CLASS_DEFINE( + PrintObjectConfig, -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(brim_offset); - OPT_PTR(brim_type); - OPT_PTR(brim_width); - OPT_PTR(clip_multipart_objects); - OPT_PTR(dont_support_bridges); - OPT_PTR(elefant_foot_compensation); - OPT_PTR(extrusion_width); - OPT_PTR(first_layer_height); - OPT_PTR(infill_only_where_needed); - OPT_PTR(interface_shells); - OPT_PTR(layer_height); - OPT_PTR(raft_contact_distance); - OPT_PTR(raft_expansion); - OPT_PTR(raft_first_layer_density); - OPT_PTR(raft_first_layer_expansion); - OPT_PTR(raft_layers); - OPT_PTR(seam_position); - OPT_PTR(slice_closing_radius); -// OPT_PTR(seam_preferred_direction); -// OPT_PTR(seam_preferred_direction_jitter); - OPT_PTR(support_material); - OPT_PTR(support_material_auto); - OPT_PTR(support_material_angle); - OPT_PTR(support_material_buildplate_only); - OPT_PTR(support_material_contact_distance); - OPT_PTR(support_material_bottom_contact_distance); - OPT_PTR(support_material_enforce_layers); - OPT_PTR(support_material_interface_contact_loops); - OPT_PTR(support_material_extruder); - OPT_PTR(support_material_extrusion_width); - OPT_PTR(support_material_interface_extruder); - OPT_PTR(support_material_interface_layers); - OPT_PTR(support_material_bottom_interface_layers); - OPT_PTR(support_material_closing_radius); - OPT_PTR(support_material_interface_spacing); - OPT_PTR(support_material_interface_speed); - OPT_PTR(support_material_pattern); - OPT_PTR(support_material_interface_pattern); - OPT_PTR(support_material_spacing); - OPT_PTR(support_material_speed); - OPT_PTR(support_material_style); - OPT_PTR(support_material_synchronize_layers); - OPT_PTR(support_material_xy_spacing); - OPT_PTR(support_material_threshold); - OPT_PTR(support_material_with_sheath); - OPT_PTR(thick_bridges); - OPT_PTR(xy_size_compensation); - OPT_PTR(wipe_into_objects); - } -}; + ((ConfigOptionFloat, brim_offset)) + ((ConfigOptionEnum, brim_type)) + ((ConfigOptionFloat, brim_width)) + ((ConfigOptionBool, clip_multipart_objects)) + ((ConfigOptionBool, dont_support_bridges)) + ((ConfigOptionFloat, elefant_foot_compensation)) + ((ConfigOptionFloatOrPercent, extrusion_width)) + ((ConfigOptionBool, infill_only_where_needed)) + // Force the generation of solid shells between adjacent materials/volumes. + ((ConfigOptionBool, interface_shells)) + ((ConfigOptionFloat, layer_height)) + ((ConfigOptionFloat, raft_contact_distance)) + ((ConfigOptionFloat, raft_expansion)) + ((ConfigOptionPercent, raft_first_layer_density)) + ((ConfigOptionFloat, raft_first_layer_expansion)) + ((ConfigOptionInt, raft_layers)) + ((ConfigOptionEnum, seam_position)) +// ((ConfigOptionFloat, seam_preferred_direction)) +// ((ConfigOptionFloat, seam_preferred_direction_jitter)) + ((ConfigOptionFloat, slice_closing_radius)) + ((ConfigOptionBool, support_material)) + // Automatic supports (generated based on support_material_threshold). + ((ConfigOptionBool, support_material_auto)) + // Direction of the support pattern (in XY plane).` + ((ConfigOptionFloat, support_material_angle)) + ((ConfigOptionBool, support_material_buildplate_only)) + ((ConfigOptionFloat, support_material_contact_distance)) + ((ConfigOptionFloat, support_material_bottom_contact_distance)) + ((ConfigOptionInt, support_material_enforce_layers)) + ((ConfigOptionInt, support_material_extruder)) + ((ConfigOptionFloatOrPercent, support_material_extrusion_width)) + ((ConfigOptionBool, support_material_interface_contact_loops)) + ((ConfigOptionInt, support_material_interface_extruder)) + ((ConfigOptionInt, support_material_interface_layers)) + ((ConfigOptionInt, support_material_bottom_interface_layers)) + // Spacing between interface lines (the hatching distance). Set zero to get a solid interface. + ((ConfigOptionFloat, support_material_interface_spacing)) + ((ConfigOptionFloatOrPercent, support_material_interface_speed)) + ((ConfigOptionEnum, support_material_pattern)) + ((ConfigOptionEnum, support_material_interface_pattern)) + // Morphological closing of support areas. Only used for "sung" supports. + ((ConfigOptionFloat, support_material_closing_radius)) + // Spacing between support material lines (the hatching distance). + ((ConfigOptionFloat, support_material_spacing)) + ((ConfigOptionFloat, support_material_speed)) + ((ConfigOptionEnum, support_material_style)) + ((ConfigOptionBool, support_material_synchronize_layers)) + // Overhang angle threshold. + ((ConfigOptionInt, support_material_threshold)) + ((ConfigOptionBool, support_material_with_sheath)) + ((ConfigOptionFloatOrPercent, support_material_xy_spacing)) + ((ConfigOptionBool, thick_bridges)) + ((ConfigOptionFloat, xy_size_compensation)) + ((ConfigOptionBool, wipe_into_objects)) +) // This object is mapped to Perl as Slic3r::Config::PrintRegion. -class PrintRegionConfig : public StaticPrintConfig -{ - STATIC_PRINT_CONFIG_CACHE(PrintRegionConfig) -public: - ConfigOptionFloat bridge_angle; - ConfigOptionInt bottom_solid_layers; - ConfigOptionFloat bottom_solid_min_thickness; - ConfigOptionFloat bridge_flow_ratio; - ConfigOptionFloat bridge_speed; - ConfigOptionBool ensure_vertical_shell_thickness; - ConfigOptionEnum top_fill_pattern; - ConfigOptionEnum bottom_fill_pattern; - ConfigOptionFloatOrPercent external_perimeter_extrusion_width; - ConfigOptionFloatOrPercent external_perimeter_speed; - ConfigOptionBool external_perimeters_first; - ConfigOptionBool extra_perimeters; - ConfigOptionFloat fill_angle; - ConfigOptionPercent fill_density; - ConfigOptionEnum fill_pattern; - ConfigOptionEnum fuzzy_skin; - ConfigOptionFloat fuzzy_skin_thickness; - ConfigOptionFloat fuzzy_skin_point_dist; - ConfigOptionBool gap_fill_enabled; - ConfigOptionFloat gap_fill_speed; - ConfigOptionFloatOrPercent infill_anchor; - ConfigOptionFloatOrPercent infill_anchor_max; - ConfigOptionInt infill_extruder; - ConfigOptionFloatOrPercent infill_extrusion_width; - ConfigOptionInt infill_every_layers; - ConfigOptionFloatOrPercent infill_overlap; - ConfigOptionFloat infill_speed; +PRINT_CONFIG_CLASS_DEFINE( + PrintRegionConfig, + + ((ConfigOptionFloat, bridge_angle)) + ((ConfigOptionInt, bottom_solid_layers)) + ((ConfigOptionFloat, bottom_solid_min_thickness)) + ((ConfigOptionFloat, bridge_flow_ratio)) + ((ConfigOptionFloat, bridge_speed)) + ((ConfigOptionBool, ensure_vertical_shell_thickness)) + ((ConfigOptionEnum, top_fill_pattern)) + ((ConfigOptionEnum, bottom_fill_pattern)) + ((ConfigOptionFloatOrPercent, external_perimeter_extrusion_width)) + ((ConfigOptionFloatOrPercent, external_perimeter_speed)) + ((ConfigOptionBool, external_perimeters_first)) + ((ConfigOptionBool, extra_perimeters)) + ((ConfigOptionFloat, fill_angle)) + ((ConfigOptionPercent, fill_density)) + ((ConfigOptionEnum, fill_pattern)) + ((ConfigOptionEnum, fuzzy_skin)) + ((ConfigOptionFloat, fuzzy_skin_thickness)) + ((ConfigOptionFloat, fuzzy_skin_point_dist)) + ((ConfigOptionBool, gap_fill_enabled)) + ((ConfigOptionFloat, gap_fill_speed)) + ((ConfigOptionFloatOrPercent, infill_anchor)) + ((ConfigOptionFloatOrPercent, infill_anchor_max)) + ((ConfigOptionInt, infill_extruder)) + ((ConfigOptionFloatOrPercent, infill_extrusion_width)) + ((ConfigOptionInt, infill_every_layers)) + ((ConfigOptionFloatOrPercent, infill_overlap)) + ((ConfigOptionFloat, infill_speed)) // Ironing options - ConfigOptionBool ironing; - ConfigOptionEnum ironing_type; - ConfigOptionPercent ironing_flowrate; - ConfigOptionFloat ironing_spacing; - ConfigOptionFloat ironing_speed; + ((ConfigOptionBool, ironing)) + ((ConfigOptionEnum, ironing_type)) + ((ConfigOptionPercent, ironing_flowrate)) + ((ConfigOptionFloat, ironing_spacing)) + ((ConfigOptionFloat, ironing_speed)) // Detect bridging perimeters - ConfigOptionBool overhangs; - ConfigOptionInt perimeter_extruder; - ConfigOptionFloatOrPercent perimeter_extrusion_width; - ConfigOptionFloat perimeter_speed; + ((ConfigOptionBool, overhangs)) + ((ConfigOptionInt, perimeter_extruder)) + ((ConfigOptionFloatOrPercent, perimeter_extrusion_width)) + ((ConfigOptionFloat, perimeter_speed)) // Total number of perimeters. - ConfigOptionInt perimeters; - ConfigOptionFloatOrPercent small_perimeter_speed; - ConfigOptionFloat solid_infill_below_area; - ConfigOptionInt solid_infill_extruder; - ConfigOptionFloatOrPercent solid_infill_extrusion_width; - ConfigOptionInt solid_infill_every_layers; - ConfigOptionFloatOrPercent solid_infill_speed; + ((ConfigOptionInt, perimeters)) + ((ConfigOptionFloatOrPercent, small_perimeter_speed)) + ((ConfigOptionFloat, solid_infill_below_area)) + ((ConfigOptionInt, solid_infill_extruder)) + ((ConfigOptionFloatOrPercent, solid_infill_extrusion_width)) + ((ConfigOptionInt, solid_infill_every_layers)) + ((ConfigOptionFloatOrPercent, solid_infill_speed)) // Detect thin walls. - ConfigOptionBool thin_walls; - ConfigOptionFloatOrPercent top_infill_extrusion_width; - ConfigOptionInt top_solid_layers; - ConfigOptionFloat top_solid_min_thickness; - ConfigOptionFloatOrPercent top_solid_infill_speed; - ConfigOptionBool wipe_into_infill; + ((ConfigOptionBool, thin_walls)) + ((ConfigOptionFloatOrPercent, top_infill_extrusion_width)) + ((ConfigOptionInt, top_solid_layers)) + ((ConfigOptionFloat, top_solid_min_thickness)) + ((ConfigOptionFloatOrPercent, top_solid_infill_speed)) + ((ConfigOptionBool, wipe_into_infill)) +) -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(bridge_angle); - OPT_PTR(bottom_solid_layers); - OPT_PTR(bottom_solid_min_thickness); - OPT_PTR(bridge_flow_ratio); - OPT_PTR(bridge_speed); - OPT_PTR(ensure_vertical_shell_thickness); - OPT_PTR(top_fill_pattern); - OPT_PTR(bottom_fill_pattern); - OPT_PTR(external_perimeter_extrusion_width); - OPT_PTR(external_perimeter_speed); - OPT_PTR(external_perimeters_first); - OPT_PTR(extra_perimeters); - OPT_PTR(fill_angle); - OPT_PTR(fill_density); - OPT_PTR(fill_pattern); - OPT_PTR(fuzzy_skin); - OPT_PTR(fuzzy_skin_thickness); - OPT_PTR(fuzzy_skin_point_dist); - OPT_PTR(gap_fill_enabled); - OPT_PTR(gap_fill_speed); - OPT_PTR(infill_anchor); - OPT_PTR(infill_anchor_max); - OPT_PTR(infill_extruder); - OPT_PTR(infill_extrusion_width); - OPT_PTR(infill_every_layers); - OPT_PTR(infill_overlap); - OPT_PTR(infill_speed); - OPT_PTR(ironing); - OPT_PTR(ironing_type); - OPT_PTR(ironing_flowrate); - OPT_PTR(ironing_spacing); - OPT_PTR(ironing_speed); - OPT_PTR(overhangs); - OPT_PTR(perimeter_extruder); - OPT_PTR(perimeter_extrusion_width); - OPT_PTR(perimeter_speed); - OPT_PTR(perimeters); - OPT_PTR(small_perimeter_speed); - OPT_PTR(solid_infill_below_area); - OPT_PTR(solid_infill_extruder); - OPT_PTR(solid_infill_extrusion_width); - OPT_PTR(solid_infill_every_layers); - OPT_PTR(solid_infill_speed); - OPT_PTR(thin_walls); - OPT_PTR(top_infill_extrusion_width); - OPT_PTR(top_solid_infill_speed); - OPT_PTR(top_solid_layers); - OPT_PTR(top_solid_min_thickness); - OPT_PTR(wipe_into_infill); - } -}; +PRINT_CONFIG_CLASS_DEFINE( + MachineEnvelopeConfig, -class MachineEnvelopeConfig : public StaticPrintConfig -{ - STATIC_PRINT_CONFIG_CACHE(MachineEnvelopeConfig) -public: - // Allowing the machine limits to be completely ignored or used just for time estimator. - ConfigOptionEnum machine_limits_usage; + // Allowing the machine limits to be completely ignored or used just for time estimator. + ((ConfigOptionEnum, machine_limits_usage)) // M201 X... Y... Z... E... [mm/sec^2] - ConfigOptionFloats machine_max_acceleration_x; - ConfigOptionFloats machine_max_acceleration_y; - ConfigOptionFloats machine_max_acceleration_z; - ConfigOptionFloats machine_max_acceleration_e; + ((ConfigOptionFloats, machine_max_acceleration_x)) + ((ConfigOptionFloats, machine_max_acceleration_y)) + ((ConfigOptionFloats, machine_max_acceleration_z)) + ((ConfigOptionFloats, machine_max_acceleration_e)) // M203 X... Y... Z... E... [mm/sec] - ConfigOptionFloats machine_max_feedrate_x; - ConfigOptionFloats machine_max_feedrate_y; - ConfigOptionFloats machine_max_feedrate_z; - ConfigOptionFloats machine_max_feedrate_e; + ((ConfigOptionFloats, machine_max_feedrate_x)) + ((ConfigOptionFloats, machine_max_feedrate_y)) + ((ConfigOptionFloats, machine_max_feedrate_z)) + ((ConfigOptionFloats, machine_max_feedrate_e)) // M204 P... R... T...[mm/sec^2] - ConfigOptionFloats machine_max_acceleration_extruding; - ConfigOptionFloats machine_max_acceleration_retracting; - ConfigOptionFloats machine_max_acceleration_travel; + ((ConfigOptionFloats, machine_max_acceleration_extruding)) + ((ConfigOptionFloats, machine_max_acceleration_retracting)) + ((ConfigOptionFloats, machine_max_acceleration_travel)) // M205 X... Y... Z... E... [mm/sec] - ConfigOptionFloats machine_max_jerk_x; - ConfigOptionFloats machine_max_jerk_y; - ConfigOptionFloats machine_max_jerk_z; - ConfigOptionFloats machine_max_jerk_e; + ((ConfigOptionFloats, machine_max_jerk_x)) + ((ConfigOptionFloats, machine_max_jerk_y)) + ((ConfigOptionFloats, machine_max_jerk_z)) + ((ConfigOptionFloats, machine_max_jerk_e)) // M205 T... [mm/sec] - ConfigOptionFloats machine_min_travel_rate; + ((ConfigOptionFloats, machine_min_travel_rate)) // M205 S... [mm/sec] - ConfigOptionFloats machine_min_extruding_rate; - -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(machine_limits_usage); - OPT_PTR(machine_max_acceleration_x); - OPT_PTR(machine_max_acceleration_y); - OPT_PTR(machine_max_acceleration_z); - OPT_PTR(machine_max_acceleration_e); - OPT_PTR(machine_max_feedrate_x); - OPT_PTR(machine_max_feedrate_y); - OPT_PTR(machine_max_feedrate_z); - OPT_PTR(machine_max_feedrate_e); - OPT_PTR(machine_max_acceleration_extruding); - OPT_PTR(machine_max_acceleration_retracting); - OPT_PTR(machine_max_acceleration_travel); - OPT_PTR(machine_max_jerk_x); - OPT_PTR(machine_max_jerk_y); - OPT_PTR(machine_max_jerk_z); - OPT_PTR(machine_max_jerk_e); - OPT_PTR(machine_min_travel_rate); - OPT_PTR(machine_min_extruding_rate); - } -}; + ((ConfigOptionFloats, machine_min_extruding_rate)) +) // This object is mapped to Perl as Slic3r::Config::GCode. -class GCodeConfig : public StaticPrintConfig +PRINT_CONFIG_CLASS_DEFINE( + GCodeConfig, + + ((ConfigOptionString, before_layer_gcode)) + ((ConfigOptionString, between_objects_gcode)) + ((ConfigOptionFloats, deretract_speed)) + ((ConfigOptionString, end_gcode)) + ((ConfigOptionStrings, end_filament_gcode)) + ((ConfigOptionString, extrusion_axis)) + ((ConfigOptionFloats, extrusion_multiplier)) + ((ConfigOptionFloats, filament_diameter)) + ((ConfigOptionFloats, filament_density)) + ((ConfigOptionStrings, filament_type)) + ((ConfigOptionBools, filament_soluble)) + ((ConfigOptionFloats, filament_cost)) + ((ConfigOptionFloats, filament_spool_weight)) + ((ConfigOptionFloats, filament_max_volumetric_speed)) + ((ConfigOptionFloats, filament_loading_speed)) + ((ConfigOptionFloats, filament_loading_speed_start)) + ((ConfigOptionFloats, filament_load_time)) + ((ConfigOptionFloats, filament_unloading_speed)) + ((ConfigOptionFloats, filament_unloading_speed_start)) + ((ConfigOptionFloats, filament_toolchange_delay)) + ((ConfigOptionFloats, filament_unload_time)) + ((ConfigOptionInts, filament_cooling_moves)) + ((ConfigOptionFloats, filament_cooling_initial_speed)) + ((ConfigOptionFloats, filament_minimal_purge_on_wipe_tower)) + ((ConfigOptionFloats, filament_cooling_final_speed)) + ((ConfigOptionStrings, filament_ramming_parameters)) + ((ConfigOptionBool, gcode_comments)) + ((ConfigOptionEnum, gcode_flavor)) + ((ConfigOptionBool, gcode_label_objects)) + ((ConfigOptionString, layer_gcode)) + ((ConfigOptionFloat, max_print_speed)) + ((ConfigOptionFloat, max_volumetric_speed)) +//#ifdef HAS_PRESSURE_EQUALIZER +// ((ConfigOptionFloat, max_volumetric_extrusion_rate_slope_positive)) +// ((ConfigOptionFloat, max_volumetric_extrusion_rate_slope_negative)) +//#endif + ((ConfigOptionPercents, retract_before_wipe)) + ((ConfigOptionFloats, retract_length)) + ((ConfigOptionFloats, retract_length_toolchange)) + ((ConfigOptionFloats, retract_lift)) + ((ConfigOptionFloats, retract_lift_above)) + ((ConfigOptionFloats, retract_lift_below)) + ((ConfigOptionFloats, retract_restart_extra)) + ((ConfigOptionFloats, retract_restart_extra_toolchange)) + ((ConfigOptionFloats, retract_speed)) + ((ConfigOptionString, start_gcode)) + ((ConfigOptionStrings, start_filament_gcode)) + ((ConfigOptionBool, single_extruder_multi_material)) + ((ConfigOptionBool, single_extruder_multi_material_priming)) + ((ConfigOptionBool, wipe_tower_no_sparse_layers)) + ((ConfigOptionString, toolchange_gcode)) + ((ConfigOptionFloat, travel_speed)) + ((ConfigOptionBool, use_firmware_retraction)) + ((ConfigOptionBool, use_relative_e_distances)) + ((ConfigOptionBool, use_volumetric_e)) + ((ConfigOptionBool, variable_layer_height)) + ((ConfigOptionFloat, cooling_tube_retraction)) + ((ConfigOptionFloat, cooling_tube_length)) + ((ConfigOptionBool, high_current_on_filament_swap)) + ((ConfigOptionFloat, parking_pos_retraction)) + ((ConfigOptionBool, remaining_times)) + ((ConfigOptionBool, silent_mode)) + ((ConfigOptionFloat, extra_loading_move)) + ((ConfigOptionString, color_change_gcode)) + ((ConfigOptionString, pause_print_gcode)) + ((ConfigOptionString, template_custom_gcode)) +) + +static inline std::string get_extrusion_axis(const GCodeConfig &cfg) { - STATIC_PRINT_CONFIG_CACHE(GCodeConfig) -public: - ConfigOptionString before_layer_gcode; - ConfigOptionString between_objects_gcode; - ConfigOptionFloats deretract_speed; - ConfigOptionString end_gcode; - ConfigOptionStrings end_filament_gcode; - ConfigOptionString extrusion_axis; - ConfigOptionFloats extrusion_multiplier; - ConfigOptionFloats filament_diameter; - ConfigOptionFloats filament_density; - ConfigOptionStrings filament_type; - ConfigOptionBools filament_soluble; - ConfigOptionFloats filament_cost; - ConfigOptionFloats filament_spool_weight; - ConfigOptionFloats filament_max_volumetric_speed; - ConfigOptionFloats filament_loading_speed; - ConfigOptionFloats filament_loading_speed_start; - ConfigOptionFloats filament_load_time; - ConfigOptionFloats filament_unloading_speed; - ConfigOptionFloats filament_unloading_speed_start; - ConfigOptionFloats filament_toolchange_delay; - ConfigOptionFloats filament_unload_time; - ConfigOptionInts filament_cooling_moves; - ConfigOptionFloats filament_cooling_initial_speed; - ConfigOptionFloats filament_minimal_purge_on_wipe_tower; - ConfigOptionFloats filament_cooling_final_speed; - ConfigOptionStrings filament_ramming_parameters; - ConfigOptionBool gcode_comments; - ConfigOptionEnum gcode_flavor; - ConfigOptionBool gcode_label_objects; - ConfigOptionString layer_gcode; - ConfigOptionFloat max_print_speed; - ConfigOptionFloat max_volumetric_speed; -#ifdef HAS_PRESSURE_EQUALIZER - ConfigOptionFloat max_volumetric_extrusion_rate_slope_positive; - ConfigOptionFloat max_volumetric_extrusion_rate_slope_negative; -#endif - ConfigOptionPercents retract_before_wipe; - ConfigOptionFloats retract_length; - ConfigOptionFloats retract_length_toolchange; - ConfigOptionFloats retract_lift; - ConfigOptionFloats retract_lift_above; - ConfigOptionFloats retract_lift_below; - ConfigOptionFloats retract_restart_extra; - ConfigOptionFloats retract_restart_extra_toolchange; - ConfigOptionFloats retract_speed; - ConfigOptionString start_gcode; - ConfigOptionStrings start_filament_gcode; - ConfigOptionBool single_extruder_multi_material; - ConfigOptionBool single_extruder_multi_material_priming; - ConfigOptionBool wipe_tower_no_sparse_layers; - ConfigOptionString toolchange_gcode; - ConfigOptionFloat travel_speed; - ConfigOptionBool use_firmware_retraction; - ConfigOptionBool use_relative_e_distances; - ConfigOptionBool use_volumetric_e; - ConfigOptionBool variable_layer_height; - ConfigOptionFloat cooling_tube_retraction; - ConfigOptionFloat cooling_tube_length; - ConfigOptionBool high_current_on_filament_swap; - ConfigOptionFloat parking_pos_retraction; - ConfigOptionBool remaining_times; - ConfigOptionBool silent_mode; - ConfigOptionFloat extra_loading_move; - ConfigOptionString color_change_gcode; - ConfigOptionString pause_print_gcode; - ConfigOptionString template_custom_gcode; - - std::string get_extrusion_axis() const - { - return - ((this->gcode_flavor.value == gcfMach3) || (this->gcode_flavor.value == gcfMachinekit)) ? "A" : - (this->gcode_flavor.value == gcfNoExtrusion) ? "" : this->extrusion_axis.value; - } - -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(before_layer_gcode); - OPT_PTR(between_objects_gcode); - OPT_PTR(deretract_speed); - OPT_PTR(end_gcode); - OPT_PTR(end_filament_gcode); - OPT_PTR(extrusion_axis); - OPT_PTR(extrusion_multiplier); - OPT_PTR(filament_diameter); - OPT_PTR(filament_density); - OPT_PTR(filament_type); - OPT_PTR(filament_soluble); - OPT_PTR(filament_cost); - OPT_PTR(filament_spool_weight); - OPT_PTR(filament_max_volumetric_speed); - OPT_PTR(filament_loading_speed); - OPT_PTR(filament_loading_speed_start); - OPT_PTR(filament_load_time); - OPT_PTR(filament_unloading_speed); - OPT_PTR(filament_unloading_speed_start); - OPT_PTR(filament_unload_time); - OPT_PTR(filament_toolchange_delay); - OPT_PTR(filament_cooling_moves); - OPT_PTR(filament_cooling_initial_speed); - OPT_PTR(filament_minimal_purge_on_wipe_tower); - OPT_PTR(filament_cooling_final_speed); - OPT_PTR(filament_ramming_parameters); - OPT_PTR(gcode_comments); - OPT_PTR(gcode_flavor); - OPT_PTR(gcode_label_objects); - OPT_PTR(layer_gcode); - OPT_PTR(max_print_speed); - OPT_PTR(max_volumetric_speed); -#ifdef HAS_PRESSURE_EQUALIZER - OPT_PTR(max_volumetric_extrusion_rate_slope_positive); - OPT_PTR(max_volumetric_extrusion_rate_slope_negative); -#endif /* HAS_PRESSURE_EQUALIZER */ - OPT_PTR(retract_before_wipe); - OPT_PTR(retract_length); - OPT_PTR(retract_length_toolchange); - OPT_PTR(retract_lift); - OPT_PTR(retract_lift_above); - OPT_PTR(retract_lift_below); - OPT_PTR(retract_restart_extra); - OPT_PTR(retract_restart_extra_toolchange); - OPT_PTR(retract_speed); - OPT_PTR(single_extruder_multi_material); - OPT_PTR(single_extruder_multi_material_priming); - OPT_PTR(wipe_tower_no_sparse_layers); - OPT_PTR(start_gcode); - OPT_PTR(start_filament_gcode); - OPT_PTR(toolchange_gcode); - OPT_PTR(travel_speed); - OPT_PTR(use_firmware_retraction); - OPT_PTR(use_relative_e_distances); - OPT_PTR(use_volumetric_e); - OPT_PTR(variable_layer_height); - OPT_PTR(cooling_tube_retraction); - OPT_PTR(cooling_tube_length); - OPT_PTR(high_current_on_filament_swap); - OPT_PTR(parking_pos_retraction); - OPT_PTR(remaining_times); - OPT_PTR(silent_mode); - OPT_PTR(extra_loading_move); - OPT_PTR(color_change_gcode); - OPT_PTR(pause_print_gcode); - OPT_PTR(template_custom_gcode); - } -}; + return + ((cfg.gcode_flavor.value == gcfMach3) || (cfg.gcode_flavor.value == gcfMachinekit)) ? "A" : + (cfg.gcode_flavor.value == gcfNoExtrusion) ? "" : cfg.extrusion_axis.value; +} // This object is mapped to Perl as Slic3r::Config::Print. -class PrintConfig : public MachineEnvelopeConfig, public GCodeConfig -{ - STATIC_PRINT_CONFIG_CACHE_DERIVED(PrintConfig) - PrintConfig() : MachineEnvelopeConfig(0), GCodeConfig(0) { initialize_cache(); *this = s_cache_PrintConfig.defaults(); } -public: +PRINT_CONFIG_CLASS_DERIVED_DEFINE( + PrintConfig, + (MachineEnvelopeConfig, GCodeConfig), - ConfigOptionBool avoid_crossing_perimeters; - ConfigOptionFloatOrPercent avoid_crossing_perimeters_max_detour; - ConfigOptionPoints bed_shape; - ConfigOptionInts bed_temperature; - ConfigOptionFloat bridge_acceleration; - ConfigOptionInts bridge_fan_speed; - ConfigOptionBool complete_objects; - ConfigOptionFloats colorprint_heights; - ConfigOptionBools cooling; - ConfigOptionFloat default_acceleration; - ConfigOptionInts disable_fan_first_layers; - ConfigOptionFloat duplicate_distance; - ConfigOptionFloat extruder_clearance_height; - ConfigOptionFloat extruder_clearance_radius; - ConfigOptionStrings extruder_colour; - ConfigOptionPoints extruder_offset; - ConfigOptionBools fan_always_on; - ConfigOptionInts fan_below_layer_time; - ConfigOptionStrings filament_colour; - ConfigOptionStrings filament_notes; - ConfigOptionFloat first_layer_acceleration; - ConfigOptionInts first_layer_bed_temperature; - ConfigOptionFloatOrPercent first_layer_extrusion_width; - ConfigOptionFloatOrPercent first_layer_speed; - ConfigOptionInts first_layer_temperature; - ConfigOptionInts full_fan_speed_layer; - ConfigOptionFloat infill_acceleration; - ConfigOptionBool infill_first; - ConfigOptionInts max_fan_speed; - ConfigOptionFloats max_layer_height; - ConfigOptionInts min_fan_speed; - ConfigOptionFloats min_layer_height; - ConfigOptionFloat max_print_height; - ConfigOptionFloats min_print_speed; - ConfigOptionFloat min_skirt_length; - ConfigOptionString notes; - ConfigOptionFloats nozzle_diameter; - ConfigOptionBool only_retract_when_crossing_perimeters; - ConfigOptionBool ooze_prevention; - ConfigOptionString output_filename_format; - ConfigOptionFloat perimeter_acceleration; - ConfigOptionStrings post_process; - ConfigOptionString printer_model; - ConfigOptionString printer_notes; - ConfigOptionFloat resolution; - ConfigOptionFloats retract_before_travel; - ConfigOptionBools retract_layer_change; - ConfigOptionFloat skirt_distance; - ConfigOptionInt skirt_height; - ConfigOptionBool draft_shield; - ConfigOptionInt skirts; - ConfigOptionInts slowdown_below_layer_time; - ConfigOptionBool spiral_vase; - ConfigOptionInt standby_temperature_delta; - ConfigOptionInts temperature; - ConfigOptionInt threads; - ConfigOptionBools wipe; - ConfigOptionBool wipe_tower; - ConfigOptionFloat wipe_tower_x; - ConfigOptionFloat wipe_tower_y; - ConfigOptionFloat wipe_tower_width; - ConfigOptionFloat wipe_tower_per_color_wipe; - ConfigOptionFloat wipe_tower_rotation_angle; - ConfigOptionFloat wipe_tower_brim_width; - ConfigOptionFloat wipe_tower_bridging; - ConfigOptionFloats wiping_volumes_matrix; - ConfigOptionFloats wiping_volumes_extruders; - ConfigOptionFloat z_offset; - -protected: - PrintConfig(int) : MachineEnvelopeConfig(1), GCodeConfig(1) {} - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - this->MachineEnvelopeConfig::initialize(cache, base_ptr); - this->GCodeConfig::initialize(cache, base_ptr); - OPT_PTR(avoid_crossing_perimeters); - OPT_PTR(avoid_crossing_perimeters_max_detour); - OPT_PTR(bed_shape); - OPT_PTR(bed_temperature); - OPT_PTR(bridge_acceleration); - OPT_PTR(bridge_fan_speed); - OPT_PTR(complete_objects); - OPT_PTR(colorprint_heights); - OPT_PTR(cooling); - OPT_PTR(default_acceleration); - OPT_PTR(disable_fan_first_layers); - OPT_PTR(duplicate_distance); - OPT_PTR(extruder_clearance_height); - OPT_PTR(extruder_clearance_radius); - OPT_PTR(extruder_colour); - OPT_PTR(extruder_offset); - OPT_PTR(fan_always_on); - OPT_PTR(fan_below_layer_time); - OPT_PTR(filament_colour); - OPT_PTR(filament_notes); - OPT_PTR(first_layer_acceleration); - OPT_PTR(first_layer_bed_temperature); - OPT_PTR(first_layer_extrusion_width); - OPT_PTR(first_layer_speed); - OPT_PTR(first_layer_temperature); - OPT_PTR(full_fan_speed_layer); - OPT_PTR(infill_acceleration); - OPT_PTR(infill_first); - OPT_PTR(max_fan_speed); - OPT_PTR(max_layer_height); - OPT_PTR(min_fan_speed); - OPT_PTR(min_layer_height); - OPT_PTR(max_print_height); - OPT_PTR(min_print_speed); - OPT_PTR(min_skirt_length); - OPT_PTR(notes); - OPT_PTR(nozzle_diameter); - OPT_PTR(only_retract_when_crossing_perimeters); - OPT_PTR(ooze_prevention); - OPT_PTR(output_filename_format); - OPT_PTR(perimeter_acceleration); - OPT_PTR(post_process); - OPT_PTR(printer_model); - OPT_PTR(printer_notes); - OPT_PTR(resolution); - OPT_PTR(retract_before_travel); - OPT_PTR(retract_layer_change); - OPT_PTR(skirt_distance); - OPT_PTR(skirt_height); - OPT_PTR(draft_shield); - OPT_PTR(skirts); - OPT_PTR(slowdown_below_layer_time); - OPT_PTR(spiral_vase); - OPT_PTR(standby_temperature_delta); - OPT_PTR(temperature); - OPT_PTR(threads); - OPT_PTR(wipe); - OPT_PTR(wipe_tower); - OPT_PTR(wipe_tower_x); - OPT_PTR(wipe_tower_y); - OPT_PTR(wipe_tower_width); - OPT_PTR(wipe_tower_per_color_wipe); - OPT_PTR(wipe_tower_rotation_angle); - OPT_PTR(wipe_tower_brim_width); - OPT_PTR(wipe_tower_bridging); - OPT_PTR(wiping_volumes_matrix); - OPT_PTR(wiping_volumes_extruders); - OPT_PTR(z_offset); - } -}; + ((ConfigOptionBool, avoid_crossing_perimeters)) + ((ConfigOptionFloatOrPercent, avoid_crossing_perimeters_max_detour)) + ((ConfigOptionPoints, bed_shape)) + ((ConfigOptionInts, bed_temperature)) + ((ConfigOptionFloat, bridge_acceleration)) + ((ConfigOptionInts, bridge_fan_speed)) + ((ConfigOptionBool, complete_objects)) + ((ConfigOptionFloats, colorprint_heights)) + ((ConfigOptionBools, cooling)) + ((ConfigOptionFloat, default_acceleration)) + ((ConfigOptionInts, disable_fan_first_layers)) + ((ConfigOptionFloat, duplicate_distance)) + ((ConfigOptionFloat, extruder_clearance_height)) + ((ConfigOptionFloat, extruder_clearance_radius)) + ((ConfigOptionStrings, extruder_colour)) + ((ConfigOptionPoints, extruder_offset)) + ((ConfigOptionBools, fan_always_on)) + ((ConfigOptionInts, fan_below_layer_time)) + ((ConfigOptionStrings, filament_colour)) + ((ConfigOptionStrings, filament_notes)) + ((ConfigOptionFloat, first_layer_acceleration)) + ((ConfigOptionInts, first_layer_bed_temperature)) + ((ConfigOptionFloatOrPercent, first_layer_extrusion_width)) + ((ConfigOptionFloatOrPercent, first_layer_height)) + ((ConfigOptionFloatOrPercent, first_layer_speed)) + ((ConfigOptionInts, first_layer_temperature)) + ((ConfigOptionInts, full_fan_speed_layer)) + ((ConfigOptionFloat, infill_acceleration)) + ((ConfigOptionBool, infill_first)) + ((ConfigOptionInts, max_fan_speed)) + ((ConfigOptionFloats, max_layer_height)) + ((ConfigOptionInts, min_fan_speed)) + ((ConfigOptionFloats, min_layer_height)) + ((ConfigOptionFloat, max_print_height)) + ((ConfigOptionFloats, min_print_speed)) + ((ConfigOptionFloat, min_skirt_length)) + ((ConfigOptionString, notes)) + ((ConfigOptionFloats, nozzle_diameter)) + ((ConfigOptionBool, only_retract_when_crossing_perimeters)) + ((ConfigOptionBool, ooze_prevention)) + ((ConfigOptionString, output_filename_format)) + ((ConfigOptionFloat, perimeter_acceleration)) + ((ConfigOptionStrings, post_process)) + ((ConfigOptionString, printer_model)) + ((ConfigOptionString, printer_notes)) + ((ConfigOptionFloat, resolution)) + ((ConfigOptionFloats, retract_before_travel)) + ((ConfigOptionBools, retract_layer_change)) + ((ConfigOptionFloat, skirt_distance)) + ((ConfigOptionInt, skirt_height)) + ((ConfigOptionBool, draft_shield)) + ((ConfigOptionInt, skirts)) + ((ConfigOptionInts, slowdown_below_layer_time)) + ((ConfigOptionBool, spiral_vase)) + ((ConfigOptionInt, standby_temperature_delta)) + ((ConfigOptionInts, temperature)) + ((ConfigOptionInt, threads)) + ((ConfigOptionBools, wipe)) + ((ConfigOptionBool, wipe_tower)) + ((ConfigOptionFloat, wipe_tower_x)) + ((ConfigOptionFloat, wipe_tower_y)) + ((ConfigOptionFloat, wipe_tower_width)) + ((ConfigOptionFloat, wipe_tower_per_color_wipe)) + ((ConfigOptionFloat, wipe_tower_rotation_angle)) + ((ConfigOptionFloat, wipe_tower_brim_width)) + ((ConfigOptionFloat, wipe_tower_bridging)) + ((ConfigOptionFloats, wiping_volumes_matrix)) + ((ConfigOptionFloats, wiping_volumes_extruders)) + ((ConfigOptionFloat, z_offset)) +) // This object is mapped to Perl as Slic3r::Config::Full. -class FullPrintConfig : - public PrintObjectConfig, - public PrintRegionConfig, - public PrintConfig -{ - STATIC_PRINT_CONFIG_CACHE_DERIVED(FullPrintConfig) - FullPrintConfig() : PrintObjectConfig(0), PrintRegionConfig(0), PrintConfig(0) { initialize_cache(); *this = s_cache_FullPrintConfig.defaults(); } +PRINT_CONFIG_CLASS_DERIVED_DEFINE0( + FullPrintConfig, + (PrintObjectConfig, PrintRegionConfig, PrintConfig) +) -public: - // Validate the FullPrintConfig. Returns an empty string on success, otherwise an error message is returned. - std::string validate(); +// Validate the FullPrintConfig. Returns an empty string on success, otherwise an error message is returned. +std::string validate(const FullPrintConfig &config); -protected: - // Protected constructor to be called to initialize ConfigCache::m_default. - FullPrintConfig(int) : PrintObjectConfig(0), PrintRegionConfig(0), PrintConfig(0) {} - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - this->PrintObjectConfig::initialize(cache, base_ptr); - this->PrintRegionConfig::initialize(cache, base_ptr); - this->PrintConfig ::initialize(cache, base_ptr); - } -}; +PRINT_CONFIG_CLASS_DEFINE( + SLAPrintConfig, + ((ConfigOptionString, output_filename_format)) +) -// This object is mapped to Perl as Slic3r::Config::PrintRegion. -class SLAPrintConfig : public StaticPrintConfig -{ - STATIC_PRINT_CONFIG_CACHE(SLAPrintConfig) -public: - ConfigOptionString output_filename_format; +PRINT_CONFIG_CLASS_DEFINE( + SLAPrintObjectConfig, -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(output_filename_format); - } -}; - -class SLAPrintObjectConfig : public StaticPrintConfig -{ - STATIC_PRINT_CONFIG_CACHE(SLAPrintObjectConfig) -public: - ConfigOptionFloat layer_height; + ((ConfigOptionFloat, layer_height)) //Number of the layers needed for the exposure time fade [3;20] - ConfigOptionInt faded_layers /*= 10*/; + ((ConfigOptionInt, faded_layers))/*= 10*/ - ConfigOptionFloat slice_closing_radius; + ((ConfigOptionFloat, slice_closing_radius)) // Enabling or disabling support creation - ConfigOptionBool supports_enable; + ((ConfigOptionBool, supports_enable)) // Diameter in mm of the pointing side of the head. - ConfigOptionFloat support_head_front_diameter /*= 0.2*/; + ((ConfigOptionFloat, support_head_front_diameter))/*= 0.2*/ // How much the pinhead has to penetrate the model surface - ConfigOptionFloat support_head_penetration /*= 0.2*/; + ((ConfigOptionFloat, support_head_penetration))/*= 0.2*/ // Width in mm from the back sphere center to the front sphere center. - ConfigOptionFloat support_head_width /*= 1.0*/; + ((ConfigOptionFloat, support_head_width))/*= 1.0*/ // Radius in mm of the support pillars. - ConfigOptionFloat support_pillar_diameter /*= 0.8*/; + ((ConfigOptionFloat, support_pillar_diameter))/*= 0.8*/ // The percentage of smaller pillars compared to the normal pillar diameter // which are used in problematic areas where a normal pilla cannot fit. - ConfigOptionPercent support_small_pillar_diameter_percent; + ((ConfigOptionPercent, support_small_pillar_diameter_percent)) // How much bridge (supporting another pinhead) can be placed on a pillar. - ConfigOptionInt support_max_bridges_on_pillar; + ((ConfigOptionInt, support_max_bridges_on_pillar)) // How the pillars are bridged together - ConfigOptionEnum support_pillar_connection_mode; + ((ConfigOptionEnum, support_pillar_connection_mode)) // Generate only ground facing supports - ConfigOptionBool support_buildplate_only; + ((ConfigOptionBool, support_buildplate_only)) // TODO: unimplemented at the moment. This coefficient will have an impact // when bridges and pillars are merged. The resulting pillar should be a bit // thicker than the ones merging into it. How much thicker? I don't know // but it will be derived from this value. - ConfigOptionFloat support_pillar_widening_factor; + ((ConfigOptionFloat, support_pillar_widening_factor)) // Radius in mm of the pillar base. - ConfigOptionFloat support_base_diameter /*= 2.0*/; + ((ConfigOptionFloat, support_base_diameter))/*= 2.0*/ // The height of the pillar base cone in mm. - ConfigOptionFloat support_base_height /*= 1.0*/; + ((ConfigOptionFloat, support_base_height))/*= 1.0*/ // The minimum distance of the pillar base from the model in mm. - ConfigOptionFloat support_base_safety_distance; /*= 1.0*/ + ((ConfigOptionFloat, support_base_safety_distance)) /*= 1.0*/ // The default angle for connecting support sticks and junctions. - ConfigOptionFloat support_critical_angle /*= 45*/; + ((ConfigOptionFloat, support_critical_angle))/*= 45*/ // The max length of a bridge in mm - ConfigOptionFloat support_max_bridge_length /*= 15.0*/; + ((ConfigOptionFloat, support_max_bridge_length))/*= 15.0*/ // The max distance of two pillars to get cross linked. - ConfigOptionFloat support_max_pillar_link_distance; + ((ConfigOptionFloat, support_max_pillar_link_distance)) // The elevation in Z direction upwards. This is the space between the pad // and the model object's bounding box bottom. Units in mm. - ConfigOptionFloat support_object_elevation /*= 5.0*/; + ((ConfigOptionFloat, support_object_elevation))/*= 5.0*/ /////// Following options influence automatic support points placement: - ConfigOptionInt support_points_density_relative; - ConfigOptionFloat support_points_minimal_distance; + ((ConfigOptionInt, support_points_density_relative)) + ((ConfigOptionFloat, support_points_minimal_distance)) // Now for the base pool (pad) ///////////////////////////////////////////// // Enabling or disabling support creation - ConfigOptionBool pad_enable; + ((ConfigOptionBool, pad_enable)) // The thickness of the pad walls - ConfigOptionFloat pad_wall_thickness /*= 2*/; + ((ConfigOptionFloat, pad_wall_thickness))/*= 2*/ // The height of the pad from the bottom to the top not considering the pit - ConfigOptionFloat pad_wall_height /*= 5*/; + ((ConfigOptionFloat, pad_wall_height))/*= 5*/ // How far should the pad extend around the contained geometry - ConfigOptionFloat pad_brim_size; + ((ConfigOptionFloat, pad_brim_size)) // The greatest distance where two individual pads are merged into one. The // distance is measured roughly from the centroids of the pads. - ConfigOptionFloat pad_max_merge_distance /*= 50*/; + ((ConfigOptionFloat, pad_max_merge_distance))/*= 50*/ // The smoothing radius of the pad edges - // ConfigOptionFloat pad_edge_radius /*= 1*/; + // ((ConfigOptionFloat, pad_edge_radius))/*= 1*/; // The slope of the pad wall... - ConfigOptionFloat pad_wall_slope; + ((ConfigOptionFloat, pad_wall_slope)) // ///////////////////////////////////////////////////////////////////////// // Zero elevation mode parameters: @@ -1215,21 +843,21 @@ public: // ///////////////////////////////////////////////////////////////////////// // Disable the elevation (ignore its value) and use the zero elevation mode - ConfigOptionBool pad_around_object; + ((ConfigOptionBool, pad_around_object)) - ConfigOptionBool pad_around_object_everywhere; + ((ConfigOptionBool, pad_around_object_everywhere)) // This is the gap between the object bottom and the generated pad - ConfigOptionFloat pad_object_gap; + ((ConfigOptionFloat, pad_object_gap)) // How far to place the connector sticks on the object pad perimeter - ConfigOptionFloat pad_object_connector_stride; + ((ConfigOptionFloat, pad_object_connector_stride)) // The width of the connectors sticks - ConfigOptionFloat pad_object_connector_width; + ((ConfigOptionFloat, pad_object_connector_width)) // How much should the tiny connectors penetrate into the model body - ConfigOptionFloat pad_object_connector_penetration; + ((ConfigOptionFloat, pad_object_connector_penetration)) // ///////////////////////////////////////////////////////////////////////// // Model hollowing parameters: @@ -1240,169 +868,85 @@ public: // - resin removal. // ///////////////////////////////////////////////////////////////////////// - ConfigOptionBool hollowing_enable; + ((ConfigOptionBool, hollowing_enable)) // The minimum thickness of the model walls to maintain. Note that the // resulting walls may be thicker due to smoothing out fine cavities where // resin could stuck. - ConfigOptionFloat hollowing_min_thickness; + ((ConfigOptionFloat, hollowing_min_thickness)) // Indirectly controls the voxel size (resolution) used by openvdb - ConfigOptionFloat hollowing_quality; + ((ConfigOptionFloat, hollowing_quality)) // Indirectly controls the minimum size of created cavities. - ConfigOptionFloat hollowing_closing_distance; + ((ConfigOptionFloat, hollowing_closing_distance)) +) -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(layer_height); - OPT_PTR(faded_layers); - OPT_PTR(slice_closing_radius); - OPT_PTR(supports_enable); - OPT_PTR(support_head_front_diameter); - OPT_PTR(support_head_penetration); - OPT_PTR(support_head_width); - OPT_PTR(support_pillar_diameter); - OPT_PTR(support_small_pillar_diameter_percent); - OPT_PTR(support_max_bridges_on_pillar); - OPT_PTR(support_pillar_connection_mode); - OPT_PTR(support_buildplate_only); - OPT_PTR(support_pillar_widening_factor); - OPT_PTR(support_base_diameter); - OPT_PTR(support_base_height); - OPT_PTR(support_base_safety_distance); - OPT_PTR(support_critical_angle); - OPT_PTR(support_max_bridge_length); - OPT_PTR(support_max_pillar_link_distance); - OPT_PTR(support_points_density_relative); - OPT_PTR(support_points_minimal_distance); - OPT_PTR(support_object_elevation); - OPT_PTR(pad_enable); - OPT_PTR(pad_wall_thickness); - OPT_PTR(pad_wall_height); - OPT_PTR(pad_brim_size); - OPT_PTR(pad_max_merge_distance); - // OPT_PTR(pad_edge_radius); - OPT_PTR(pad_wall_slope); - OPT_PTR(pad_around_object); - OPT_PTR(pad_around_object_everywhere); - OPT_PTR(pad_object_gap); - OPT_PTR(pad_object_connector_stride); - OPT_PTR(pad_object_connector_width); - OPT_PTR(pad_object_connector_penetration); - OPT_PTR(hollowing_enable); - OPT_PTR(hollowing_min_thickness); - OPT_PTR(hollowing_quality); - OPT_PTR(hollowing_closing_distance); - } -}; +PRINT_CONFIG_CLASS_DEFINE( + SLAMaterialConfig, -class SLAMaterialConfig : public StaticPrintConfig -{ - STATIC_PRINT_CONFIG_CACHE(SLAMaterialConfig) -public: - ConfigOptionFloat initial_layer_height; - ConfigOptionFloat bottle_cost; - ConfigOptionFloat bottle_volume; - ConfigOptionFloat bottle_weight; - ConfigOptionFloat material_density; - ConfigOptionFloat exposure_time; - ConfigOptionFloat initial_exposure_time; - ConfigOptionFloats material_correction; -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(initial_layer_height); - OPT_PTR(bottle_cost); - OPT_PTR(bottle_volume); - OPT_PTR(bottle_weight); - OPT_PTR(material_density); - OPT_PTR(exposure_time); - OPT_PTR(initial_exposure_time); - OPT_PTR(material_correction); - } -}; + ((ConfigOptionFloat, initial_layer_height)) + ((ConfigOptionFloat, bottle_cost)) + ((ConfigOptionFloat, bottle_volume)) + ((ConfigOptionFloat, bottle_weight)) + ((ConfigOptionFloat, material_density)) + ((ConfigOptionFloat, exposure_time)) + ((ConfigOptionFloat, initial_exposure_time)) + ((ConfigOptionFloats, material_correction)) +) -class SLAPrinterConfig : public StaticPrintConfig -{ - STATIC_PRINT_CONFIG_CACHE(SLAPrinterConfig) -public: - ConfigOptionEnum printer_technology; - ConfigOptionPoints bed_shape; - ConfigOptionFloat max_print_height; - ConfigOptionFloat display_width; - ConfigOptionFloat display_height; - ConfigOptionInt display_pixels_x; - ConfigOptionInt display_pixels_y; - ConfigOptionEnum display_orientation; - ConfigOptionBool display_mirror_x; - ConfigOptionBool display_mirror_y; - ConfigOptionFloats relative_correction; - ConfigOptionFloat absolute_correction; - ConfigOptionFloat elefant_foot_compensation; - ConfigOptionFloat elefant_foot_min_width; - ConfigOptionFloat gamma_correction; - ConfigOptionFloat fast_tilt_time; - ConfigOptionFloat slow_tilt_time; - ConfigOptionFloat area_fill; - ConfigOptionFloat min_exposure_time; - ConfigOptionFloat max_exposure_time; - ConfigOptionFloat min_initial_exposure_time; - ConfigOptionFloat max_initial_exposure_time; -protected: - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - OPT_PTR(printer_technology); - OPT_PTR(bed_shape); - OPT_PTR(max_print_height); - OPT_PTR(display_width); - OPT_PTR(display_height); - OPT_PTR(display_pixels_x); - OPT_PTR(display_pixels_y); - OPT_PTR(display_mirror_x); - OPT_PTR(display_mirror_y); - OPT_PTR(display_orientation); - OPT_PTR(relative_correction); - OPT_PTR(absolute_correction); - OPT_PTR(elefant_foot_compensation); - OPT_PTR(elefant_foot_min_width); - OPT_PTR(gamma_correction); - OPT_PTR(fast_tilt_time); - OPT_PTR(slow_tilt_time); - OPT_PTR(area_fill); - OPT_PTR(min_exposure_time); - OPT_PTR(max_exposure_time); - OPT_PTR(min_initial_exposure_time); - OPT_PTR(max_initial_exposure_time); - } -}; +PRINT_CONFIG_CLASS_DEFINE( + SLAPrinterConfig, -class SLAFullPrintConfig : public SLAPrinterConfig, public SLAPrintConfig, public SLAPrintObjectConfig, public SLAMaterialConfig -{ - STATIC_PRINT_CONFIG_CACHE_DERIVED(SLAFullPrintConfig) - SLAFullPrintConfig() : SLAPrinterConfig(0), SLAPrintConfig(0), SLAPrintObjectConfig(0), SLAMaterialConfig(0) { initialize_cache(); *this = s_cache_SLAFullPrintConfig.defaults(); } + ((ConfigOptionEnum, printer_technology)) + ((ConfigOptionPoints, bed_shape)) + ((ConfigOptionFloat, max_print_height)) + ((ConfigOptionFloat, display_width)) + ((ConfigOptionFloat, display_height)) + ((ConfigOptionInt, display_pixels_x)) + ((ConfigOptionInt, display_pixels_y)) + ((ConfigOptionEnum,display_orientation)) + ((ConfigOptionBool, display_mirror_x)) + ((ConfigOptionBool, display_mirror_y)) + ((ConfigOptionFloats, relative_correction)) + ((ConfigOptionFloat, absolute_correction)) + ((ConfigOptionFloat, elefant_foot_compensation)) + ((ConfigOptionFloat, elefant_foot_min_width)) + ((ConfigOptionFloat, gamma_correction)) + ((ConfigOptionFloat, fast_tilt_time)) + ((ConfigOptionFloat, slow_tilt_time)) + ((ConfigOptionFloat, area_fill)) + ((ConfigOptionFloat, min_exposure_time)) + ((ConfigOptionFloat, max_exposure_time)) + ((ConfigOptionFloat, min_initial_exposure_time)) + ((ConfigOptionFloat, max_initial_exposure_time)) +) -public: - // Validate the SLAFullPrintConfig. Returns an empty string on success, otherwise an error message is returned. -// std::string validate(); - -protected: - // Protected constructor to be called to initialize ConfigCache::m_default. - SLAFullPrintConfig(int) : SLAPrinterConfig(0), SLAPrintConfig(0), SLAPrintObjectConfig(0), SLAMaterialConfig(0) {} - void initialize(StaticCacheBase &cache, const char *base_ptr) - { - this->SLAPrinterConfig ::initialize(cache, base_ptr); - this->SLAPrintConfig ::initialize(cache, base_ptr); - this->SLAPrintObjectConfig::initialize(cache, base_ptr); - this->SLAMaterialConfig ::initialize(cache, base_ptr); - } -}; +PRINT_CONFIG_CLASS_DERIVED_DEFINE0( + SLAFullPrintConfig, + (SLAPrinterConfig, SLAPrintConfig, SLAPrintObjectConfig, SLAMaterialConfig) +) #undef STATIC_PRINT_CONFIG_CACHE #undef STATIC_PRINT_CONFIG_CACHE_BASE #undef STATIC_PRINT_CONFIG_CACHE_DERIVED -#undef OPT_PTR +#undef PRINT_CONFIG_CLASS_ELEMENT_DEFINITION +#undef PRINT_CONFIG_CLASS_ELEMENT_EQUAL +#undef PRINT_CONFIG_CLASS_ELEMENT_HASH +#undef PRINT_CONFIG_CLASS_ELEMENT_INITIALIZATION +#undef PRINT_CONFIG_CLASS_ELEMENT_INITIALIZATION2 +#undef PRINT_CONFIG_CLASS_DEFINE +#undef PRINT_CONFIG_CLASS_DERIVED_CLASS_LIST +#undef PRINT_CONFIG_CLASS_DERIVED_CLASS_LIST_ITEM +#undef PRINT_CONFIG_CLASS_DERIVED_DEFINE +#undef PRINT_CONFIG_CLASS_DERIVED_DEFINE0 +#undef PRINT_CONFIG_CLASS_DERIVED_DEFINE1 +#undef PRINT_CONFIG_CLASS_DERIVED_HASH +#undef PRINT_CONFIG_CLASS_DERIVED_EQUAL +#undef PRINT_CONFIG_CLASS_DERIVED_INITCACHE_ITEM +#undef PRINT_CONFIG_CLASS_DERIVED_INITCACHE +#undef PRINT_CONFIG_CLASS_DERIVED_INITIALIZER +#undef PRINT_CONFIG_CLASS_DERIVED_INITIALIZER_ITEM class CLIActionsConfigDef : public ConfigDef { diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index ab39fbbde..46069849b 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -97,6 +97,15 @@ PrintBase::ApplyStatus PrintObject::set_instances(PrintInstances &&instances) return status; } +std::vector> PrintObject::all_regions() const +{ + std::vector> out; + out.reserve(m_all_regions.size()); + for (size_t i = 0; i < m_all_regions.size(); ++ i) + out.emplace_back(*m_all_regions[i]); + return out; +} + // Called by make_perimeters() // 1) Decides Z positions of the layers, // 2) Initializes layers and their regions @@ -173,8 +182,8 @@ void PrintObject::make_perimeters() // but we don't generate any extra perimeter if fill density is zero, as they would be floating // inside the object - infill_only_where_needed should be the method of choice for printing // hollow objects - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { - const PrintRegion ®ion = *m_print->regions()[region_id]; + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { + const PrintRegion ®ion = this->printing_region(region_id); if (! region.config().extra_perimeters || region.config().perimeters == 0 || region.config().fill_density == 0 || this->layer_count() < 2) continue; @@ -186,7 +195,7 @@ void PrintObject::make_perimeters() m_print->throw_if_canceled(); LayerRegion &layerm = *m_layers[layer_idx]->m_regions[region_id]; const LayerRegion &upper_layerm = *m_layers[layer_idx+1]->m_regions[region_id]; - const Polygons upper_layerm_polygons = upper_layerm.slices; + const Polygons upper_layerm_polygons = to_polygons(upper_layerm.slices.surfaces); // Filter upper layer polygons in intersection_ppl by their bounding boxes? // my $upper_layerm_poly_bboxes= [ map $_->bounding_box, @{$upper_layerm_polygons} ]; const double total_loop_length = total_length(upper_layerm_polygons); @@ -294,7 +303,7 @@ void PrintObject::prepare_infill() // Debugging output. #ifdef SLIC3R_DEBUG_SLICE_PROCESSING - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { for (const Layer *layer : m_layers) { LayerRegion *layerm = layer->m_regions[region_id]; layerm->export_region_slices_to_svg_debug("6_discover_vertical_shells-final"); @@ -313,7 +322,7 @@ void PrintObject::prepare_infill() m_print->throw_if_canceled(); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { for (const Layer *layer : m_layers) { LayerRegion *layerm = layer->m_regions[region_id]; layerm->export_region_slices_to_svg_debug("7_discover_horizontal_shells-final"); @@ -332,7 +341,7 @@ void PrintObject::prepare_infill() m_print->throw_if_canceled(); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { for (const Layer *layer : m_layers) { LayerRegion *layerm = layer->m_regions[region_id]; layerm->export_region_slices_to_svg_debug("8_clip_surfaces-final"); @@ -351,7 +360,7 @@ void PrintObject::prepare_infill() m_print->throw_if_canceled(); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { for (const Layer *layer : m_layers) { LayerRegion *layerm = layer->m_regions[region_id]; layerm->export_region_slices_to_svg_debug("9_prepare_infill-final"); @@ -716,10 +725,10 @@ bool PrintObject::invalidate_step(PrintObjectStep step) } else if (step == posSlice) { invalidated |= this->invalidate_steps({ posPerimeters, posPrepareInfill, posInfill, posIroning, posSupportMaterial }); invalidated |= m_print->invalidate_steps({ psSkirt, psBrim }); - this->m_slicing_params.valid = false; + m_slicing_params.valid = false; } else if (step == posSupportMaterial) { invalidated |= m_print->invalidate_steps({ psSkirt, psBrim }); - this->m_slicing_params.valid = false; + m_slicing_params.valid = false; } // Wipe tower depends on the ordering of extruders, which in turn depends on everything. @@ -736,19 +745,11 @@ bool PrintObject::invalidate_all_steps() // First call the "invalidate" functions, which may cancel background processing. bool result = Inherited::invalidate_all_steps() | m_print->invalidate_all_steps(); // Then reset some of the depending values. - this->m_slicing_params.valid = false; - this->region_volumes.clear(); + m_slicing_params.valid = false; + m_region_volumes.clear(); return result; } -static const PrintRegion* first_printing_region(const PrintObject &print_object) -{ - for (size_t idx_region = 0; idx_region < print_object.region_volumes.size(); ++ idx_region) - if (!print_object.region_volumes.empty()) - return print_object.print()->regions()[idx_region]; - return nullptr; -} - // This function analyzes slices of a region (SurfaceCollection slices). // Each region slice (instance of Surface) is analyzed, whether it is supported or whether it is the top surface. // Initially all slices are of type stInternal. @@ -769,13 +770,13 @@ void PrintObject::detect_surfaces_type() // should be visible. bool spiral_vase = this->print()->config().spiral_vase.value; bool interface_shells = ! spiral_vase && m_config.interface_shells.value; - size_t num_layers = spiral_vase ? std::min(size_t(first_printing_region(*this)->config().bottom_solid_layers), m_layers.size()) : m_layers.size(); + size_t num_layers = spiral_vase ? std::min(size_t(this->printing_region(0).config().bottom_solid_layers), m_layers.size()) : m_layers.size(); - for (size_t idx_region = 0; idx_region < this->region_volumes.size(); ++ idx_region) { - BOOST_LOG_TRIVIAL(debug) << "Detecting solid surfaces for region " << idx_region << " in parallel - start"; + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { + BOOST_LOG_TRIVIAL(debug) << "Detecting solid surfaces for region " << region_id << " in parallel - start"; #ifdef SLIC3R_DEBUG_SLICE_PROCESSING for (Layer *layer : m_layers) - layer->m_regions[idx_region]->export_region_fill_surfaces_to_svg_debug("1_detect_surfaces_type-initial"); + layer->m_regions[region_id]->export_region_fill_surfaces_to_svg_debug("1_detect_surfaces_type-initial"); #endif /* SLIC3R_DEBUG_SLICE_PROCESSING */ // If interface shells are allowed, the region->surfaces cannot be overwritten as they may be used by other threads. @@ -791,7 +792,7 @@ void PrintObject::detect_surfaces_type() ((num_layers > 1) ? num_layers - 1 : num_layers) : // In non-spiral vase mode, go over all layers. m_layers.size()), - [this, idx_region, interface_shells, &surfaces_new](const tbb::blocked_range& range) { + [this, region_id, interface_shells, &surfaces_new](const tbb::blocked_range& range) { // If we have soluble support material, don't bridge. The overhang will be squished against a soluble layer separating // the support from the print. SurfaceType surface_type_bottom_other = @@ -799,9 +800,9 @@ void PrintObject::detect_surfaces_type() stBottom : stBottomBridge; for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++ idx_layer) { m_print->throw_if_canceled(); - // BOOST_LOG_TRIVIAL(trace) << "Detecting solid surfaces for region " << idx_region << " and layer " << layer->print_z; + // BOOST_LOG_TRIVIAL(trace) << "Detecting solid surfaces for region " << region_id << " and layer " << layer->print_z; Layer *layer = m_layers[idx_layer]; - LayerRegion *layerm = layer->m_regions[idx_region]; + LayerRegion *layerm = layer->m_regions[region_id]; // comparison happens against the *full* slices (considering all regions) // unless internal shells are requested Layer *upper_layer = (idx_layer + 1 < this->layer_count()) ? m_layers[idx_layer + 1] : nullptr; @@ -809,19 +810,14 @@ void PrintObject::detect_surfaces_type() // collapse very narrow parts (using the safety offset in the diff is not enough) float offset = layerm->flow(frExternalPerimeter).scaled_width() / 10.f; - Polygons layerm_slices_surfaces = to_polygons(layerm->slices.surfaces); - // find top surfaces (difference between current surfaces // of current layer and upper one) Surfaces top; if (upper_layer) { - Polygons upper_slices = interface_shells ? - to_polygons(upper_layer->m_regions[idx_region]->slices.surfaces) : - to_polygons(upper_layer->lslices); - surfaces_append(top, - //FIXME implement offset2_ex working over ExPolygons, that should be a bit more efficient than calling offset_ex twice. - offset_ex(offset_ex(diff_ex(layerm_slices_surfaces, upper_slices, true), -offset), offset), - stTop); + ExPolygons upper_slices = interface_shells ? + diff_ex(layerm->slices.surfaces, upper_layer->m_regions[region_id]->slices.surfaces, ApplySafetyOffset::Yes) : + diff_ex(layerm->slices.surfaces, upper_layer->lslices, ApplySafetyOffset::Yes); + surfaces_append(top, offset2_ex(upper_slices, -offset, offset), stTop); } else { // if no upper layer, all surfaces of this one are solid // we clone surfaces because we're going to clear the slices collection @@ -836,17 +832,17 @@ void PrintObject::detect_surfaces_type() #if 0 //FIXME Why is this branch failing t\multi.t ? Polygons lower_slices = interface_shells ? - to_polygons(lower_layer->get_region(idx_region)->slices.surfaces) : + to_polygons(lower_layer->get_region(region_id)->slices.surfaces) : to_polygons(lower_layer->slices); surfaces_append(bottom, - offset2_ex(diff(layerm_slices_surfaces, lower_slices, true), -offset, offset), + offset2_ex(diff(layerm->slices.surfaces, lower_slices, true), -offset, offset), surface_type_bottom_other); #else // Any surface lying on the void is a true bottom bridge (an overhang) surfaces_append( bottom, offset2_ex( - diff(layerm_slices_surfaces, to_polygons(lower_layer->lslices), true), + diff_ex(layerm->slices.surfaces, lower_layer->lslices, ApplySafetyOffset::Yes), -offset, offset), surface_type_bottom_other); // if user requested internal shells, we need to identify surfaces @@ -857,10 +853,10 @@ void PrintObject::detect_surfaces_type() surfaces_append( bottom, offset2_ex( - diff( - intersection(layerm_slices_surfaces, to_polygons(lower_layer->lslices)), // supported - to_polygons(lower_layer->m_regions[idx_region]->slices.surfaces), - true), + diff_ex( + intersection(layerm->slices.surfaces, lower_layer->lslices), // supported + lower_layer->m_regions[region_id]->slices.surfaces, + ApplySafetyOffset::Yes), -offset, offset), stBottom); } @@ -882,9 +878,7 @@ void PrintObject::detect_surfaces_type() // if $Slic3r::debug; Polygons top_polygons = to_polygons(std::move(top)); top.clear(); - surfaces_append(top, - diff_ex(top_polygons, to_polygons(bottom), false), - stTop); + surfaces_append(top, diff_ex(top_polygons, bottom), stTop); } #ifdef SLIC3R_DEBUG_SLICE_PROCESSING @@ -894,21 +888,24 @@ void PrintObject::detect_surfaces_type() expolygons_with_attributes.emplace_back(std::make_pair(union_ex(top), SVG::ExPolygonAttributes("green"))); expolygons_with_attributes.emplace_back(std::make_pair(union_ex(bottom), SVG::ExPolygonAttributes("brown"))); expolygons_with_attributes.emplace_back(std::make_pair(to_expolygons(layerm->slices.surfaces), SVG::ExPolygonAttributes("black"))); - SVG::export_expolygons(debug_out_path("1_detect_surfaces_type_%d_region%d-layer_%f.svg", iRun ++, idx_region, layer->print_z).c_str(), expolygons_with_attributes); + SVG::export_expolygons(debug_out_path("1_detect_surfaces_type_%d_region%d-layer_%f.svg", iRun ++, region_id, layer->print_z).c_str(), expolygons_with_attributes); } #endif /* SLIC3R_DEBUG_SLICE_PROCESSING */ // save surfaces to layer Surfaces &surfaces_out = interface_shells ? surfaces_new[idx_layer] : layerm->slices.surfaces; - surfaces_out.clear(); + Surfaces surfaces_backup; + if (! interface_shells) { + surfaces_backup = std::move(surfaces_out); + surfaces_out.clear(); + } + const Surfaces &surfaces_prev = interface_shells ? layerm->slices.surfaces : surfaces_backup; // find internal surfaces (difference between top/bottom surfaces and others) { Polygons topbottom = to_polygons(top); polygons_append(topbottom, to_polygons(bottom)); - surfaces_append(surfaces_out, - diff_ex(layerm_slices_surfaces, topbottom, false), - stInternal); + surfaces_append(surfaces_out, diff_ex(surfaces_prev, topbottom), stInternal); } surfaces_append(surfaces_out, std::move(top)); @@ -928,25 +925,25 @@ void PrintObject::detect_surfaces_type() if (interface_shells) { // Move surfaces_new to layerm->slices.surfaces for (size_t idx_layer = 0; idx_layer < num_layers; ++ idx_layer) - m_layers[idx_layer]->m_regions[idx_region]->slices.surfaces = std::move(surfaces_new[idx_layer]); + m_layers[idx_layer]->m_regions[region_id]->slices.surfaces = std::move(surfaces_new[idx_layer]); } if (spiral_vase) { if (num_layers > 1) // Turn the last bottom layer infill to a top infill, so it will be extruded with a proper pattern. - m_layers[num_layers - 1]->m_regions[idx_region]->slices.set_type(stTop); + m_layers[num_layers - 1]->m_regions[region_id]->slices.set_type(stTop); for (size_t i = num_layers; i < m_layers.size(); ++ i) - m_layers[i]->m_regions[idx_region]->slices.set_type(stInternal); + m_layers[i]->m_regions[region_id]->slices.set_type(stInternal); } - BOOST_LOG_TRIVIAL(debug) << "Detecting solid surfaces for region " << idx_region << " - clipping in parallel - start"; + BOOST_LOG_TRIVIAL(debug) << "Detecting solid surfaces for region " << region_id << " - clipping in parallel - start"; // Fill in layerm->fill_surfaces by trimming the layerm->slices by the cummulative layerm->fill_surfaces. tbb::parallel_for( tbb::blocked_range(0, m_layers.size()), - [this, idx_region](const tbb::blocked_range& range) { + [this, region_id](const tbb::blocked_range& range) { for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++ idx_layer) { m_print->throw_if_canceled(); - LayerRegion *layerm = m_layers[idx_layer]->m_regions[idx_region]; + LayerRegion *layerm = m_layers[idx_layer]->m_regions[region_id]; layerm->slices_to_fill_surfaces_clipped(); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING layerm->export_region_fill_surfaces_to_svg_debug("1_detect_surfaces_type-final"); @@ -954,7 +951,7 @@ void PrintObject::detect_surfaces_type() } // for each layer of a region }); m_print->throw_if_canceled(); - BOOST_LOG_TRIVIAL(debug) << "Detecting solid surfaces for region " << idx_region << " - clipping in parallel - end"; + BOOST_LOG_TRIVIAL(debug) << "Detecting solid surfaces for region " << region_id << " - clipping in parallel - end"; } // for each this->print->region_count // Mark the object to have the region slices classified (typed, which also means they are split based on whether they are supported, bridging, top layers etc.) @@ -970,8 +967,8 @@ void PrintObject::process_external_surfaces() // Is there any printing region, that has zero infill? If so, then we don't want the expansion to be performed over the complete voids, but only // over voids, which are supported by the layer below. bool has_voids = false; - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) - if (! this->region_volumes.empty() && this->print()->regions()[region_id]->config().fill_density == 0) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) + if (this->printing_region(region_id).config().fill_density == 0) { has_voids = true; break; } @@ -1007,12 +1004,12 @@ void PrintObject::process_external_surfaces() m_print->throw_if_canceled(); Polygons voids; for (const LayerRegion *layerm : m_layers[layer_idx]->regions()) { - if (layerm->region()->config().fill_density.value == 0.) + if (layerm->region().config().fill_density.value == 0.) for (const Surface &surface : layerm->fill_surfaces.surfaces) // Shrink the holes, let the layer above expand slightly inside the unsupported areas. polygons_append(voids, offset(surface.expolygon, unsupported_width)); } - surfaces_covered[layer_idx] = diff(to_polygons(this->m_layers[layer_idx]->lslices), voids); + surfaces_covered[layer_idx] = diff(m_layers[layer_idx]->lslices, voids); } } ); @@ -1020,7 +1017,7 @@ void PrintObject::process_external_surfaces() BOOST_LOG_TRIVIAL(debug) << "Collecting surfaces covered with extrusions in parallel - end"; } - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++region_id) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++region_id) { BOOST_LOG_TRIVIAL(debug) << "Processing external surfaces for region " << region_id << " in parallel - start"; tbb::parallel_for( tbb::blocked_range(0, m_layers.size()), @@ -1028,7 +1025,7 @@ void PrintObject::process_external_surfaces() for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { m_print->throw_if_canceled(); // BOOST_LOG_TRIVIAL(trace) << "Processing external surface, layer" << m_layers[layer_idx]->print_z; - m_layers[layer_idx]->get_region((int)region_id)->process_external_surfaces( + m_layers[layer_idx]->get_region(int(region_id))->process_external_surfaces( (layer_idx == 0) ? nullptr : m_layers[layer_idx - 1], (layer_idx == 0 || surfaces_covered.empty() || surfaces_covered[layer_idx - 1].empty()) ? nullptr : &surfaces_covered[layer_idx - 1]); } @@ -1053,7 +1050,7 @@ void PrintObject::discover_vertical_shells() Polygons holes; }; bool spiral_vase = this->print()->config().spiral_vase.value; - size_t num_layers = spiral_vase ? std::min(size_t(first_printing_region(*this)->config().bottom_solid_layers), m_layers.size()) : m_layers.size(); + size_t num_layers = spiral_vase ? std::min(size_t(this->printing_region(0).config().bottom_solid_layers), m_layers.size()) : m_layers.size(); coordf_t min_layer_height = this->slicing_parameters().min_layer_height; // Does this region possibly produce more than 1 top or bottom layer? auto has_extra_layers_fn = [min_layer_height](const PrintRegionConfig &config) { @@ -1068,14 +1065,14 @@ void PrintObject::discover_vertical_shells() num_extra_layers(config.bottom_solid_layers, config.bottom_solid_min_thickness) > 0; }; std::vector cache_top_botom_regions(num_layers, DiscoverVerticalShellsCacheEntry()); - bool top_bottom_surfaces_all_regions = this->region_volumes.size() > 1 && ! m_config.interface_shells.value; + bool top_bottom_surfaces_all_regions = this->num_printing_regions() > 1 && ! m_config.interface_shells.value; if (top_bottom_surfaces_all_regions) { // This is a multi-material print and interface_shells are disabled, meaning that the vertical shell thickness // is calculated over all materials. // Is the "ensure vertical wall thickness" applicable to any region? bool has_extra_layers = false; - for (size_t idx_region = 0; idx_region < this->region_volumes.size(); ++idx_region) { - const PrintRegionConfig &config = m_print->get_region(idx_region)->config(); + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++region_id) { + const PrintRegionConfig &config = this->printing_region(region_id).config(); if (config.ensure_vertical_shell_thickness.value && has_extra_layers_fn(config)) { has_extra_layers = true; break; @@ -1091,7 +1088,7 @@ void PrintObject::discover_vertical_shells() tbb::blocked_range(0, num_layers, grain_size), [this, &cache_top_botom_regions](const tbb::blocked_range& range) { const SurfaceType surfaces_bottom[2] = { stBottom, stBottomBridge }; - const size_t num_regions = this->region_volumes.size(); + const size_t num_regions = this->num_printing_regions(); for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++ idx_layer) { m_print->throw_if_canceled(); const Layer &layer = *m_layers[idx_layer]; @@ -1103,21 +1100,21 @@ void PrintObject::discover_vertical_shells() static size_t debug_idx = 0; ++ debug_idx; #endif /* SLIC3R_DEBUG_SLICE_PROCESSING */ - for (size_t idx_region = 0; idx_region < num_regions; ++ idx_region) { - LayerRegion &layerm = *layer.m_regions[idx_region]; + for (size_t region_id = 0; region_id < num_regions; ++ region_id) { + LayerRegion &layerm = *layer.m_regions[region_id]; float min_perimeter_infill_spacing = float(layerm.flow(frSolidInfill).scaled_spacing()) * 1.05f; // Top surfaces. - append(cache.top_surfaces, offset(to_expolygons(layerm.slices.filter_by_type(stTop)), min_perimeter_infill_spacing)); - append(cache.top_surfaces, offset(to_expolygons(layerm.fill_surfaces.filter_by_type(stTop)), min_perimeter_infill_spacing)); + append(cache.top_surfaces, offset(layerm.slices.filter_by_type(stTop), min_perimeter_infill_spacing)); + append(cache.top_surfaces, offset(layerm.fill_surfaces.filter_by_type(stTop), min_perimeter_infill_spacing)); // Bottom surfaces. - append(cache.bottom_surfaces, offset(to_expolygons(layerm.slices.filter_by_types(surfaces_bottom, 2)), min_perimeter_infill_spacing)); - append(cache.bottom_surfaces, offset(to_expolygons(layerm.fill_surfaces.filter_by_types(surfaces_bottom, 2)), min_perimeter_infill_spacing)); + append(cache.bottom_surfaces, offset(layerm.slices.filter_by_types(surfaces_bottom, 2), min_perimeter_infill_spacing)); + append(cache.bottom_surfaces, offset(layerm.fill_surfaces.filter_by_types(surfaces_bottom, 2), min_perimeter_infill_spacing)); // Calculate the maximum perimeter offset as if the slice was extruded with a single extruder only. // First find the maxium number of perimeters per region slice. unsigned int perimeters = 0; for (Surface &s : layerm.slices.surfaces) perimeters = std::max(perimeters, s.extra_perimeters); - perimeters += layerm.region()->config().perimeters.value; + perimeters += layerm.region().config().perimeters.value; // Then calculate the infill offset. if (perimeters > 0) { Flow extflow = layerm.flow(frExternalPerimeter); @@ -1129,8 +1126,8 @@ void PrintObject::discover_vertical_shells() polygons_append(cache.holes, to_polygons(layerm.fill_expolygons)); } // Save some computing time by reducing the number of polygons. - cache.top_surfaces = union_(cache.top_surfaces, false); - cache.bottom_surfaces = union_(cache.bottom_surfaces, false); + cache.top_surfaces = union_(cache.top_surfaces); + cache.bottom_surfaces = union_(cache.bottom_surfaces); // For a multi-material print, simulate perimeter / infill split as if only a single extruder has been used for the whole print. if (perimeter_offset > 0.) { // The layer.lslices are forced to merge by expanding them first. @@ -1145,17 +1142,17 @@ void PrintObject::discover_vertical_shells() } #endif /* SLIC3R_DEBUG_SLICE_PROCESSING */ } - cache.holes = union_(cache.holes, false); + cache.holes = union_(cache.holes); } }); m_print->throw_if_canceled(); BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells in parallel - end : cache top / bottom"; } - for (size_t idx_region = 0; idx_region < this->region_volumes.size(); ++ idx_region) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { PROFILE_BLOCK(discover_vertical_shells_region); - const PrintRegion ®ion = *m_print->get_region(idx_region); + const PrintRegion ®ion = this->printing_region(region_id); if (! region.config().ensure_vertical_shell_thickness.value) // This region will be handled by discover_horizontal_shells(). continue; @@ -1169,38 +1166,38 @@ void PrintObject::discover_vertical_shells() if (! top_bottom_surfaces_all_regions) { // This is either a single material print, or a multi-material print and interface_shells are enabled, meaning that the vertical shell thickness // is calculated over a single material. - BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << idx_region << " in parallel - start : cache top / bottom"; + BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << region_id << " in parallel - start : cache top / bottom"; tbb::parallel_for( tbb::blocked_range(0, num_layers, grain_size), - [this, idx_region, &cache_top_botom_regions](const tbb::blocked_range& range) { + [this, region_id, &cache_top_botom_regions](const tbb::blocked_range& range) { const SurfaceType surfaces_bottom[2] = { stBottom, stBottomBridge }; for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++ idx_layer) { m_print->throw_if_canceled(); Layer &layer = *m_layers[idx_layer]; - LayerRegion &layerm = *layer.m_regions[idx_region]; + LayerRegion &layerm = *layer.m_regions[region_id]; float min_perimeter_infill_spacing = float(layerm.flow(frSolidInfill).scaled_spacing()) * 1.05f; // Top surfaces. auto &cache = cache_top_botom_regions[idx_layer]; - cache.top_surfaces = offset(to_expolygons(layerm.slices.filter_by_type(stTop)), min_perimeter_infill_spacing); - append(cache.top_surfaces, offset(to_expolygons(layerm.fill_surfaces.filter_by_type(stTop)), min_perimeter_infill_spacing)); + cache.top_surfaces = offset(layerm.slices.filter_by_type(stTop), min_perimeter_infill_spacing); + append(cache.top_surfaces, offset(layerm.fill_surfaces.filter_by_type(stTop), min_perimeter_infill_spacing)); // Bottom surfaces. - cache.bottom_surfaces = offset(to_expolygons(layerm.slices.filter_by_types(surfaces_bottom, 2)), min_perimeter_infill_spacing); - append(cache.bottom_surfaces, offset(to_expolygons(layerm.fill_surfaces.filter_by_types(surfaces_bottom, 2)), min_perimeter_infill_spacing)); - // Holes over all regions. Only collect them once, they are valid for all idx_region iterations. + cache.bottom_surfaces = offset(layerm.slices.filter_by_types(surfaces_bottom, 2), min_perimeter_infill_spacing); + append(cache.bottom_surfaces, offset(layerm.fill_surfaces.filter_by_types(surfaces_bottom, 2), min_perimeter_infill_spacing)); + // Holes over all regions. Only collect them once, they are valid for all region_id iterations. if (cache.holes.empty()) { - for (size_t idx_region = 0; idx_region < layer.regions().size(); ++ idx_region) - polygons_append(cache.holes, to_polygons(layer.regions()[idx_region]->fill_expolygons)); + for (size_t region_id = 0; region_id < layer.regions().size(); ++ region_id) + polygons_append(cache.holes, to_polygons(layer.regions()[region_id]->fill_expolygons)); } } }); m_print->throw_if_canceled(); - BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << idx_region << " in parallel - end : cache top / bottom"; + BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << region_id << " in parallel - end : cache top / bottom"; } - BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << idx_region << " in parallel - start : ensure vertical wall thickness"; + BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << region_id << " in parallel - start : ensure vertical wall thickness"; tbb::parallel_for( tbb::blocked_range(0, num_layers, grain_size), - [this, idx_region, &cache_top_botom_regions] + [this, region_id, &cache_top_botom_regions] (const tbb::blocked_range& range) { // printf("discover_vertical_shells from %d to %d\n", range.begin(), range.end()); for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++ idx_layer) { @@ -1212,8 +1209,8 @@ void PrintObject::discover_vertical_shells() #endif /* SLIC3R_DEBUG_SLICE_PROCESSING */ Layer *layer = m_layers[idx_layer]; - LayerRegion *layerm = layer->m_regions[idx_region]; - const PrintRegionConfig ®ion_config = layerm->region()->config(); + LayerRegion *layerm = layer->m_regions[region_id]; + const PrintRegionConfig ®ion_config = layerm->region().config(); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING layerm->export_region_slices_to_svg_debug("4_discover_vertical_shells-initial"); @@ -1269,7 +1266,7 @@ void PrintObject::discover_vertical_shells() polygons_append(shell, cache.top_surfaces); // Running the union_ using the Clipper library piece by piece is cheaper // than running the union_ all at once. - shell = union_(shell, false); + shell = union_(shell); } } } @@ -1288,7 +1285,7 @@ void PrintObject::discover_vertical_shells() polygons_append(shell, cache.bottom_surfaces); // Running the union_ using the Clipper library piece by piece is cheaper // than running the union_ all at once. - shell = union_(shell, false); + shell = union_(shell); } } } @@ -1308,7 +1305,7 @@ void PrintObject::discover_vertical_shells() } #endif #ifdef SLIC3R_DEBUG_SLICE_PROCESSING - shell_ex = union_ex(shell, true); + shell_ex = union_safety_offset_ex(shell); #endif /* SLIC3R_DEBUG_SLICE_PROCESSING */ } @@ -1354,7 +1351,7 @@ void PrintObject::discover_vertical_shells() // Trim the shells region by the internal & internal void surfaces. const SurfaceType surfaceTypesInternal[] = { stInternal, stInternalVoid, stInternalSolid }; const Polygons polygonsInternal = to_polygons(layerm->fill_surfaces.filter_by_types(surfaceTypesInternal, 3)); - shell = intersection(shell, polygonsInternal, true); + shell = intersection(shell, polygonsInternal, ApplySafetyOffset::Yes); polygons_append(shell, diff(polygonsInternal, holes)); if (shell.empty()) continue; @@ -1392,14 +1389,14 @@ void PrintObject::discover_vertical_shells() polygons_append(shell, intersection(offset(too_narrow, margin), polygonsInternal)); } #endif - ExPolygons new_internal_solid = intersection_ex(polygonsInternal, shell, false); + ExPolygons new_internal_solid = intersection_ex(polygonsInternal, shell); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING { Slic3r::SVG svg(debug_out_path("discover_vertical_shells-regularized-%d.svg", debug_idx), get_extents(shell_before)); // Source shell. - svg.draw(union_ex(shell_before, true)); + svg.draw(union_safety_offset_ex(shell_before)); // Shell trimmed to the internal surfaces. - svg.draw_outline(union_ex(shell, true), "black", "blue", scale_(0.05)); + svg.draw_outline(union_safety_offset_ex(shell), "black", "blue", scale_(0.05)); // Regularized infill region. svg.draw_outline(new_internal_solid, "red", "magenta", scale_(0.05)); svg.Close(); @@ -1407,16 +1404,8 @@ void PrintObject::discover_vertical_shells() #endif /* SLIC3R_DEBUG_SLICE_PROCESSING */ // Trim the internal & internalvoid by the shell. - Slic3r::ExPolygons new_internal = diff_ex( - to_polygons(layerm->fill_surfaces.filter_by_type(stInternal)), - shell, - false - ); - Slic3r::ExPolygons new_internal_void = diff_ex( - to_polygons(layerm->fill_surfaces.filter_by_type(stInternalVoid)), - shell, - false - ); + Slic3r::ExPolygons new_internal = diff_ex(layerm->fill_surfaces.filter_by_type(stInternal), shell); + Slic3r::ExPolygons new_internal_void = diff_ex(layerm->fill_surfaces.filter_by_type(stInternalVoid), shell); #ifdef SLIC3R_DEBUG_SLICE_PROCESSING { @@ -1435,11 +1424,11 @@ void PrintObject::discover_vertical_shells() } // for each layer }); m_print->throw_if_canceled(); - BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << idx_region << " in parallel - end"; + BOOST_LOG_TRIVIAL(debug) << "Discovering vertical shells for region " << region_id << " in parallel - end"; #ifdef SLIC3R_DEBUG_SLICE_PROCESSING for (size_t idx_layer = 0; idx_layer < m_layers.size(); ++idx_layer) { - LayerRegion *layerm = m_layers[idx_layer]->get_region(idx_region); + LayerRegion *layerm = m_layers[idx_layer]->get_region(region_id); layerm->export_region_slices_to_svg_debug("4_discover_vertical_shells-final"); layerm->export_region_fill_surfaces_to_svg_debug("4_discover_vertical_shells-final"); } @@ -1457,8 +1446,8 @@ void PrintObject::bridge_over_infill() { BOOST_LOG_TRIVIAL(info) << "Bridge over infill..." << log_memory_info(); - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { - const PrintRegion ®ion = *m_print->regions()[region_id]; + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { + const PrintRegion ®ion = this->printing_region(region_id); // skip bridging in case there are no voids if (region.config().fill_density.value == 100) @@ -1521,8 +1510,8 @@ void PrintObject::bridge_over_infill() #endif // compute the remaning internal solid surfaces as difference - ExPolygons not_to_bridge = diff_ex(internal_solid, to_polygons(to_bridge), true); - to_bridge = intersection_ex(to_polygons(to_bridge), internal_solid, true); + ExPolygons not_to_bridge = diff_ex(internal_solid, to_bridge, ApplySafetyOffset::Yes); + to_bridge = intersection_ex(to_bridge, internal_solid, ApplySafetyOffset::Yes); // build the new collection of fill_surfaces layerm->fill_surfaces.remove_type(stInternalSolid); for (ExPolygon &ex : to_bridge) @@ -1680,6 +1669,7 @@ SlicingParameters PrintObject::slicing_parameters(const DynamicPrintConfig& full object_extruders); } sort_remove_duplicates(object_extruders); + //FIXME add painting extruders if (object_max_z <= 0.f) object_max_z = (float)model_object.raw_bounding_box().size().z(); @@ -1690,10 +1680,9 @@ SlicingParameters PrintObject::slicing_parameters(const DynamicPrintConfig& full std::vector PrintObject::object_extruders() const { std::vector extruders; - extruders.reserve(this->region_volumes.size() * 3); - for (size_t idx_region = 0; idx_region < this->region_volumes.size(); ++ idx_region) - if (! this->region_volumes[idx_region].empty()) - m_print->get_region(idx_region)->collect_object_printing_extruders(extruders); + extruders.reserve(this->all_regions().size() * 3); + for (const PrintRegion ®ion : this->all_regions()) + region.collect_object_printing_extruders(*this->print(), extruders); sort_remove_duplicates(extruders); return extruders; } @@ -1771,8 +1760,8 @@ void PrintObject::_slice(const std::vector &layer_height_profile) layer->lower_layer = prev; } // Make sure all layers contain layer region objects for all regions. - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) - layer->add_region(this->print()->get_region(region_id)); + for (size_t region_id = 0; region_id < m_region_volumes.size(); ++ region_id) + layer->add_region(&this->printing_region(region_id)); prev = layer; } } @@ -1782,16 +1771,15 @@ void PrintObject::_slice(const std::vector &layer_height_profile) bool has_z_ranges = false; size_t num_volumes = 0; size_t num_modifiers = 0; - for (int region_id = 0; region_id < (int)this->region_volumes.size(); ++ region_id) { + for (int region_id = 0; region_id < int(m_region_volumes.size()); ++ region_id) { int last_volume_id = -1; - for (const std::pair &volume_and_range : this->region_volumes[region_id]) { - const int volume_id = volume_and_range.second; - const ModelVolume *model_volume = this->model_object()->volumes[volume_id]; + for (const PrintRegionVolumes::VolumeWithZRange &volume_w_zrange : m_region_volumes[region_id].volumes) { + const ModelVolume *model_volume = this->model_object()->volumes[volume_w_zrange.volume_idx]; if (model_volume->is_model_part()) { - if (last_volume_id == volume_id) { + if (last_volume_id == volume_w_zrange.volume_idx) { has_z_ranges = true; } else { - last_volume_id = volume_id; + last_volume_id = volume_w_zrange.volume_idx; if (all_volumes_single_region == -2) // first model volume met all_volumes_single_region = region_id; @@ -1814,14 +1802,14 @@ void PrintObject::_slice(const std::vector &layer_height_profile) if (! has_z_ranges && (! m_config.clip_multipart_objects.value || all_volumes_single_region >= 0)) { // Cheap path: Slice regions without mutual clipping. // The cheap path is possible if no clipping is allowed or if slicing volumes of just a single region. - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + for (size_t region_id = 0; region_id < m_region_volumes.size(); ++ region_id) { BOOST_LOG_TRIVIAL(debug) << "Slicing objects - region " << region_id; // slicing in parallel size_t slicing_mode_normal_below_layer = 0; if (spiral_vase) { // Slice the bottom layers with SlicingMode::Regular. // This needs to be in sync with LayerRegion::make_perimeters() spiral_vase! - const PrintRegionConfig &config = this->print()->regions()[region_id]->config(); + const PrintRegionConfig &config = this->printing_region(region_id).config(); slicing_mode_normal_below_layer = size_t(config.bottom_solid_layers.value); for (; slicing_mode_normal_below_layer < slice_zs.size() && slice_zs[slicing_mode_normal_below_layer] < config.bottom_solid_min_thickness - EPSILON; ++ slicing_mode_normal_below_layer); @@ -1847,22 +1835,22 @@ void PrintObject::_slice(const std::vector &layer_height_profile) }; std::vector sliced_volumes; sliced_volumes.reserve(num_volumes); - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { - const std::vector> &volumes_and_ranges = this->region_volumes[region_id]; - for (size_t i = 0; i < volumes_and_ranges.size(); ) { - int volume_id = volumes_and_ranges[i].second; + for (size_t region_id = 0; region_id < m_region_volumes.size(); ++ region_id) { + const PrintRegionVolumes &volumes_and_ranges = m_region_volumes[region_id]; + for (size_t i = 0; i < volumes_and_ranges.volumes.size(); ) { + int volume_id = volumes_and_ranges.volumes[i].volume_idx; const ModelVolume *model_volume = this->model_object()->volumes[volume_id]; if (model_volume->is_model_part()) { BOOST_LOG_TRIVIAL(debug) << "Slicing objects - volume " << volume_id; // Find the ranges of this volume. Ranges in volumes_and_ranges must not overlap for a single volume. std::vector ranges; - ranges.emplace_back(volumes_and_ranges[i].first); + ranges.emplace_back(volumes_and_ranges.volumes[i].layer_height_range); size_t j = i + 1; - for (; j < volumes_and_ranges.size() && volume_id == volumes_and_ranges[j].second; ++ j) - if (! ranges.empty() && std::abs(ranges.back().second - volumes_and_ranges[j].first.first) < EPSILON) - ranges.back().second = volumes_and_ranges[j].first.second; + for (; j < volumes_and_ranges.volumes.size() && volume_id == volumes_and_ranges.volumes[j].volume_idx; ++ j) + if (! ranges.empty() && std::abs(ranges.back().second - volumes_and_ranges.volumes[j].layer_height_range.first) < EPSILON) + ranges.back().second = volumes_and_ranges.volumes[j].layer_height_range.second; else - ranges.emplace_back(volumes_and_ranges[j].first); + ranges.emplace_back(volumes_and_ranges.volumes[j].layer_height_range); // slicing in parallel sliced_volumes.emplace_back(volume_id, (int)region_id, this->slice_volume(slice_zs, ranges, slicing_mode, *model_volume)); i = j; @@ -1891,7 +1879,7 @@ void PrintObject::_slice(const std::vector &layer_height_profile) slices = offset_ex(std::move(slices), delta); if (! processed.empty()) // Trim by the slices of already processed regions. - slices = diff_ex(to_polygons(std::move(slices)), processed); + slices = diff_ex(slices, processed); if (size_t(&sliced_volume - &sliced_volumes.front()) + 1 < sliced_volumes.size()) // Collect the already processed regions to trim the to be processed regions. polygons_append(processed, slices); @@ -1899,7 +1887,7 @@ void PrintObject::_slice(const std::vector &layer_height_profile) } } // Collect and union volumes of a single region. - for (int region_id = 0; region_id < (int)this->region_volumes.size(); ++ region_id) { + for (int region_id = 0; region_id < int(m_region_volumes.size()); ++ region_id) { ExPolygons expolygons; size_t num_volumes = 0; for (SlicedVolume &sliced_volume : sliced_volumes) @@ -1920,8 +1908,8 @@ void PrintObject::_slice(const std::vector &layer_height_profile) } // Slice all modifier volumes. - if (this->region_volumes.size() > 1) { - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + if (m_region_volumes.size() > 1) { + for (size_t region_id = 0; region_id < m_region_volumes.size(); ++ region_id) { BOOST_LOG_TRIVIAL(debug) << "Slicing modifier volumes - region " << region_id; // slicing in parallel std::vector expolygons_by_layer = this->slice_modifiers(region_id, slice_zs); @@ -1934,7 +1922,7 @@ void PrintObject::_slice(const std::vector &layer_height_profile) tbb::blocked_range(0, m_layers.size()), [this, &expolygons_by_layer, region_id](const tbb::blocked_range& range) { for (size_t layer_id = range.begin(); layer_id < range.end(); ++ layer_id) { - for (size_t other_region_id = 0; other_region_id < this->region_volumes.size(); ++ other_region_id) { + for (size_t other_region_id = 0; other_region_id < m_region_volumes.size(); ++ other_region_id) { if (region_id == other_region_id) continue; Layer *layer = m_layers[layer_id]; @@ -1942,12 +1930,11 @@ void PrintObject::_slice(const std::vector &layer_height_profile) LayerRegion *other_layerm = layer->m_regions[other_region_id]; if (layerm == nullptr || other_layerm == nullptr || other_layerm->slices.empty() || expolygons_by_layer[layer_id].empty()) continue; - Polygons other_slices = to_polygons(other_layerm->slices); - ExPolygons my_parts = intersection_ex(other_slices, to_polygons(expolygons_by_layer[layer_id])); + ExPolygons my_parts = intersection_ex(other_layerm->slices.surfaces, expolygons_by_layer[layer_id]); if (my_parts.empty()) continue; // Remove such parts from original region. - other_layerm->slices.set(diff_ex(other_slices, to_polygons(my_parts)), stInternal); + other_layerm->slices.set(diff_ex(other_layerm->slices.surfaces, my_parts), stInternal); // Append new parts to our region. layerm->slices.append(std::move(my_parts), stInternal); } @@ -2034,7 +2021,7 @@ end: slices = offset_ex(std::move(slices), xy_compensation_scaled); if (region_id > 0 && clip) // Trim by the slices of already processed regions. - slices = diff_ex(to_polygons(std::move(slices)), processed); + slices = diff_ex(slices, processed); if (clip && (region_id + 1 < layer->m_regions.size())) // Collect the already processed regions to trim the to be processed regions. polygons_append(processed, slices); @@ -2075,9 +2062,9 @@ end: std::vector PrintObject::slice_region(size_t region_id, const std::vector &z, SlicingMode mode, size_t slicing_mode_normal_below_layer, SlicingMode mode_below) const { std::vector volumes; - if (region_id < this->region_volumes.size()) { - for (const std::pair &volume_and_range : this->region_volumes[region_id]) { - const ModelVolume *volume = this->model_object()->volumes[volume_and_range.second]; + if (region_id < m_region_volumes.size()) { + for (const PrintRegionVolumes::VolumeWithZRange &volume_w_zrange : m_region_volumes[region_id].volumes) { + const ModelVolume *volume = this->model_object()->volumes[volume_w_zrange.volume_idx]; if (volume->is_model_part()) volumes.emplace_back(volume); } @@ -2085,27 +2072,27 @@ std::vector PrintObject::slice_region(size_t region_id, const std::v return this->slice_volumes(z, mode, slicing_mode_normal_below_layer, mode_below, volumes); } -// Z ranges are not applicable to modifier meshes, therefore a single volume will be found in volume_and_range at most once. +// Z ranges are not applicable to modifier meshes, therefore a single volume will be found in volume_w_zrange at most once. std::vector PrintObject::slice_modifiers(size_t region_id, const std::vector &slice_zs) const { std::vector out; - if (region_id < this->region_volumes.size()) + if (region_id < m_region_volumes.size()) { std::vector> volume_ranges; - const std::vector> &volumes_and_ranges = this->region_volumes[region_id]; - volume_ranges.reserve(volumes_and_ranges.size()); - for (size_t i = 0; i < volumes_and_ranges.size(); ) { - int volume_id = volumes_and_ranges[i].second; + const PrintRegionVolumes &volumes_and_ranges = m_region_volumes[region_id]; + volume_ranges.reserve(volumes_and_ranges.volumes.size()); + for (size_t i = 0; i < volumes_and_ranges.volumes.size(); ) { + int volume_id = volumes_and_ranges.volumes[i].volume_idx; const ModelVolume *model_volume = this->model_object()->volumes[volume_id]; if (model_volume->is_modifier()) { std::vector ranges; - ranges.emplace_back(volumes_and_ranges[i].first); + ranges.emplace_back(volumes_and_ranges.volumes[i].layer_height_range); size_t j = i + 1; - for (; j < volumes_and_ranges.size() && volume_id == volumes_and_ranges[j].second; ++ j) { - if (! ranges.empty() && std::abs(ranges.back().second - volumes_and_ranges[j].first.first) < EPSILON) - ranges.back().second = volumes_and_ranges[j].first.second; + for (; j < volumes_and_ranges.volumes.size() && volume_id == volumes_and_ranges.volumes[j].volume_idx; ++ j) { + if (! ranges.empty() && std::abs(ranges.back().second - volumes_and_ranges.volumes[j].layer_height_range.first) < EPSILON) + ranges.back().second = volumes_and_ranges.volumes[j].layer_height_range.second; else - ranges.emplace_back(volumes_and_ranges[j].first); + ranges.emplace_back(volumes_and_ranges.volumes[j].layer_height_range); } volume_ranges.emplace_back(std::move(ranges)); i = j; @@ -2127,8 +2114,8 @@ std::vector PrintObject::slice_modifiers(size_t region_id, const std if (equal_ranges && volume_ranges.front().size() == 1 && volume_ranges.front().front() == t_layer_height_range(0, DBL_MAX)) { // No modifier in this region was split to layer spans. std::vector volumes; - for (const std::pair &volume_and_range : this->region_volumes[region_id]) { - const ModelVolume *volume = this->model_object()->volumes[volume_and_range.second]; + for (const PrintRegionVolumes::VolumeWithZRange &volume_w_zrange : m_region_volumes[region_id].volumes) { + const ModelVolume *volume = this->model_object()->volumes[volume_w_zrange.volume_idx]; if (volume->is_modifier()) volumes.emplace_back(volume); } @@ -2136,19 +2123,19 @@ std::vector PrintObject::slice_modifiers(size_t region_id, const std } else { // Some modifier in this region was split to layer spans. std::vector merge; - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { - const std::vector> &volumes_and_ranges = this->region_volumes[region_id]; - for (size_t i = 0; i < volumes_and_ranges.size(); ) { - int volume_id = volumes_and_ranges[i].second; + for (size_t region_id = 0; region_id < m_region_volumes.size(); ++ region_id) { + const PrintRegionVolumes &volumes_and_ranges = m_region_volumes[region_id]; + for (size_t i = 0; i < volumes_and_ranges.volumes.size(); ) { + int volume_id = volumes_and_ranges.volumes[i].volume_idx; const ModelVolume *model_volume = this->model_object()->volumes[volume_id]; if (model_volume->is_modifier()) { BOOST_LOG_TRIVIAL(debug) << "Slicing modifiers - volume " << volume_id; // Find the ranges of this volume. Ranges in volumes_and_ranges must not overlap for a single volume. std::vector ranges; - ranges.emplace_back(volumes_and_ranges[i].first); + ranges.emplace_back(volumes_and_ranges.volumes[i].layer_height_range); size_t j = i + 1; - for (; j < volumes_and_ranges.size() && volume_id == volumes_and_ranges[j].second; ++ j) - ranges.emplace_back(volumes_and_ranges[j].first); + for (; j < volumes_and_ranges.volumes.size() && volume_id == volumes_and_ranges.volumes[j].volume_idx; ++ j) + ranges.emplace_back(volumes_and_ranges.volumes[j].layer_height_range); // slicing in parallel std::vector this_slices = this->slice_volume(slice_zs, ranges, SlicingMode::Regular, *model_volume); // Variable this_slices could be empty if no value of slice_zs is within any of the ranges of this volume. @@ -2223,6 +2210,7 @@ std::vector PrintObject::slice_volumes( TriangleMesh vol_mesh(model_volume.mesh()); vol_mesh.transform(model_volume.get_matrix(), true); mesh.merge(vol_mesh); + mesh.repair(false); } if (mesh.stl.stats.number_of_facets > 0) { mesh.transform(m_trafo, true); @@ -2365,7 +2353,7 @@ std::string PrintObject::_fix_slicing_errors() if (lower_surfaces) for (const auto &surface : *lower_surfaces) polygons_append(holes, surface.expolygon.holes); - layerm->slices.set(diff_ex(union_(outer), holes, false), stInternal); + layerm->slices.set(diff_ex(union_(outer), holes), stInternal); } // Update layer slices after repairing the single regions. layer->make_slices(); @@ -2423,9 +2411,15 @@ void PrintObject::simplify_slices(double distance) // fill_surfaces but we only turn them into VOID surfaces, thus preserving the boundaries. void PrintObject::clip_fill_surfaces() { - if (! m_config.infill_only_where_needed.value || - ! std::any_of(this->print()->regions().begin(), this->print()->regions().end(), - [](const PrintRegion *region) { return region->config().fill_density > 0; })) + if (! m_config.infill_only_where_needed.value) + return; + bool has_infill = false; + for (size_t i = 0; i < this->num_printing_regions(); ++ i) + if (this->printing_region(i).config().fill_density > 0) { + has_infill = true; + break; + } + if (! has_infill) return; // We only want infill under ceilings; this is almost like an @@ -2478,7 +2472,7 @@ void PrintObject::clip_fill_surfaces() upper_internal = intersection(overhangs, lower_layer_internal_surfaces); // Apply new internal infill to regions. for (LayerRegion *layerm : lower_layer->m_regions) { - if (layerm->region()->config().fill_density.value == 0) + if (layerm->region().config().fill_density.value == 0) continue; SurfaceType internal_surface_types[] = { stInternal, stInternalVoid }; Polygons internal; @@ -2486,8 +2480,8 @@ void PrintObject::clip_fill_surfaces() if (surface.surface_type == stInternal || surface.surface_type == stInternalVoid) polygons_append(internal, std::move(surface.expolygon)); layerm->fill_surfaces.remove_types(internal_surface_types, 2); - layerm->fill_surfaces.append(intersection_ex(internal, upper_internal, true), stInternal); - layerm->fill_surfaces.append(diff_ex (internal, upper_internal, true), stInternalVoid); + layerm->fill_surfaces.append(intersection_ex(internal, upper_internal, ApplySafetyOffset::Yes), stInternal); + layerm->fill_surfaces.append(diff_ex (internal, upper_internal, ApplySafetyOffset::Yes), stInternalVoid); // If there are voids it means that our internal infill is not adjacent to // perimeters. In this case it would be nice to add a loop around infill to // make it more robust and nicer. TODO. @@ -2503,12 +2497,12 @@ void PrintObject::discover_horizontal_shells() { BOOST_LOG_TRIVIAL(trace) << "discover_horizontal_shells()"; - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { for (size_t i = 0; i < m_layers.size(); ++ i) { m_print->throw_if_canceled(); Layer *layer = m_layers[i]; LayerRegion *layerm = layer->regions()[region_id]; - const PrintRegionConfig ®ion_config = layerm->region()->config(); + const PrintRegionConfig ®ion_config = layerm->region().config(); if (region_config.solid_infill_every_layers.value > 0 && region_config.fill_density.value > 0 && (i % region_config.solid_infill_every_layers) == 0) { // Insert a solid internal layer. Mark stInternal surfaces as stInternalSolid or stInternalBridge. @@ -2584,7 +2578,7 @@ void PrintObject::discover_horizontal_shells() for (const Surface &surface : neighbor_layerm->fill_surfaces.surfaces) if (surface.surface_type == stInternal || surface.surface_type == stInternalSolid) polygons_append(internal, to_polygons(surface.expolygon)); - new_internal_solid = intersection(solid, internal, true); + new_internal_solid = intersection(solid, internal, ApplySafetyOffset::Yes); } if (new_internal_solid.empty()) { // No internal solid needed on this layer. In order to decide whether to continue @@ -2611,8 +2605,7 @@ void PrintObject::discover_horizontal_shells() float margin = float(neighbor_layerm->flow(frExternalPerimeter).scaled_width()); Polygons too_narrow = diff( new_internal_solid, - offset2(new_internal_solid, -margin, +margin, jtMiter, 5), - true); + offset2(new_internal_solid, -margin, +margin + ClipperSafetyOffset, jtMiter, 5)); // Trim the regularized region by the original region. if (! too_narrow.empty()) new_internal_solid = solid = diff(new_internal_solid, too_narrow); @@ -2631,8 +2624,7 @@ void PrintObject::discover_horizontal_shells() // have the same angle, so the next shell would be grown even more and so on. Polygons too_narrow = diff( new_internal_solid, - offset2(new_internal_solid, -margin, +margin, ClipperLib::jtMiter, 5), - true); + offset2(new_internal_solid, -margin, +margin + ClipperSafetyOffset, ClipperLib::jtMiter, 5)); if (! too_narrow.empty()) { // grow the collapsing parts and add the extra area to the neighbor layer // as well as to our original surfaces so that we support this @@ -2660,15 +2652,12 @@ void PrintObject::discover_horizontal_shells() // and new ones SurfaceCollection backup = std::move(neighbor_layerm->fill_surfaces); polygons_append(new_internal_solid, to_polygons(backup.filter_by_type(stInternalSolid))); - ExPolygons internal_solid = union_ex(new_internal_solid, false); + ExPolygons internal_solid = union_ex(new_internal_solid); // assign new internal-solid surfaces to layer neighbor_layerm->fill_surfaces.set(internal_solid, stInternalSolid); // subtract intersections from layer surfaces to get resulting internal surfaces Polygons polygons_internal = to_polygons(std::move(internal_solid)); - ExPolygons internal = diff_ex( - to_polygons(backup.filter_by_type(stInternal)), - polygons_internal, - true); + ExPolygons internal = diff_ex(backup.filter_by_type(stInternal), polygons_internal, ApplySafetyOffset::Yes); // assign resulting internal surfaces to layer neighbor_layerm->fill_surfaces.append(internal, stInternal); polygons_append(polygons_internal, to_polygons(std::move(internal))); @@ -2679,7 +2668,7 @@ void PrintObject::discover_horizontal_shells() backup.group(&top_bottom_groups); for (SurfacesPtr &group : top_bottom_groups) neighbor_layerm->fill_surfaces.append( - diff_ex(to_polygons(group), polygons_internal), + diff_ex(group, polygons_internal), // Use an existing surface as a template, it carries the bridge angle etc. *group.front()); } @@ -2689,7 +2678,7 @@ void PrintObject::discover_horizontal_shells() } // for each region #ifdef SLIC3R_DEBUG_SLICE_PROCESSING - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { for (const Layer *layer : m_layers) { const LayerRegion *layerm = layer->m_regions[region_id]; layerm->export_region_slices_to_svg_debug("5_discover_horizontal_shells"); @@ -2705,16 +2694,16 @@ void PrintObject::discover_horizontal_shells() void PrintObject::combine_infill() { // Work on each region separately. - for (size_t region_id = 0; region_id < this->region_volumes.size(); ++ region_id) { - const PrintRegion *region = this->print()->regions()[region_id]; - const size_t every = region->config().infill_every_layers.value; - if (every < 2 || region->config().fill_density == 0.) + for (size_t region_id = 0; region_id < this->num_printing_regions(); ++ region_id) { + const PrintRegion ®ion = this->printing_region(region_id); + const size_t every = region.config().infill_every_layers.value; + if (every < 2 || region.config().fill_density == 0.) continue; // Limit the number of combined layers to the maximum height allowed by this regions' nozzle. //FIXME limit the layer height to max_layer_height double nozzle_diameter = std::min( - this->print()->config().nozzle_diameter.get_at(region->config().infill_extruder.value - 1), - this->print()->config().nozzle_diameter.get_at(region->config().solid_infill_extruder.value - 1)); + this->print()->config().nozzle_diameter.get_at(region.config().infill_extruder.value - 1), + this->print()->config().nozzle_diameter.get_at(region.config().solid_infill_extruder.value - 1)); // define the combinations std::vector combine(m_layers.size(), 0); { @@ -2758,10 +2747,7 @@ void PrintObject::combine_infill() ExPolygons intersection = to_expolygons(layerms.front()->fill_surfaces.filter_by_type(stInternal)); // Start looping from the second layer and intersect the current intersection with it. for (size_t i = 1; i < layerms.size(); ++ i) - intersection = intersection_ex( - to_polygons(intersection), - to_polygons(layerms[i]->fill_surfaces.filter_by_type(stInternal)), - false); + intersection = intersection_ex(layerms[i]->fill_surfaces.filter_by_type(stInternal), intersection); double area_threshold = layerms.front()->infill_area_threshold(); if (! intersection.empty() && area_threshold > 0.) intersection.erase(std::remove_if(intersection.begin(), intersection.end(), @@ -2781,18 +2767,18 @@ void PrintObject::combine_infill() 0.5f * layerms.back()->flow(frPerimeter).scaled_width() + // Because fill areas for rectilinear and honeycomb are grown // later to overlap perimeters, we need to counteract that too. - ((region->config().fill_pattern == ipRectilinear || - region->config().fill_pattern == ipMonotonic || - region->config().fill_pattern == ipGrid || - region->config().fill_pattern == ipLine || - region->config().fill_pattern == ipHoneycomb) ? 1.5f : 0.5f) * + ((region.config().fill_pattern == ipRectilinear || + region.config().fill_pattern == ipMonotonic || + region.config().fill_pattern == ipGrid || + region.config().fill_pattern == ipLine || + region.config().fill_pattern == ipHoneycomb) ? 1.5f : 0.5f) * layerms.back()->flow(frSolidInfill).scaled_width(); for (ExPolygon &expoly : intersection) polygons_append(intersection_with_clearance, offset(expoly, clearance_offset)); for (LayerRegion *layerm : layerms) { - Polygons internal = to_polygons(layerm->fill_surfaces.filter_by_type(stInternal)); + Polygons internal = to_polygons(std::move(layerm->fill_surfaces.filter_by_type(stInternal))); layerm->fill_surfaces.remove_type(stInternal); - layerm->fill_surfaces.append(diff_ex(internal, intersection_with_clearance, false), stInternal); + layerm->fill_surfaces.append(diff_ex(internal, intersection_with_clearance), stInternal); if (layerm == layerms.back()) { // Apply surfaces back with adjusted depth to the uppermost layer. Surface templ(stInternal, ExPolygon()); @@ -2804,7 +2790,7 @@ void PrintObject::combine_infill() } else { // Save void surfaces. layerm->fill_surfaces.append( - intersection_ex(internal, intersection_with_clearance, false), + intersection_ex(internal, intersection_with_clearance), stInternalVoid); } } diff --git a/src/libslic3r/PrintRegion.cpp b/src/libslic3r/PrintRegion.cpp index 837200984..5dba1316e 100644 --- a/src/libslic3r/PrintRegion.cpp +++ b/src/libslic3r/PrintRegion.cpp @@ -20,11 +20,12 @@ unsigned int PrintRegion::extruder(FlowRole role) const Flow PrintRegion::flow(const PrintObject &object, FlowRole role, double layer_height, bool first_layer) const { - ConfigOptionFloatOrPercent config_width; + const PrintConfig &print_config = object.print()->config(); + ConfigOptionFloatOrPercent config_width; // Get extrusion width from configuration. // (might be an absolute value, or a percent value, or zero for auto) - if (first_layer && m_print->config().first_layer_extrusion_width.value > 0) { - config_width = m_print->config().first_layer_extrusion_width; + if (first_layer && print_config.first_layer_extrusion_width.value > 0) { + config_width = print_config.first_layer_extrusion_width; } else if (role == frExternalPerimeter) { config_width = m_config.external_perimeter_extrusion_width; } else if (role == frPerimeter) { @@ -44,7 +45,7 @@ Flow PrintRegion::flow(const PrintObject &object, FlowRole role, double layer_he // Get the configured nozzle_diameter for the extruder associated to the flow role requested. // Here this->extruder(role) - 1 may underflow to MAX_INT, but then the get_at() will follback to zero'th element, so everything is all right. - auto nozzle_diameter = float(m_print->config().nozzle_diameter.get_at(this->extruder(role) - 1)); + auto nozzle_diameter = float(print_config.nozzle_diameter.get_at(this->extruder(role) - 1)); return Flow::new_from_config_width(role, config_width, nozzle_diameter, float(layer_height)); } @@ -76,17 +77,17 @@ void PrintRegion::collect_object_printing_extruders(const PrintConfig &print_con emplace_extruder(region_config.solid_infill_extruder); } -void PrintRegion::collect_object_printing_extruders(std::vector &object_extruders) const +void PrintRegion::collect_object_printing_extruders(const Print &print, std::vector &object_extruders) const { // PrintRegion, if used by some PrintObject, shall have all the extruders set to an existing printer extruder. // If not, then there must be something wrong with the Print::apply() function. #ifndef NDEBUG - auto num_extruders = (int)print()->config().nozzle_diameter.size(); + auto num_extruders = int(print.config().nozzle_diameter.size()); assert(this->config().perimeter_extruder <= num_extruders); assert(this->config().infill_extruder <= num_extruders); assert(this->config().solid_infill_extruder <= num_extruders); #endif - collect_object_printing_extruders(print()->config(), this->config(), print()->has_brim(), object_extruders); + collect_object_printing_extruders(print.config(), this->config(), print.has_brim(), object_extruders); } } diff --git a/src/libslic3r/SLA/AGGRaster.hpp b/src/libslic3r/SLA/AGGRaster.hpp index 849cec30a..2243a3c1b 100644 --- a/src/libslic3r/SLA/AGGRaster.hpp +++ b/src/libslic3r/SLA/AGGRaster.hpp @@ -4,7 +4,6 @@ #include #include "libslic3r/ExPolygon.hpp" #include "libslic3r/MTUtils.hpp" -#include // For rasterizing #include @@ -21,10 +20,7 @@ namespace Slic3r { inline const Polygon& contour(const ExPolygon& p) { return p.contour; } -inline const ClipperLib::Path& contour(const ClipperLib::Polygon& p) { return p.Contour; } - inline const Polygons& holes(const ExPolygon& p) { return p.holes; } -inline const ClipperLib::Paths& holes(const ClipperLib::Polygon& p) { return p.Holes; } namespace sla { @@ -77,8 +73,6 @@ protected: double getPx(const Point &p) { return p(0) * m_pxdim_scaled.w_mm; } double getPy(const Point &p) { return p(1) * m_pxdim_scaled.h_mm; } agg::path_storage to_path(const Polygon &poly) { return to_path(poly.points); } - double getPx(const ClipperLib::IntPoint &p) { return p.X * m_pxdim_scaled.w_mm; } - double getPy(const ClipperLib::IntPoint& p) { return p.Y * m_pxdim_scaled.h_mm; } template agg::path_storage _to_path(const PointVec& v) { @@ -168,7 +162,6 @@ public: } void draw(const ExPolygon &poly) override { _draw(poly); } - void draw(const ClipperLib::Polygon &poly) override { _draw(poly); } EncodedRaster encode(RasterEncoder encoder) const override { diff --git a/src/libslic3r/SLA/ConcaveHull.cpp b/src/libslic3r/SLA/ConcaveHull.cpp index d3c0d1022..172408989 100644 --- a/src/libslic3r/SLA/ConcaveHull.cpp +++ b/src/libslic3r/SLA/ConcaveHull.cpp @@ -42,9 +42,10 @@ Point ConcaveHull::centroid(const Points &pp) // As it shows, the current offset_ex in ClipperUtils hangs if used in jtRound // mode -static ClipperLib::Paths fast_offset(const ClipperLib::Paths &paths, - coord_t delta, - ClipperLib::JoinType jointype) +template +static ClipperLib::Paths fast_offset(PolygonsProvider &&paths, + coord_t delta, + ClipperLib::JoinType jointype) { using ClipperLib::ClipperOffset; using ClipperLib::etClosedPolygon; @@ -61,7 +62,7 @@ static ClipperLib::Paths fast_offset(const ClipperLib::Paths &paths, return {}; } - offs.AddPaths(paths, jointype, etClosedPolygon); + offs.AddPaths(std::forward(paths), jointype, etClosedPolygon); Paths result; offs.Execute(result, static_cast(delta)); @@ -157,11 +158,9 @@ ExPolygons ConcaveHull::to_expolygons() const ExPolygons offset_waffle_style_ex(const ConcaveHull &hull, coord_t delta) { - ClipperLib::Paths paths = Slic3rMultiPoints_to_ClipperPaths(hull.polygons()); - paths = fast_offset(paths, 2 * delta, ClipperLib::jtRound); - paths = fast_offset(paths, -delta, ClipperLib::jtRound); - ExPolygons ret = ClipperPaths_to_Slic3rExPolygons(paths); - for (ExPolygon &p : ret) p.holes = {}; + ExPolygons ret = ClipperPaths_to_Slic3rExPolygons( + fast_offset(fast_offset(ClipperUtils::PolygonsProvider(hull.polygons()), 2 * delta, ClipperLib::jtRound), -delta, ClipperLib::jtRound)); + for (ExPolygon &p : ret) p.holes.clear(); return ret; } diff --git a/src/libslic3r/SLA/Pad.cpp b/src/libslic3r/SLA/Pad.cpp index 927c32589..e11914a1c 100644 --- a/src/libslic3r/SLA/Pad.cpp +++ b/src/libslic3r/SLA/Pad.cpp @@ -179,10 +179,10 @@ PadSkeleton divide_blueprint(const ExPolygons &bp) ret.outer.reserve(size_t(ptree.Total())); for (ClipperLib::PolyTree::PolyNode *node : ptree.Childs) { - ExPolygon poly(ClipperPath_to_Slic3rPolygon(node->Contour)); + ExPolygon poly; + poly.contour.points = std::move(node->Contour); for (ClipperLib::PolyTree::PolyNode *child : node->Childs) { - poly.holes.emplace_back( - ClipperPath_to_Slic3rPolygon(child->Contour)); + poly.holes.emplace_back(std::move(child->Contour)); traverse_pt(child->Childs, &ret.inner); } @@ -342,18 +342,18 @@ public: template ExPolygon offset_contour_only(const ExPolygon &poly, coord_t delta, Args...args) { - ExPolygons tmp = offset_ex(poly.contour, float(delta), args...); + Polygons tmp = offset(poly.contour, float(delta), args...); if (tmp.empty()) return {}; Polygons holes = poly.holes; for (auto &h : holes) h.reverse(); - tmp = diff_ex(to_polygons(tmp), holes); + ExPolygons tmp2 = diff_ex(tmp, holes); - if (tmp.empty()) return {}; + if (tmp2.empty()) return {}; - return tmp.front(); + return std::move(tmp2.front()); } bool add_cavity(Contour3D &pad, ExPolygon &top_poly, const PadConfig3D &cfg, diff --git a/src/libslic3r/SLA/RasterBase.hpp b/src/libslic3r/SLA/RasterBase.hpp index 9f9f29cd5..bbb83b5a0 100644 --- a/src/libslic3r/SLA/RasterBase.hpp +++ b/src/libslic3r/SLA/RasterBase.hpp @@ -11,8 +11,6 @@ #include #include -namespace ClipperLib { struct Polygon; } - namespace Slic3r { template using uqptr = std::unique_ptr; @@ -92,7 +90,6 @@ public: /// Draw a polygon with holes. virtual void draw(const ExPolygon& poly) = 0; - virtual void draw(const ClipperLib::Polygon& poly) = 0; /// Get the resolution of the raster. virtual Resolution resolution() const = 0; diff --git a/src/libslic3r/SLA/SupportPointGenerator.cpp b/src/libslic3r/SLA/SupportPointGenerator.cpp index 7a4c29068..bbc6b03fa 100644 --- a/src/libslic3r/SLA/SupportPointGenerator.cpp +++ b/src/libslic3r/SLA/SupportPointGenerator.cpp @@ -12,11 +12,9 @@ #include "ClipperUtils.hpp" #include "Tesselate.hpp" #include "ExPolygonCollection.hpp" +#include "MinAreaBoundingBox.hpp" #include "libslic3r.h" -#include "libnest2d/backends/clipper/geometries.hpp" -#include "libnest2d/utils/rotcalipers.hpp" - #include #include @@ -181,9 +179,8 @@ static std::vector make_layers( } } if (! top.islands_below.empty()) { - Polygons top_polygons = to_polygons(*top.polygon); Polygons bottom_polygons = top.polygons_below(); - top.overhangs = diff_ex(top_polygons, bottom_polygons); + top.overhangs = diff_ex(*top.polygon, bottom_polygons); if (! top.overhangs.empty()) { // Produce 2 bands around the island, a safe band for dangling overhangs @@ -193,7 +190,7 @@ static std::vector make_layers( auto overh_mask = offset(bottom_polygons, slope_offset, ClipperLib::jtSquare); // Absolutely hopeless overhangs are those outside the unsafe band - top.overhangs = diff_ex(top_polygons, overh_mask); + top.overhangs = diff_ex(*top.polygon, overh_mask); // Now cut out the supported core from the safe band // and cut the safe band from the unsafe band to get distinct @@ -201,8 +198,8 @@ static std::vector make_layers( overh_mask = diff(overh_mask, dangl_mask); dangl_mask = diff(dangl_mask, bottom_polygons); - top.dangling_areas = intersection_ex(top_polygons, dangl_mask); - top.overhangs_slopes = intersection_ex(top_polygons, overh_mask); + top.dangling_areas = intersection_ex(*top.polygon, dangl_mask); + top.overhangs_slopes = intersection_ex(*top.polygon, overh_mask); top.overhangs_area = 0.f; std::vector> expolys_with_areas; @@ -400,7 +397,7 @@ std::vector sample_expolygon(const ExPolygons &expolys, float samples_per void sample_expolygon_boundary(const ExPolygon & expoly, float samples_per_mm, std::vector &out, - std::mt19937 & rng) + std::mt19937 & /*rng*/) { double point_stepping_scaled = scale_(1.f) / samples_per_mm; for (size_t i_contour = 0; i_contour <= expoly.holes.size(); ++ i_contour) { @@ -553,9 +550,8 @@ void SupportPointGenerator::uniformly_cover(const ExPolygons& islands, Structure // auto bb = get_extents(islands); if (flags & icfIsNew) { - auto chull_ex = ExPolygonCollection{islands}.convex_hull(); - auto chull = Slic3rMultiPoint_to_ClipperPath(chull_ex); - auto rotbox = libnest2d::minAreaBoundingBox(chull); + auto chull = ExPolygonCollection{islands}.convex_hull(); + auto rotbox = MinAreaBoundigBox{chull, MinAreaBoundigBox::pcConvex}; Vec2d bbdim = {unscaled(rotbox.width()), unscaled(rotbox.height())}; if (bbdim.x() > bbdim.y()) std::swap(bbdim.x(), bbdim.y()); diff --git a/src/libslic3r/SLA/SupportPointGenerator.hpp b/src/libslic3r/SLA/SupportPointGenerator.hpp index d7588e3ba..441b82de1 100644 --- a/src/libslic3r/SLA/SupportPointGenerator.hpp +++ b/src/libslic3r/SLA/SupportPointGenerator.hpp @@ -90,7 +90,7 @@ public: float overlap_area(const Structure &rhs) const { double out = 0.; if (this->bbox.overlap(rhs.bbox)) { - Polygons polys = intersection(to_polygons(*this->polygon), to_polygons(*rhs.polygon), false); + Polygons polys = intersection(*this->polygon, *rhs.polygon); for (const Polygon &poly : polys) out += poly.area(); } diff --git a/src/libslic3r/SLAPrint.hpp b/src/libslic3r/SLAPrint.hpp index adb80c29a..f5f422b3d 100644 --- a/src/libslic3r/SLAPrint.hpp +++ b/src/libslic3r/SLAPrint.hpp @@ -9,7 +9,6 @@ #include "Point.hpp" #include "MTUtils.hpp" #include "Zipper.hpp" -#include namespace Slic3r { @@ -268,7 +267,7 @@ protected: void config_apply(const ConfigBase &other, bool ignore_nonexistent = false) { m_config.apply(other, ignore_nonexistent); } void config_apply_only(const ConfigBase &other, const t_config_option_keys &keys, bool ignore_nonexistent = false) - { this->m_config.apply_only(other, keys, ignore_nonexistent); } + { m_config.apply_only(other, keys, ignore_nonexistent); } void set_trafo(const Transform3d& trafo, bool left_handed) { m_transformed_rmesh.invalidate([this, &trafo, left_handed](){ m_trafo = trafo; m_left_handed = left_handed; }); @@ -483,7 +482,7 @@ public: // The collection of slice records for the current level. std::vector> m_slices; - std::vector m_transformed_slices; + ExPolygons m_transformed_slices; template void transformed_slices(Container&& c) { @@ -507,7 +506,7 @@ public: auto slices() const -> const decltype (m_slices)& { return m_slices; } - const std::vector & transformed_slices() const { + const ExPolygons & transformed_slices() const { return m_transformed_slices; } }; diff --git a/src/libslic3r/SLAPrintSteps.cpp b/src/libslic3r/SLAPrintSteps.cpp index c393eb295..108159b89 100644 --- a/src/libslic3r/SLAPrintSteps.cpp +++ b/src/libslic3r/SLAPrintSteps.cpp @@ -16,9 +16,6 @@ #include -// For geometry algorithms with native Clipper types (no copies and conversions) -#include - #include #include "I18N.hpp" @@ -717,55 +714,49 @@ void SLAPrint::Steps::slice_supports(SLAPrintObject &po) { report_status(-2, "", SlicingStatus::RELOAD_SLA_PREVIEW); } -using ClipperPoint = ClipperLib::IntPoint; -using ClipperPolygon = ClipperLib::Polygon; // see clipper_polygon.hpp in libnest2d -using ClipperPolygons = std::vector; +//static ClipperPolygons polyunion(const ClipperPolygons &subjects) +//{ +// ClipperLib::Clipper clipper; -static ClipperPolygons polyunion(const ClipperPolygons &subjects) -{ - ClipperLib::Clipper clipper; +// bool closed = true; - bool closed = true; +// for(auto& path : subjects) { +// clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed); +// clipper.AddPaths(path.Holes, ClipperLib::ptSubject, closed); +// } - for(auto& path : subjects) { - clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed); - clipper.AddPaths(path.Holes, ClipperLib::ptSubject, closed); - } +// auto mode = ClipperLib::pftPositive; - auto mode = ClipperLib::pftPositive; +// return libnest2d::clipper_execute(clipper, ClipperLib::ctUnion, mode, mode); +//} - return libnest2d::clipper_execute(clipper, ClipperLib::ctUnion, mode, mode); -} +//static ClipperPolygons polydiff(const ClipperPolygons &subjects, const ClipperPolygons& clips) +//{ +// ClipperLib::Clipper clipper; -static ClipperPolygons polydiff(const ClipperPolygons &subjects, const ClipperPolygons& clips) -{ - ClipperLib::Clipper clipper; +// bool closed = true; - bool closed = true; +// for(auto& path : subjects) { +// clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed); +// clipper.AddPaths(path.Holes, ClipperLib::ptSubject, closed); +// } - for(auto& path : subjects) { - clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed); - clipper.AddPaths(path.Holes, ClipperLib::ptSubject, closed); - } +// for(auto& path : clips) { +// clipper.AddPath(path.Contour, ClipperLib::ptClip, closed); +// clipper.AddPaths(path.Holes, ClipperLib::ptClip, closed); +// } - for(auto& path : clips) { - clipper.AddPath(path.Contour, ClipperLib::ptClip, closed); - clipper.AddPaths(path.Holes, ClipperLib::ptClip, closed); - } +// auto mode = ClipperLib::pftPositive; - auto mode = ClipperLib::pftPositive; - - return libnest2d::clipper_execute(clipper, ClipperLib::ctDifference, mode, mode); -} +// return libnest2d::clipper_execute(clipper, ClipperLib::ctDifference, mode, mode); +//} // get polygons for all instances in the object -static ClipperPolygons get_all_polygons(const SliceRecord& record, SliceOrigin o) +static ExPolygons get_all_polygons(const SliceRecord& record, SliceOrigin o) { - namespace sl = libnest2d::sl; - if (!record.print_obj()) return {}; - ClipperPolygons polygons; + ExPolygons polygons; auto &input_polygons = record.get_slice(o); auto &instances = record.print_obj()->instances(); bool is_lefthanded = record.print_obj()->is_left_handed(); @@ -776,43 +767,42 @@ static ClipperPolygons get_all_polygons(const SliceRecord& record, SliceOrigin o for (size_t i = 0; i < instances.size(); ++i) { - ClipperPolygon poly; + ExPolygon poly; // We need to reverse if is_lefthanded is true but bool needreverse = is_lefthanded; // should be a move - poly.Contour.reserve(polygon.contour.size() + 1); + poly.contour.points.reserve(polygon.contour.size() + 1); auto& cntr = polygon.contour.points; if(needreverse) for(auto it = cntr.rbegin(); it != cntr.rend(); ++it) - poly.Contour.emplace_back(it->x(), it->y()); + poly.contour.points.emplace_back(it->x(), it->y()); else for(auto& p : cntr) - poly.Contour.emplace_back(p.x(), p.y()); + poly.contour.points.emplace_back(p.x(), p.y()); for(auto& h : polygon.holes) { - poly.Holes.emplace_back(); - auto& hole = poly.Holes.back(); - hole.reserve(h.points.size() + 1); + poly.holes.emplace_back(); + auto& hole = poly.holes.back(); + hole.points.reserve(h.points.size() + 1); if(needreverse) for(auto it = h.points.rbegin(); it != h.points.rend(); ++it) - hole.emplace_back(it->x(), it->y()); + hole.points.emplace_back(it->x(), it->y()); else for(auto& p : h.points) - hole.emplace_back(p.x(), p.y()); + hole.points.emplace_back(p.x(), p.y()); } if(is_lefthanded) { - for(auto& p : poly.Contour) p.X = -p.X; - for(auto& h : poly.Holes) for(auto& p : h) p.X = -p.X; + for(auto& p : poly.contour) p.x() = -p.x(); + for(auto& h : poly.holes) for(auto& p : h) p.x() = -p.x(); } - sl::rotate(poly, double(instances[i].rotation)); - sl::translate(poly, ClipperPoint{instances[i].shift.x(), - instances[i].shift.y()}); + poly.rotate(double(instances[i].rotation)); + poly.translate(Point{instances[i].shift.x(), instances[i].shift.y()}); polygons.emplace_back(std::move(poly)); } @@ -878,9 +868,6 @@ void SLAPrint::Steps::merge_slices_and_eval_stats() { print_statistics.clear(); - // libnest calculates positive area for clockwise polygons, Slic3r is in counter-clockwise - auto areafn = [](const ClipperPolygon& poly) { return - libnest2d::sl::area(poly); }; - const double area_fill = printer_config.area_fill.getFloat()*0.01;// 0.5 (50%); const double fast_tilt = printer_config.fast_tilt_time.getFloat();// 5.0; const double slow_tilt = printer_config.slow_tilt_time.getFloat();// 8.0; @@ -913,7 +900,7 @@ void SLAPrint::Steps::merge_slices_and_eval_stats() { // Going to parallel: auto printlayerfn = [this, // functions and read only vars - areafn, area_fill, display_area, exp_time, init_exp_time, fast_tilt, slow_tilt, delta_fade_time, + area_fill, display_area, exp_time, init_exp_time, fast_tilt, slow_tilt, delta_fade_time, // write vars &mutex, &models_volume, &supports_volume, &estim_time, &slow_layers, @@ -931,8 +918,8 @@ void SLAPrint::Steps::merge_slices_and_eval_stats() { // Calculation of the consumed material - ClipperPolygons model_polygons; - ClipperPolygons supports_polygons; + ExPolygons model_polygons; + ExPolygons supports_polygons; size_t c = std::accumulate(layer.slices().begin(), layer.slices().end(), @@ -954,44 +941,44 @@ void SLAPrint::Steps::merge_slices_and_eval_stats() { for(const SliceRecord& record : layer.slices()) { - ClipperPolygons modelslices = get_all_polygons(record, soModel); - for(ClipperPolygon& p_tmp : modelslices) model_polygons.emplace_back(std::move(p_tmp)); + ExPolygons modelslices = get_all_polygons(record, soModel); + for(ExPolygon& p_tmp : modelslices) model_polygons.emplace_back(std::move(p_tmp)); - ClipperPolygons supportslices = get_all_polygons(record, soSupport); - for(ClipperPolygon& p_tmp : supportslices) supports_polygons.emplace_back(std::move(p_tmp)); + ExPolygons supportslices = get_all_polygons(record, soSupport); + for(ExPolygon& p_tmp : supportslices) supports_polygons.emplace_back(std::move(p_tmp)); } - model_polygons = polyunion(model_polygons); + model_polygons = union_ex(model_polygons); double layer_model_area = 0; - for (const ClipperPolygon& polygon : model_polygons) - layer_model_area += areafn(polygon); + for (const ExPolygon& polygon : model_polygons) + layer_model_area += area(polygon); if (layer_model_area < 0 || layer_model_area > 0) { Lock lck(mutex); models_volume += layer_model_area * l_height; } if(!supports_polygons.empty()) { - if(model_polygons.empty()) supports_polygons = polyunion(supports_polygons); - else supports_polygons = polydiff(supports_polygons, model_polygons); + if(model_polygons.empty()) supports_polygons = union_ex(supports_polygons); + else supports_polygons = diff_ex(supports_polygons, model_polygons); // allegedly, union of subject is done withing the diff according to the pftPositive polyFillType } double layer_support_area = 0; - for (const ClipperPolygon& polygon : supports_polygons) - layer_support_area += areafn(polygon); + for (const ExPolygon& polygon : supports_polygons) + layer_support_area += area(polygon); if (layer_support_area < 0 || layer_support_area > 0) { Lock lck(mutex); supports_volume += layer_support_area * l_height; } // Here we can save the expensively calculated polygons for printing - ClipperPolygons trslices; + ExPolygons trslices; trslices.reserve(model_polygons.size() + supports_polygons.size()); - for(ClipperPolygon& poly : model_polygons) trslices.emplace_back(std::move(poly)); - for(ClipperPolygon& poly : supports_polygons) trslices.emplace_back(std::move(poly)); + for(ExPolygon& poly : model_polygons) trslices.emplace_back(std::move(poly)); + for(ExPolygon& poly : supports_polygons) trslices.emplace_back(std::move(poly)); - layer.transformed_slices(polyunion(trslices)); + layer.transformed_slices(union_ex(trslices)); // Calculation of the slow and fast layers to the future controlling those values on FW @@ -1074,7 +1061,7 @@ void SLAPrint::Steps::rasterize() PrintLayer& printlayer = m_print->m_printer_input[idx]; if(canceled()) return; - for (const ClipperLib::Polygon& poly : printlayer.transformed_slices()) + for (const ExPolygon& poly : printlayer.transformed_slices()) raster.draw(poly); // Status indication guarded with the spinlock diff --git a/src/libslic3r/SVG.cpp b/src/libslic3r/SVG.cpp index 7308d7e50..6bc334eec 100644 --- a/src/libslic3r/SVG.cpp +++ b/src/libslic3r/SVG.cpp @@ -273,8 +273,8 @@ std::string SVG::get_path_d(const ClipperLib::Path &path, double scale, bool clo std::ostringstream d; d << "M "; for (ClipperLib::Path::const_iterator p = path.begin(); p != path.end(); ++p) { - d << to_svg_x(scale * p->X - origin(0)) << " "; - d << to_svg_y(scale * p->Y - origin(1)) << " "; + d << to_svg_x(scale * p->x() - origin(0)) << " "; + d << to_svg_y(scale * p->y() - origin(1)) << " "; } if (closed) d << "z"; return d.str(); diff --git a/src/libslic3r/Slicing.cpp b/src/libslic3r/Slicing.cpp index d0b1e9ce2..82b3cf1b6 100644 --- a/src/libslic3r/Slicing.cpp +++ b/src/libslic3r/Slicing.cpp @@ -64,9 +64,9 @@ SlicingParameters SlicingParameters::create_from_config( coordf_t object_height, const std::vector &object_extruders) { - coordf_t first_layer_height = (object_config.first_layer_height.value <= 0) ? - object_config.layer_height.value : - object_config.first_layer_height.get_abs_value(object_config.layer_height.value); + assert(! print_config.first_layer_height.percent); + coordf_t first_layer_height = (print_config.first_layer_height.value <= 0) ? + object_config.layer_height.value : print_config.first_layer_height.value; // If object_config.support_material_extruder == 0 resp. object_config.support_material_interface_extruder == 0, // print_config.nozzle_diameter.get_at(size_t(-1)) returns the 0th nozzle diameter, // which is consistent with the requirement that if support_material_extruder == 0 resp. support_material_interface_extruder == 0, diff --git a/src/libslic3r/SupportMaterial.cpp b/src/libslic3r/SupportMaterial.cpp index 08cd04b90..5eb9c9433 100644 --- a/src/libslic3r/SupportMaterial.cpp +++ b/src/libslic3r/SupportMaterial.cpp @@ -345,17 +345,14 @@ PrintObjectSupportMaterial::PrintObjectSupportMaterial(const PrintObject *object // Evaluate the XY gap between the object outer perimeters and the support structures. // Evaluate the XY gap between the object outer perimeters and the support structures. coordf_t external_perimeter_width = 0.; - size_t num_nonempty_regions = 0; coordf_t bridge_flow_ratio = 0; - for (size_t region_id = 0; region_id < object->region_volumes.size(); ++ region_id) - if (! object->region_volumes[region_id].empty()) { - ++ num_nonempty_regions; - const PrintRegion ®ion = *object->print()->get_region(region_id); - external_perimeter_width = std::max(external_perimeter_width, coordf_t(region.flow(*object, frExternalPerimeter, slicing_params.layer_height).width())); - bridge_flow_ratio += region.config().bridge_flow_ratio; - } + for (size_t region_id = 0; region_id < object->num_printing_regions(); ++ region_id) { + const PrintRegion ®ion = object->printing_region(region_id); + external_perimeter_width = std::max(external_perimeter_width, coordf_t(region.flow(*object, frExternalPerimeter, slicing_params.layer_height).width())); + bridge_flow_ratio += region.config().bridge_flow_ratio; + } m_support_params.gap_xy = m_object_config->support_material_xy_spacing.get_abs_value(external_perimeter_width); - bridge_flow_ratio /= num_nonempty_regions; + bridge_flow_ratio /= object->num_printing_regions(); m_support_params.support_material_bottom_interface_flow = m_slicing_params.soluble_interface || ! m_object_config->thick_bridges ? m_support_params.support_material_interface_flow.with_flow_ratio(bridge_flow_ratio) : @@ -364,7 +361,7 @@ PrintObjectSupportMaterial::PrintObjectSupportMaterial(const PrintObject *object m_support_params.can_merge_support_regions = m_object_config->support_material_extruder.value == m_object_config->support_material_interface_extruder.value; if (!m_support_params.can_merge_support_regions && (m_object_config->support_material_extruder.value == 0 || m_object_config->support_material_interface_extruder.value == 0)) { // One of the support extruders is of "don't care" type. - auto object_extruders = m_object->print()->object_extruders(); + auto object_extruders = m_object->object_extruders(); if (object_extruders.size() == 1 && *object_extruders.begin() == std::max(m_object_config->support_material_extruder.value, m_object_config->support_material_interface_extruder.value)) // Object is printed with the same extruder as the support. @@ -801,7 +798,7 @@ public: Polygons support_polygons_simplified = m_grid.contours_simplified(offset_in_grid, fill_holes); #endif // SUPPORT_USE_AGG_RASTERIZER - ExPolygons islands = diff_ex(support_polygons_simplified, *m_trimming_polygons, false); + ExPolygons islands = diff_ex(support_polygons_simplified, *m_trimming_polygons); // Extract polygons, which contain some of the island_samples. Polygons out; @@ -815,7 +812,7 @@ public: // Expanding, thus m_support_polygons are all inside islands. union_ex(*m_support_polygons) : // Shrinking, thus m_support_polygons may be trimmed a tiny bit by islands. - intersection_ex(*m_support_polygons, to_polygons(islands))); + intersection_ex(*m_support_polygons, islands)); std::vector> samples_inside; for (ExPolygon &island : islands) { @@ -932,7 +929,7 @@ public: } // Deserialization constructor - bool deserialize_(const std::string &path, int which = -1) + bool deserialize_(const std::string &path, int which = -1) { FILE *file = ::fopen(path.c_str(), "rb"); if (file == nullptr) @@ -961,7 +958,7 @@ public: poly.points.emplace_back(Point(x * scale, y * scale)); } if (which == -1 || which == i) - m_support_polygons_deserialized.emplace_back(std::move(poly)); + m_support_polygons_deserialized.emplace_back(std::move(poly)); printf("Polygon %d, area: %lf\n", i, area(poly.points)); } ::fread(&n_polygons, 4, 1, file); @@ -984,14 +981,14 @@ public: m_support_polygons_deserialized = simplify_polygons(m_support_polygons_deserialized, false); //m_support_polygons_deserialized = to_polygons(union_ex(m_support_polygons_deserialized, false)); - // Create an EdgeGrid, initialize it with projection, initialize signed distance field. - coord_t grid_resolution = coord_t(scale_(m_support_spacing)); - BoundingBox bbox = get_extents(*m_support_polygons); + // Create an EdgeGrid, initialize it with projection, initialize signed distance field. + coord_t grid_resolution = coord_t(scale_(m_support_spacing)); + BoundingBox bbox = get_extents(*m_support_polygons); bbox.offset(20); - bbox.align_to_grid(grid_resolution); - m_grid.set_bbox(bbox); - m_grid.create(*m_support_polygons, grid_resolution); - m_grid.calculate_sdf(); + bbox.align_to_grid(grid_resolution); + m_grid.set_bbox(bbox); + m_grid.create(*m_support_polygons, grid_resolution); + m_grid.calculate_sdf(); return true; } @@ -1254,7 +1251,7 @@ namespace SupportMaterialInternal { // Surface supporting this layer, expanded by 0.5 * nozzle_diameter, as we consider this kind of overhang to be sufficiently supported. Polygons lower_grown_slices = offset(lower_layer_polygons, //FIXME to mimic the decision in the perimeter generator, we should use half the external perimeter width. - 0.5f * float(scale_(print_config.nozzle_diameter.get_at(layerm->region()->config().perimeter_extruder-1))), + 0.5f * float(scale_(print_config.nozzle_diameter.get_at(layerm->region().config().perimeter_extruder-1))), SUPPORT_SURFACES_OFFSET_PARAMETERS); // Collect perimeters of this layer. //FIXME split_at_first_point() could split a bridge mid-way @@ -1285,7 +1282,7 @@ namespace SupportMaterialInternal { // Is the straight perimeter segment supported at both sides? Point pts[2] = { polyline.first_point(), polyline.last_point() }; bool supported[2] = { false, false }; - for (size_t i = 0; i < lower_layer.lslices.size() && ! (supported[0] && supported[1]); ++ i) + for (size_t i = 0; i < lower_layer.lslices.size() && ! (supported[0] && supported[1]); ++ i) for (int j = 0; j < 2; ++ j) if (! supported[j] && lower_layer.lslices_bboxes[i].contains(pts[j]) && lower_layer.lslices[i].contains(pts[j])) supported[j] = true; @@ -1307,7 +1304,7 @@ namespace SupportMaterialInternal { // Offset unsupported edges into polygons. offset(layerm->unsupported_bridge_edges, scale_(SUPPORT_MATERIAL_MARGIN), SUPPORT_SURFACES_OFFSET_PARAMETERS)); // Remove bridged areas from the supported areas. - contact_polygons = diff(contact_polygons, bridges, true); + contact_polygons = diff(contact_polygons, bridges, ApplySafetyOffset::Yes); #ifdef SLIC3R_DEBUG static int iRun = 0; @@ -1338,7 +1335,7 @@ std::vector PrintObjectSupportMaterial::buildplate_covered(const Print Polygons &covered = buildplate_covered[layer_id]; covered = buildplate_covered[layer_id - 1]; polygons_append(covered, offset(lower_layer.lslices, scale_(0.01))); - covered = union_(covered, false); // don't apply the safety offset. + covered = union_(covered); } BOOST_LOG_TRIVIAL(debug) << "PrintObjectSupportMaterial::buildplate_covered() - end"; } @@ -1437,7 +1434,7 @@ static inline std::tuple detect_overhangs( 0.5f * fw); // Overhang polygons for this layer and region. Polygons diff_polygons; - Polygons layerm_polygons = to_polygons(layerm->slices); + Polygons layerm_polygons = to_polygons(layerm->slices.surfaces); if (lower_layer_offset == 0.f) { // Support everything. diff_polygons = diff(layerm_polygons, lower_layer_polygons); @@ -1469,13 +1466,13 @@ static inline std::tuple detect_overhangs( diff_polygons = diff(diff_polygons, annotations.buildplate_covered[layer_id]); } if (! diff_polygons.empty()) { - // Offset the support regions back to a full overhang, restrict them to the full overhang. - // This is done to increase size of the supporting columns below, as they are calculated by - // propagating these contact surfaces downwards. - diff_polygons = diff( - intersection(offset(diff_polygons, lower_layer_offset, SUPPORT_SURFACES_OFFSET_PARAMETERS), layerm_polygons), - lower_layer_polygons); - } + // Offset the support regions back to a full overhang, restrict them to the full overhang. + // This is done to increase size of the supporting columns below, as they are calculated by + // propagating these contact surfaces downwards. + diff_polygons = diff( + intersection(offset(diff_polygons, lower_layer_offset, SUPPORT_SURFACES_OFFSET_PARAMETERS), layerm_polygons), + lower_layer_polygons); + } } } @@ -1489,7 +1486,7 @@ static inline std::tuple detect_overhangs( // Subtracting them as they are may leave unwanted narrow // residues of diff_polygons that would then be supported. diff_polygons = diff(diff_polygons, - offset(union_(to_polygons(std::move(annotations.blockers_layers[layer_id]))), float(1000.*SCALED_EPSILON))); + offset(union_(annotations.blockers_layers[layer_id]), float(1000.*SCALED_EPSILON))); } #ifdef SLIC3R_DEBUG @@ -1538,7 +1535,7 @@ static inline std::tuple detect_overhangs( slices_margin.offset = slices_margin_offset; slices_margin.polygons = (slices_margin_offset == 0.f) ? lower_layer_polygons : - offset2(to_polygons(lower_layer.lslices), - no_interface_offset * 0.5f, slices_margin_offset + no_interface_offset * 0.5f, SUPPORT_SURFACES_OFFSET_PARAMETERS); + offset2(lower_layer.lslices, - no_interface_offset * 0.5f, slices_margin_offset + no_interface_offset * 0.5f, SUPPORT_SURFACES_OFFSET_PARAMETERS); if (buildplate_only && ! annotations.buildplate_covered[layer_id].empty()) { if (has_enforcer) // Make a backup of trimming polygons before enforcing "on build plate only". @@ -1569,9 +1566,9 @@ static inline std::tuple detect_overhangs( if (has_enforcer) { // Enforce supports (as if with 90 degrees of slope) for the regions covered by the enforcer meshes. #ifdef SLIC3R_DEBUG - ExPolygons enforcers_united = union_ex(to_polygons(annotations.enforcers_layers[layer_id]), false); + ExPolygons enforcers_united = union_ex(annotations.enforcers_layers[layer_id]); #endif // SLIC3R_DEBUG - enforcer_polygons = diff(intersection(to_polygons(layer.lslices), to_polygons(std::move(annotations.enforcers_layers[layer_id]))), + enforcer_polygons = diff(intersection(layer.lslices, annotations.enforcers_layers[layer_id]), // Inflate just a tiny bit to avoid intersection of the overhang areas with the object. offset(lower_layer_polygons, 0.05f * fw, SUPPORT_SURFACES_OFFSET_PARAMETERS)); #ifdef SLIC3R_DEBUG @@ -1640,7 +1637,7 @@ static inline std::pairregion()->bridging_height_avg(print_config); + bridging_height += region->region().bridging_height_avg(print_config); bridging_height /= coordf_t(layer.regions().size()); coordf_t bridging_print_z = layer.print_z - bridging_height - slicing_params.gap_support_object; if (bridging_print_z >= slicing_params.first_print_layer_height - EPSILON) { @@ -1981,7 +1978,7 @@ static inline PrintObjectSupportMaterial::MyLayer* detect_bottom_contacts( if (top.empty()) return nullptr; - Polygons touching = intersection(top, supports_projected, false); + Polygons touching = intersection(top, supports_projected); if (touching.empty()) return nullptr; @@ -2080,7 +2077,7 @@ static inline std::pair project_support_to_grid(const Layer // Remove the areas that touched from the projection that will continue on next, lower, top surfaces. // Polygons trimming = union_(to_polygons(layer.slices), touching, true); Polygons trimming = layer_buildplate_covered ? std::move(*layer_buildplate_covered) : offset(layer.lslices, float(SCALED_EPSILON)); - Polygons overhangs_projection = diff(overhangs, trimming, false); + Polygons overhangs_projection = diff(overhangs, trimming); #ifdef SLIC3R_DEBUG SVG::export_expolygons(debug_out_path("support-support-areas-%s-raw-%d-%lf.svg", debug_name, iRun, layer.print_z), @@ -2685,7 +2682,7 @@ void PrintObjectSupportMaterial::generate_base_layers( layer_intermediate.polygons = diff( polygons_new, polygons_trimming, - true); // safety offset to merge the touching source polygons + ApplySafetyOffset::Yes); // safety offset to merge the touching source polygons layer_intermediate.layer_type = sltBase; #if 0 @@ -2767,14 +2764,13 @@ void PrintObjectSupportMaterial::trim_support_layers_by_object( const Layer &object_layer = *object.layers()[i]; bool some_region_overlaps = false; for (LayerRegion *region : object_layer.regions()) { - coordf_t bridging_height = region->region()->bridging_height_avg(*this->m_print_config); + coordf_t bridging_height = region->region().bridging_height_avg(*m_print_config); if (object_layer.print_z - bridging_height > support_layer.print_z + gap_extra_above - EPSILON) break; some_region_overlaps = true; polygons_append(polygons_trimming, - offset(to_expolygons(region->fill_surfaces.filter_by_type(stBottomBridge)), - gap_xy_scaled, SUPPORT_SURFACES_OFFSET_PARAMETERS)); - if (region->region()->config().overhangs.value) + offset(region->fill_surfaces.filter_by_type(stBottomBridge), gap_xy_scaled, SUPPORT_SURFACES_OFFSET_PARAMETERS)); + if (region->region().config().overhangs.value) // Add bridging perimeters. SupportMaterialInternal::collect_bridging_perimeter_areas(region->perimeters, gap_xy_scaled, polygons_trimming); } @@ -2989,9 +2985,9 @@ std::pairfill_surface(&surface, fill_params); - } catch (InfillFailedException &) { - } + } catch (InfillFailedException &) { + } extrusion_entities_append_paths( dst, std::move(polylines), @@ -3186,7 +3182,7 @@ struct MyLayerExtruded MyLayerExtruded& operator=(MyLayerExtruded &&rhs) { this->layer = rhs.layer; this->extrusions = std::move(rhs.extrusions); - this->m_polygons_to_extrude = std::move(rhs.m_polygons_to_extrude); + m_polygons_to_extrude = std::move(rhs.m_polygons_to_extrude); rhs.layer = nullptr; return *this; } @@ -3221,21 +3217,21 @@ struct MyLayerExtruded m_polygons_to_extrude = std::make_unique(this->layer->polygons); } Slic3r::polygons_append(*m_polygons_to_extrude, std::move(*other.m_polygons_to_extrude)); - *m_polygons_to_extrude = union_(*m_polygons_to_extrude, true); + *m_polygons_to_extrude = union_safety_offset(*m_polygons_to_extrude); other.m_polygons_to_extrude.reset(); } else if (m_polygons_to_extrude != nullptr) { assert(other.m_polygons_to_extrude == nullptr); // The other layer has no extrusions generated yet, if it has no m_polygons_to_extrude (its area to extrude was not reduced yet). assert(other.extrusions.empty()); Slic3r::polygons_append(*m_polygons_to_extrude, other.layer->polygons); - *m_polygons_to_extrude = union_(*m_polygons_to_extrude, true); + *m_polygons_to_extrude = union_safety_offset(*m_polygons_to_extrude); } // 2) Merge the extrusions. this->extrusions.insert(this->extrusions.end(), other.extrusions.begin(), other.extrusions.end()); other.extrusions.clear(); // 3) Merge the infill polygons. Slic3r::polygons_append(this->layer->polygons, std::move(other.layer->polygons)); - this->layer->polygons = union_(this->layer->polygons, true); + this->layer->polygons = union_safety_offset(this->layer->polygons); other.layer->polygons.clear(); } @@ -3615,8 +3611,8 @@ void modulate_extrusion_by_overlapping_layers( const PrintObjectSupportMaterial::MyLayer &overlapping_layer = *overlapping_layers[i_overlapping_layer]; ExtrusionPathFragment &frag = path_fragments[i_overlapping_layer]; Polygons polygons_trimming = offset(union_ex(overlapping_layer.polygons), float(scale_(0.5*extrusion_width))); - frag.polylines = intersection_pl(path_fragments.back().polylines, polygons_trimming, false); - path_fragments.back().polylines = diff_pl(path_fragments.back().polylines, polygons_trimming, false); + frag.polylines = intersection_pl(path_fragments.back().polylines, polygons_trimming); + path_fragments.back().polylines = diff_pl(path_fragments.back().polylines, polygons_trimming); // Adjust the extrusion parameters for a reduced layer height and a non-bridging flow (nozzle_dmr = -1, does not matter). assert(this_layer.print_z > overlapping_layer.print_z); frag.height = float(this_layer.print_z - overlapping_layer.print_z); @@ -4039,7 +4035,7 @@ void PrintObjectSupportMaterial::generate_toolpaths( // Destination layer_ex.extrusions, // Regions to fill - union_ex(layer_ex.polygons_to_extrude(), true), + union_safety_offset_ex(layer_ex.polygons_to_extrude()), // Filler and its parameters filler_interface.get(), float(density), // Extrusion parameters @@ -4061,7 +4057,7 @@ void PrintObjectSupportMaterial::generate_toolpaths( base_interface_layer.extrusions, //base_layer_interface.extrusions, // Regions to fill - union_ex(base_interface_layer.polygons_to_extrude(), true), + union_safety_offset_ex(base_interface_layer.polygons_to_extrude()), // Filler and its parameters filler, float(interface_density), // Extrusion parameters diff --git a/src/libslic3r/Surface.hpp b/src/libslic3r/Surface.hpp index fbebe5610..4920efbbf 100644 --- a/src/libslic3r/Surface.hpp +++ b/src/libslic3r/Surface.hpp @@ -90,7 +90,6 @@ public: return *this; } - operator Polygons() const { return this->expolygon; } double area() const { return this->expolygon.area(); } bool empty() const { return expolygon.empty(); } void clear() { expolygon.clear(); } @@ -107,6 +106,16 @@ public: typedef std::vector Surfaces; typedef std::vector SurfacesPtr; +inline Polygons to_polygons(const Surface &surface) +{ + return to_polygons(surface.expolygon); +} + +inline Polygons to_polygons(Surface &&surface) +{ + return to_polygons(std::move(surface.expolygon)); +} + inline Polygons to_polygons(const Surfaces &src) { size_t num = 0; diff --git a/src/libslic3r/SurfaceCollection.cpp b/src/libslic3r/SurfaceCollection.cpp index 6db599306..ec847d2a3 100644 --- a/src/libslic3r/SurfaceCollection.cpp +++ b/src/libslic3r/SurfaceCollection.cpp @@ -6,18 +6,7 @@ namespace Slic3r { -SurfaceCollection::operator Polygons() const -{ - return to_polygons(surfaces); -} - -SurfaceCollection::operator ExPolygons() const -{ - return to_expolygons(surfaces); -} - -void -SurfaceCollection::simplify(double tolerance) +void SurfaceCollection::simplify(double tolerance) { Surfaces ss; for (Surfaces::const_iterator it_s = this->surfaces.begin(); it_s != this->surfaces.end(); ++it_s) { @@ -33,8 +22,7 @@ SurfaceCollection::simplify(double tolerance) } /* group surfaces by common properties */ -void -SurfaceCollection::group(std::vector *retval) +void SurfaceCollection::group(std::vector *retval) { for (Surfaces::iterator it = this->surfaces.begin(); it != this->surfaces.end(); ++it) { // find a group with the same properties @@ -54,8 +42,7 @@ SurfaceCollection::group(std::vector *retval) } } -SurfacesPtr -SurfaceCollection::filter_by_type(const SurfaceType type) +SurfacesPtr SurfaceCollection::filter_by_type(const SurfaceType type) { SurfacesPtr ss; for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) { @@ -64,8 +51,7 @@ SurfaceCollection::filter_by_type(const SurfaceType type) return ss; } -SurfacesPtr -SurfaceCollection::filter_by_types(const SurfaceType *types, int ntypes) +SurfacesPtr SurfaceCollection::filter_by_types(const SurfaceType *types, int ntypes) { SurfacesPtr ss; for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) { @@ -79,8 +65,7 @@ SurfaceCollection::filter_by_types(const SurfaceType *types, int ntypes) return ss; } -void -SurfaceCollection::filter_by_type(SurfaceType type, Polygons* polygons) +void SurfaceCollection::filter_by_type(SurfaceType type, Polygons* polygons) { for (Surfaces::iterator surface = this->surfaces.begin(); surface != this->surfaces.end(); ++surface) { if (surface->surface_type == type) { @@ -90,8 +75,7 @@ SurfaceCollection::filter_by_type(SurfaceType type, Polygons* polygons) } } -void -SurfaceCollection::keep_type(const SurfaceType type) +void SurfaceCollection::keep_type(const SurfaceType type) { size_t j = 0; for (size_t i = 0; i < surfaces.size(); ++ i) { @@ -105,8 +89,7 @@ SurfaceCollection::keep_type(const SurfaceType type) surfaces.erase(surfaces.begin() + j, surfaces.end()); } -void -SurfaceCollection::keep_types(const SurfaceType *types, int ntypes) +void SurfaceCollection::keep_types(const SurfaceType *types, int ntypes) { size_t j = 0; for (size_t i = 0; i < surfaces.size(); ++ i) { @@ -127,8 +110,7 @@ SurfaceCollection::keep_types(const SurfaceType *types, int ntypes) surfaces.erase(surfaces.begin() + j, surfaces.end()); } -void -SurfaceCollection::remove_type(const SurfaceType type) +void SurfaceCollection::remove_type(const SurfaceType type) { size_t j = 0; for (size_t i = 0; i < surfaces.size(); ++ i) { @@ -142,8 +124,7 @@ SurfaceCollection::remove_type(const SurfaceType type) surfaces.erase(surfaces.begin() + j, surfaces.end()); } -void -SurfaceCollection::remove_types(const SurfaceType *types, int ntypes) +void SurfaceCollection::remove_types(const SurfaceType *types, int ntypes) { size_t j = 0; for (size_t i = 0; i < surfaces.size(); ++ i) { diff --git a/src/libslic3r/SurfaceCollection.hpp b/src/libslic3r/SurfaceCollection.hpp index 9f0324d20..7e01a68df 100644 --- a/src/libslic3r/SurfaceCollection.hpp +++ b/src/libslic3r/SurfaceCollection.hpp @@ -12,11 +12,10 @@ class SurfaceCollection public: Surfaces surfaces; - SurfaceCollection() {}; - SurfaceCollection(const Surfaces &surfaces) : surfaces(surfaces) {}; + SurfaceCollection() = default; + SurfaceCollection(const Surfaces& surfaces) : surfaces(surfaces) {}; SurfaceCollection(Surfaces &&surfaces) : surfaces(std::move(surfaces)) {}; - operator Polygons() const; - operator ExPolygons() const; + void simplify(double tolerance); void group(std::vector *retval); template bool any_internal_contains(const T &item) const { diff --git a/src/libslic3r/Technologies.hpp b/src/libslic3r/Technologies.hpp index 316cff195..480ca0ee5 100644 --- a/src/libslic3r/Technologies.hpp +++ b/src/libslic3r/Technologies.hpp @@ -59,6 +59,16 @@ #define ENABLE_EXTENDED_M73_LINES (1 && ENABLE_VALIDATE_CUSTOM_GCODE) // Enable a modified version of automatic downscale on load of objects too big #define ENABLE_MODIFIED_DOWNSCALE_ON_LOAD_OBJECTS_TOO_BIG (1 && ENABLE_2_4_0_ALPHA0) +// Enable scrollable legend in preview +#define ENABLE_SCROLLABLE_LEGEND (1 && ENABLE_2_4_0_ALPHA0) +// Enable visualization of start gcode as regular toolpaths +#define ENABLE_START_GCODE_VISUALIZATION (1 && ENABLE_2_4_0_ALPHA0) +// Enable visualization of seams in preview +#define ENABLE_SEAMS_VISUALIZATION (1 && ENABLE_2_4_0_ALPHA0) +// Enable project dirty state manager +#define ENABLE_PROJECT_DIRTY_STATE (1 && ENABLE_2_4_0_ALPHA0) +// Enable project dirty state manager debug window +#define ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW (0 && ENABLE_PROJECT_DIRTY_STATE) // Enable to push object instances under the bed #define ENABLE_ALLOW_NEGATIVE_Z (1 && ENABLE_2_4_0_ALPHA0) #define DISABLE_ALLOW_NEGATIVE_Z_FOR_SLA (1 && ENABLE_ALLOW_NEGATIVE_Z) diff --git a/src/libslic3r/TriangleMesh.cpp b/src/libslic3r/TriangleMesh.cpp index f8fa1ca17..7b5c40466 100644 --- a/src/libslic3r/TriangleMesh.cpp +++ b/src/libslic3r/TriangleMesh.cpp @@ -357,10 +357,14 @@ void TriangleMesh::transform(const Transform3d& t, bool fix_left_handed) its_transform(its, t); if (fix_left_handed && t.matrix().block(0, 0, 3, 3).determinant() < 0.) { // Left handed transformation is being applied. It is a good idea to flip the faces and their normals. - this->repair(false); - stl_reverse_all_facets(&stl); - this->its.clear(); - this->require_shared_vertices(); + // As for the assert: the repair function would fix the normals, reversing would + // break them again. The caller should provide a mesh that does not need repair. + // The repair call is left here so things don't break more than they were. + assert(this->repaired); + this->repair(false); + stl_reverse_all_facets(&stl); + this->its.clear(); + this->require_shared_vertices(); } } @@ -369,11 +373,12 @@ void TriangleMesh::transform(const Matrix3d& m, bool fix_left_handed) stl_transform(&stl, m); its_transform(its, m); if (fix_left_handed && m.determinant() < 0.) { - // Left handed transformation is being applied. It is a good idea to flip the faces and their normals. + // See comments in function above. + assert(this->repaired); this->repair(false); stl_reverse_all_facets(&stl); - this->its.clear(); - this->require_shared_vertices(); + this->its.clear(); + this->require_shared_vertices(); } } @@ -1799,9 +1804,9 @@ void TriangleMeshSlicer::make_expolygons(const Polygons &loops, const float clos // append to the supplied collection if (safety_offset > 0) - expolygons_append(*slices, offset2_ex(union_ex(loops, false), +safety_offset, -safety_offset)); + expolygons_append(*slices, offset2_ex(union_ex(loops), +safety_offset, -safety_offset)); else - expolygons_append(*slices, union_ex(loops, false)); + expolygons_append(*slices, union_ex(loops)); } void TriangleMeshSlicer::make_expolygons(std::vector &lines, const float closing_radius, ExPolygons* slices) const diff --git a/src/libslic3r/clipper.cpp b/src/libslic3r/clipper.cpp new file mode 100644 index 000000000..8f38ba621 --- /dev/null +++ b/src/libslic3r/clipper.cpp @@ -0,0 +1,13 @@ +// Hackish wrapper around the ClipperLib library to compile the Clipper library using Slic3r::Point. + +#include "clipper.hpp" + +// Don't include for the second time. +#define clipper_hpp + +// Override ClipperLib namespace to Slic3r::ClipperLib +#define CLIPPERLIB_NAMESPACE_PREFIX Slic3r +// Override Slic3r::ClipperLib::IntPoint to Slic3r::Point +#define CLIPPERLIB_INTPOINT_TYPE Slic3r::Point + +#include diff --git a/src/libslic3r/clipper.hpp b/src/libslic3r/clipper.hpp new file mode 100644 index 000000000..b0dd51a4f --- /dev/null +++ b/src/libslic3r/clipper.hpp @@ -0,0 +1,26 @@ +// Hackish wrapper around the ClipperLib library to compile the Clipper library using Slic3r's own Point type. + +#ifndef slic3r_clipper_hpp + +#ifdef clipper_hpp +#error "You should include the libslic3r/clipper.hpp before clipper/clipper.hpp" +#endif + +#ifdef CLIPPERLIB_USE_XYZ +#error "Something went wrong. Using clipper.hpp with Slic3r Point type, but CLIPPERLIB_USE_XYZ is defined." +#endif + +#define slic3r_clipper_hpp + +#include "Point.hpp" + +#define CLIPPERLIB_NAMESPACE_PREFIX Slic3r +#define CLIPPERLIB_INTPOINT_TYPE Slic3r::Point + +#include + +#undef clipper_hpp +#undef CLIPPERLIB_NAMESPACE_PREFIX +#undef CLIPPERLIB_INTPOINT_TYPE + +#endif // slic3r_clipper_hpp diff --git a/src/libslic3r/libslic3r.h b/src/libslic3r/libslic3r.h index efdecbac8..2b0c94161 100644 --- a/src/libslic3r/libslic3r.h +++ b/src/libslic3r/libslic3r.h @@ -308,6 +308,10 @@ IntegerOnly> reserve_vector(I capacity) return ret; } +// Borrowed from C++20 +template +using remove_cvref_t = std::remove_cv_t>; + } // namespace Slic3r #endif diff --git a/src/libslic3r/pchheader.hpp b/src/libslic3r/pchheader.hpp index 9386fdf36..b55755b89 100644 --- a/src/libslic3r/pchheader.hpp +++ b/src/libslic3r/pchheader.hpp @@ -114,7 +114,7 @@ #include #include -#include +#include "clipper.hpp" #include "BoundingBox.hpp" #include "ClipperUtils.hpp" #include "Config.hpp" @@ -129,8 +129,6 @@ #include "libslic3r.h" #include "libslic3r_version.h" -#include "clipper.hpp" - #include #include diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 4b3a1c6ca..aa3bf01c4 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -189,6 +189,10 @@ set(SLIC3R_GUI_SOURCES GUI/UnsavedChangesDialog.hpp GUI/ExtraRenderers.cpp GUI/ExtraRenderers.hpp + GUI/ProjectDirtyStateManager.hpp + GUI/ProjectDirtyStateManager.cpp + GUI/DesktopIntegrationDialog.cpp + GUI/DesktopIntegrationDialog.hpp Utils/Http.cpp Utils/Http.hpp Utils/FixModelByWin10.cpp diff --git a/src/slic3r/GUI/3DBed.cpp b/src/slic3r/GUI/3DBed.cpp index 1c43e7eb0..29551ac15 100644 --- a/src/slic3r/GUI/3DBed.cpp +++ b/src/slic3r/GUI/3DBed.cpp @@ -194,7 +194,7 @@ bool Bed3D::set_shape(const Pointfs& shape, const std::string& custom_texture, c const BoundingBox& bed_bbox = poly.contour.bounding_box(); calc_gridlines(poly, bed_bbox); - m_polygon = offset_ex(poly.contour, (float)bed_bbox.radius() * 1.7f, jtRound, scale_(0.5))[0].contour; + m_polygon = offset(poly.contour, (float)bed_bbox.radius() * 1.7f, jtRound, scale_(0.5))[0]; reset(); m_texture.reset(); diff --git a/src/slic3r/GUI/BackgroundSlicingProcess.cpp b/src/slic3r/GUI/BackgroundSlicingProcess.cpp index 089fba656..2869f11c8 100644 --- a/src/slic3r/GUI/BackgroundSlicingProcess.cpp +++ b/src/slic3r/GUI/BackgroundSlicingProcess.cpp @@ -145,7 +145,7 @@ void BackgroundSlicingProcess::process_fff() // Passing the timestamp evt.SetInt((int)(m_fff_print->step_state_with_timestamp(PrintStep::psSlicingFinished).timestamp)); wxQueueEvent(GUI::wxGetApp().mainframe->m_plater, evt.Clone()); - m_fff_print->export_gcode(m_temp_output_path, m_gcode_result, m_thumbnail_cb); + m_fff_print->export_gcode(m_temp_output_path, m_gcode_result, [this](const ThumbnailsParams& params) { return this->render_thumbnails(params); }); if (this->set_step_started(bspsGCodeFinalize)) { if (! m_export_path.empty()) { wxQueueEvent(GUI::wxGetApp().mainframe->m_plater, new wxCommandEvent(m_event_export_began_id)); @@ -221,21 +221,14 @@ void BackgroundSlicingProcess::process_sla() const std::string export_path = m_sla_print->print_statistics().finalize_output_path(m_export_path); + ThumbnailsList thumbnails = this->render_thumbnails( + ThumbnailsParams{current_print()->full_print_config().option("thumbnails")->values, true, true, true, true}); + Zipper zipper(export_path); - m_sla_archive.export_print(zipper, *m_sla_print); - - if (m_thumbnail_cb != nullptr) - { - ThumbnailsList thumbnails; - m_thumbnail_cb(thumbnails, current_print()->full_print_config().option("thumbnails")->values, true, true, true, true); -// m_thumbnail_cb(thumbnails, current_print()->full_print_config().option("thumbnails")->values, true, false, true, true); // renders also supports and pad - for (const ThumbnailData& data : thumbnails) - { - if (data.is_valid()) - write_thumbnail(zipper, data); - } - } - + m_sla_archive.export_print(zipper, *m_sla_print); // true, false, true, true); // renders also supports and pad + for (const ThumbnailData& data : thumbnails) + if (data.is_valid()) + write_thumbnail(zipper, data); zipper.finalize(); m_print->set_status(100, (boost::format(_utf8(L("Masked SLA file exported to %1%"))) % export_path).str()); @@ -362,16 +355,19 @@ bool BackgroundSlicingProcess::start() return true; } +// To be called on the UI thread. bool BackgroundSlicingProcess::stop() { // m_print->state_mutex() shall NOT be held. Unfortunately there is no interface to test for it. std::unique_lock lck(m_mutex); if (m_state == STATE_INITIAL) { -// this->m_export_path.clear(); +// m_export_path.clear(); return false; } // assert(this->running()); if (m_state == STATE_STARTED || m_state == STATE_RUNNING) { + // Cancel any task planned by the background thread on UI thread. + cancel_ui_task(m_ui_task); m_print->cancel(); // Wait until the background processing stops by being canceled. m_condition.wait(lck, [this](){ return m_state == STATE_CANCELED; }); @@ -383,7 +379,7 @@ bool BackgroundSlicingProcess::stop() m_state = STATE_IDLE; m_print->set_cancel_callback([](){}); } -// this->m_export_path.clear(); +// m_export_path.clear(); return true; } @@ -396,7 +392,7 @@ bool BackgroundSlicingProcess::reset() return stopped; } -// To be called by Print::apply() through the Print::m_cancel_callback to stop the background +// To be called by Print::apply() on the UI thread through the Print::m_cancel_callback to stop the background // processing before changing any data of running or finalized milestones. // This function shall not trigger any UI update through the wxWidgets event. void BackgroundSlicingProcess::stop_internal() @@ -408,6 +404,8 @@ void BackgroundSlicingProcess::stop_internal() std::unique_lock lck(m_mutex); assert(m_state == STATE_STARTED || m_state == STATE_RUNNING || m_state == STATE_FINISHED || m_state == STATE_CANCELED); if (m_state == STATE_STARTED || m_state == STATE_RUNNING) { + // Cancel any task planned by the background thread on UI thread. + cancel_ui_task(m_ui_task); // At this point of time the worker thread may be blocking on m_print->state_mutex(). // Set the print state to canceled before unlocking the state_mutex(), so when the worker thread wakes up, // it throws the CanceledException(). @@ -424,6 +422,60 @@ void BackgroundSlicingProcess::stop_internal() m_print->set_cancel_callback([](){}); } +// Execute task from background thread on the UI thread. Returns true if processed, false if cancelled. +bool BackgroundSlicingProcess::execute_ui_task(std::function task) +{ + bool running = false; + if (m_mutex.try_lock()) { + // Cancellation is either not in process, or already canceled and waiting for us to finish. + // There must be no UI task planned. + assert(! m_ui_task); + if (! m_print->canceled()) { + running = true; + m_ui_task = std::make_shared(); + } + m_mutex.unlock(); + } else { + // Cancellation is in process. + } + + bool result = false; + if (running) { + std::shared_ptr ctx = m_ui_task; + GUI::wxGetApp().mainframe->m_plater->CallAfter([task, ctx]() { + // Running on the UI thread, thus ctx->state does not need to be guarded with mutex against ::cancel_ui_task(). + assert(ctx->state == UITask::Planned || ctx->state == UITask::Canceled); + if (ctx->state == UITask::Planned) { + task(); + std::unique_lock lck(ctx->mutex); + ctx->state = UITask::Finished; + } + // Wake up the worker thread from the UI thread. + ctx->condition.notify_all(); + }); + + { + std::unique_lock lock(ctx->mutex); + ctx->condition.wait(lock, [&ctx]{ return ctx->state == UITask::Finished || ctx->state == UITask::Canceled; }); + } + result = ctx->state == UITask::Finished; + m_ui_task.reset(); + } + + return result; +} + +// To be called on the UI thread from ::stop() and ::stop_internal(). +void BackgroundSlicingProcess::cancel_ui_task(std::shared_ptr task) +{ + if (task) { + std::unique_lock lck(task->mutex); + task->state = UITask::Canceled; + lck.unlock(); + task->condition.notify_all(); + } +} + bool BackgroundSlicingProcess::empty() const { assert(m_print != nullptr); @@ -444,7 +496,7 @@ Print::ApplyStatus BackgroundSlicingProcess::apply(const Model &model, const Dyn assert(config.opt_enum("printer_technology") == m_print->technology()); Print::ApplyStatus invalidated = m_print->apply(model, config); if ((invalidated & PrintBase::APPLY_STATUS_INVALIDATED) != 0 && m_print->technology() == ptFFF && - !this->m_fff_print->is_step_done(psGCodeExport)) { + !m_fff_print->is_step_done(psGCodeExport)) { // Some FFF status was invalidated, and the G-code was not exported yet. // Let the G-code preview UI know that the final G-code preview is not valid. // In addition, this early memory deallocation reduces memory footprint. @@ -546,19 +598,14 @@ void BackgroundSlicingProcess::prepare_upload() } else { m_upload_job.upload_data.upload_path = m_sla_print->print_statistics().finalize_output_path(m_upload_job.upload_data.upload_path.string()); + ThumbnailsList thumbnails = this->render_thumbnails( + ThumbnailsParams{current_print()->full_print_config().option("thumbnails")->values, true, true, true, true}); + // true, false, true, true); // renders also supports and pad Zipper zipper{source_path.string()}; m_sla_archive.export_print(zipper, *m_sla_print, m_upload_job.upload_data.upload_path.string()); - if (m_thumbnail_cb != nullptr) - { - ThumbnailsList thumbnails; - m_thumbnail_cb(thumbnails, current_print()->full_print_config().option("thumbnails")->values, true, true, true, true); -// m_thumbnail_cb(thumbnails, current_print()->full_print_config().option("thumbnails")->values, true, false, true, true); // renders also supports and pad - for (const ThumbnailData& data : thumbnails) - { - if (data.is_valid()) - write_thumbnail(zipper, data); - } - } + for (const ThumbnailData& data : thumbnails) + if (data.is_valid()) + write_thumbnail(zipper, data); zipper.finalize(); } @@ -569,4 +616,13 @@ void BackgroundSlicingProcess::prepare_upload() GUI::wxGetApp().printhost_job_queue().enqueue(std::move(m_upload_job)); } +// Executed by the background thread, to start a task on the UI thread. +ThumbnailsList BackgroundSlicingProcess::render_thumbnails(const ThumbnailsParams ¶ms) +{ + ThumbnailsList thumbnails; + if (m_thumbnail_cb) + this->execute_ui_task([this, ¶ms, &thumbnails](){ thumbnails = m_thumbnail_cb(params); }); + return thumbnails; +} + }; // namespace Slic3r diff --git a/src/slic3r/GUI/BackgroundSlicingProcess.hpp b/src/slic3r/GUI/BackgroundSlicingProcess.hpp index d3819f15c..dc24ec0ad 100644 --- a/src/slic3r/GUI/BackgroundSlicingProcess.hpp +++ b/src/slic3r/GUI/BackgroundSlicingProcess.hpp @@ -212,6 +212,23 @@ private: std::condition_variable m_condition; State m_state = STATE_INITIAL; + // For executing tasks from the background thread on UI thread synchronously (waiting for result) using wxWidgets CallAfter(). + // When the background proces is canceled, the UITask has to be invalidated as well, so that it will not be + // executed on the UI thread referencing invalid data. + struct UITask { + enum State { + Planned, + Finished, + Canceled, + }; + State state = Planned; + std::mutex mutex; + std::condition_variable condition; + }; + // Only one UI task may be planned by the background thread to be executed on the UI thread, as the background + // thread is blocking until the UI thread calculation finishes. + std::shared_ptr m_ui_task; + PrintState m_step_state; mutable tbb::mutex m_step_state_mutex; bool set_step_started(BackgroundSlicingProcessStep step); @@ -222,6 +239,12 @@ private: // If the background processing stop was requested, throw CanceledException. void throw_if_canceled() const { if (m_print->canceled()) throw CanceledException(); } void prepare_upload(); + // To be executed at the background thread. + ThumbnailsList render_thumbnails(const ThumbnailsParams ¶ms); + // Execute task from background thread on the UI thread synchronously. Returns true if processed, false if cancelled before executing the task. + bool execute_ui_task(std::function task); + // To be called from inside m_mutex to cancel a planned UI task. + static void cancel_ui_task(std::shared_ptr task); // wxWidgets command ID to be sent to the plater to inform that the slicing is finished, and the G-code export will continue. int m_event_slicing_completed_id = 0; diff --git a/src/slic3r/GUI/ConfigManipulation.cpp b/src/slic3r/GUI/ConfigManipulation.cpp index cd7805a88..d55758538 100644 --- a/src/slic3r/GUI/ConfigManipulation.cpp +++ b/src/slic3r/GUI/ConfigManipulation.cpp @@ -45,7 +45,7 @@ void ConfigManipulation::update_print_fff_config(DynamicPrintConfig* config, con // layer_height shouldn't be equal to zero if (config->opt_float("layer_height") < EPSILON) { - const wxString msg_text = _(L("Zero layer height is not valid.\n\nThe layer height will be reset to 0.01.")); + const wxString msg_text = _(L("Layer height is not valid.\n\nThe layer height will be reset to 0.01.")); wxMessageDialog dialog(nullptr, msg_text, _(L("Layer height")), wxICON_WARNING | wxOK); DynamicPrintConfig new_conf = *config; is_msg_dlg_already_exist = true; @@ -55,9 +55,9 @@ void ConfigManipulation::update_print_fff_config(DynamicPrintConfig* config, con is_msg_dlg_already_exist = false; } - if (fabs(config->option("first_layer_height")->value - 0) < EPSILON) + if (config->option("first_layer_height")->value < EPSILON) { - const wxString msg_text = _(L("Zero first layer height is not valid.\n\nThe first layer height will be reset to 0.01.")); + const wxString msg_text = _(L("First layer height is not valid.\n\nThe first layer height will be reset to 0.01.")); wxMessageDialog dialog(nullptr, msg_text, _(L("First layer height")), wxICON_WARNING | wxOK); DynamicPrintConfig new_conf = *config; is_msg_dlg_already_exist = true; diff --git a/src/slic3r/GUI/ConfigWizard.cpp b/src/slic3r/GUI/ConfigWizard.cpp index bd6986d3e..52df39fd5 100644 --- a/src/slic3r/GUI/ConfigWizard.cpp +++ b/src/slic3r/GUI/ConfigWizard.cpp @@ -26,14 +26,18 @@ #include #include +#include "libslic3r/Platform.hpp" #include "libslic3r/Utils.hpp" #include "libslic3r/Config.hpp" #include "GUI.hpp" #include "GUI_App.hpp" #include "GUI_Utils.hpp" #include "GUI_ObjectManipulation.hpp" +#include "Field.hpp" +#include "DesktopIntegrationDialog.hpp" #include "slic3r/Config/Snapshot.hpp" #include "slic3r/Utils/PresetUpdater.hpp" +#include "format.hpp" #if defined(__linux__) && defined(__WXGTK3__) #define wxLinux_gtk3 true @@ -450,7 +454,6 @@ void ConfigWizardPage::append_spacer(int space) content->AddSpacer(space); } - // Wizard pages PageWelcome::PageWelcome(ConfigWizard *parent) @@ -469,9 +472,21 @@ PageWelcome::PageWelcome(ConfigWizard *parent) , cbox_reset(append( new wxCheckBox(this, wxID_ANY, _L("Remove user profiles (a snapshot will be taken beforehand)")) )) + , cbox_integrate(append( + new wxCheckBox(this, wxID_ANY, _L("Perform desktop integration (Sets this binary to be searchable by the system).")) + )) { welcome_text->Hide(); cbox_reset->Hide(); +#ifdef __linux__ + if (!DesktopIntegrationDialog::is_integrated()) + cbox_integrate->Show(true); + else + cbox_integrate->Hide(); +#else + cbox_integrate->Hide(); +#endif + } void PageWelcome::set_run_reason(ConfigWizard::RunReason run_reason) @@ -479,6 +494,14 @@ void PageWelcome::set_run_reason(ConfigWizard::RunReason run_reason) const bool data_empty = run_reason == ConfigWizard::RR_DATA_EMPTY; welcome_text->Show(data_empty); cbox_reset->Show(!data_empty); +#ifdef __linux__ + if (!DesktopIntegrationDialog::is_integrated()) + cbox_integrate->Show(true); + else + cbox_integrate->Hide(); +#else + cbox_integrate->Hide(); +#endif } @@ -1361,20 +1384,39 @@ void PageBedShape::apply_custom_config(DynamicPrintConfig &config) config.set_key_value("bed_custom_model", new ConfigOptionString(custom_model)); } +static void focus_event(wxFocusEvent& e, wxTextCtrl* ctrl, double def_value) +{ + e.Skip(); + wxString str = ctrl->GetValue(); + // Replace the first occurence of comma in decimal number. + bool was_replace = str.Replace(",", ".", false) > 0; + double val = 0.0; + if (!str.ToCDouble(&val)) { + if (val == 0.0) + val = def_value; + ctrl->SetValue(double_to_string(val)); + show_error(nullptr, _L("Invalid numeric input.")); + ctrl->SetFocus(); + } + else if (was_replace) + ctrl->SetValue(double_to_string(val)); +} + PageDiameters::PageDiameters(ConfigWizard *parent) : ConfigWizardPage(parent, _L("Filament and Nozzle Diameters"), _L("Print Diameters"), 1) - , spin_nozzle(new wxSpinCtrlDouble(this, wxID_ANY)) - , spin_filam(new wxSpinCtrlDouble(this, wxID_ANY)) + , diam_nozzle(new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(Field::def_width_thinner() * wxGetApp().em_unit(), wxDefaultCoord))) + , diam_filam (new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(Field::def_width_thinner() * wxGetApp().em_unit(), wxDefaultCoord))) { - spin_nozzle->SetDigits(2); - spin_nozzle->SetIncrement(0.1); auto *default_nozzle = print_config_def.get("nozzle_diameter")->get_default_value(); - spin_nozzle->SetValue(default_nozzle != nullptr && default_nozzle->size() > 0 ? default_nozzle->get_at(0) : 0.5); + wxString value = double_to_string(default_nozzle != nullptr && default_nozzle->size() > 0 ? default_nozzle->get_at(0) : 0.5); + diam_nozzle->SetValue(value); - spin_filam->SetDigits(2); - spin_filam->SetIncrement(0.25); auto *default_filam = print_config_def.get("filament_diameter")->get_default_value(); - spin_filam->SetValue(default_filam != nullptr && default_filam->size() > 0 ? default_filam->get_at(0) : 3.0); + value = double_to_string(default_filam != nullptr && default_filam->size() > 0 ? default_filam->get_at(0) : 3.0); + diam_filam->SetValue(value); + + diam_nozzle->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { focus_event(e, diam_nozzle, 0.5); }, diam_nozzle->GetId()); + diam_filam ->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { focus_event(e, diam_filam , 3.0); }, diam_filam->GetId()); append_text(_L("Enter the diameter of your printer's hot end nozzle.")); @@ -1383,7 +1425,7 @@ PageDiameters::PageDiameters(ConfigWizard *parent) auto *unit_nozzle = new wxStaticText(this, wxID_ANY, _L("mm")); sizer_nozzle->AddGrowableCol(0, 1); sizer_nozzle->Add(text_nozzle, 0, wxALIGN_CENTRE_VERTICAL); - sizer_nozzle->Add(spin_nozzle); + sizer_nozzle->Add(diam_nozzle); sizer_nozzle->Add(unit_nozzle, 0, wxALIGN_CENTRE_VERTICAL); append(sizer_nozzle); @@ -1397,16 +1439,21 @@ PageDiameters::PageDiameters(ConfigWizard *parent) auto *unit_filam = new wxStaticText(this, wxID_ANY, _L("mm")); sizer_filam->AddGrowableCol(0, 1); sizer_filam->Add(text_filam, 0, wxALIGN_CENTRE_VERTICAL); - sizer_filam->Add(spin_filam); + sizer_filam->Add(diam_filam); sizer_filam->Add(unit_filam, 0, wxALIGN_CENTRE_VERTICAL); append(sizer_filam); } void PageDiameters::apply_custom_config(DynamicPrintConfig &config) { - auto *opt_nozzle = new ConfigOptionFloats(1, spin_nozzle->GetValue()); + double val = 0.0; + diam_nozzle->GetValue().ToCDouble(&val); + auto *opt_nozzle = new ConfigOptionFloats(1, val); config.set_key_value("nozzle_diameter", opt_nozzle); - auto *opt_filam = new ConfigOptionFloats(1, spin_filam->GetValue()); + + val = 0.0; + diam_filam->GetValue().ToCDouble(&val); + auto * opt_filam = new ConfigOptionFloats(1, val); config.set_key_value("filament_diameter", opt_filam); auto set_extrusion_width = [&config, opt_nozzle](const char *key, double dmr) { @@ -2373,6 +2420,12 @@ void ConfigWizard::priv::apply_config(AppConfig *app_config, PresetBundle *prese } } +#ifdef __linux__ + // Desktop integration on Linux + if (page_welcome->integrate_desktop()) + DesktopIntegrationDialog::perform_desktop_integration(); +#endif + // Decide whether to create snapshot based on run_reason and the reset profile checkbox bool snapshot = true; Snapshot::Reason snapshot_reason = Snapshot::SNAPSHOT_UPGRADE; @@ -2490,7 +2543,6 @@ void ConfigWizard::priv::apply_config(AppConfig *app_config, PresetBundle *prese // Update the selections from the compatibilty. preset_bundle->export_selections(*app_config); } - void ConfigWizard::priv::update_presets_in_config(const std::string& section, const std::string& alias_key, bool add) { const PresetAliases& aliases = section == AppConfig::SECTION_FILAMENTS ? aliases_fff : aliases_sla; diff --git a/src/slic3r/GUI/ConfigWizard.hpp b/src/slic3r/GUI/ConfigWizard.hpp index 942f4b4ce..86245836b 100644 --- a/src/slic3r/GUI/ConfigWizard.hpp +++ b/src/slic3r/GUI/ConfigWizard.hpp @@ -45,7 +45,6 @@ public: bool run(RunReason reason, StartPage start_page = SP_WELCOME); static const wxString& name(const bool from_menu = false); - protected: void on_dpi_changed(const wxRect &suggested_rect) override ; diff --git a/src/slic3r/GUI/ConfigWizard_private.hpp b/src/slic3r/GUI/ConfigWizard_private.hpp index eee906ae7..ea39e04ab 100644 --- a/src/slic3r/GUI/ConfigWizard_private.hpp +++ b/src/slic3r/GUI/ConfigWizard_private.hpp @@ -227,10 +227,12 @@ struct PageWelcome: ConfigWizardPage { wxStaticText *welcome_text; wxCheckBox *cbox_reset; + wxCheckBox *cbox_integrate; PageWelcome(ConfigWizard *parent); bool reset_user_profile() const { return cbox_reset != nullptr ? cbox_reset->GetValue() : false; } + bool integrate_desktop() const { return cbox_integrate != nullptr ? cbox_integrate->GetValue() : false; } virtual void set_run_reason(ConfigWizard::RunReason run_reason) override; }; @@ -449,8 +451,8 @@ struct PageBedShape: ConfigWizardPage struct PageDiameters: ConfigWizardPage { - wxSpinCtrlDouble *spin_nozzle; - wxSpinCtrlDouble *spin_filam; + wxTextCtrl *diam_nozzle; + wxTextCtrl *diam_filam; PageDiameters(ConfigWizard *parent); virtual void apply_custom_config(DynamicPrintConfig &config); @@ -615,7 +617,9 @@ struct ConfigWizard::priv void apply_config(AppConfig *app_config, PresetBundle *preset_bundle, const PresetUpdater *updater); // #ys_FIXME_alise void update_presets_in_config(const std::string& section, const std::string& alias_key, bool add); - +#ifdef __linux__ + void perform_desktop_integration() const; +#endif bool check_fff_selected(); // Used to decide whether to display Filaments page bool check_sla_selected(); // Used to decide whether to display SLA Materials page diff --git a/src/slic3r/GUI/DesktopIntegrationDialog.cpp b/src/slic3r/GUI/DesktopIntegrationDialog.cpp new file mode 100644 index 000000000..a2f7c8933 --- /dev/null +++ b/src/slic3r/GUI/DesktopIntegrationDialog.cpp @@ -0,0 +1,408 @@ +#ifdef __linux__ +#include "DesktopIntegrationDialog.hpp" +#include "GUI_App.hpp" +#include "format.hpp" +#include "I18N.hpp" +#include "NotificationManager.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Utils.hpp" +#include "libslic3r/Platform.hpp" + +#include +#include + +#include +#include + +namespace Slic3r { +namespace GUI { + +namespace integrate_desktop_internal{ +// Disects path strings stored in system variable divided by ':' and adds into vector +static void resolve_path_from_var(const std::string& var, std::vector& paths) +{ + wxString wxdirs; + if (! wxGetEnv(boost::nowide::widen(var), &wxdirs) || wxdirs.empty() ) + return; + std::string dirs = boost::nowide::narrow(wxdirs); + for (size_t i = dirs.find(':'); i != std::string::npos; i = dirs.find(':')) + { + paths.push_back(dirs.substr(0, i)); + if (dirs.size() > i+1) + dirs = dirs.substr(i+1); + } + paths.push_back(dirs); +} +// Return true if directory in path p+dir_name exists +static bool contains_path_dir(const std::string& p, const std::string& dir_name) +{ + if (p.empty() || dir_name.empty()) + return false; + boost::filesystem::path path(p + (p[p.size()-1] == '/' ? "" : "/") + dir_name); + if (boost::filesystem::exists(path) && boost::filesystem::is_directory(path)) { + //BOOST_LOG_TRIVIAL(debug) << path.string() << " " << std::oct << boost::filesystem::status(path).permissions(); + return true; //boost::filesystem::status(path).permissions() & boost::filesystem::owner_write; + } else + BOOST_LOG_TRIVIAL(debug) << path.string() << " doesnt exists"; + return false; +} +// Creates directory in path if not exists yet +static void create_dir(const boost::filesystem::path& path) +{ + if (boost::filesystem::exists(path)) + return; + BOOST_LOG_TRIVIAL(debug)<< "creating " << path.string(); + boost::system::error_code ec; + boost::filesystem::create_directory(path, ec); + if (ec) + BOOST_LOG_TRIVIAL(error)<< "create directory failed: " << ec.message(); +} +// Starts at basic_path (excluded) and creates all directories in dir_path +static void create_path(const std::string& basic_path, const std::string& dir_path) +{ + if (basic_path.empty() || dir_path.empty()) + return; + + boost::filesystem::path path(basic_path); + std::string dirs = dir_path; + for (size_t i = dirs.find('/'); i != std::string::npos; i = dirs.find('/')) + { + std::string dir = dirs.substr(0, i); + path = boost::filesystem::path(path.string() +"/"+ dir); + create_dir(path); + dirs = dirs.substr(i+1); + } + path = boost::filesystem::path(path.string() +"/"+ dirs); + create_dir(path); +} +// Calls our internal copy_file function to copy file at icon_path to dest_path +static bool copy_icon(const std::string& icon_path, const std::string& dest_path) +{ + BOOST_LOG_TRIVIAL(debug) <<"icon from "<< icon_path; + BOOST_LOG_TRIVIAL(debug) <<"icon to "<< dest_path; + std::string error_message; + auto cfr = copy_file(icon_path, dest_path, error_message, false); + if (cfr) { + BOOST_LOG_TRIVIAL(debug) << "Copy icon fail(" << cfr << "): " << error_message; + return false; + } + BOOST_LOG_TRIVIAL(debug) << "Copy icon success."; + return true; +} +// Creates new file filled with data. +static bool create_desktop_file(const std::string& path, const std::string& data) +{ + BOOST_LOG_TRIVIAL(debug) <<".desktop to "<< path; + std::ofstream output(path); + output << data; + struct stat buffer; + if (stat(path.c_str(), &buffer) == 0) + { + BOOST_LOG_TRIVIAL(debug) << "Desktop file created."; + return true; + } + BOOST_LOG_TRIVIAL(debug) << "Desktop file NOT created."; + return false; +} +} // namespace integratec_desktop_internal + +// methods that actually do / undo desktop integration. Static to be accesible from anywhere. +bool DesktopIntegrationDialog::is_integrated() +{ + const char *appimage_env = std::getenv("APPIMAGE"); + if (!appimage_env) + return false; + + const AppConfig *app_config = wxGetApp().app_config; + std::string path(app_config->get("desktop_integration_app_path")); + BOOST_LOG_TRIVIAL(debug) << "Desktop integration desktop file path: " << path; + + if (path.empty()) + return false; + + // confirmation that PrusaSlicer.desktop exists + struct stat buffer; + return (stat (path.c_str(), &buffer) == 0); +} +bool DesktopIntegrationDialog::integration_possible() +{ + + const char *appimage_env = std::getenv("APPIMAGE"); + if (!appimage_env) + return false; + return true; +} +void DesktopIntegrationDialog::perform_desktop_integration() +{ + BOOST_LOG_TRIVIAL(debug) << "performing desktop integration"; + + // Path to appimage + const char *appimage_env = std::getenv("APPIMAGE"); + std::string appimage_path; + if (appimage_env) { + try { + appimage_path = boost::filesystem::canonical(boost::filesystem::path(appimage_env)).string(); + } catch (std::exception &) { + } + } else { + // not appimage - not performing + BOOST_LOG_TRIVIAL(error) << "Performing desktop integration failed - not Appimage executable."; + wxGetApp().plater()->get_notification_manager()->push_notification(NotificationType::DesktopIntegrationFail); + return; + } + + // Find directories icons and applications + // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. + // If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used. + // $XDG_DATA_DIRS defines the preference-ordered set of base directories to search for data files in addition to the $XDG_DATA_HOME base directory. + // The directories in $XDG_DATA_DIRS should be seperated with a colon ':'. + // If $XDG_DATA_DIRS is either not set or empty, a value equal to /usr/local/share/:/usr/share/ should be used. + std::vectortarget_candidates; + integrate_desktop_internal::resolve_path_from_var("XDG_DATA_HOME", target_candidates); + integrate_desktop_internal::resolve_path_from_var("XDG_DATA_DIRS", target_candidates); + + AppConfig *app_config = wxGetApp().app_config; + // suffix string to create different desktop file for alpha, beta. + + std::string version_suffix; + std::string name_suffix; + std::string version(SLIC3R_VERSION); + if (version.find("alpha") != std::string::npos) + { + version_suffix = "-alpha"; + name_suffix = " - alpha"; + }else if (version.find("beta") != std::string::npos) + { + version_suffix = "-beta"; + name_suffix = " - beta"; + } + + // theme path to icon destination + std::string icon_theme_path; + std::string icon_theme_dirs; + + if (platform_flavor() == PlatformFlavor::LinuxOnChromium) { + icon_theme_path = "hicolor/96x96/apps/"; + icon_theme_dirs = "/hicolor/96x96/apps"; + } + + + std::string target_dir_icons; + std::string target_dir_desktop; + + // slicer icon + // iterate thru target_candidates to find icons folder + for (size_t i = 0; i < target_candidates.size(); ++i) { + // Copy icon PrusaSlicer.png from resources_dir()/icons to target_dir_icons/icons/ + if (integrate_desktop_internal::contains_path_dir(target_candidates[i], "icons")) { + target_dir_icons = target_candidates[i]; + std::string icon_path = GUI::format("%1%/icons/PrusaSlicer.png",resources_dir()); + std::string dest_path = GUI::format("%1%/icons/%2%PrusaSlicer%3%.png", target_dir_icons, icon_theme_path, version_suffix); + if (integrate_desktop_internal::copy_icon(icon_path, dest_path)) + break; // success + else + target_dir_icons.clear(); // copying failed + // if all failed - try creating default home folder + if (i == target_candidates.size() - 1) { + // create $HOME/.local/share + integrate_desktop_internal::create_path(boost::nowide::narrow(wxFileName::GetHomeDir()), ".local/share/icons" + icon_theme_dirs); + // copy icon + target_dir_icons = GUI::format("%1%/.local/share",wxFileName::GetHomeDir()); + std::string icon_path = GUI::format("%1%/icons/PrusaSlicer.png",resources_dir()); + std::string dest_path = GUI::format("%1%/icons/%2%PrusaSlicer%3%.png", target_dir_icons, icon_theme_path, version_suffix); + if (!integrate_desktop_internal::contains_path_dir(target_dir_icons, "icons") + || !integrate_desktop_internal::copy_icon(icon_path, dest_path)) { + // every attempt failed - icon wont be present + target_dir_icons.clear(); + } + } + } + } + if(target_dir_icons.empty()) { + BOOST_LOG_TRIVIAL(error) << "Copying PrusaSlicer icon to icons directory failed."; + } else + // save path to icon + app_config->set("desktop_integration_icon_slicer_path", GUI::format("%1%/icons/%2%PrusaSlicer%3%.png", target_dir_icons, icon_theme_path, version_suffix)); + + // desktop file + // iterate thru target_candidates to find applications folder + for (size_t i = 0; i < target_candidates.size(); ++i) + { + if (integrate_desktop_internal::contains_path_dir(target_candidates[i], "applications")) { + target_dir_desktop = target_candidates[i]; + // Write slicer desktop file + std::string desktop_file = GUI::format( + "[Desktop Entry]\n" + "Name=PrusaSlicer%1%\n" + "GenericName=3D Printing Software\n" + "Icon=PrusaSlicer%2%\n" + "Exec=%3% %%F\n" + "Terminal=false\n" + "Type=Application\n" + "MimeType=model/stl;application/vnd.ms-3mfdocument;application/prs.wavefront-obj;application/x-amf;\n" + "Categories=Graphics;3DGraphics;Engineering;\n" + "Keywords=3D;Printing;Slicer;slice;3D;printer;convert;gcode;stl;obj;amf;SLA\n" + "StartupNotify=false\n" + "StartupWMClass=prusa-slicer", name_suffix, version_suffix, appimage_path); + + std::string path = GUI::format("%1%/applications/PrusaSlicer%2%.desktop", target_dir_desktop, version_suffix); + if (integrate_desktop_internal::create_desktop_file(path, desktop_file)){ + BOOST_LOG_TRIVIAL(debug) << "PrusaSlicer.desktop file installation success."; + break; + } else { + // write failed - try another path + BOOST_LOG_TRIVIAL(error) << "PrusaSlicer.desktop file installation failed."; + target_dir_desktop.clear(); + } + // if all failed - try creating default home folder + if (i == target_candidates.size() - 1) { + // create $HOME/.local/share + integrate_desktop_internal::create_path(boost::nowide::narrow(wxFileName::GetHomeDir()), ".local/share/applications"); + // create desktop file + target_dir_desktop = GUI::format("%1%/.local/share",wxFileName::GetHomeDir()); + std::string path = GUI::format("%1%/applications/PrusaSlicer%2%.desktop", target_dir_desktop, version_suffix); + if (integrate_desktop_internal::contains_path_dir(target_dir_desktop, "applications")) { + if (!integrate_desktop_internal::create_desktop_file(path, desktop_file)) { + // Desktop file not written - end desktop integration + BOOST_LOG_TRIVIAL(error) << "Performing desktop integration failed - could not create desktop file"; + return; + } + } else { + // Desktop file not written - end desktop integration + BOOST_LOG_TRIVIAL(error) << "Performing desktop integration failed - could not find applications directory"; + return; + } + } + } + } + if(target_dir_desktop.empty()) { + // Desktop file not written - end desktop integration + BOOST_LOG_TRIVIAL(error) << "Performing desktop integration failed - could not find applications directory"; + wxGetApp().plater()->get_notification_manager()->push_notification(NotificationType::DesktopIntegrationFail); + return; + } + // save path to desktop file + app_config->set("desktop_integration_app_path", GUI::format("%1%/applications/PrusaSlicer%2%.desktop", target_dir_desktop, version_suffix)); + + // Repeat for Gcode viewer - use same paths as for slicer files + // Icon + if (!target_dir_icons.empty()) + { + std::string icon_path = GUI::format("%1%/icons/PrusaSlicer-gcodeviewer_192px.png",resources_dir()); + std::string dest_path = GUI::format("%1%/icons/%2%PrusaSlicer-gcodeviewer%3%.png", target_dir_icons, icon_theme_path, version_suffix); + if (integrate_desktop_internal::copy_icon(icon_path, dest_path)) + // save path to icon + app_config->set("desktop_integration_icon_viewer_path", dest_path); + else + BOOST_LOG_TRIVIAL(error) << "Copying Gcode Viewer icon to icons directory failed."; + } + + // Desktop file + std::string desktop_file = GUI::format( + "[Desktop Entry]\n" + "Name=Prusa Gcode Viewer%1%\n" + "GenericName=3D Printing Software\n" + "Icon=PrusaSlicer-gcodeviewer%2%\n" + "Exec=%3% --gcodeviwer %%F\n" + "Terminal=false\n" + "Type=Application\n" + "MimeType=text/x.gcode;\n" + "Categories=Graphics;3DGraphics;\n" + "Keywords=3D;Printing;Slicer;\n" + "StartupNotify=false", name_suffix, version_suffix, appimage_path); + + std::string desktop_path = GUI::format("%1%/applications/PrusaSlicerGcodeViewer%2%.desktop", target_dir_desktop, version_suffix); + if (integrate_desktop_internal::create_desktop_file(desktop_path, desktop_file)) + // save path to desktop file + app_config->set("desktop_integration_app_viewer_path", desktop_path); + else { + BOOST_LOG_TRIVIAL(error) << "Performing desktop integration failed - could create gcode viewer desktop file"; + wxGetApp().plater()->get_notification_manager()->push_notification(NotificationType::DesktopIntegrationFail); + } + wxGetApp().plater()->get_notification_manager()->push_notification(NotificationType::DesktopIntegrationSuccess); +} +void DesktopIntegrationDialog::undo_desktop_intgration() +{ + const char *appimage_env = std::getenv("APPIMAGE"); + if (!appimage_env) { + BOOST_LOG_TRIVIAL(error) << "Undo desktop integration failed - not Appimage executable."; + wxGetApp().plater()->get_notification_manager()->push_notification(NotificationType::UndoDesktopIntegrationFail); + return; + } + const AppConfig *app_config = wxGetApp().app_config; + // slicer .desktop + std::string path = std::string(app_config->get("desktop_integration_app_path")); + if (!path.empty()) { + BOOST_LOG_TRIVIAL(debug) << "removing " << path; + std::remove(path.c_str()); + } + // slicer icon + path = std::string(app_config->get("desktop_integration_icon_slicer_path")); + if (!path.empty()) { + BOOST_LOG_TRIVIAL(debug) << "removing " << path; + std::remove(path.c_str()); + } + // gcode viwer .desktop + path = std::string(app_config->get("desktop_integration_app_viewer_path")); + if (!path.empty()) { + BOOST_LOG_TRIVIAL(debug) << "removing " << path; + std::remove(path.c_str()); + } + // gcode viewer icon + path = std::string(app_config->get("desktop_integration_icon_viewer_path")); + if (!path.empty()) { + BOOST_LOG_TRIVIAL(debug) << "removing " << path; + std::remove(path.c_str()); + } + wxGetApp().plater()->get_notification_manager()->push_notification(NotificationType::UndoDesktopIntegrationSuccess); +} + +DesktopIntegrationDialog::DesktopIntegrationDialog(wxWindow *parent) +: wxDialog(parent, wxID_ANY, _(L("Desktop Integration")), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER) +{ + bool can_undo = DesktopIntegrationDialog::is_integrated(); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + + wxString text = _L("Desktop Integration sets this binary to be searchable by the system.\n\nPress \"Perform\" to proceed."); + if (can_undo) + text += "\nPress \"Undo\" to remove previous integration."; + + vbox->Add( + new wxStaticText( this, wxID_ANY, text), + // , wxDefaultPosition, wxSize(100,50), wxTE_MULTILINE), + 1, // make vertically stretchable + wxEXPAND | // make horizontally stretchable + wxALL, // and make border all around + 10 ); // set border width to 10 + + + wxBoxSizer *btn_szr = new wxBoxSizer(wxHORIZONTAL); + wxButton *btn_perform = new wxButton(this, wxID_ANY, _L("Perform")); + btn_szr->Add(btn_perform, 0, wxALL, 10); + + btn_perform->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { DesktopIntegrationDialog::perform_desktop_integration(); EndModal(wxID_ANY); }); + + if (can_undo){ + wxButton *btn_undo = new wxButton(this, wxID_ANY, _L("Undo")); + btn_szr->Add(btn_undo, 0, wxALL, 10); + btn_undo->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { DesktopIntegrationDialog::undo_desktop_intgration(); EndModal(wxID_ANY); }); + } + wxButton *btn_cancel = new wxButton(this, wxID_ANY, _L("Cancel")); + btn_szr->Add(btn_cancel, 0, wxALL, 10); + btn_cancel->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { EndModal(wxID_ANY); }); + + vbox->Add(btn_szr, 0, wxALIGN_CENTER); + + SetSizerAndFit(vbox); +} + +DesktopIntegrationDialog::~DesktopIntegrationDialog() +{ + +} + +} // namespace GUI +} // namespace Slic3r +#endif // __linux__ \ No newline at end of file diff --git a/src/slic3r/GUI/DesktopIntegrationDialog.hpp b/src/slic3r/GUI/DesktopIntegrationDialog.hpp new file mode 100644 index 000000000..74a0a68f9 --- /dev/null +++ b/src/slic3r/GUI/DesktopIntegrationDialog.hpp @@ -0,0 +1,39 @@ +#ifdef __linux__ +#ifndef slic3r_DesktopIntegrationDialog_hpp_ +#define slic3r_DesktopIntegrationDialog_hpp_ + +#include + +namespace Slic3r { +namespace GUI { +class DesktopIntegrationDialog : public wxDialog +{ +public: + DesktopIntegrationDialog(wxWindow *parent); + DesktopIntegrationDialog(DesktopIntegrationDialog &&) = delete; + DesktopIntegrationDialog(const DesktopIntegrationDialog &) = delete; + DesktopIntegrationDialog &operator=(DesktopIntegrationDialog &&) = delete; + DesktopIntegrationDialog &operator=(const DesktopIntegrationDialog &) = delete; + ~DesktopIntegrationDialog(); + + // methods that actually do / undo desktop integration. Static to be accesible from anywhere. + + // returns true if path to PrusaSlicer.desktop is stored in App Config and existence of desktop file. + // Does not check if desktop file leads to this binary or existence of icons and viewer desktop file. + static bool is_integrated(); + // true if appimage + static bool integration_possible(); + // Creates Desktop files and icons for both PrusaSlicer and GcodeViewer. + // Stores paths into App Config. + // Rewrites if files already existed. + static void perform_desktop_integration(); + // Deletes Desktop files and icons for both PrusaSlicer and GcodeViewer at paths stored in App Config. + static void undo_desktop_intgration(); +private: + +}; +} // namespace GUI +} // namespace Slic3r + +#endif // slic3r_DesktopIntegrationDialog_hpp_ +#endif // __linux__ \ No newline at end of file diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index eacf69c91..233bdf1cd 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -17,6 +17,7 @@ #include "GLCanvas3D.hpp" #include "GLToolbar.hpp" #include "GUI_Preview.hpp" +#include "GUI_ObjectManipulation.hpp" #include #include @@ -143,6 +144,9 @@ bool GCodeViewer::Path::matches(const GCodeProcessor::MoveVertex& move) const case EMoveType::Custom_GCode: case EMoveType::Retract: case EMoveType::Unretract: +#if ENABLE_SEAMS_VISUALIZATION + case EMoveType::Seam: +#endif // ENABLE_SEAMS_VISUALIZATION case EMoveType::Extrude: { // use rounding to reduce the number of generated paths #if ENABLE_SPLITTED_VERTEX_BUFFER @@ -540,6 +544,9 @@ const std::vector GCodeViewer::Extrusion_Role_Colors {{ const std::vector GCodeViewer::Options_Colors {{ { 0.803f, 0.135f, 0.839f }, // Retractions { 0.287f, 0.679f, 0.810f }, // Unretractions +#if ENABLE_SEAMS_VISUALIZATION + { 0.900f, 0.900f, 0.900f }, // Seams +#endif // ENABLE_SEAMS_VISUALIZATION { 0.758f, 0.744f, 0.389f }, // ToolChanges { 0.856f, 0.582f, 0.546f }, // ColorChanges { 0.322f, 0.942f, 0.512f }, // PausePrints @@ -582,11 +589,20 @@ GCodeViewer::GCodeViewer() case EMoveType::Pause_Print: case EMoveType::Custom_GCode: case EMoveType::Retract: +#if ENABLE_SEAMS_VISUALIZATION + case EMoveType::Unretract: + case EMoveType::Seam: { + buffer.render_primitive_type = TBuffer::ERenderPrimitiveType::Point; + buffer.vertices.format = VBuffer::EFormat::Position; + break; + } +#else case EMoveType::Unretract: { buffer.render_primitive_type = TBuffer::ERenderPrimitiveType::Point; buffer.vertices.format = VBuffer::EFormat::Position; break; } +#endif // ENABLE_SEAMS_VISUALIZATION case EMoveType::Wipe: case EMoveType::Extrude: { buffer.render_primitive_type = TBuffer::ERenderPrimitiveType::Triangle; @@ -672,13 +688,13 @@ void GCodeViewer::load(const GCodeProcessor::Result& gcode_result, const Print& wxGetApp().plater()->set_bed_shape(bed_shape, texture, model, gcode_result.bed_shape.empty()); } - m_time_statistics = gcode_result.time_statistics; + m_print_statistics = gcode_result.print_statistics; - if (m_time_estimate_mode != PrintEstimatedTimeStatistics::ETimeMode::Normal) { - float time = m_time_statistics.modes[static_cast(m_time_estimate_mode)].time; + if (m_time_estimate_mode != PrintEstimatedStatistics::ETimeMode::Normal) { + float time = m_print_statistics.modes[static_cast(m_time_estimate_mode)].time; if (time == 0.0f || - short_time(get_time_dhms(time)) == short_time(get_time_dhms(m_time_statistics.modes[static_cast(PrintEstimatedTimeStatistics::ETimeMode::Normal)].time))) - m_time_estimate_mode = PrintEstimatedTimeStatistics::ETimeMode::Normal; + short_time(get_time_dhms(time)) == short_time(get_time_dhms(m_print_statistics.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].time))) + m_time_estimate_mode = PrintEstimatedStatistics::ETimeMode::Normal; } } @@ -773,7 +789,7 @@ void GCodeViewer::reset() m_layers.reset(); m_layers_z_range = { 0, 0 }; m_roles = std::vector(); - m_time_statistics.reset(); + m_print_statistics.reset(); #if ENABLE_GCODE_WINDOW m_sequential_view.gcode_window.reset(); #endif // ENABLE_GCODE_WINDOW @@ -796,10 +812,18 @@ void GCodeViewer::render() const case EMoveType::Pause_Print: case EMoveType::Custom_GCode: case EMoveType::Retract: +#if ENABLE_SEAMS_VISUALIZATION + case EMoveType::Unretract: + case EMoveType::Seam: { + buffer.shader = wxGetApp().is_glsl_version_greater_or_equal_to(1, 20) ? "options_120" : "options_110"; + break; + } +#else case EMoveType::Unretract: { buffer.shader = wxGetApp().is_glsl_version_greater_or_equal_to(1, 20) ? "options_120" : "options_110"; break; } +#endif // ENABLE_SEAMS_VISUALIZATION case EMoveType::Wipe: case EMoveType::Extrude: { buffer.shader = "gouraud_light"; @@ -938,6 +962,9 @@ unsigned int GCodeViewer::get_options_visibility_flags() const flags = set_flag(flags, static_cast(Preview::OptionType::Wipe), is_toolpath_move_type_visible(EMoveType::Wipe)); flags = set_flag(flags, static_cast(Preview::OptionType::Retractions), is_toolpath_move_type_visible(EMoveType::Retract)); flags = set_flag(flags, static_cast(Preview::OptionType::Unretractions), is_toolpath_move_type_visible(EMoveType::Unretract)); +#if ENABLE_SEAMS_VISUALIZATION + flags = set_flag(flags, static_cast(Preview::OptionType::Seams), is_toolpath_move_type_visible(EMoveType::Seam)); +#endif // ENABLE_SEAMS_VISUALIZATION flags = set_flag(flags, static_cast(Preview::OptionType::ToolChanges), is_toolpath_move_type_visible(EMoveType::Tool_change)); flags = set_flag(flags, static_cast(Preview::OptionType::ColorChanges), is_toolpath_move_type_visible(EMoveType::Color_change)); flags = set_flag(flags, static_cast(Preview::OptionType::PausePrints), is_toolpath_move_type_visible(EMoveType::Pause_Print)); @@ -958,6 +985,9 @@ void GCodeViewer::set_options_visibility_from_flags(unsigned int flags) set_toolpath_move_type_visible(EMoveType::Wipe, is_flag_set(static_cast(Preview::OptionType::Wipe))); set_toolpath_move_type_visible(EMoveType::Retract, is_flag_set(static_cast(Preview::OptionType::Retractions))); set_toolpath_move_type_visible(EMoveType::Unretract, is_flag_set(static_cast(Preview::OptionType::Unretractions))); +#if ENABLE_SEAMS_VISUALIZATION + set_toolpath_move_type_visible(EMoveType::Seam, is_flag_set(static_cast(Preview::OptionType::Seams))); +#endif // ENABLE_SEAMS_VISUALIZATION set_toolpath_move_type_visible(EMoveType::Tool_change, is_flag_set(static_cast(Preview::OptionType::ToolChanges))); set_toolpath_move_type_visible(EMoveType::Color_change, is_flag_set(static_cast(Preview::OptionType::ColorChanges))); set_toolpath_move_type_visible(EMoveType::Pause_Print, is_flag_set(static_cast(Preview::OptionType::PausePrints))); @@ -1595,13 +1625,15 @@ void GCodeViewer::load_toolpaths(const GCodeProcessor::Result& gcode_result) #if ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS const std::array first_seg_v_offsets = convert_vertices_offset(vbuffer_size, { 0, 1, 2, 3, 4, 5, 6, 7 }); const std::array non_first_seg_v_offsets = convert_vertices_offset(vbuffer_size, { -4, 0, -2, 1, 2, 3, 4, 5 }); -#endif // ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS - + bool is_first_segment = (last_path.vertices_count() == 1); + if (is_first_segment || vbuffer_size == 0) { +#else if (last_path.vertices_count() == 1 || vbuffer_size == 0) { +#endif // ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS // 1st segment or restart into a new vertex buffer // =============================================== #if ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS - if (last_path.vertices_count() == 1) + if (is_first_segment) // starting cap triangles append_starting_cap_triangles(indices, first_seg_v_offsets); #endif // ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS @@ -1679,7 +1711,7 @@ void GCodeViewer::load_toolpaths(const GCodeProcessor::Result& gcode_result) #if ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS if (next != nullptr && (curr.type != next->type || !last_path.matches(*next))) // ending cap triangles - append_ending_cap_triangles(indices, non_first_seg_v_offsets); + append_ending_cap_triangles(indices, is_first_segment ? first_seg_v_offsets : non_first_seg_v_offsets); #endif // ENABLE_REDUCED_TOOLPATHS_SEGMENT_CAPS last_path.sub_paths.back().last = { ibuffer_id, indices.size() - 1, move_id, curr.position }; @@ -1714,7 +1746,11 @@ void GCodeViewer::load_toolpaths(const GCodeProcessor::Result& gcode_result) // for the gcode viewer we need to take in account all moves to correctly size the printbed m_paths_bounding_box.merge(move.position.cast()); else { +#if ENABLE_START_GCODE_VISUALIZATION + if (move.type == EMoveType::Extrude && move.extrusion_role != erCustom && move.width != 0.0f && move.height != 0.0f) +#else if (move.type == EMoveType::Extrude && move.width != 0.0f && move.height != 0.0f) +#endif // ENABLE_START_GCODE_VISUALIZATION m_paths_bounding_box.merge(move.position.cast()); } } @@ -3163,6 +3199,9 @@ void GCodeViewer::refresh_render_paths(bool keep_sequential_current_first, bool case EMoveType::Custom_GCode: { color = Options_Colors[static_cast(EOptionsColors::CustomGCodes)]; break; } case EMoveType::Retract: { color = Options_Colors[static_cast(EOptionsColors::Retractions)]; break; } case EMoveType::Unretract: { color = Options_Colors[static_cast(EOptionsColors::Unretractions)]; break; } +#if ENABLE_SEAMS_VISUALIZATION + case EMoveType::Seam: { color = Options_Colors[static_cast(EOptionsColors::Seams)]; break; } +#endif // ENABLE_SEAMS_VISUALIZATION case EMoveType::Extrude: { if (!top_layer_only || m_sequential_view.current.last == global_endpoints.last || @@ -4013,14 +4052,25 @@ void GCodeViewer::render_legend() const if (!m_legend_enabled) return; +#if ENABLE_SCROLLABLE_LEGEND + const Size cnv_size = wxGetApp().plater()->get_current_canvas3D()->get_canvas_size(); +#endif // ENABLE_SCROLLABLE_LEGEND + ImGuiWrapper& imgui = *wxGetApp().imgui(); imgui.set_next_window_pos(0.0f, 0.0f, ImGuiCond_Always); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::SetNextWindowBgAlpha(0.6f); +#if ENABLE_SCROLLABLE_LEGEND + const float max_height = 0.75f * static_cast(cnv_size.get_height()); + const float child_height = 0.3333f * max_height; + ImGui::SetNextWindowSizeConstraints({ 0.0f, 0.0f }, { -1.0f, max_height }); + imgui.begin(std::string("Legend"), ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove); +#else imgui.begin(std::string("Legend"), ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove); ImDrawList* draw_list = ImGui::GetWindowDrawList(); +#endif // ENABLE_SCROLLABLE_LEGEND enum class EItemType : unsigned char { @@ -4030,95 +4080,126 @@ void GCodeViewer::render_legend() const Line }; - const PrintEstimatedTimeStatistics::Mode& time_mode = m_time_statistics.modes[static_cast(m_time_estimate_mode)]; + const PrintEstimatedStatistics::Mode& time_mode = m_print_statistics.modes[static_cast(m_time_estimate_mode)]; +#if ENABLE_SCROLLABLE_LEGEND + bool show_estimated_time = time_mode.time > 0.0f && (m_view_type == EViewType::FeatureType || + (m_view_type == EViewType::ColorPrint && !time_mode.custom_gcode_times.empty())); +#endif // ENABLE_SCROLLABLE_LEGEND - float icon_size = ImGui::GetTextLineHeight(); - float percent_bar_size = 2.0f * ImGui::GetTextLineHeight(); + const float icon_size = ImGui::GetTextLineHeight(); + const float percent_bar_size = 2.0f * ImGui::GetTextLineHeight(); - auto append_item = [this, draw_list, icon_size, percent_bar_size, &imgui](EItemType type, const Color& color, const std::string& label, - bool visible = true, const std::string& time = "", float percent = 0.0f, float max_percent = 0.0f, const std::array& offsets = { 0.0f, 0.0f }, + bool imperial_units = wxGetApp().app_config->get("use_inches") == "1"; + +#if ENABLE_SCROLLABLE_LEGEND + auto append_item = [this, icon_size, percent_bar_size, &imgui, imperial_units](EItemType type, const Color& color, const std::string& label, +#else + auto append_item = [this, draw_list, icon_size, percent_bar_size, &imgui, imperial_units](EItemType type, const Color& color, const std::string& label, +#endif // ENABLE_SCROLLABLE_LEGEND + bool visible = true, const std::string& time = "", float percent = 0.0f, float max_percent = 0.0f, const std::array& offsets = { 0.0f, 0.0f, 0.0f, 0.0f }, + double used_filament_m = 0.0, double used_filament_g = 0.0, std::function callback = nullptr) { - if (!visible) - ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.3333f); - ImVec2 pos = ImGui::GetCursorScreenPos(); - switch (type) { - default: - case EItemType::Rect: { - draw_list->AddRectFilled({ pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, - ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f })); - break; - } - case EItemType::Circle: { - ImVec2 center(0.5f * (pos.x + pos.x + icon_size), 0.5f * (pos.y + pos.y + icon_size)); - if (m_buffers[buffer_id(EMoveType::Retract)].shader == "options_120") { - draw_list->AddCircleFilled(center, 0.5f * icon_size, - ImGui::GetColorU32({ 0.5f * color[0], 0.5f * color[1], 0.5f * color[2], 1.0f }), 16); - float radius = 0.5f * icon_size; - draw_list->AddCircleFilled(center, radius, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 16); - radius = 0.5f * icon_size * 0.01f * 33.0f; - draw_list->AddCircleFilled(center, radius, ImGui::GetColorU32({ 0.5f * color[0], 0.5f * color[1], 0.5f * color[2], 1.0f }), 16); - } - else - draw_list->AddCircleFilled(center, 0.5f * icon_size, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 16); + if (!visible) + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.3333f); - break; - } - case EItemType::Hexagon: { - ImVec2 center(0.5f * (pos.x + pos.x + icon_size), 0.5f * (pos.y + pos.y + icon_size)); - draw_list->AddNgonFilled(center, 0.5f * icon_size, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 6); - break; - } - case EItemType::Line: { - draw_list->AddLine({ pos.x + 1, pos.y + icon_size - 1 }, { pos.x + icon_size - 1, pos.y + 1 }, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 3.0f); - break; - } - } - - // draw text - ImGui::Dummy({ icon_size, icon_size }); - ImGui::SameLine(); - if (callback != nullptr) { - if (ImGui::MenuItem(label.c_str())) - callback(); - else { - // show tooltip - if (ImGui::IsItemHovered()) { - if (!visible) - ImGui::PopStyleVar(); - ImGui::PushStyleColor(ImGuiCol_PopupBg, ImGuiWrapper::COL_WINDOW_BACKGROUND); - ImGui::BeginTooltip(); - imgui.text(visible ? _u8L("Click to hide") : _u8L("Click to show")); - ImGui::EndTooltip(); - ImGui::PopStyleColor(); - if (!visible) - ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.3333f); - - // to avoid the tooltip to change size when moving the mouse - wxGetApp().plater()->get_current_canvas3D()->set_as_dirty(); - wxGetApp().plater()->get_current_canvas3D()->request_extra_frame(); - } - } - - if (!time.empty()) { - ImGui::SameLine(offsets[0]); - imgui.text(time); - ImGui::SameLine(offsets[1]); - pos = ImGui::GetCursorScreenPos(); - float width = std::max(1.0f, percent_bar_size * percent / max_percent); - draw_list->AddRectFilled({ pos.x, pos.y + 2.0f }, { pos.x + width, pos.y + icon_size - 2.0f }, - ImGui::GetColorU32(ImGuiWrapper::COL_ORANGE_LIGHT)); - ImGui::Dummy({ percent_bar_size, icon_size }); - ImGui::SameLine(); - char buf[64]; - ::sprintf(buf, "%.1f%%", 100.0f * percent); - ImGui::TextUnformatted((percent > 0.0f) ? buf : ""); - } +#if ENABLE_SCROLLABLE_LEGEND + ImDrawList* draw_list = ImGui::GetWindowDrawList(); +#endif // ENABLE_SCROLLABLE_LEGEND + ImVec2 pos = ImGui::GetCursorScreenPos(); + switch (type) { + default: + case EItemType::Rect: { + draw_list->AddRectFilled({ pos.x + 1.0f, pos.y + 1.0f }, { pos.x + icon_size - 1.0f, pos.y + icon_size - 1.0f }, + ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f })); + break; + } + case EItemType::Circle: { + ImVec2 center(0.5f * (pos.x + pos.x + icon_size), 0.5f * (pos.y + pos.y + icon_size)); + if (m_buffers[buffer_id(EMoveType::Retract)].shader == "options_120") { + draw_list->AddCircleFilled(center, 0.5f * icon_size, + ImGui::GetColorU32({ 0.5f * color[0], 0.5f * color[1], 0.5f * color[2], 1.0f }), 16); + float radius = 0.5f * icon_size; + draw_list->AddCircleFilled(center, radius, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 16); + radius = 0.5f * icon_size * 0.01f * 33.0f; + draw_list->AddCircleFilled(center, radius, ImGui::GetColorU32({ 0.5f * color[0], 0.5f * color[1], 0.5f * color[2], 1.0f }), 16); } else - imgui.text(label); + draw_list->AddCircleFilled(center, 0.5f * icon_size, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 16); - if (!visible) - ImGui::PopStyleVar(); + break; + } + case EItemType::Hexagon: { + ImVec2 center(0.5f * (pos.x + pos.x + icon_size), 0.5f * (pos.y + pos.y + icon_size)); + draw_list->AddNgonFilled(center, 0.5f * icon_size, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 6); + break; + } + case EItemType::Line: { + draw_list->AddLine({ pos.x + 1, pos.y + icon_size - 1 }, { pos.x + icon_size - 1, pos.y + 1 }, ImGui::GetColorU32({ color[0], color[1], color[2], 1.0f }), 3.0f); + break; + } + } + + // draw text + ImGui::Dummy({ icon_size, icon_size }); + ImGui::SameLine(); + if (callback != nullptr) { + if (ImGui::MenuItem(label.c_str())) + callback(); + else { + // show tooltip + if (ImGui::IsItemHovered()) { + if (!visible) + ImGui::PopStyleVar(); + ImGui::PushStyleColor(ImGuiCol_PopupBg, ImGuiWrapper::COL_WINDOW_BACKGROUND); + ImGui::BeginTooltip(); + imgui.text(visible ? _u8L("Click to hide") : _u8L("Click to show")); + ImGui::EndTooltip(); + ImGui::PopStyleColor(); + if (!visible) + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.3333f); + + // to avoid the tooltip to change size when moving the mouse + wxGetApp().plater()->get_current_canvas3D()->set_as_dirty(); + wxGetApp().plater()->get_current_canvas3D()->request_extra_frame(); + } + } + + if (!time.empty()) { + ImGui::SameLine(offsets[0]); + imgui.text(time); + ImGui::SameLine(offsets[1]); + pos = ImGui::GetCursorScreenPos(); + const float width = std::max(1.0f, percent_bar_size * percent / max_percent); + draw_list->AddRectFilled({ pos.x, pos.y + 2.0f }, { pos.x + width, pos.y + icon_size - 2.0f }, + ImGui::GetColorU32(ImGuiWrapper::COL_ORANGE_LIGHT)); + ImGui::Dummy({ percent_bar_size, icon_size }); + ImGui::SameLine(); + char buf[64]; + ::sprintf(buf, "%.1f%%", 100.0f * percent); + ImGui::TextUnformatted((percent > 0.0f) ? buf : ""); + ImGui::SameLine(offsets[2]); + ::sprintf(buf, imperial_units ? "%.2f in" : "%.2f m", used_filament_m); + imgui.text(buf); + ImGui::SameLine(offsets[3]); + ::sprintf(buf, "%.2f g", used_filament_g); + imgui.text(buf); + } + } + else { + imgui.text(label); + if (used_filament_m > 0.0) { + char buf[64]; + ImGui::SameLine(offsets[0]); + ::sprintf(buf, imperial_units ? "%.2f in" : "%.2f m", used_filament_m); + imgui.text(buf); + ImGui::SameLine(offsets[1]); + ::sprintf(buf, "%.2f g", used_filament_g); + imgui.text(buf); + } + } + + if (!visible) + ImGui::PopStyleVar(); }; auto append_range = [append_item](const Extrusions::Range& range, unsigned int decimals) { @@ -4136,19 +4217,20 @@ void GCodeViewer::render_legend() const append_range_item(0, range.min, decimals); } else { - float step_size = range.step_size(); + const float step_size = range.step_size(); for (int i = static_cast(Range_Colors.size()) - 1; i >= 0; --i) { append_range_item(i, range.min + static_cast(i) * step_size, decimals); } } }; - auto append_headers = [&imgui](const std::array& texts, const std::array& offsets) { - imgui.text(texts[0]); - ImGui::SameLine(offsets[0]); - imgui.text(texts[1]); - ImGui::SameLine(offsets[1]); - imgui.text(texts[2]); + auto append_headers = [&imgui](const std::array& texts, const std::array& offsets) { + size_t i = 0; + for (; i < offsets.size(); i++) { + imgui.text(texts[i]); + ImGui::SameLine(offsets[i]); + } + imgui.text(texts[i]); ImGui::Separator(); }; @@ -4161,11 +4243,12 @@ void GCodeViewer::render_legend() const }; auto calculate_offsets = [max_width](const std::vector& labels, const std::vector& times, - const std::array& titles, float extra_size = 0.0f) { + const std::array& titles, float extra_size = 0.0f) { const ImGuiStyle& style = ImGui::GetStyle(); - std::array ret = { 0.0f, 0.0f }; + std::array ret = { 0.0f, 0.0f, 0.0f, 0.0f }; ret[0] = max_width(labels, titles[0], extra_size) + 3.0f * style.ItemSpacing.x; - ret[1] = ret[0] + max_width(times, titles[1]) + style.ItemSpacing.x; + for (size_t i = 1; i < titles.size(); i++) + ret[i] = ret[i-1] + max_width(times, titles[i]) + style.ItemSpacing.x; return ret; }; @@ -4185,8 +4268,8 @@ void GCodeViewer::render_legend() const if (lower_b == zs.end()) continue; - double current_z = *lower_b; - double previous_z = (lower_b == zs.begin()) ? 0.0 : *(--lower_b); + const double current_z = *lower_b; + const double previous_z = (lower_b == zs.begin()) ? 0.0 : *(--lower_b); // to avoid duplicate values, check adding values if (ret.empty() || !(ret.back().second.first == previous_z && ret.back().second.second == current_z)) @@ -4216,16 +4299,27 @@ void GCodeViewer::render_legend() const return _u8L("from") + " " + std::string(buf1) + " " + _u8L("to") + " " + std::string(buf2) + " " + _u8L("mm"); }; - auto role_time_and_percent = [ time_mode](ExtrusionRole role) { + auto role_time_and_percent = [time_mode](ExtrusionRole role) { auto it = std::find_if(time_mode.roles_times.begin(), time_mode.roles_times.end(), [role](const std::pair& item) { return role == item.first; }); return (it != time_mode.roles_times.end()) ? std::make_pair(it->second, it->second / time_mode.time) : std::make_pair(0.0f, 0.0f); }; + auto used_filament_per_role = [this, imperial_units](ExtrusionRole role) { + auto it = m_print_statistics.used_filaments_per_role.find(role); + if (it == m_print_statistics.used_filaments_per_role.end()) + return std::make_pair(0.0, 0.0); + + double koef = imperial_units ? 1000.0 / ObjectManipulation::in_to_mm : 1.0; + return std::make_pair(it->second.first * koef, it->second.second); + }; + // data used to properly align items in columns when showing time - std::array offsets = { 0.0f, 0.0f }; + std::array offsets = { 0.0f, 0.0f, 0.0f, 0.0f }; std::vector labels; std::vector times; std::vector percents; + std::vector used_filaments_m; + std::vector used_filaments_g; float max_percent = 0.0f; if (m_view_type == EViewType::FeatureType) { @@ -4238,10 +4332,73 @@ void GCodeViewer::render_legend() const times.push_back((time > 0.0f) ? short_time(get_time_dhms(time)) : ""); percents.push_back(percent); max_percent = std::max(max_percent, percent); + auto [used_filament_m, used_filament_g] = used_filament_per_role(role); + used_filaments_m.push_back(used_filament_m); + used_filaments_g.push_back(used_filament_g); } } - offsets = calculate_offsets(labels, times, { _u8L("Feature type"), _u8L("Time") }, icon_size); + std::string longest_percentage_string; + for (double item : percents) { + char buffer[64]; + ::sprintf(buffer, "%.2f %%", item); + if (::strlen(buffer) > longest_percentage_string.length()) + longest_percentage_string = buffer; + } + longest_percentage_string += " "; + if (_u8L("Percentage").length() > longest_percentage_string.length()) + longest_percentage_string = _u8L("Percentage"); + + std::string longest_used_filament_string; + for (double item : used_filaments_m) { + char buffer[64]; + ::sprintf(buffer, imperial_units ? "%.2f in" : "%.2f m", item); + if (::strlen(buffer) > longest_used_filament_string.length()) + longest_used_filament_string = buffer; + } + + offsets = calculate_offsets(labels, times, { _u8L("Feature type"), _u8L("Time"), longest_percentage_string, longest_used_filament_string }, icon_size); + } + + // get used filament (meters and grams) from used volume in respect to the active extruder + auto get_used_filament_from_volume = [imperial_units](double volume, int extruder_id) { + const std::vector& filament_presets = wxGetApp().preset_bundle->filament_presets; + const PresetCollection& filaments = wxGetApp().preset_bundle->filaments; + + double koef = imperial_units ? 1.0/ObjectManipulation::in_to_mm : 0.001; + + std::pair ret = { 0.0, 0.0 }; + if (const Preset* filament_preset = filaments.find_preset(filament_presets[extruder_id], false)) { + double filament_radius = 0.5 * filament_preset->config.opt_float("filament_diameter", 0); + double s = PI * sqr(filament_radius); + ret.first = volume / s * koef; + double filament_density = filament_preset->config.opt_float("filament_density", 0); + ret.second = volume * filament_density * 0.001; + } + return ret; + }; + + if (m_view_type == EViewType::Tool) { + // calculate used filaments data + for (size_t extruder_id : m_extruder_ids) { + if (m_print_statistics.volumes_per_extruder.find(extruder_id) == m_print_statistics.volumes_per_extruder.end()) + continue; + double volume = m_print_statistics.volumes_per_extruder.at(extruder_id); + + auto [used_filament_m, used_filament_g] = get_used_filament_from_volume(volume, extruder_id); + used_filaments_m.push_back(used_filament_m); + used_filaments_g.push_back(used_filament_g); + } + + std::string longest_used_filament_string; + for (double item : used_filaments_m) { + char buffer[64]; + ::sprintf(buffer, imperial_units ? "%.2f in" : "%.2f m", item); + if (::strlen(buffer) > longest_used_filament_string.length()) + longest_used_filament_string = buffer; + } + + offsets = calculate_offsets(labels, times, { "Extruder NNN", longest_used_filament_string }, icon_size); } // extrusion paths section -> title @@ -4249,7 +4406,7 @@ void GCodeViewer::render_legend() const { case EViewType::FeatureType: { - append_headers({ _u8L("Feature type"), _u8L("Time"), _u8L("Percentage") }, offsets); + append_headers({ _u8L("Feature type"), _u8L("Time"), _u8L("Percentage"), _u8L("Used filament") }, offsets); break; } case EViewType::Height: { imgui.title(_u8L("Height (mm)")); break; } @@ -4258,7 +4415,11 @@ void GCodeViewer::render_legend() const case EViewType::FanSpeed: { imgui.title(_u8L("Fan Speed (%)")); break; } case EViewType::Temperature: { imgui.title(_u8L("Temperature (°C)")); break; } case EViewType::VolumetricRate: { imgui.title(_u8L("Volumetric flow rate (mm³/s)")); break; } - case EViewType::Tool: { imgui.title(_u8L("Tool")); break; } + case EViewType::Tool: + { + append_headers({ _u8L("Tool"), _u8L("Used filament") }, offsets); + break; + } case EViewType::ColorPrint: { imgui.title(_u8L("Color Print")); break; } default: { break; } } @@ -4272,9 +4433,9 @@ void GCodeViewer::render_legend() const ExtrusionRole role = m_roles[i]; if (role >= erCount) continue; - bool visible = is_visible(role); + const bool visible = is_visible(role); append_item(EItemType::Rect, Extrusion_Role_Colors[static_cast(role)], labels[i], - visible, times[i], percents[i], max_percent, offsets, [this, role, visible]() { + visible, times[i], percents[i], max_percent, offsets, used_filaments_m[i], used_filaments_g[i], [this, role, visible]() { Extrusions* extrusions = const_cast(&m_extrusions); extrusions->role_visibility_flags = visible ? extrusions->role_visibility_flags & ~(1 << role) : extrusions->role_visibility_flags | (1 << role); // update buffers' render paths @@ -4296,16 +4457,33 @@ void GCodeViewer::render_legend() const case EViewType::Tool: { // shows only extruders actually used - for (unsigned char i : m_extruder_ids) { - append_item(EItemType::Rect, m_tool_colors[i], _u8L("Extruder") + " " + std::to_string(i + 1)); + size_t i = 0; + for (unsigned char extruder_id : m_extruder_ids) { + append_item(EItemType::Rect, m_tool_colors[extruder_id], _u8L("Extruder") + " " + std::to_string(extruder_id + 1), + true, "", 0.0f, 0.0f, offsets, used_filaments_m[i], used_filaments_g[i]); + i++; } break; } case EViewType::ColorPrint: { +#if ENABLE_SCROLLABLE_LEGEND const std::vector& custom_gcode_per_print_z = wxGetApp().plater()->model().custom_gcode_per_print_z.gcodes; + size_t total_items = 1; + for (unsigned char i : m_extruder_ids) { + total_items += color_print_ranges(i, custom_gcode_per_print_z).size(); + } + + const bool need_scrollable = static_cast(total_items) * (icon_size + ImGui::GetStyle().ItemSpacing.y) > child_height; + + // add scrollable region, if needed + if (need_scrollable) + ImGui::BeginChild("color_prints", { -1.0f, child_height }, false); +#else + const std::vector& custom_gcode_per_print_z = wxGetApp().plater()->model().custom_gcode_per_print_z.gcodes; +#endif // ENABLE_SCROLLABLE_LEGEND if (m_extruders_count == 1) { // single extruder use case - std::vector>> cp_values = color_print_ranges(0, custom_gcode_per_print_z); + const std::vector>> cp_values = color_print_ranges(0, custom_gcode_per_print_z); const int items_cnt = static_cast(cp_values.size()); if (items_cnt == 0) { // There are no color changes, but there are some pause print or custom Gcode append_item(EItemType::Rect, m_tool_colors.front(), _u8L("Default color")); @@ -4328,7 +4506,7 @@ void GCodeViewer::render_legend() const else { // multi extruder use case // shows only extruders actually used for (unsigned char i : m_extruder_ids) { - std::vector>> cp_values = color_print_ranges(i, custom_gcode_per_print_z); + const std::vector>> cp_values = color_print_ranges(i, custom_gcode_per_print_z); const int items_cnt = static_cast(cp_values.size()); if (items_cnt == 0) { // There are no color changes, but there are some pause print or custom Gcode append_item(EItemType::Rect, m_tool_colors[i], _u8L("Extruder") + " " + std::to_string(i + 1) + " " + _u8L("default color")); @@ -4354,6 +4532,10 @@ void GCodeViewer::render_legend() const } } } +#if ENABLE_SCROLLABLE_LEGEND + if (need_scrollable) + ImGui::EndChild(); +#endif // ENABLE_SCROLLABLE_LEGEND break; } @@ -4379,10 +4561,11 @@ void GCodeViewer::render_legend() const Color color1; Color color2; Times times; + std::pair used_filament {0.0f, 0.0f}; }; using PartialTimes = std::vector; - auto generate_partial_times = [this](const TimesList& times) { + auto generate_partial_times = [this, get_used_filament_from_volume](const TimesList& times, const std::vector& used_filaments) { PartialTimes items; std::vector custom_gcode_per_print_z = wxGetApp().plater()->model().custom_gcode_per_print_z.gcodes; @@ -4392,6 +4575,7 @@ void GCodeViewer::render_legend() const last_color[i] = m_tool_colors[i]; } int last_extruder_id = 1; + int color_change_idx = 0; for (const auto& time_rec : times) { switch (time_rec.first) { @@ -4407,14 +4591,14 @@ void GCodeViewer::render_legend() const case CustomGCode::ColorChange: { auto it = std::find_if(custom_gcode_per_print_z.begin(), custom_gcode_per_print_z.end(), [time_rec](const CustomGCode::Item& item) { return item.type == time_rec.first; }); if (it != custom_gcode_per_print_z.end()) { - items.push_back({ PartialTime::EType::Print, it->extruder, last_color[it->extruder - 1], Color(), time_rec.second }); + items.push_back({ PartialTime::EType::Print, it->extruder, last_color[it->extruder - 1], Color(), time_rec.second, get_used_filament_from_volume(used_filaments[color_change_idx++], it->extruder-1) }); items.push_back({ PartialTime::EType::ColorChange, it->extruder, last_color[it->extruder - 1], decode_color(it->color), time_rec.second }); last_color[it->extruder - 1] = decode_color(it->color); last_extruder_id = it->extruder; custom_gcode_per_print_z.erase(it); } else - items.push_back({ PartialTime::EType::Print, last_extruder_id, last_color[last_extruder_id - 1], Color(), time_rec.second }); + items.push_back({ PartialTime::EType::Print, last_extruder_id, last_color[last_extruder_id - 1], Color(), time_rec.second, get_used_filament_from_volume(used_filaments[color_change_idx++], last_extruder_id -1) }); break; } @@ -4425,7 +4609,7 @@ void GCodeViewer::render_legend() const return items; }; - auto append_color_change = [&imgui](const Color& color1, const Color& color2, const std::array& offsets, const Times& times) { + auto append_color_change = [&imgui](const Color& color1, const Color& color2, const std::array& offsets, const Times& times) { imgui.text(_u8L("Color change")); ImGui::SameLine(); @@ -4444,7 +4628,7 @@ void GCodeViewer::render_legend() const imgui.text(short_time(get_time_dhms(times.second - times.first))); }; - auto append_print = [&imgui](const Color& color, const std::array& offsets, const Times& times) { + auto append_print = [&imgui, imperial_units](const Color& color, const std::array& offsets, const Times& times, std::pair used_filament) { imgui.text(_u8L("Print")); ImGui::SameLine(); @@ -4460,9 +4644,19 @@ void GCodeViewer::render_legend() const imgui.text(short_time(get_time_dhms(times.second))); ImGui::SameLine(offsets[1]); imgui.text(short_time(get_time_dhms(times.first))); + if (used_filament.first > 0.0f) { + char buffer[64]; + ImGui::SameLine(offsets[2]); + ::sprintf(buffer, imperial_units ? "%.2f in" : "%.2f m", used_filament.first); + imgui.text(buffer); + + ImGui::SameLine(offsets[3]); + ::sprintf(buffer, "%.2f g", used_filament.second); + imgui.text(buffer); + } }; - PartialTimes partial_times = generate_partial_times(time_mode.custom_gcode_times); + PartialTimes partial_times = generate_partial_times(time_mode.custom_gcode_times, m_print_statistics.volumes_per_color_change); if (!partial_times.empty()) { labels.clear(); times.clear(); @@ -4476,15 +4670,34 @@ void GCodeViewer::render_legend() const } times.push_back(short_time(get_time_dhms(item.times.second))); } - offsets = calculate_offsets(labels, times, { _u8L("Event"), _u8L("Remaining time") }, 2.0f * icon_size); + + + std::string longest_used_filament_string; + for (const PartialTime& item : partial_times) { + if (item.used_filament.first > 0.0f) { + char buffer[64]; + ::sprintf(buffer, imperial_units ? "%.2f in" : "%.2f m", item.used_filament.first); + if (::strlen(buffer) > longest_used_filament_string.length()) + longest_used_filament_string = buffer; + } + } + + offsets = calculate_offsets(labels, times, { _u8L("Event"), _u8L("Remaining time"), _u8L("Duration"), longest_used_filament_string }, 2.0f * icon_size); ImGui::Spacing(); - append_headers({ _u8L("Event"), _u8L("Remaining time"), _u8L("Duration") }, offsets); + append_headers({ _u8L("Event"), _u8L("Remaining time"), _u8L("Duration"), _u8L("Used filament") }, offsets); +#if ENABLE_SCROLLABLE_LEGEND + const bool need_scrollable = static_cast(partial_times.size()) * (icon_size + ImGui::GetStyle().ItemSpacing.y) > child_height; + if (need_scrollable) + // add scrollable region + ImGui::BeginChild("events", { -1.0f, child_height }, false); +#endif // ENABLE_SCROLLABLE_LEGEND + for (const PartialTime& item : partial_times) { switch (item.type) { case PartialTime::EType::Print: { - append_print(item.color1, offsets, item.times); + append_print(item.color1, offsets, item.times, item.used_filament); break; } case PartialTime::EType::Pause: { @@ -4499,6 +4712,11 @@ void GCodeViewer::render_legend() const } } } + +#if ENABLE_SCROLLABLE_LEGEND + if (need_scrollable) + ImGui::EndChild(); +#endif // ENABLE_SCROLLABLE_LEGEND } } @@ -4557,7 +4775,12 @@ void GCodeViewer::render_legend() const available(EMoveType::Pause_Print) || available(EMoveType::Retract) || available(EMoveType::Tool_change) || +#if ENABLE_SEAMS_VISUALIZATION + available(EMoveType::Unretract) || + available(EMoveType::Seam); +#else available(EMoveType::Unretract); +#endif // ENABLE_SEAMS_VISUALIZATION }; auto add_option = [this, append_item](EMoveType move_type, EOptionsColors color, const std::string& text) { @@ -4575,6 +4798,9 @@ void GCodeViewer::render_legend() const // items add_option(EMoveType::Retract, EOptionsColors::Retractions, _u8L("Retractions")); add_option(EMoveType::Unretract, EOptionsColors::Unretractions, _u8L("Deretractions")); +#if ENABLE_SEAMS_VISUALIZATION + add_option(EMoveType::Seam, EOptionsColors::Seams, _u8L("Seams")); +#endif // ENABLE_SEAMS_VISUALIZATION add_option(EMoveType::Tool_change, EOptionsColors::ToolChanges, _u8L("Tool changes")); add_option(EMoveType::Color_change, EOptionsColors::ColorChanges, _u8L("Color changes")); add_option(EMoveType::Pause_Print, EOptionsColors::PausePrints, _u8L("Print pauses")); @@ -4634,10 +4860,14 @@ void GCodeViewer::render_legend() const } // total estimated printing time section +#if ENABLE_SCROLLABLE_LEGEND + if (show_estimated_time) { +#else if (time_mode.time > 0.0f && (m_view_type == EViewType::FeatureType || (m_view_type == EViewType::ColorPrint && !time_mode.custom_gcode_times.empty()))) { ImGui::Spacing(); +#endif // ENABLE_SCROLLABLE_LEGEND ImGui::Spacing(); ImGui::PushStyleColor(ImGuiCol_Separator, { 1.0f, 1.0f, 1.0f, 1.0f }); ImGui::Separator(); @@ -4647,12 +4877,12 @@ void GCodeViewer::render_legend() const ImGui::AlignTextToFramePadding(); switch (m_time_estimate_mode) { - case PrintEstimatedTimeStatistics::ETimeMode::Normal: + case PrintEstimatedStatistics::ETimeMode::Normal: { imgui.text(_u8L("Estimated printing time") + " [" + _u8L("Normal mode") + "]:"); break; } - case PrintEstimatedTimeStatistics::ETimeMode::Stealth: + case PrintEstimatedStatistics::ETimeMode::Stealth: { imgui.text(_u8L("Estimated printing time") + " [" + _u8L("Stealth mode") + "]:"); break; @@ -4662,18 +4892,18 @@ void GCodeViewer::render_legend() const ImGui::SameLine(); imgui.text(short_time(get_time_dhms(time_mode.time))); - auto show_mode_button = [this, &imgui](const wxString& label, PrintEstimatedTimeStatistics::ETimeMode mode) { + auto show_mode_button = [this, &imgui](const wxString& label, PrintEstimatedStatistics::ETimeMode mode) { bool show = false; - for (size_t i = 0; i < m_time_statistics.modes.size(); ++i) { + for (size_t i = 0; i < m_print_statistics.modes.size(); ++i) { if (i != static_cast(mode) && - short_time(get_time_dhms(m_time_statistics.modes[static_cast(mode)].time)) != short_time(get_time_dhms(m_time_statistics.modes[i].time))) { + short_time(get_time_dhms(m_print_statistics.modes[static_cast(mode)].time)) != short_time(get_time_dhms(m_print_statistics.modes[i].time))) { show = true; break; } } - if (show && m_time_statistics.modes[static_cast(mode)].roles_times.size() > 0) { + if (show && m_print_statistics.modes[static_cast(mode)].roles_times.size() > 0) { if (imgui.button(label)) { - *const_cast(&m_time_estimate_mode) = mode; + *const_cast(&m_time_estimate_mode) = mode; wxGetApp().plater()->get_current_canvas3D()->set_as_dirty(); wxGetApp().plater()->get_current_canvas3D()->request_extra_frame(); } @@ -4681,12 +4911,12 @@ void GCodeViewer::render_legend() const }; switch (m_time_estimate_mode) { - case PrintEstimatedTimeStatistics::ETimeMode::Normal: { - show_mode_button(_L("Show stealth mode"), PrintEstimatedTimeStatistics::ETimeMode::Stealth); + case PrintEstimatedStatistics::ETimeMode::Normal: { + show_mode_button(_L("Show stealth mode"), PrintEstimatedStatistics::ETimeMode::Stealth); break; } - case PrintEstimatedTimeStatistics::ETimeMode::Stealth: { - show_mode_button(_L("Show normal mode"), PrintEstimatedTimeStatistics::ETimeMode::Normal); + case PrintEstimatedStatistics::ETimeMode::Stealth: { + show_mode_button(_L("Show normal mode"), PrintEstimatedStatistics::ETimeMode::Normal); break; } default : { assert(false); break; } diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index 051260b72..112c681d4 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -46,6 +46,9 @@ class GCodeViewer { Retractions, Unretractions, +#if ENABLE_SEAMS_VISUALIZATION + Seams, +#endif // ENABLE_SEAMS_VISUALIZATION ToolChanges, ColorChanges, PausePrints, @@ -693,8 +696,8 @@ private: Shells m_shells; EViewType m_view_type{ EViewType::FeatureType }; bool m_legend_enabled{ true }; - PrintEstimatedTimeStatistics m_time_statistics; - PrintEstimatedTimeStatistics::ETimeMode m_time_estimate_mode{ PrintEstimatedTimeStatistics::ETimeMode::Normal }; + PrintEstimatedStatistics m_print_statistics; + PrintEstimatedStatistics::ETimeMode m_time_estimate_mode{ PrintEstimatedStatistics::ETimeMode::Normal }; #if ENABLE_GCODE_VIEWER_STATISTICS Statistics m_statistics; #endif // ENABLE_GCODE_VIEWER_STATISTICS diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index f99947293..8873af245 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -1,7 +1,6 @@ #include "libslic3r/libslic3r.h" #include "GLCanvas3D.hpp" -#include "admesh/stl.h" #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/GCode/ThumbnailData.hpp" @@ -1672,8 +1671,10 @@ void GLCanvas3D::render() if (m_picking_enabled) m_mouse.scene_position = _mouse_to_3d(m_mouse.position.cast()); - _render_current_gizmo(); + // sidebar hints need to be rendered before the gizmos because the depth buffer + // could be invalidated by the following gizmo render methods _render_selection_sidebar_hints(); + _render_current_gizmo(); #if ENABLE_RENDER_PICKING_PASS } #endif // ENABLE_RENDER_PICKING_PASS @@ -1712,6 +1713,11 @@ void GLCanvas3D::render() } #endif // ENABLE_RENDER_STATISTICS +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + if (wxGetApp().is_editor() && wxGetApp().plater()->is_view3D_shown()) + wxGetApp().plater()->render_project_state_debug_window(); +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + #if ENABLE_CAMERA_STATISTICS camera.debug_render(); #endif // ENABLE_CAMERA_STATISTICS @@ -3146,7 +3152,7 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) } if (m_gizmos.on_mouse(evt)) { - if (wxWindow::FindFocus() != this->m_canvas) + if (wxWindow::FindFocus() != m_canvas) // Grab keyboard focus for input in gizmo dialogs. m_canvas->SetFocus(); @@ -3169,7 +3175,7 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) m_mouse.set_move_start_threshold_position_2D_as_invalid(); } - if (evt.ButtonDown() && wxWindow::FindFocus() != this->m_canvas) + if (evt.ButtonDown() && wxWindow::FindFocus() != m_canvas) // Grab keyboard focus on any mouse click event. m_canvas->SetFocus(); @@ -4829,8 +4835,16 @@ void GLCanvas3D::_resize(unsigned int w, unsigned int h) if (m_canvas == nullptr && m_context == nullptr) return; +#if ENABLE_SCROLLABLE_LEGEND + const std::array new_size = { w, h }; + if (m_old_size == new_size) + return; + + m_old_size = new_size; +#endif // ENABLE_SCROLLABLE_LEGEND + auto *imgui = wxGetApp().imgui(); - imgui->set_display_size((float)w, (float)h); + imgui->set_display_size(static_cast(w), static_cast(h)); const float font_size = 1.5f * wxGetApp().em_unit(); #if ENABLE_RETINA_GL imgui->set_scaling(font_size, 1.0f, m_retina_helper->get_scale_factor()); @@ -4838,6 +4852,10 @@ void GLCanvas3D::_resize(unsigned int w, unsigned int h) imgui->set_scaling(font_size, m_canvas->GetContentScaleFactor(), 1.0f); #endif +#if ENABLE_SCROLLABLE_LEGEND + this->request_extra_frame(); +#endif // ENABLE_SCROLLABLE_LEGEND + // ensures that this canvas is current _set_current(); } @@ -4878,8 +4896,7 @@ void GLCanvas3D::_update_camera_zoom(double zoom) void GLCanvas3D::_refresh_if_shown_on_screen() { - if (_is_shown_on_screen()) - { + if (_is_shown_on_screen()) { const Size& cnv_size = get_canvas_size(); _resize((unsigned int)cnv_size.get_width(), (unsigned int)cnv_size.get_height()); @@ -5048,8 +5065,9 @@ void GLCanvas3D::_render_background() const if (!m_volumes.empty()) use_error_color &= _is_any_volume_outside(); else { - BoundingBoxf3 test_volume = (m_config != nullptr) ? print_volume(*m_config) : BoundingBoxf3(); - use_error_color &= (test_volume.radius() > 0.0) ? !test_volume.contains(m_gcode_viewer.get_paths_bounding_box()) : false; + const BoundingBoxf3 test_volume = (m_config != nullptr) ? print_volume(*m_config) : BoundingBoxf3(); + const BoundingBoxf3& paths_volume = m_gcode_viewer.get_paths_bounding_box(); + use_error_color &= (test_volume.radius() > 0.0 && paths_volume.radius() > 0.0) ? !test_volume.contains(paths_volume) : false; } } @@ -5983,7 +6001,7 @@ void GLCanvas3D::_load_print_object_toolpaths(const PrintObject& print_object, c { if (layerm->slices.surfaces.empty()) continue; - const PrintRegionConfig& cfg = layerm->region()->config(); + const PrintRegionConfig& cfg = layerm->region().config(); if (cfg.perimeter_extruder.value == m_selected_extruder || cfg.infill_extruder.value == m_selected_extruder || cfg.solid_infill_extruder.value == m_selected_extruder ) { @@ -6006,7 +6024,7 @@ void GLCanvas3D::_load_print_object_toolpaths(const PrintObject& print_object, c for (const LayerRegion *layerm : layer->regions()) { if (is_selected_separate_extruder) { - const PrintRegionConfig& cfg = layerm->region()->config(); + const PrintRegionConfig& cfg = layerm->region().config(); if (cfg.perimeter_extruder.value != m_selected_extruder || cfg.infill_extruder.value != m_selected_extruder || cfg.solid_infill_extruder.value != m_selected_extruder) @@ -6014,7 +6032,7 @@ void GLCanvas3D::_load_print_object_toolpaths(const PrintObject& print_object, c } if (ctxt.has_perimeters) _3DScene::extrusionentity_to_verts(layerm->perimeters, float(layer->print_z), copy, - volume(idx_layer, layerm->region()->config().perimeter_extruder.value, 0)); + volume(idx_layer, layerm->region().config().perimeter_extruder.value, 0)); if (ctxt.has_infill) { for (const ExtrusionEntity *ee : layerm->fills.entities) { // fill represents infill extrusions of a single island. @@ -6023,8 +6041,8 @@ void GLCanvas3D::_load_print_object_toolpaths(const PrintObject& print_object, c _3DScene::extrusionentity_to_verts(*fill, float(layer->print_z), copy, volume(idx_layer, is_solid_infill(fill->entities.front()->role()) ? - layerm->region()->config().solid_infill_extruder : - layerm->region()->config().infill_extruder, + layerm->region().config().solid_infill_extruder : + layerm->region().config().infill_extruder, 1)); } } @@ -6249,7 +6267,7 @@ void GLCanvas3D::_load_sla_shells() #else v.indexed_vertex_array.load_mesh(mesh); #endif // ENABLE_SMOOTH_NORMALS - v.indexed_vertex_array.finalize_geometry(this->m_initialized); + v.indexed_vertex_array.finalize_geometry(m_initialized); v.shader_outside_printer_detection_enabled = outside_printer_detection_enabled; v.composite_id.volume_id = volume_id; v.set_instance_offset(unscale(instance.shift.x(), instance.shift.y(), 0)); diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index bff8d6e05..10457d877 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -471,6 +471,10 @@ private: Model* m_model; BackgroundSlicingProcess *m_process; +#if ENABLE_SCROLLABLE_LEGEND + std::array m_old_size{ 0, 0 }; +#endif // ENABLE_SCROLLABLE_LEGEND + // Screen is only refreshed from the OnIdle handler if it is dirty. bool m_dirty; bool m_initialized; diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 3023041f6..803ab5a14 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -68,6 +69,7 @@ #include "UnsavedChangesDialog.hpp" #include "SavePresetDialog.hpp" #include "PrintHostDialogs.hpp" +#include "DesktopIntegrationDialog.hpp" #include "BitmapCache.hpp" @@ -244,10 +246,11 @@ private: // credits infornation credits = title + " " + - _L("is based on Slic3r by Alessandro Ranellucci and the RepRap community.") + "\n\n" + + _L("is based on Slic3r by Alessandro Ranellucci and the RepRap community.") + "\n" + + _L("Developed by Prusa Research.")+ "\n\n" + title + " " + _L("is licensed under the") + " " + _L("GNU Affero General Public License, version 3") + "\n\n" + _L("Contributions by Vojtech Bubnik, Enrico Turri, Oleksandra Iushchenko, Tamas Meszaros, Lukas Matena, Vojtech Kral, David Kocik and numerous others.") + "\n\n" + - _L("Artwork model by Nora Al-Badri and Jan Nikolai Nelles"); + _L("Artwork model by M Boyer"); title_font = version_font = credits_font = init_font; } @@ -632,8 +635,17 @@ void GUI_App::post_init() //FIXME this is not strictly correct, as one may pass a print/filament/printer profile here instead of a full config. this->mainframe->load_config_file(this->init_params->load_configs.back()); // If loading a 3MF file, the config is loaded from the last one. - if (! this->init_params->input_files.empty()) - this->plater()->load_files(this->init_params->input_files, true, true); + if (!this->init_params->input_files.empty()) { + const std::vector res = this->plater()->load_files(this->init_params->input_files, true, true); + if (!res.empty() && this->init_params->input_files.size() == 1) { + // Update application titlebar when opening a project file + const std::string& filename = this->init_params->input_files.front(); + if (boost::algorithm::iends_with(filename, ".amf") || + boost::algorithm::iends_with(filename, ".amf.xml") || + boost::algorithm::iends_with(filename, ".3mf")) + this->plater()->set_project_filename(filename); + } + } if (! this->init_params->extra_config.empty()) this->mainframe->load_config(this->init_params->extra_config); } @@ -904,6 +916,14 @@ bool GUI_App::on_init_inner() } else load_current_presets(); + +#if ENABLE_PROJECT_DIRTY_STATE + if (plater_ != nullptr) { + plater_->reset_project_dirty_initial_presets(); + plater_->update_project_dirty_from_presets(); + } +#endif // ENABLE_PROJECT_DIRTY_STATE + mainframe->Show(true); obj_list()->set_min_height(); @@ -1623,6 +1643,10 @@ void GUI_App::add_config_menu(wxMenuBar *menu) local_menu->Append(config_id_base + ConfigMenuSnapshots, _L("&Configuration Snapshots") + dots, _L("Inspect / activate configuration snapshots")); local_menu->Append(config_id_base + ConfigMenuTakeSnapshot, _L("Take Configuration &Snapshot"), _L("Capture a configuration snapshot")); local_menu->Append(config_id_base + ConfigMenuUpdate, _L("Check for updates"), _L("Check for configuration updates")); +#ifdef __linux__ + if (DesktopIntegrationDialog::integration_possible()) + local_menu->Append(config_id_base + ConfigMenuDesktopIntegration, _L("Desktop Integration"), _L("Desktop Integration")); +#endif local_menu->AppendSeparator(); } local_menu->Append(config_id_base + ConfigMenuPreferences, _L("&Preferences") + dots + @@ -1663,9 +1687,18 @@ void GUI_App::add_config_menu(wxMenuBar *menu) case ConfigMenuUpdate: check_updates(true); break; +#ifdef __linux__ + case ConfigMenuDesktopIntegration: + show_desktop_integration_dialog(); + break; +#endif case ConfigMenuTakeSnapshot: // Take a configuration snapshot. +#if ENABLE_PROJECT_DIRTY_STATE + if (check_and_save_current_preset_changes()) { +#else if (check_unsaved_changes()) { +#endif // ENABLE_PROJECT_DIRTY_STATE wxTextEntryDialog dlg(nullptr, _L("Taking configuration snapshot"), _L("Snapshot name")); // set current normal font for dialog children, @@ -1680,7 +1713,11 @@ void GUI_App::add_config_menu(wxMenuBar *menu) } break; case ConfigMenuSnapshots: +#if ENABLE_PROJECT_DIRTY_STATE + if (check_and_save_current_preset_changes()) { +#else if (check_unsaved_changes()) { +#endif // ENABLE_PROJECT_DIRTY_STATE std::string on_snapshot; if (Config::SnapshotDB::singleton().is_on_snapshot(*app_config)) on_snapshot = app_config->get("on_snapshot"); @@ -1781,8 +1818,57 @@ void GUI_App::add_config_menu(wxMenuBar *menu) menu->Append(local_menu, _L("&Configuration")); } +#if ENABLE_PROJECT_DIRTY_STATE +bool GUI_App::has_unsaved_preset_changes() const +{ + PrinterTechnology printer_technology = preset_bundle->printers.get_edited_preset().printer_technology(); + for (const Tab* const tab : tabs_list) { + if (tab->supports_printer_technology(printer_technology) && tab->saved_preset_is_dirty()) + return true; + } + return false; +} + +bool GUI_App::has_current_preset_changes() const +{ + PrinterTechnology printer_technology = preset_bundle->printers.get_edited_preset().printer_technology(); + for (const Tab* const tab : tabs_list) { + if (tab->supports_printer_technology(printer_technology) && tab->current_preset_is_dirty()) + return true; + } + return false; +} + +void GUI_App::update_saved_preset_from_current_preset() +{ + PrinterTechnology printer_technology = preset_bundle->printers.get_edited_preset().printer_technology(); + for (Tab* tab : tabs_list) { + if (tab->supports_printer_technology(printer_technology)) + tab->update_saved_preset_from_current_preset(); + } +} + +std::vector> GUI_App::get_selected_presets() const +{ + std::vector> ret; + PrinterTechnology printer_technology = preset_bundle->printers.get_edited_preset().printer_technology(); + for (Tab* tab : tabs_list) { + if (tab->supports_printer_technology(printer_technology)) { + const PresetCollection* presets = tab->get_presets(); + ret.push_back({ static_cast(presets->type()), presets->get_selected_preset_name() }); + } + } + return ret; +} +#endif // ENABLE_PROJECT_DIRTY_STATE + // This is called when closing the application, when loading a config file or when starting the config wizard // to notify the user whether he is aware that some preset changes will be lost. +#if ENABLE_PROJECT_DIRTY_STATE +bool GUI_App::check_and_save_current_preset_changes(const wxString& header) +{ + if (this->plater()->model().objects.empty() && has_current_preset_changes()) { +#else bool GUI_App::check_unsaved_changes(const wxString &header) { PrinterTechnology printer_technology = preset_bundle->printers.get_edited_preset().printer_technology(); @@ -1794,8 +1880,8 @@ bool GUI_App::check_unsaved_changes(const wxString &header) break; } - if (has_unsaved_changes) - { + if (has_unsaved_changes) { +#endif // ENABLE_PROJECT_DIRTY_STATE UnsavedChangesDialog dlg(header); if (wxGetApp().app_config->get("default_action_on_close_application") == "none" && dlg.ShowModal() == wxID_CANCEL) return false; @@ -2055,6 +2141,15 @@ bool GUI_App::run_wizard(ConfigWizard::RunReason reason, ConfigWizard::StartPage return res; } +void GUI_App::show_desktop_integration_dialog() +{ +#ifdef __linux__ + //wxCHECK_MSG(mainframe != nullptr, false, "Internal error: Main frame not created / null"); + DesktopIntegrationDialog dialog(mainframe); + dialog.ShowModal(); +#endif //__linux__ +} + #if ENABLE_THUMBNAIL_GENERATOR_DEBUG void GUI_App::gcode_thumbnails_debug() { diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index f1ee0746a..2613c51b1 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -76,6 +76,7 @@ enum ConfigMenuIDs { ConfigMenuSnapshots, ConfigMenuTakeSnapshot, ConfigMenuUpdate, + ConfigMenuDesktopIntegration, ConfigMenuPreferences, ConfigMenuModeSimple, ConfigMenuModeAdvanced, @@ -209,7 +210,15 @@ public: void update_mode(); void add_config_menu(wxMenuBar *menu); - bool check_unsaved_changes(const wxString &header = wxString()); +#if ENABLE_PROJECT_DIRTY_STATE + bool has_unsaved_preset_changes() const; + bool has_current_preset_changes() const; + void update_saved_preset_from_current_preset(); + std::vector> get_selected_presets() const; + bool check_and_save_current_preset_changes(const wxString& header = wxString()); +#else + bool check_unsaved_changes(const wxString& header = wxString()); +#endif // ENABLE_PROJECT_DIRTY_STATE bool check_print_host_queue(); bool checked_tab(Tab* tab); void load_current_presets(bool check_printer_presets = true); @@ -268,6 +277,7 @@ public: void open_web_page_localized(const std::string &http_address); bool run_wizard(ConfigWizard::RunReason reason, ConfigWizard::StartPage start_page = ConfigWizard::SP_WELCOME); + void show_desktop_integration_dialog(); #if ENABLE_THUMBNAIL_GENERATOR_DEBUG // temporary and debug only -> extract thumbnails from selected gcode and save them as png files diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index b5c2bb221..28053971f 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -7,6 +7,9 @@ #include "GUI_App.hpp" #include "I18N.hpp" #include "Plater.hpp" +#if ENABLE_PROJECT_DIRTY_STATE +#include "MainFrame.hpp" +#endif // ENABLE_PROJECT_DIRTY_STATE #include "OptionsGroup.hpp" #include "Tab.hpp" @@ -1457,12 +1460,15 @@ void ObjectList::load_shape_object(const std::string& type_name) if (obj_idx < 0) return; - take_snapshot(_(L("Add Shape"))); + take_snapshot(_L("Add Shape")); // Create mesh BoundingBoxf3 bb; TriangleMesh mesh = create_mesh(type_name, bb); - load_mesh_object(mesh, _(L("Shape")) + "-" + _(type_name)); + load_mesh_object(mesh, _L("Shape") + "-" + _(type_name)); +#if ENABLE_PROJECT_DIRTY_STATE + wxGetApp().mainframe->update_title(); +#endif // ENABLE_PROJECT_DIRTY_STATE } void ObjectList::load_mesh_object(const TriangleMesh &mesh, const wxString &name, bool center) @@ -2467,28 +2473,22 @@ void ObjectList::unselect_objects() m_prevent_list_events = false; } -void ObjectList::select_current_object(int idx) +void ObjectList::select_object_item(bool is_msr_gizmo) { - m_prevent_list_events = true; - UnselectAll(); - if (idx >= 0) - Select(m_objects_model->GetItemById(idx)); - part_selection_changed(); - m_prevent_list_events = false; -} + if (wxDataViewItem item = GetSelection()) { + ItemType type = m_objects_model->GetItemType(item); + bool is_volume_item = type == itVolume || type == itSettings && m_objects_model->GetItemType(m_objects_model->GetParent(item)) == itVolume; + if (is_msr_gizmo && is_volume_item || type == itObject) + return; -void ObjectList::select_current_volume(int idx, int vol_idx) -{ - if (vol_idx < 0) { - select_current_object(idx); - return; + if (wxDataViewItem obj_item = m_objects_model->GetTopParent(item)) { + m_prevent_list_events = true; + UnselectAll(); + Select(obj_item); + part_selection_changed(); + m_prevent_list_events = false; + } } - m_prevent_list_events = true; - UnselectAll(); - if (idx >= 0) - Select(m_objects_model->GetItemByVolumeId(idx, vol_idx)); - part_selection_changed(); - m_prevent_list_events = false; } static void update_selection(wxDataViewItemArray& sels, ObjectList::SELECTION_MODE mode, ObjectDataViewModel* model) @@ -2893,7 +2893,8 @@ void ObjectList::update_selections() { const auto item = GetSelection(); if (selection.is_single_full_object()) { - if (m_objects_model->GetItemType(m_objects_model->GetParent(item)) & itObject) + if (m_objects_model->GetItemType(m_objects_model->GetParent(item)) & itObject && + m_objects_model->GetObjectIdByItem(item) == selection.get_object_idx() ) return; sels.Add(m_objects_model->GetItemById(selection.get_object_idx())); } diff --git a/src/slic3r/GUI/GUI_ObjectList.hpp b/src/slic3r/GUI/GUI_ObjectList.hpp index 5812e26f7..8bcfec11c 100644 --- a/src/slic3r/GUI/GUI_ObjectList.hpp +++ b/src/slic3r/GUI/GUI_ObjectList.hpp @@ -291,10 +291,9 @@ public: // #ys_FIXME_to_delete // Unselect all objects in the list on c++ side void unselect_objects(); - // Select current object in the list on c++ side - void select_current_object(int idx); - // Select current volume in the list on c++ side - void select_current_volume(int idx, int vol_idx); + // Select object item in the ObjectList, when some gizmo is activated + // "is_msr_gizmo" indicates if Move/Scale/Rotate gizmo was activated + void select_object_item(bool is_msr_gizmo); // Remove objects/sub-object from the list void remove(); diff --git a/src/slic3r/GUI/GUI_Preview.cpp b/src/slic3r/GUI/GUI_Preview.cpp index e67ddb045..52223b3d4 100644 --- a/src/slic3r/GUI/GUI_Preview.cpp +++ b/src/slic3r/GUI/GUI_Preview.cpp @@ -235,7 +235,7 @@ bool Preview::init(wxWindow* parent, Model* model) _L("Ironing") + "|1|" + _L("Bridge infill") + "|1|" + _L("Gap fill") + "|1|" + - _L("Skirt") + "|1|" + + _L("Skirt/Brim") + "|1|" + _L("Support material") + "|1|" + _L("Support material interface") + "|1|" + _L("Wipe tower") + "|1|" + @@ -250,6 +250,9 @@ bool Preview::init(wxWindow* parent, Model* model) get_option_type_string(OptionType::Wipe) + "|0|" + get_option_type_string(OptionType::Retractions) + "|0|" + get_option_type_string(OptionType::Unretractions) + "|0|" + +#if ENABLE_SEAMS_VISUALIZATION + get_option_type_string(OptionType::Seams) + "|0|" + +#endif // ENABLE_SEAMS_VISUALIZATION get_option_type_string(OptionType::ToolChanges) + "|0|" + get_option_type_string(OptionType::ColorChanges) + "|0|" + get_option_type_string(OptionType::PausePrints) + "|0|" + @@ -640,7 +643,7 @@ void Preview::update_layers_slider(const std::vector& layers_z, bool kee if (sla_print_technology) m_layers_slider->SetLayersTimes(plater->sla_print().print_statistics().layers_times); else { - auto print_mode_stat = m_gcode_result->time_statistics.modes.front(); + auto print_mode_stat = m_gcode_result->print_statistics.modes.front(); m_layers_slider->SetLayersTimes(print_mode_stat.layers_times, print_mode_stat.time); } @@ -1008,6 +1011,9 @@ wxString Preview::get_option_type_string(OptionType type) const case OptionType::Wipe: { return _L("Wipe"); } case OptionType::Retractions: { return _L("Retractions"); } case OptionType::Unretractions: { return _L("Deretractions"); } +#if ENABLE_SEAMS_VISUALIZATION + case OptionType::Seams: { return _L("Seams"); } +#endif // ENABLE_SEAMS_VISUALIZATION case OptionType::ToolChanges: { return _L("Tool changes"); } case OptionType::ColorChanges: { return _L("Color changes"); } case OptionType::PausePrints: { return _L("Print pauses"); } diff --git a/src/slic3r/GUI/GUI_Preview.hpp b/src/slic3r/GUI/GUI_Preview.hpp index 3bf0e21ae..d49e6e7ac 100644 --- a/src/slic3r/GUI/GUI_Preview.hpp +++ b/src/slic3r/GUI/GUI_Preview.hpp @@ -116,6 +116,9 @@ public: Wipe, Retractions, Unretractions, +#if ENABLE_SEAMS_VISUALIZATION + Seams, +#endif // ENABLE_SEAMS_VISUALIZATION ToolChanges, ColorChanges, PausePrints, diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp index 91aef75d9..3a932c598 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp @@ -32,6 +32,42 @@ GLGizmoPainterBase::GLGizmoPainterBase(GLCanvas3D& parent, const std::string& ic +#if ENABLE_PROJECT_DIRTY_STATE +// port of 948bc382655993721d93d3b9fce9b0186fcfb211 +void GLGizmoPainterBase::activate_internal_undo_redo_stack(bool activate) +{ + Plater* plater = wxGetApp().plater(); + + // Following is needed to prevent taking an extra snapshot when the activation of + // the internal stack happens when the gizmo is already active (such as open gizmo, + // close gizmo, undo, start painting). The internal stack does not activate on the + // undo, because that would obliterate all future of the main stack (user would + // have to close the gizmo himself, he has no access to main undo/redo after the + // internal stack opens). We don't want the "entering" snapshot taken in this case, + // because there already is one. + std::string last_snapshot_name; + plater->undo_redo_topmost_string_getter(plater->can_undo(), last_snapshot_name); + + if (activate && !m_internal_stack_active) { + std::string str = get_painter_type() == PainterGizmoType::FDM_SUPPORTS + ? _u8L("Entering Paint-on supports") + : _u8L("Entering Seam painting"); + if (last_snapshot_name != str) + Plater::TakeSnapshot(plater, str); + plater->enter_gizmos_stack(); + m_internal_stack_active = true; + } + if (!activate && m_internal_stack_active) { + plater->leave_gizmos_stack(); + std::string str = get_painter_type() == PainterGizmoType::SEAM + ? _u8L("Leaving Seam painting") + : _u8L("Leaving Paint-on supports"); + if (last_snapshot_name != str) + Plater::TakeSnapshot(plater, str); + m_internal_stack_active = false; + } +} +#else void GLGizmoPainterBase::activate_internal_undo_redo_stack(bool activate) { if (activate && ! m_internal_stack_active) { @@ -51,6 +87,7 @@ void GLGizmoPainterBase::activate_internal_undo_redo_stack(bool activate) m_internal_stack_active = false; } } +#endif // ENABLE_PROJECT_DIRTY_STATE diff --git a/src/slic3r/GUI/Gizmos/GLGizmoSlaSupports.cpp b/src/slic3r/GUI/Gizmos/GLGizmoSlaSupports.cpp index b200623f4..7ff274aac 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoSlaSupports.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoSlaSupports.cpp @@ -45,18 +45,18 @@ bool GLGizmoSlaSupports::on_init() { m_shortcut_key = WXK_CONTROL_L; - m_desc["head_diameter"] = _(L("Head diameter")) + ": "; - m_desc["lock_supports"] = _(L("Lock supports under new islands")); - m_desc["remove_selected"] = _(L("Remove selected points")); - m_desc["remove_all"] = _(L("Remove all points")); - m_desc["apply_changes"] = _(L("Apply changes")); - m_desc["discard_changes"] = _(L("Discard changes")); - m_desc["minimal_distance"] = _(L("Minimal points distance")) + ": "; - m_desc["points_density"] = _(L("Support points density")) + ": "; - m_desc["auto_generate"] = _(L("Auto-generate points")); - m_desc["manual_editing"] = _(L("Manual editing")); - m_desc["clipping_of_view"] = _(L("Clipping of view"))+ ": "; - m_desc["reset_direction"] = _(L("Reset direction")); + m_desc["head_diameter"] = _L("Head diameter") + ": "; + m_desc["lock_supports"] = _L("Lock supports under new islands"); + m_desc["remove_selected"] = _L("Remove selected points"); + m_desc["remove_all"] = _L("Remove all points"); + m_desc["apply_changes"] = _L("Apply changes"); + m_desc["discard_changes"] = _L("Discard changes"); + m_desc["minimal_distance"] = _L("Minimal points distance") + ": "; + m_desc["points_density"] = _L("Support points density") + ": "; + m_desc["auto_generate"] = _L("Auto-generate points"); + m_desc["manual_editing"] = _L("Manual editing"); + m_desc["clipping_of_view"] = _L("Clipping of view")+ ": "; + m_desc["reset_direction"] = _L("Reset direction"); return true; } @@ -372,7 +372,7 @@ bool GLGizmoSlaSupports::gizmo_event(SLAGizmoEventType action, const Vec2d& mous if (m_selection_empty) { std::pair pos_and_normal; if (unproject_on_mesh(mouse_position, pos_and_normal)) { // we got an intersection - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("Add support point"))); + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Add support point")); m_editing_cache.emplace_back(sla::SupportPoint(pos_and_normal.first, m_new_point_head_diameter/2.f, false), false, pos_and_normal.second); m_parent.set_as_dirty(); m_wait_for_up_event = true; @@ -512,7 +512,7 @@ void GLGizmoSlaSupports::delete_selected_points(bool force) std::abort(); } - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("Delete support point"))); + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Delete support point")); for (unsigned int idx=0; idxconfig.set("support_points_minimal_distance", m_minimal_point_distance_stash); mo->config.set("support_points_density_relative", (int)m_density_stash); - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("Support parameter change"))); + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Support parameter change")); mo->config.set("support_points_minimal_distance", minimal_point_distance); mo->config.set("support_points_density_relative", (int)density); wxGetApp().obj_list()->update_and_show_object_settings_item(); @@ -867,10 +867,9 @@ bool GLGizmoSlaSupports::on_is_selectable() const std::string GLGizmoSlaSupports::on_get_name() const { - return (_(L("SLA Support Points")) + " [L]").ToUTF8().data(); + return (_L("SLA Support Points") + " [L]").ToUTF8().data(); } - CommonGizmosDataID GLGizmoSlaSupports::on_get_requirements() const { return CommonGizmosDataID( @@ -895,7 +894,11 @@ void GLGizmoSlaSupports::on_set_state() // data are not yet available, the CallAfter will postpone taking the // snapshot until they are. No, it does not feel right. wxGetApp().CallAfter([]() { - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("SLA gizmo turned on"))); +#if ENABLE_PROJECT_DIRTY_STATE + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Entering SLA gizmo")); +#else + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("SLA gizmo turned on")); +#endif // ENABLE_PROJECT_DIRTY_STATE }); } @@ -909,8 +912,8 @@ void GLGizmoSlaSupports::on_set_state() wxGetApp().CallAfter([this]() { // Following is called through CallAfter, because otherwise there was a problem // on OSX with the wxMessageDialog being shown several times when clicked into. - wxMessageDialog dlg(GUI::wxGetApp().mainframe, _(L("Do you want to save your manually " - "edited support points?")) + "\n",_(L("Save changes?")), wxICON_QUESTION | wxYES | wxNO); + wxMessageDialog dlg(GUI::wxGetApp().mainframe, _L("Do you want to save your manually " + "edited support points?") + "\n",_L("Save changes?"), wxICON_QUESTION | wxYES | wxNO); if (dlg.ShowModal() == wxID_YES) editing_mode_apply_changes(); else @@ -922,7 +925,11 @@ void GLGizmoSlaSupports::on_set_state() else { // we are actually shutting down disable_editing_mode(); // so it is not active next time the gizmo opens - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("SLA gizmo turned off"))); +#if ENABLE_PROJECT_DIRTY_STATE + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Leaving SLA gizmo")); +#else + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("SLA gizmo turned off")); +#endif // ENABLE_PROJECT_DIRTY_STATE m_normal_cache.clear(); m_old_mo_id = -1; } @@ -953,7 +960,7 @@ void GLGizmoSlaSupports::on_stop_dragging() && backup.support_point.pos != m_point_before_drag.support_point.pos) // and it was moved, not just selected { m_editing_cache[m_hover_id] = m_point_before_drag; - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("Move support point"))); + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Move support point")); m_editing_cache[m_hover_id] = backup; } } @@ -1046,7 +1053,7 @@ void GLGizmoSlaSupports::editing_mode_apply_changes() disable_editing_mode(); // this leaves the editing mode undo/redo stack and must be done before the snapshot is taken if (unsaved_changes()) { - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("Support points edit"))); + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Support points edit")); m_normal_cache.clear(); for (const CacheEntry& ce : m_editing_cache) @@ -1125,14 +1132,14 @@ void GLGizmoSlaSupports::get_data_from_backend() void GLGizmoSlaSupports::auto_generate() { wxMessageDialog dlg(GUI::wxGetApp().plater(), - _(L("Autogeneration will erase all manually edited points.")) + "\n\n" + - _(L("Are you sure you want to do it?")) + "\n", - _(L("Warning")), wxICON_WARNING | wxYES | wxNO); + _L("Autogeneration will erase all manually edited points.") + "\n\n" + + _L("Are you sure you want to do it?") + "\n", + _L("Warning"), wxICON_WARNING | wxYES | wxNO); ModelObject* mo = m_c->selection_info()->model_object(); if (mo->sla_points_status != sla::PointsStatus::UserModified || m_normal_cache.empty() || dlg.ShowModal() == wxID_YES) { - Plater::TakeSnapshot snapshot(wxGetApp().plater(), _(L("Autogenerate support points"))); + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _L("Autogenerate support points")); wxGetApp().CallAfter([this]() { reslice_SLA_supports(); }); mo->sla_points_status = sla::PointsStatus::Generating; } @@ -1180,7 +1187,7 @@ bool GLGizmoSlaSupports::unsaved_changes() const } SlaGizmoHelpDialog::SlaGizmoHelpDialog() -: wxDialog(nullptr, wxID_ANY, _(L("SLA gizmo keyboard shortcuts")), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER) +: wxDialog(nullptr, wxID_ANY, _L("SLA gizmo keyboard shortcuts"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER) { SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); const wxString ctrl = GUI::shortkey_ctrl_prefix(); @@ -1191,7 +1198,7 @@ SlaGizmoHelpDialog::SlaGizmoHelpDialog() const wxFont& font = wxGetApp().small_font(); const wxFont& bold_font = wxGetApp().bold_font(); - auto note_text = new wxStaticText(this, wxID_ANY, _(L("Note: some shortcuts work in (non)editing mode only."))); + auto note_text = new wxStaticText(this, wxID_ANY, _L("Note: some shortcuts work in (non)editing mode only.")); note_text->SetFont(font); auto vsizer = new wxBoxSizer(wxVERTICAL); @@ -1209,21 +1216,21 @@ SlaGizmoHelpDialog::SlaGizmoHelpDialog() vsizer->AddSpacer(20); std::vector> shortcuts; - shortcuts.push_back(std::make_pair(_(L("Left click")), _(L("Add point")))); - shortcuts.push_back(std::make_pair(_(L("Right click")), _(L("Remove point")))); - shortcuts.push_back(std::make_pair(_(L("Drag")), _(L("Move point")))); - shortcuts.push_back(std::make_pair(ctrl+_(L("Left click")), _(L("Add point to selection")))); - shortcuts.push_back(std::make_pair(alt+_(L("Left click")), _(L("Remove point from selection")))); - shortcuts.push_back(std::make_pair(wxString("Shift+")+_(L("Drag")), _(L("Select by rectangle")))); - shortcuts.push_back(std::make_pair(alt+_(L("Drag")), _(L("Deselect by rectangle")))); - shortcuts.push_back(std::make_pair(ctrl+"A", _(L("Select all points")))); - shortcuts.push_back(std::make_pair("Delete", _(L("Remove selected points")))); - shortcuts.push_back(std::make_pair(ctrl+_(L("Mouse wheel")), _(L("Move clipping plane")))); - shortcuts.push_back(std::make_pair("R", _(L("Reset clipping plane")))); - shortcuts.push_back(std::make_pair("Enter", _(L("Apply changes")))); - shortcuts.push_back(std::make_pair("Esc", _(L("Discard changes")))); - shortcuts.push_back(std::make_pair("M", _(L("Switch to editing mode")))); - shortcuts.push_back(std::make_pair("A", _(L("Auto-generate points")))); + shortcuts.push_back(std::make_pair(_L("Left click"), _L("Add point"))); + shortcuts.push_back(std::make_pair(_L("Right click"), _L("Remove point"))); + shortcuts.push_back(std::make_pair(_L("Drag"), _L("Move point"))); + shortcuts.push_back(std::make_pair(ctrl+_L("Left click"), _L("Add point to selection"))); + shortcuts.push_back(std::make_pair(alt+_L("Left click"), _L("Remove point from selection"))); + shortcuts.push_back(std::make_pair(wxString("Shift+")+_L("Drag"), _L("Select by rectangle"))); + shortcuts.push_back(std::make_pair(alt+_(L("Drag")), _L("Deselect by rectangle"))); + shortcuts.push_back(std::make_pair(ctrl+"A", _L("Select all points"))); + shortcuts.push_back(std::make_pair("Delete", _L("Remove selected points"))); + shortcuts.push_back(std::make_pair(ctrl+_L("Mouse wheel"), _L("Move clipping plane"))); + shortcuts.push_back(std::make_pair("R", _L("Reset clipping plane"))); + shortcuts.push_back(std::make_pair("Enter", _L("Apply changes"))); + shortcuts.push_back(std::make_pair("Esc", _L("Discard changes"))); + shortcuts.push_back(std::make_pair("M", _L("Switch to editing mode"))); + shortcuts.push_back(std::make_pair("A", _L("Auto-generate points"))); for (const auto& pair : shortcuts) { auto shortcut = new wxStaticText(this, wxID_ANY, pair.first); diff --git a/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp b/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp index 2f1396d63..bd02cbbbb 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp @@ -5,6 +5,7 @@ #include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_ObjectManipulation.hpp" +#include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/Utils/UndoRedo.hpp" #include "slic3r/GUI/NotificationManager.hpp" @@ -1084,8 +1085,10 @@ void GLGizmosManager::update_on_off_state(const Vec2d& mouse_pos) return; size_t idx = get_gizmo_idx_from_mouse(mouse_pos); - if (idx != Undefined && m_gizmos[idx]->is_activable() && m_hover == idx) + if (idx != Undefined && m_gizmos[idx]->is_activable() && m_hover == idx) { activate_gizmo(m_current == idx ? Undefined : (EType)idx); + wxGetApp().obj_list()->select_object_item((EType)idx <= Rotate); + } } std::string GLGizmosManager::update_hover_state(const Vec2d& mouse_pos) diff --git a/src/slic3r/GUI/ImGuiWrapper.cpp b/src/slic3r/GUI/ImGuiWrapper.cpp index db7af046b..5726477ab 100644 --- a/src/slic3r/GUI/ImGuiWrapper.cpp +++ b/src/slic3r/GUI/ImGuiWrapper.cpp @@ -488,8 +488,7 @@ bool ImGuiWrapper::undo_redo_list(const ImVec2& size, const bool is_undo, bool ( int i=0; const char* item_text; - while (items_getter(is_undo, i, &item_text)) - { + while (items_getter(is_undo, i, &item_text)) { ImGui::Selectable(item_text, i < hovered); if (ImGui::IsItemHovered()) { diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index 9c426dcd9..8c54e10f8 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -206,7 +206,14 @@ DPIFrame(NULL, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_S // declare events Bind(wxEVT_CLOSE_WINDOW, [this](wxCloseEvent& event) { +#if ENABLE_PROJECT_DIRTY_STATE + if (m_plater != nullptr) + m_plater->save_project_if_dirty(); + + if (event.CanVeto() && !wxGetApp().check_and_save_current_preset_changes()) { +#else if (event.CanVeto() && !wxGetApp().check_unsaved_changes()) { +#endif // ENABLE_PROJECT_DIRTY_STATE event.Veto(); return; } @@ -487,8 +494,14 @@ void MainFrame::update_title() // m_plater->get_project_filename() produces file name including path, but excluding extension. // Don't try to remove the extension, it would remove part of the file name after the last dot! wxString project = from_path(into_path(m_plater->get_project_filename()).filename()); +#if ENABLE_PROJECT_DIRTY_STATE + wxString dirty_marker = (!m_plater->model().objects.empty() && m_plater->is_project_dirty()) ? "*" : ""; + if (!dirty_marker.empty() || !project.empty()) + title = dirty_marker + project + " - "; +#else if (!project.empty()) title += (project + " - "); +#endif // ENABLE_PROJECT_DIRTY_STATE } std::string build_id = wxGetApp().is_editor() ? SLIC3R_BUILD_ID : GCODEVIEWER_BUILD_ID; @@ -672,10 +685,36 @@ bool MainFrame::can_start_new_project() const return (m_plater != nullptr) && (!m_plater->get_project_filename(".3mf").IsEmpty() || !m_plater->model().objects.empty()); } +#if ENABLE_PROJECT_DIRTY_STATE +bool MainFrame::can_save() const +{ + return (m_plater != nullptr) && !m_plater->model().objects.empty() && !m_plater->get_project_filename().empty() && m_plater->is_project_dirty(); +} + +bool MainFrame::can_save_as() const +{ + return (m_plater != nullptr) && !m_plater->model().objects.empty(); +} + +void MainFrame::save_project() +{ + save_project_as(m_plater->get_project_filename(".3mf")); +} + +void MainFrame::save_project_as(const wxString& filename) +{ + bool ret = (m_plater != nullptr) ? m_plater->export_3mf(into_path(filename)) : false; + if (ret) { +// wxGetApp().update_saved_preset_from_current_preset(); + m_plater->reset_project_dirty_after_save(); + } +} +#else bool MainFrame::can_save() const { return (m_plater != nullptr) && !m_plater->model().objects.empty(); } +#endif // ENABLE_PROJECT_DIRTY_STATE bool MainFrame::can_export_model() const { @@ -984,16 +1023,27 @@ void MainFrame::init_menubar_as_editor() Bind(wxEVT_UPDATE_UI, [this](wxUpdateUIEvent& evt) { evt.Enable(m_recent_projects.GetCount() > 0); }, recent_projects_submenu->GetId()); +#if ENABLE_PROJECT_DIRTY_STATE + append_menu_item(fileMenu, wxID_ANY, _L("&Save Project") + "\tCtrl+S", _L("Save current project file"), + [this](wxCommandEvent&) { save_project(); }, "save", nullptr, + [this](){return m_plater != nullptr && can_save(); }, this); +#else append_menu_item(fileMenu, wxID_ANY, _L("&Save Project") + "\tCtrl+S", _L("Save current project file"), [this](wxCommandEvent&) { if (m_plater) m_plater->export_3mf(into_path(m_plater->get_project_filename(".3mf"))); }, "save", nullptr, [this](){return m_plater != nullptr && can_save(); }, this); +#endif // ENABLE_PROJECT_DIRTY_STATE #ifdef __APPLE__ append_menu_item(fileMenu, wxID_ANY, _L("Save Project &as") + dots + "\tCtrl+Shift+S", _L("Save current project file as"), #else append_menu_item(fileMenu, wxID_ANY, _L("Save Project &as") + dots + "\tCtrl+Alt+S", _L("Save current project file as"), #endif // __APPLE__ +#if ENABLE_PROJECT_DIRTY_STATE + [this](wxCommandEvent&) { save_project_as(); }, "save", nullptr, + [this](){return m_plater != nullptr && can_save_as(); }, this); +#else [this](wxCommandEvent&) { if (m_plater) m_plater->export_3mf(); }, "save", nullptr, [this](){return m_plater != nullptr && can_save(); }, this); +#endif // ENABLE_PROJECT_DIRTY_STATE fileMenu->AppendSeparator(); @@ -1483,10 +1533,10 @@ void MainFrame::repair_stl() output_file = dlg.GetPath(); } - auto tmesh = new Slic3r::TriangleMesh(); - tmesh->ReadSTLFile(input_file.ToUTF8().data()); - tmesh->repair(); - tmesh->WriteOBJFile(output_file.ToUTF8().data()); + Slic3r::TriangleMesh tmesh; + tmesh.ReadSTLFile(input_file.ToUTF8().data()); + tmesh.repair(); + tmesh.WriteOBJFile(output_file.ToUTF8().data()); Slic3r::GUI::show_info(this, L("Your file was repaired."), L("Repair")); } @@ -1518,7 +1568,11 @@ void MainFrame::export_config() // Load a config file containing a Print, Filament & Printer preset. void MainFrame::load_config_file() { +#if ENABLE_PROJECT_DIRTY_STATE + if (!wxGetApp().check_and_save_current_preset_changes()) +#else if (!wxGetApp().check_unsaved_changes()) +#endif // ENABLE_PROJECT_DIRTY_STATE return; wxFileDialog dlg(this, _L("Select configuration to load:"), !m_last_config.IsEmpty() ? get_dir_name(m_last_config) : wxGetApp().app_config->get_last_dir(), @@ -1547,7 +1601,11 @@ bool MainFrame::load_config_file(const std::string &path) void MainFrame::export_configbundle(bool export_physical_printers /*= false*/) { +#if ENABLE_PROJECT_DIRTY_STATE + if (!wxGetApp().check_and_save_current_preset_changes()) +#else if (!wxGetApp().check_unsaved_changes()) +#endif // ENABLE_PROJECT_DIRTY_STATE return; // validate current configuration in case it's dirty auto err = wxGetApp().preset_bundle->full_config().validate(); @@ -1579,7 +1637,11 @@ void MainFrame::export_configbundle(bool export_physical_printers /*= false*/) // but that behavior was not documented and likely buggy. void MainFrame::load_configbundle(wxString file/* = wxEmptyString, const bool reset_user_profile*/) { +#if ENABLE_PROJECT_DIRTY_STATE + if (!wxGetApp().check_and_save_current_preset_changes()) +#else if (!wxGetApp().check_unsaved_changes()) +#endif // ENABLE_PROJECT_DIRTY_STATE return; if (file.IsEmpty()) { wxFileDialog dlg(this, _L("Select configuration to load:"), diff --git a/src/slic3r/GUI/MainFrame.hpp b/src/slic3r/GUI/MainFrame.hpp index 0971fdc77..307cdf1ae 100644 --- a/src/slic3r/GUI/MainFrame.hpp +++ b/src/slic3r/GUI/MainFrame.hpp @@ -91,7 +91,9 @@ class MainFrame : public DPIFrame void on_value_changed(wxCommandEvent&); bool can_start_new_project() const; +#if !ENABLE_PROJECT_DIRTY_STATE bool can_save() const; +#endif // !ENABLE_PROJECT_DIRTY_STATE bool can_export_model() const; bool can_export_toolpaths() const; bool can_export_supports() const; @@ -184,6 +186,13 @@ public: // Propagate changed configuration from the Tab to the Plater and save changes to the AppConfig void on_config_changed(DynamicPrintConfig* cfg) const ; +#if ENABLE_PROJECT_DIRTY_STATE + bool can_save() const; + bool can_save_as() const; + void save_project(); + void save_project_as(const wxString& filename = wxString()); +#endif // ENABLE_PROJECT_DIRTY_STATE + void add_to_recent_projects(const wxString& filename); PrintHostQueueDialog* printhost_queue_dlg() { return m_printhost_queue_dlg; } diff --git a/src/slic3r/GUI/NotificationManager.hpp b/src/slic3r/GUI/NotificationManager.hpp index 17657948e..1bcb93de0 100644 --- a/src/slic3r/GUI/NotificationManager.hpp +++ b/src/slic3r/GUI/NotificationManager.hpp @@ -82,7 +82,13 @@ enum class NotificationType // Notification emitted by Print::validate PrintValidateWarning, // Notification telling user to quit SLA supports manual editing - QuitSLAManualMode + QuitSLAManualMode, + // Desktop integration basic info + DesktopIntegrationSuccess, + DesktopIntegrationFail, + UndoDesktopIntegrationSuccess, + UndoDesktopIntegrationFail + }; class NotificationManager @@ -514,6 +520,14 @@ private: "To export the G-code correctly, check the \"Color Change G-code\" in \"Printer Settings > Custom G-code\"") }, {NotificationType::EmptyAutoColorChange, NotificationLevel::RegularNotification, 10, _u8L("This model doesn't allow to automatically add the color changes") }, + {NotificationType::DesktopIntegrationSuccess, NotificationLevel::RegularNotification, 10, + _u8L("Desktop integration was successful.") }, + {NotificationType::DesktopIntegrationFail, NotificationLevel::WarningNotification, 10, + _u8L("Desktop integration failed.") }, + {NotificationType::UndoDesktopIntegrationSuccess, NotificationLevel::RegularNotification, 10, + _u8L("Undo desktop integration was successful.") }, + {NotificationType::UndoDesktopIntegrationFail, NotificationLevel::WarningNotification, 10, + _u8L("Undo desktop integration failed.") }, //{NotificationType::NewAppAvailable, NotificationLevel::ImportantNotification, 20, _u8L("New vesion of PrusaSlicer is available.", _u8L("Download page.") }, //{NotificationType::LoadingFailed, NotificationLevel::RegularNotification, 20, _u8L("Loading of model has Failed") }, //{NotificationType::DeviceEjected, NotificationLevel::RegularNotification, 10, _u8L("Removable device has been safely ejected")} // if we want changeble text (like here name of device), we need to do it as CustomNotification diff --git a/src/slic3r/GUI/OptionsGroup.hpp b/src/slic3r/GUI/OptionsGroup.hpp index 11a52d648..96fe94e0f 100644 --- a/src/slic3r/GUI/OptionsGroup.hpp +++ b/src/slic3r/GUI/OptionsGroup.hpp @@ -228,7 +228,7 @@ public: int config_type() const throw() { return m_config_type; } const t_opt_map& opt_map() const throw() { return m_opt_map; } - void set_config_category_and_type(const wxString &category, int type) { this->m_config_category = category; this->m_config_type = type; } + void set_config_category_and_type(const wxString &category, int type) { m_config_category = category; m_config_type = type; } void set_config(DynamicPrintConfig* config) { m_config = config; m_modelconfig = nullptr; } Option get_option(const std::string& opt_key, int opt_index = -1); Line create_single_option_line(const std::string& title, const wxString& path = wxEmptyString, int idx = -1) /*const*/{ diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 9f23de421..24d32b116 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -81,6 +81,9 @@ #include "InstanceCheck.hpp" #include "NotificationManager.hpp" #include "PresetComboBoxes.hpp" +#if ENABLE_PROJECT_DIRTY_STATE +#include "ProjectDirtyStateManager.hpp" +#endif // ENABLE_PROJECT_DIRTY_STATE #ifdef __APPLE__ #include "Gizmos/GLGizmosManager.hpp" @@ -976,7 +979,6 @@ void Sidebar::sys_color_changed() for (PlaterPresetComboBox* combo : p->combos_filament) combo->msw_rescale(); - p->frequently_changed_parameters->msw_rescale(); p->object_list->msw_rescale(); p->object_list->sys_color_changed(); p->object_manipulation->sys_color_changed(); @@ -1173,10 +1175,10 @@ void Sidebar::update_sliced_info_sizer() new_label += format_wxstr(":\n - %1%\n - %2%", _L("objects"), _L("wipe tower")); wxString info_text = is_wipe_tower ? - wxString::Format("%.2f \n%.2f \n%.2f", ps.total_used_filament / /*1000*/koef, - (ps.total_used_filament - ps.total_wipe_tower_filament) / /*1000*/koef, - ps.total_wipe_tower_filament / /*1000*/koef) : - wxString::Format("%.2f", ps.total_used_filament / /*1000*/koef); + wxString::Format("%.2f \n%.2f \n%.2f", ps.total_used_filament / koef, + (ps.total_used_filament - ps.total_wipe_tower_filament) / koef, + ps.total_wipe_tower_filament / koef) : + wxString::Format("%.2f", ps.total_used_filament / koef); p->sliced_info->SetTextAndShow(siFilament_m, info_text, new_label); koef = imperial_units ? pow(ObjectManipulation::mm_to_in, 3) : 1.0f; @@ -1204,7 +1206,7 @@ void Sidebar::update_sliced_info_sizer() filament_weight = ps.total_weight; else { double filament_density = filament_preset->config.opt_float("filament_density", 0); - filament_weight = filament.second * filament_density * 2.4052f * 0.001; // assumes 1.75mm filament diameter; + filament_weight = filament.second * filament_density/* *2.4052f*/ * 0.001; // assumes 1.75mm filament diameter; new_label += "\n - " + format_wxstr(_L("Filament at extruder %1%"), filament.first + 1); info_text += wxString::Format("\n%.2f", filament_weight); @@ -1358,7 +1360,8 @@ void Sidebar::update_ui_from_settings() update_sliced_info_sizer(); // update Cut gizmo, if it's open p->plater->canvas3D()->update_gizmos_on_off_state(); - p->plater->canvas3D()->request_extra_frame(); + p->plater->set_current_canvas_as_dirty(); + p->plater->get_current_canvas3D()->request_extra_frame(); } std::vector& Sidebar::combos_filament() @@ -1396,7 +1399,13 @@ bool PlaterDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString &fi this->MSWUpdateDragImageOnLeave(); #endif // WIN32 +#if ENABLE_PROJECT_DIRTY_STATE + bool res = (m_plater != nullptr) ? m_plater->load_files(filenames) : false; + wxGetApp().mainframe->update_title(); + return res; +#else return (m_plater != nullptr) ? m_plater->load_files(filenames) : false; +#endif // ENABLE_PROJECT_DIRTY_STATE } // State to manage showing after export notifications and device ejecting @@ -1440,6 +1449,10 @@ struct Plater::priv Preview *preview; NotificationManager* notification_manager { nullptr }; +#if ENABLE_PROJECT_DIRTY_STATE + ProjectDirtyStateManager dirty_state; +#endif // ENABLE_PROJECT_DIRTY_STATE + BackgroundSlicingProcess background_process; bool suppressed_backround_processing_update { false }; @@ -1510,6 +1523,31 @@ struct Plater::priv priv(Plater *q, MainFrame *main_frame); ~priv(); +#if ENABLE_PROJECT_DIRTY_STATE + bool is_project_dirty() const { return dirty_state.is_dirty(); } + void update_project_dirty_from_presets() { dirty_state.update_from_presets(); } + bool save_project_if_dirty() { + if (dirty_state.is_dirty()) { + MainFrame* mainframe = wxGetApp().mainframe; + if (mainframe->can_save_as()) { + wxMessageDialog dlg(mainframe, _L("Do you want to save the changes to the current project ?"), wxString(SLIC3R_APP_NAME), wxYES_NO | wxCANCEL); + int res = dlg.ShowModal(); + if (res == wxID_YES) + mainframe->save_project_as(wxGetApp().plater()->get_project_filename()); + else if (res == wxID_CANCEL) + return false; + } + } + return true; + } + void reset_project_dirty_after_save() { dirty_state.reset_after_save(); } + void reset_project_dirty_initial_presets() { dirty_state.reset_initial_presets(); } + +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + void render_project_state_debug_window() const { dirty_state.render_debug_window(); } +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW +#endif // ENABLE_PROJECT_DIRTY_STATE + enum class UpdateParams { FORCE_FULL_SCREEN_REFRESH = 1, FORCE_BACKGROUND_PROCESSING_UPDATE = 2, @@ -1593,8 +1631,8 @@ struct Plater::priv void redo(); void undo_redo_to(size_t time_to_load); - void suppress_snapshots() { this->m_prevent_snapshots++; } - void allow_snapshots() { this->m_prevent_snapshots--; } + void suppress_snapshots() { m_prevent_snapshots++; } + void allow_snapshots() { m_prevent_snapshots--; } void process_validation_warning(const std::string& warning) const; @@ -1689,7 +1727,7 @@ struct Plater::priv bool can_split(bool to_objects) const; void generate_thumbnail(ThumbnailData& data, unsigned int w, unsigned int h, bool printable_only, bool parts_only, bool show_bed, bool transparent_background); - void generate_thumbnails(ThumbnailsList& thumbnails, const Vec2ds& sizes, bool printable_only, bool parts_only, bool show_bed, bool transparent_background); + ThumbnailsList generate_thumbnails(const ThumbnailsParams& params); void bring_instance_forward() const; @@ -1765,15 +1803,7 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) background_process.set_fff_print(&fff_print); background_process.set_sla_print(&sla_print); background_process.set_gcode_result(&gcode_result); - background_process.set_thumbnail_cb([this](ThumbnailsList& thumbnails, const Vec2ds& sizes, bool printable_only, bool parts_only, bool show_bed, bool transparent_background) - { - std::packaged_task task([this](ThumbnailsList& thumbnails, const Vec2ds& sizes, bool printable_only, bool parts_only, bool show_bed, bool transparent_background) { - generate_thumbnails(thumbnails, sizes, printable_only, parts_only, show_bed, transparent_background); - }); - std::future result = task.get_future(); - wxTheApp->CallAfter([&]() { task(thumbnails, sizes, printable_only, parts_only, show_bed, transparent_background); }); - result.wait(); - }); + background_process.set_thumbnail_cb([this](const ThumbnailsParams& params) { return this->generate_thumbnails(params); }); background_process.set_slicing_completed_event(EVT_SLICING_COMPLETED); background_process.set_finished_event(EVT_PROCESS_COMPLETED); background_process.set_export_began_event(EVT_EXPORT_BEGAN); @@ -3818,17 +3848,17 @@ void Plater::priv::generate_thumbnail(ThumbnailData& data, unsigned int w, unsig view3D->get_canvas3d()->render_thumbnail(data, w, h, printable_only, parts_only, show_bed, transparent_background); } -void Plater::priv::generate_thumbnails(ThumbnailsList& thumbnails, const Vec2ds& sizes, bool printable_only, bool parts_only, bool show_bed, bool transparent_background) +ThumbnailsList Plater::priv::generate_thumbnails(const ThumbnailsParams& params) { - thumbnails.clear(); - for (const Vec2d& size : sizes) - { + ThumbnailsList thumbnails; + for (const Vec2d& size : params.sizes) { thumbnails.push_back(ThumbnailData()); Point isize(size); // round to ints - generate_thumbnail(thumbnails.back(), isize.x(), isize.y(), printable_only, parts_only, show_bed, transparent_background); + generate_thumbnail(thumbnails.back(), isize.x(), isize.y(), params.printable_only, params.parts_only, params.show_bed, params.transparent_background); if (!thumbnails.back().is_valid()) thumbnails.pop_back(); } + return thumbnails; } wxString Plater::priv::get_project_filename(const wxString& extension) const @@ -4217,9 +4247,9 @@ int Plater::priv::get_active_snapshot_index() void Plater::priv::take_snapshot(const std::string& snapshot_name) { - if (this->m_prevent_snapshots > 0) + if (m_prevent_snapshots > 0) return; - assert(this->m_prevent_snapshots >= 0); + assert(m_prevent_snapshots >= 0); UndoRedo::SnapshotData snapshot_data; snapshot_data.printer_technology = this->printer_technology; if (this->view3D->is_layers_editing_enabled()) @@ -4249,6 +4279,11 @@ void Plater::priv::take_snapshot(const std::string& snapshot_name) } this->undo_redo_stack().take_snapshot(snapshot_name, model, view3D->get_canvas3d()->get_selection(), view3D->get_canvas3d()->get_gizmos_manager(), snapshot_data); this->undo_redo_stack().release_least_recently_used(); + +#if ENABLE_PROJECT_DIRTY_STATE + dirty_state.update_from_undo_redo_stack(ProjectDirtyStateManager::UpdateType::TakeSnapshot); +#endif // ENABLE_PROJECT_DIRTY_STATE + // Save the last active preset name of a particular printer technology. ((this->printer_technology == ptFFF) ? m_last_fff_printer_profile_name : m_last_sla_printer_profile_name) = wxGetApp().preset_bundle->printers.get_selected_preset_name(); BOOST_LOG_TRIVIAL(info) << "Undo / Redo snapshot taken: " << snapshot_name << ", Undo / Redo stack memory: " << Slic3r::format_memsize_MB(this->undo_redo_stack().memsize()) << log_memory_info(); @@ -4289,8 +4324,13 @@ void Plater::priv::undo_redo_to(std::vector::const_iterator if (printer_technology_changed) { // Switching the printer technology when jumping forwards / backwards in time. Switch to the last active printer profile of the other type. std::string s_pt = (it_snapshot->snapshot_data.printer_technology == ptFFF) ? "FFF" : "SLA"; +#if ENABLE_PROJECT_DIRTY_STATE + if (!wxGetApp().check_and_save_current_preset_changes(format_wxstr(_L( + "%1% printer was active at the time the target Undo / Redo snapshot was taken. Switching to %1% printer requires reloading of %1% presets."), s_pt))) +#else if (! wxGetApp().check_unsaved_changes(format_wxstr(_L( "%1% printer was active at the time the target Undo / Redo snapshot was taken. Switching to %1% printer requires reloading of %1% presets."), s_pt))) +#endif // ENABLE_PROJECT_DIRTY_STATE // Don't switch the profiles. return; } @@ -4379,6 +4419,10 @@ void Plater::priv::undo_redo_to(std::vector::const_iterator if (! view3D->is_layers_editing_enabled() && this->layers_height_allowed() && new_variable_layer_editing_active) view3D->get_canvas3d()->force_main_toolbar_left_action(view3D->get_canvas3d()->get_main_toolbar_item_id("layersediting")); } + +#if ENABLE_PROJECT_DIRTY_STATE + dirty_state.update_from_undo_redo_stack(ProjectDirtyStateManager::UpdateType::UndoRedoTo); +#endif // ENABLE_PROJECT_DIRTY_STATE } void Plater::priv::update_after_undo_redo(const UndoRedo::Snapshot& snapshot, bool /* temp_snapshot_was_taken */) @@ -4462,9 +4506,16 @@ Plater::Plater(wxWindow *parent, MainFrame *main_frame) // Initialization performed in the private c-tor } -Plater::~Plater() -{ -} +#if ENABLE_PROJECT_DIRTY_STATE +bool Plater::is_project_dirty() const { return p->is_project_dirty(); } +void Plater::update_project_dirty_from_presets() { p->update_project_dirty_from_presets(); } +bool Plater::save_project_if_dirty() { return p->save_project_if_dirty(); } +void Plater::reset_project_dirty_after_save() { p->reset_project_dirty_after_save(); } +void Plater::reset_project_dirty_initial_presets() { p->reset_project_dirty_initial_presets(); } +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW +void Plater::render_project_state_debug_window() const { p->render_project_state_debug_window(); } +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW +#endif // ENABLE_PROJECT_DIRTY_STATE Sidebar& Plater::sidebar() { return *p->sidebar; } Model& Plater::model() { return p->model; } @@ -4475,12 +4526,30 @@ SLAPrint& Plater::sla_print() { return p->sla_print; } void Plater::new_project() { +#if ENABLE_PROJECT_DIRTY_STATE + if (!p->save_project_if_dirty()) + return; +#endif // ENABLE_PROJECT_DIRTY_STATE + p->select_view_3D("3D"); +#if ENABLE_PROJECT_DIRTY_STATE + take_snapshot(_L("New Project")); + Plater::SuppressSnapshots suppress(this); + reset(); + reset_project_dirty_initial_presets(); + update_project_dirty_from_presets(); +#else wxPostEvent(p->view3D->get_wxglcanvas(), SimpleEvent(EVT_GLTOOLBAR_DELETE_ALL)); +#endif // ENABLE_PROJECT_DIRTY_STATE } void Plater::load_project() { +#if ENABLE_PROJECT_DIRTY_STATE + if (!p->save_project_if_dirty()) + return; +#endif // ENABLE_PROJECT_DIRTY_STATE + // Ask user for a project file name. wxString input_file; wxGetApp().load_project(this, input_file); @@ -4504,8 +4573,16 @@ void Plater::load_project(const wxString& filename) std::vector res = load_files(input_paths); // if res is empty no data has been loaded +#if ENABLE_PROJECT_DIRTY_STATE + if (!res.empty()) { + p->set_project_filename(filename); + reset_project_dirty_initial_presets(); + update_project_dirty_from_presets(); + } +#else if (!res.empty()) p->set_project_filename(filename); +#endif // ENABLE_PROJECT_DIRTY_STATE } void Plater::add_model(bool imperial_units/* = false*/) @@ -4536,7 +4613,13 @@ void Plater::add_model(bool imperial_units/* = false*/) } Plater::TakeSnapshot snapshot(this, snapshot_label); +#if ENABLE_PROJECT_DIRTY_STATE + std::vector res = load_files(paths, true, false, imperial_units); + if (!res.empty()) + wxGetApp().mainframe->update_title(); +#else load_files(paths, true, false, imperial_units); +#endif // ENABLE_PROJECT_DIRTY_STATE } void Plater::import_sl1_archive() @@ -5095,6 +5178,30 @@ void Plater::export_stl(bool extended, bool selection_only) if (selection_only && (obj_idx == -1 || selection.is_wipe_tower())) return; + // Following lambda generates a combined mesh for export with normals pointing outwards. + auto mesh_to_export = [](const ModelObject* mo, bool instances) -> TriangleMesh { + TriangleMesh mesh; + for (const ModelVolume *v : mo->volumes) + if (v->is_model_part()) { + TriangleMesh vol_mesh(v->mesh()); + vol_mesh.repair(); + vol_mesh.transform(v->get_matrix(), true); + mesh.merge(vol_mesh); + } + mesh.repair(); + if (instances) { + TriangleMesh vols_mesh(mesh); + mesh = TriangleMesh(); + for (const ModelInstance *i : mo->instances) { + TriangleMesh m = vols_mesh; + m.transform(i->get_matrix(), true); + mesh.merge(m); + } + } + mesh.repair(); + return mesh; + }; + TriangleMesh mesh; if (p->printer_technology == ptFFF) { if (selection_only) { @@ -5102,20 +5209,21 @@ void Plater::export_stl(bool extended, bool selection_only) if (selection.get_mode() == Selection::Instance) { if (selection.is_single_full_object()) - mesh = model_object->mesh(); + mesh = mesh_to_export(model_object, true); else - mesh = model_object->full_raw_mesh(); + mesh = mesh_to_export(model_object, false); } else { const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); mesh = model_object->volumes[volume->volume_idx()]->mesh(); - mesh.transform(volume->get_volume_transformation().get_matrix()); + mesh.transform(volume->get_volume_transformation().get_matrix(), true); mesh.translate(-model_object->origin_translation.cast()); } } else { - mesh = p->model.mesh(); + for (const ModelObject *o : p->model.objects) + mesh.merge(mesh_to_export(o, true)); } } else @@ -5226,24 +5334,39 @@ void Plater::export_amf() } } +#if ENABLE_PROJECT_DIRTY_STATE +bool Plater::export_3mf(const boost::filesystem::path& output_path) +#else void Plater::export_3mf(const boost::filesystem::path& output_path) +#endif // ENABLE_PROJECT_DIRTY_STATE { if (p->model.objects.empty() || canvas3D()->get_gizmos_manager().is_in_editing_mode(true)) +#if ENABLE_PROJECT_DIRTY_STATE + return false; +#else return; +#endif // ENABLE_PROJECT_DIRTY_STATE wxString path; bool export_config = true; - if (output_path.empty()) - { + if (output_path.empty()) { path = p->get_export_file(FT_3MF); +#if ENABLE_PROJECT_DIRTY_STATE + if (path.empty()) { return false; } +#else if (path.empty()) { return; } +#endif // ENABLE_PROJECT_DIRTY_STATE } else path = from_path(output_path); if (!path.Lower().EndsWith(".3mf")) +#if ENABLE_PROJECT_DIRTY_STATE + return false; +#else return; +#endif // ENABLE_PROJECT_DIRTY_STATE DynamicPrintConfig cfg = wxGetApp().preset_bundle->full_config_secure(); const std::string path_u8 = into_u8(path); @@ -5251,6 +5374,19 @@ void Plater::export_3mf(const boost::filesystem::path& output_path) bool full_pathnames = wxGetApp().app_config->get("export_sources_full_pathnames") == "1"; ThumbnailData thumbnail_data; p->generate_thumbnail(thumbnail_data, THUMBNAIL_SIZE_3MF.first, THUMBNAIL_SIZE_3MF.second, false, true, true, true); +#if ENABLE_PROJECT_DIRTY_STATE + bool ret = Slic3r::store_3mf(path_u8.c_str(), &p->model, export_config ? &cfg : nullptr, full_pathnames, &thumbnail_data); + if (ret) { + // Success + p->statusbar()->set_status_text(format_wxstr(_L("3MF file exported to %s"), path)); + p->set_project_filename(path); + } + else { + // Failure + p->statusbar()->set_status_text(format_wxstr(_L("Error exporting 3MF file %s"), path)); + } + return ret; +#else if (Slic3r::store_3mf(path_u8.c_str(), &p->model, export_config ? &cfg : nullptr, full_pathnames, &thumbnail_data)) { // Success p->statusbar()->set_status_text(format_wxstr(_L("3MF file exported to %s"), path)); @@ -5260,6 +5396,7 @@ void Plater::export_3mf(const boost::filesystem::path& output_path) // Failure p->statusbar()->set_status_text(format_wxstr(_L("Error exporting 3MF file %s"), path)); } +#endif // ENABLE_PROJECT_DIRTY_STATE } void Plater::reload_from_disk() @@ -5716,7 +5853,7 @@ wxString Plater::get_project_filename(const wxString& extension) const void Plater::set_project_filename(const wxString& filename) { - return p->set_project_filename(filename); + p->set_project_filename(filename); } bool Plater::is_export_gcode_scheduled() const @@ -6143,6 +6280,9 @@ bool Plater::can_mirror() const { return p->can_mirror(); } bool Plater::can_split(bool to_objects) const { return p->can_split(to_objects); } const UndoRedo::Stack& Plater::undo_redo_stack_main() const { return p->undo_redo_stack_main(); } void Plater::clear_undo_redo_stack_main() { p->undo_redo_stack_main().clear(); } +#if ENABLE_PROJECT_DIRTY_STATE +const UndoRedo::Stack& Plater::undo_redo_stack_active() const { return p->undo_redo_stack(); } +#endif // ENABLE_PROJECT_DIRTY_STATE void Plater::enter_gizmos_stack() { p->enter_gizmos_stack(); } void Plater::leave_gizmos_stack() { p->leave_gizmos_stack(); } bool Plater::inside_snapshot_capture() { return p->inside_snapshot_capture(); } diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index e99feee82..e6a5160f3 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -128,7 +128,18 @@ public: Plater(const Plater &) = delete; Plater &operator=(Plater &&) = delete; Plater &operator=(const Plater &) = delete; - ~Plater(); + ~Plater() = default; + +#if ENABLE_PROJECT_DIRTY_STATE + bool is_project_dirty() const; + void update_project_dirty_from_presets(); + bool save_project_if_dirty(); + void reset_project_dirty_after_save(); + void reset_project_dirty_initial_presets(); +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + void render_project_state_debug_window() const; +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW +#endif // ENABLE_PROJECT_DIRTY_STATE Sidebar& sidebar(); Model& model(); @@ -198,7 +209,11 @@ public: void export_gcode(bool prefer_removable); void export_stl(bool extended = false, bool selection_only = false); void export_amf(); +#if ENABLE_PROJECT_DIRTY_STATE + bool export_3mf(const boost::filesystem::path& output_path = boost::filesystem::path()); +#else void export_3mf(const boost::filesystem::path& output_path = boost::filesystem::path()); +#endif // ENABLE_PROJECT_DIRTY_STATE void reload_from_disk(); void reload_all_from_disk(); bool has_toolpaths_to_export() const; @@ -228,6 +243,9 @@ public: // For the memory statistics. const Slic3r::UndoRedo::Stack& undo_redo_stack_main() const; void clear_undo_redo_stack_main(); +#if ENABLE_PROJECT_DIRTY_STATE + const Slic3r::UndoRedo::Stack& undo_redo_stack_active() const; +#endif // ENABLE_PROJECT_DIRTY_STATE // Enter / leave the Gizmos specific Undo / Redo stack. To be used by the SLA support point editing gizmo. void enter_gizmos_stack(); void leave_gizmos_stack(); diff --git a/src/slic3r/GUI/PresetComboBoxes.cpp b/src/slic3r/GUI/PresetComboBoxes.cpp index c6a3006b7..7630c44bb 100644 --- a/src/slic3r/GUI/PresetComboBoxes.cpp +++ b/src/slic3r/GUI/PresetComboBoxes.cpp @@ -134,7 +134,7 @@ void PresetComboBox::OnSelect(wxCommandEvent& evt) auto marker = reinterpret_cast(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_DISABLED && marker < LABEL_ITEM_MAX) - this->SetSelection(this->m_last_selected); + this->SetSelection(m_last_selected); else if (on_selection_changed && (m_last_selected != selected_item || m_collection->current_is_dirty())) { m_last_selected = selected_item; on_selection_changed(selected_item); @@ -698,7 +698,7 @@ void PlaterPresetComboBox::OnSelect(wxCommandEvent &evt) auto marker = reinterpret_cast(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_MARKER && marker < LABEL_ITEM_MAX) { - this->SetSelection(this->m_last_selected); + this->SetSelection(m_last_selected); evt.StopPropagation(); if (marker == LABEL_ITEM_MARKER) return; @@ -715,8 +715,8 @@ void PlaterPresetComboBox::OnSelect(wxCommandEvent &evt) } return; } - else if (marker == LABEL_ITEM_PHYSICAL_PRINTER || this->m_last_selected != selected_item || m_collection->current_is_dirty()) - this->m_last_selected = selected_item; + else if (marker == LABEL_ITEM_PHYSICAL_PRINTER || m_last_selected != selected_item || m_collection->current_is_dirty()) + m_last_selected = selected_item; evt.Skip(); } @@ -973,7 +973,7 @@ void TabPresetComboBox::OnSelect(wxCommandEvent &evt) auto marker = reinterpret_cast(this->GetClientData(selected_item)); if (marker >= LABEL_ITEM_DISABLED && marker < LABEL_ITEM_MAX) { - this->SetSelection(this->m_last_selected); + this->SetSelection(m_last_selected); if (marker == LABEL_ITEM_WIZARD_PRINTERS) wxTheApp->CallAfter([this]() { wxGetApp().run_wizard(ConfigWizard::RR_USER, ConfigWizard::SP_PRINTERS); diff --git a/src/slic3r/GUI/PresetHints.cpp b/src/slic3r/GUI/PresetHints.cpp index 181dcfda4..0e2b7f836 100644 --- a/src/slic3r/GUI/PresetHints.cpp +++ b/src/slic3r/GUI/PresetHints.cpp @@ -86,7 +86,8 @@ std::string PresetHints::maximum_volumetric_flow_description(const PresetBundle // Print config values double layer_height = print_config.opt_float("layer_height"); - double first_layer_height = print_config.get_abs_value("first_layer_height", layer_height); + assert(! print_config.option("first_layer_height")->percent); + double first_layer_height = print_config.opt_float("first_layer_height"); double support_material_speed = print_config.opt_float("support_material_speed"); double support_material_interface_speed = print_config.get_abs_value("support_material_interface_speed", support_material_speed); double bridge_speed = print_config.opt_float("bridge_speed"); diff --git a/src/slic3r/GUI/ProjectDirtyStateManager.cpp b/src/slic3r/GUI/ProjectDirtyStateManager.cpp new file mode 100644 index 000000000..d538b0cf7 --- /dev/null +++ b/src/slic3r/GUI/ProjectDirtyStateManager.cpp @@ -0,0 +1,412 @@ +#include "libslic3r/libslic3r.h" + +#include "ProjectDirtyStateManager.hpp" +#include "ImGuiWrapper.hpp" +#include "GUI_App.hpp" +#include "MainFrame.hpp" +#include "I18N.hpp" +#include "Plater.hpp" +#include "../Utils/UndoRedo.hpp" + +#include + +#include +#include + +#if ENABLE_PROJECT_DIRTY_STATE + +namespace Slic3r { +namespace GUI { + +enum class EStackType +{ + Main, + Gizmo +}; + +// returns the current active snapshot (the topmost snapshot in the undo part of the stack) in the given stack +static const UndoRedo::Snapshot* get_active_snapshot(const UndoRedo::Stack& stack) { + const std::vector& snapshots = stack.snapshots(); + const size_t active_snapshot_time = stack.active_snapshot_time(); + const auto it = std::lower_bound(snapshots.begin(), snapshots.end(), UndoRedo::Snapshot(active_snapshot_time)); + const int idx = it - snapshots.begin() - 1; + const Slic3r::UndoRedo::Snapshot* ret = (0 <= idx && (size_t)idx < snapshots.size() - 1) ? + &snapshots[idx] : nullptr; + + assert(ret != nullptr); + return ret; +} + +// returns the last saveable snapshot (the topmost snapshot in the undo part of the stack that can be saved) in the given stack +static const UndoRedo::Snapshot* get_last_saveable_snapshot(EStackType type, const UndoRedo::Stack& stack, + const ProjectDirtyStateManager::DirtyState::Gizmos& gizmos, size_t last_save_main) { + + // returns true if the given snapshot is not saveable + auto skip_main = [&gizmos, last_save_main, &stack](const UndoRedo::Snapshot& snapshot) { + auto is_gizmo_with_modifications = [&gizmos, &stack](const UndoRedo::Snapshot& snapshot) { + if (boost::starts_with(snapshot.name, _utf8("Entering"))) { + if (gizmos.current) + return true; + + std::string topmost_redo; + wxGetApp().plater()->undo_redo_topmost_string_getter(false, topmost_redo); + if (boost::starts_with(topmost_redo, _utf8("Leaving"))) { + const std::vector& snapshots = stack.snapshots(); + const UndoRedo::Snapshot* leaving_snapshot = &(*std::lower_bound(snapshots.begin(), snapshots.end(), UndoRedo::Snapshot(snapshot.timestamp + 1))); + if (gizmos.is_used_and_modified(*leaving_snapshot)) + return true; + } + } + return false; + }; + + if (snapshot.name == _utf8("New Project")) + return true; + else if (snapshot.name == _utf8("Reset Project")) + return true; + else if (boost::starts_with(snapshot.name, _utf8("Load Project:"))) + return true; + else if (boost::starts_with(snapshot.name, _utf8("Selection"))) + return true; + else if (boost::starts_with(snapshot.name, _utf8("Entering"))) { + if (last_save_main != snapshot.timestamp + 1 && !is_gizmo_with_modifications(snapshot)) + return true; + } + else if (boost::starts_with(snapshot.name, _utf8("Leaving"))) { + if (last_save_main != snapshot.timestamp && !gizmos.is_used_and_modified(snapshot)) + return true; + } + + return false; + }; + + // returns true if the given snapshot is not saveable + auto skip_gizmo = [](const UndoRedo::Snapshot& snapshot) { + // put here any needed condition to skip the snapshot + return false; + }; + + const UndoRedo::Snapshot* curr = get_active_snapshot(stack); + const std::vector& snapshots = stack.snapshots(); + size_t shift = 1; + while (curr->timestamp > 0 && ((type == EStackType::Main && skip_main(*curr)) || (type == EStackType::Gizmo && skip_gizmo(*curr)))) { + const UndoRedo::Snapshot* temp = curr; + curr = &(*std::lower_bound(snapshots.begin(), snapshots.end(), UndoRedo::Snapshot(curr->timestamp - shift))); + shift = (curr == temp) ? shift + 1 : 1; + } + if (type == EStackType::Main) { + if (boost::starts_with(curr->name, _utf8("Entering")) && last_save_main == curr->timestamp + 1) { + std::string topmost_redo; + wxGetApp().plater()->undo_redo_topmost_string_getter(false, topmost_redo); + if (boost::starts_with(topmost_redo, _utf8("Leaving"))) + curr = &(*std::lower_bound(snapshots.begin(), snapshots.end(), UndoRedo::Snapshot(curr->timestamp + 1))); + } + } + return curr->timestamp > 0 ? curr : nullptr; +} + +// returns the name of the gizmo contained in the given string +static std::string extract_gizmo_name(const std::string& s) { + static const std::array prefixes = { _utf8("Entering"), _utf8("Leaving") }; + + std::string ret; + for (const std::string& prefix : prefixes) { + if (boost::starts_with(s, prefix)) + ret = s.substr(prefix.length() + 1); + + if (!ret.empty()) + break; + } + return ret; +} + +void ProjectDirtyStateManager::DirtyState::Gizmos::add_used(const UndoRedo::Snapshot& snapshot) +{ + const std::string name = extract_gizmo_name(snapshot.name); + auto it = used.find(name); + if (it == used.end()) + it = used.insert({ name, { {} } }).first; + + it->second.modified_timestamps.push_back(snapshot.timestamp); +} + +void ProjectDirtyStateManager::DirtyState::Gizmos::remove_obsolete_used(const Slic3r::UndoRedo::Stack& main_stack) +{ + const std::vector& snapshots = main_stack.snapshots(); + for (auto& item : used) { + auto it = item.second.modified_timestamps.begin(); + while (it != item.second.modified_timestamps.end()) { + size_t timestamp = *it; + auto snapshot_it = std::find_if(snapshots.begin(), snapshots.end(), [timestamp](const Slic3r::UndoRedo::Snapshot& snapshot) { return snapshot.timestamp == timestamp; }); + if (snapshot_it == snapshots.end()) + it = item.second.modified_timestamps.erase(it); + else + ++it; + } + } +} + +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW +bool ProjectDirtyStateManager::DirtyState::Gizmos::any_used_modified() const +{ + for (auto& [name, gizmo] : used) { + if (!gizmo.modified_timestamps.empty()) + return true; + } + return false; +} +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + +// returns true if the given snapshot is contained in any of the gizmos caches +bool ProjectDirtyStateManager::DirtyState::Gizmos::is_used_and_modified(const UndoRedo::Snapshot& snapshot) const +{ + for (const auto& item : used) { + for (size_t i : item.second.modified_timestamps) { + if (i == snapshot.timestamp) + return true; + } + } + return false; +} + +void ProjectDirtyStateManager::DirtyState::Gizmos::reset() +{ + used.clear(); +} + +void ProjectDirtyStateManager::update_from_undo_redo_stack(UpdateType type) +{ + if (!wxGetApp().initialized()) + return; + + const Plater* plater = wxGetApp().plater(); + const UndoRedo::Stack& main_stack = plater->undo_redo_stack_main(); + const UndoRedo::Stack& active_stack = plater->undo_redo_stack_active(); + + if (&main_stack == &active_stack) + update_from_undo_redo_main_stack(type, main_stack); + else + update_from_undo_redo_gizmo_stack(type, active_stack); + + wxGetApp().mainframe->update_title(); +} + +void ProjectDirtyStateManager::update_from_presets() +{ + m_state.presets = false; + std::vector> selected_presets = wxGetApp().get_selected_presets(); + for (const auto& [type, name] : selected_presets) { + m_state.presets |= !m_initial_presets[type].empty() && m_initial_presets[type] != name; + } + m_state.presets |= wxGetApp().has_unsaved_preset_changes(); + wxGetApp().mainframe->update_title(); +} + +void ProjectDirtyStateManager::reset_after_save() +{ + const Plater* plater = wxGetApp().plater(); + const UndoRedo::Stack& main_stack = plater->undo_redo_stack_main(); + const UndoRedo::Stack& active_stack = plater->undo_redo_stack_active(); + + if (&main_stack == &active_stack) { + const UndoRedo::Snapshot* saveable_snapshot = get_last_saveable_snapshot(EStackType::Main, main_stack, m_state.gizmos, m_last_save.main); + m_last_save.main = (saveable_snapshot != nullptr) ? saveable_snapshot->timestamp : 0; + } + else { + const UndoRedo::Snapshot* main_active_snapshot = get_active_snapshot(main_stack); + if (boost::starts_with(main_active_snapshot->name, _utf8("Entering"))) { + if (m_state.gizmos.current) + m_last_save.main = main_active_snapshot->timestamp + 1; + } + const UndoRedo::Snapshot* saveable_snapshot = get_last_saveable_snapshot(EStackType::Gizmo, active_stack, m_state.gizmos, m_last_save.main); + m_last_save.gizmo = saveable_snapshot->timestamp; + } + + reset_initial_presets(); + m_state.reset(); + wxGetApp().mainframe->update_title(); +} + +void ProjectDirtyStateManager::reset_initial_presets() +{ + m_initial_presets = std::array(); + std::vector> selected_presets = wxGetApp().get_selected_presets(); + for (const auto& [type, name] : selected_presets) { + m_initial_presets[type] = name; + } +} + +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW +void ProjectDirtyStateManager::render_debug_window() const +{ + ImGuiWrapper& imgui = *wxGetApp().imgui(); + + auto color = [](bool value) { + return value ? ImVec4(1.0f, 0.49f, 0.216f, 1.0f) /* orange */: ImVec4(1.0f, 1.0f, 1.0f, 1.0f) /* white */; + }; + auto bool_to_text = [](bool value) { + return value ? "true" : "false"; + }; + auto append_bool_item = [color, bool_to_text, &imgui](const std::string& name, bool value) { + imgui.text_colored(color(value), name); + ImGui::SameLine(); + imgui.text_colored(color(value), bool_to_text(value)); + }; + auto append_int_item = [&imgui](const std::string& name, int value) { + imgui.text(name); + ImGui::SameLine(); + imgui.text(std::to_string(value)); + }; + auto append_snapshot_item = [&imgui](const std::string& label, const UndoRedo::Snapshot* snapshot) { + imgui.text(label); + ImGui::SameLine(100); + if (snapshot != nullptr) + imgui.text(snapshot->name + " (" + std::to_string(snapshot->timestamp) + ")"); + else + imgui.text("-"); + }; + + imgui.begin(std::string("Project dirty state statistics"), ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); + + if (ImGui::CollapsingHeader("Dirty state", ImGuiTreeNodeFlags_DefaultOpen)) { + append_bool_item("Overall:", is_dirty()); + ImGui::Separator(); + append_bool_item("Plater:", m_state.plater); + append_bool_item("Presets:", m_state.presets); + append_bool_item("Current gizmo:", m_state.gizmos.current); + } + + if (ImGui::CollapsingHeader("Last save timestamps", ImGuiTreeNodeFlags_DefaultOpen)) { + append_int_item("Main:", m_last_save.main); + append_int_item("Current gizmo:", m_last_save.gizmo); + } + + const UndoRedo::Stack& main_stack = wxGetApp().plater()->undo_redo_stack_main(); + const UndoRedo::Snapshot* main_active_snapshot = get_active_snapshot(main_stack); + const UndoRedo::Snapshot* main_last_saveable_snapshot = get_last_saveable_snapshot(EStackType::Main, main_stack, m_state.gizmos, m_last_save.main); + const std::vector& main_snapshots = main_stack.snapshots(); + + if (ImGui::CollapsingHeader("Main snapshots", ImGuiTreeNodeFlags_DefaultOpen)) { + append_snapshot_item("Active:", main_active_snapshot); + append_snapshot_item("Last saveable:", main_last_saveable_snapshot); + } + + if (ImGui::CollapsingHeader("Main undo/redo stack", ImGuiTreeNodeFlags_DefaultOpen)) { + for (const UndoRedo::Snapshot& snapshot : main_snapshots) { + bool active = main_active_snapshot->timestamp == snapshot.timestamp; + imgui.text_colored(color(active), snapshot.name); + ImGui::SameLine(150); + imgui.text_colored(color(active), " (" + std::to_string(snapshot.timestamp) + ")"); + if (&snapshot == main_last_saveable_snapshot) { + ImGui::SameLine(); + imgui.text_colored(color(active), " (S)"); + } + if (m_last_save.main > 0 && m_last_save.main == snapshot.timestamp) { + ImGui::SameLine(); + imgui.text_colored(color(active), " (LS)"); + } + } + } + + const UndoRedo::Stack& active_stack = wxGetApp().plater()->undo_redo_stack_active(); + if (&active_stack != &main_stack) { + if (ImGui::CollapsingHeader("Gizmo undo/redo stack", ImGuiTreeNodeFlags_DefaultOpen)) { + const UndoRedo::Snapshot* active_active_snapshot = get_active_snapshot(active_stack); + const std::vector& active_snapshots = active_stack.snapshots(); + for (const UndoRedo::Snapshot& snapshot : active_snapshots) { + bool active = active_active_snapshot->timestamp == snapshot.timestamp; + imgui.text_colored(color(active), snapshot.name); + ImGui::SameLine(150); + imgui.text_colored(color(active), " (" + std::to_string(snapshot.timestamp) + ")"); + } + } + } + + if (m_state.gizmos.any_used_modified()) { + if (ImGui::CollapsingHeader("Gizmos", ImGuiTreeNodeFlags_DefaultOpen)) { + ImGui::Indent(10.0f); + for (const auto& [name, gizmo] : m_state.gizmos.used) { + if (!gizmo.modified_timestamps.empty()) { + if (ImGui::CollapsingHeader(name.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) { + std::string modified_timestamps; + for (size_t i = 0; i < gizmo.modified_timestamps.size(); ++i) { + if (i > 0) + modified_timestamps += " | "; + modified_timestamps += std::to_string(gizmo.modified_timestamps[i]); + } + imgui.text(modified_timestamps); + } + } + } + ImGui::Unindent(10.0f); + } + } + + imgui.end(); +} +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + +void ProjectDirtyStateManager::update_from_undo_redo_main_stack(UpdateType type, const Slic3r::UndoRedo::Stack& stack) +{ + m_state.plater = false; + + if (type == UpdateType::TakeSnapshot) { + if (m_last_save.main != 0) { + const std::vector& snapshots = stack.snapshots(); + auto snapshot_it = std::find_if(snapshots.begin(), snapshots.end(), [this](const Slic3r::UndoRedo::Snapshot& snapshot) { return snapshot.timestamp == m_last_save.main; }); + if (snapshot_it == snapshots.end()) + m_last_save.main = 0; + } + m_state.gizmos.remove_obsolete_used(stack); + } + + const UndoRedo::Snapshot* active_snapshot = get_active_snapshot(stack); + if (active_snapshot->name == _utf8("New Project") || + active_snapshot->name == _utf8("Reset Project") || + boost::starts_with(active_snapshot->name, _utf8("Load Project:"))) + return; + + if (boost::starts_with(active_snapshot->name, _utf8("Entering"))) { + if (type == UpdateType::UndoRedoTo) { + std::string topmost_redo; + wxGetApp().plater()->undo_redo_topmost_string_getter(false, topmost_redo); + if (boost::starts_with(topmost_redo, _utf8("Leaving"))) { + const std::vector& snapshots = stack.snapshots(); + const UndoRedo::Snapshot* leaving_snapshot = &(*std::lower_bound(snapshots.begin(), snapshots.end(), UndoRedo::Snapshot(active_snapshot->timestamp + 1))); + if (m_state.gizmos.is_used_and_modified(*leaving_snapshot)) { + m_state.plater = (leaving_snapshot != nullptr && leaving_snapshot->timestamp != m_last_save.main); + return; + } + } + } + m_state.gizmos.current = false; + m_last_save.gizmo = 0; + } + else if (boost::starts_with(active_snapshot->name, _utf8("Leaving"))) { + if (m_state.gizmos.current) + m_state.gizmos.add_used(*active_snapshot); + m_state.gizmos.current = false; + m_last_save.gizmo = 0; + } + + const UndoRedo::Snapshot* last_saveable_snapshot = get_last_saveable_snapshot(EStackType::Main, stack, m_state.gizmos, m_last_save.main); + m_state.plater = (last_saveable_snapshot != nullptr && last_saveable_snapshot->timestamp != m_last_save.main); +} + +void ProjectDirtyStateManager::update_from_undo_redo_gizmo_stack(UpdateType type, const Slic3r::UndoRedo::Stack& stack) +{ + m_state.gizmos.current = false; + + const UndoRedo::Snapshot* active_snapshot = get_active_snapshot(stack); + if (active_snapshot->name == "Gizmos-Initial") + return; + + const UndoRedo::Snapshot* last_saveable_snapshot = get_last_saveable_snapshot(EStackType::Gizmo, stack, m_state.gizmos, m_last_save.main); + m_state.gizmos.current = (last_saveable_snapshot != nullptr && last_saveable_snapshot->timestamp != m_last_save.gizmo); +} + +} // namespace GUI +} // namespace Slic3r + +#endif // ENABLE_PROJECT_DIRTY_STATE + diff --git a/src/slic3r/GUI/ProjectDirtyStateManager.hpp b/src/slic3r/GUI/ProjectDirtyStateManager.hpp new file mode 100644 index 000000000..f7ce81a62 --- /dev/null +++ b/src/slic3r/GUI/ProjectDirtyStateManager.hpp @@ -0,0 +1,96 @@ +#ifndef slic3r_ProjectDirtyStateManager_hpp_ +#define slic3r_ProjectDirtyStateManager_hpp_ + +#include "libslic3r/Preset.hpp" + +#if ENABLE_PROJECT_DIRTY_STATE + +namespace Slic3r { +namespace UndoRedo { +class Stack; +struct Snapshot; +} // namespace UndoRedo + +namespace GUI { +class ProjectDirtyStateManager +{ +public: + enum class UpdateType : unsigned char + { + TakeSnapshot, + UndoRedoTo + }; + + struct DirtyState + { + struct Gizmos + { + struct Gizmo + { + std::vector modified_timestamps; + }; + + bool current{ false }; + std::map used; + + void add_used(const UndoRedo::Snapshot& snapshot); + void remove_obsolete_used(const Slic3r::UndoRedo::Stack& main_stack); +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + bool any_used_modified() const; +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + bool is_used_and_modified(const UndoRedo::Snapshot& snapshot) const; + void reset(); + }; + + bool plater{ false }; + bool presets{ false }; + Gizmos gizmos; + + bool is_dirty() const { return plater || presets || gizmos.current; } + void reset() { + plater = false; + presets = false; + gizmos.current = false; + } + }; + +private: + struct LastSaveTimestamps + { + size_t main{ 0 }; + size_t gizmo{ 0 }; + + void reset() { + main = 0; + gizmo = 0; + } + }; + + DirtyState m_state; + LastSaveTimestamps m_last_save; + + // keeps track of initial selected presets + std::array m_initial_presets; + +public: + bool is_dirty() const { return m_state.is_dirty(); } + void update_from_undo_redo_stack(UpdateType type); + void update_from_presets(); + void reset_after_save(); + void reset_initial_presets(); +#if ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + void render_debug_window() const; +#endif // ENABLE_PROJECT_DIRTY_STATE_DEBUG_WINDOW + +private: + void update_from_undo_redo_main_stack(UpdateType type, const Slic3r::UndoRedo::Stack& stack); + void update_from_undo_redo_gizmo_stack(UpdateType type, const Slic3r::UndoRedo::Stack& stack); +}; + +} // namespace GUI +} // namespace Slic3r + +#endif // ENABLE_PROJECT_DIRTY_STATE + +#endif // slic3r_ProjectDirtyStateManager_hpp_ + diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index 13512d534..4cf71363d 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -1178,7 +1178,7 @@ void Selection::render_center(bool gizmo_is_dragging) const if (!m_valid || is_empty() || m_quadric == nullptr) return; - Vec3d center = gizmo_is_dragging ? m_cache.dragging_center : get_bounding_box().center(); + const Vec3d center = gizmo_is_dragging ? m_cache.dragging_center : get_bounding_box().center(); glsafe(::glDisable(GL_DEPTH_TEST)); @@ -1247,7 +1247,7 @@ void Selection::render_sidebar_hints(const std::string& sidebar_field) const } else { glsafe(::glTranslated(center(0), center(1), center(2))); if (requires_local_axes()) { - Transform3d orient_matrix = (*m_volumes)[*m_list.begin()]->get_instance_transformation().get_matrix(true, false, true, true); + const Transform3d orient_matrix = (*m_volumes)[*m_list.begin()]->get_instance_transformation().get_matrix(true, false, true, true); glsafe(::glMultMatrixd(orient_matrix.data())); } } @@ -1935,7 +1935,7 @@ void Selection::render_sidebar_layers_hints(const std::string& sidebar_field) co if (pos == std::string::npos) return; - double min_z = std::stod(field.substr(pos + 1)); + const double min_z = std::stod(field.substr(pos + 1)); // extract type field = field.substr(0, pos); @@ -1943,7 +1943,7 @@ void Selection::render_sidebar_layers_hints(const std::string& sidebar_field) co if (pos == std::string::npos) return; - int type = std::stoi(field.substr(pos + 1)); + const int type = std::stoi(field.substr(pos + 1)); const BoundingBoxf3& box = get_bounding_box(); @@ -1954,8 +1954,8 @@ void Selection::render_sidebar_layers_hints(const std::string& sidebar_field) co // view dependend order of rendering to keep correct transparency bool camera_on_top = wxGetApp().plater()->get_camera().is_looking_downward(); - float z1 = camera_on_top ? min_z : max_z; - float z2 = camera_on_top ? max_z : min_z; + const float z1 = camera_on_top ? min_z : max_z; + const float z2 = camera_on_top ? max_z : min_z; glsafe(::glEnable(GL_DEPTH_TEST)); glsafe(::glDisable(GL_CULL_FACE)); diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 0e954a906..5920ab5e3 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -940,7 +940,7 @@ void Tab::update_visibility() page->update_visibility(m_mode, page.get() == m_active_page); rebuild_page_tree(); - if (this->m_type == Preset::TYPE_SLA_PRINT) + if (m_type == Preset::TYPE_SLA_PRINT) update_description_lines(); Layout(); @@ -1217,9 +1217,8 @@ void Tab::apply_config_from_cache() // to update number of "filament" selection boxes when the number of extruders change. void Tab::on_presets_changed() { - if (wxGetApp().plater() == nullptr) { + if (wxGetApp().plater() == nullptr) return; - } // Instead of PostEvent (EVT_TAB_PRESETS_CHANGED) just call update_presets wxGetApp().plater()->sidebar().update_presets(m_type); @@ -1237,6 +1236,10 @@ void Tab::on_presets_changed() // clear m_dependent_tabs after first update from select_preset() // to avoid needless preset loading from update() function m_dependent_tabs.clear(); + +#if ENABLE_PROJECT_DIRTY_STATE + wxGetApp().plater()->update_project_dirty_from_presets(); +#endif // ENABLE_PROJECT_DIRTY_STATE } void Tab::build_preset_description_line(ConfigOptionsGroup* optgroup) @@ -2113,10 +2116,16 @@ wxSizer* Tab::description_line_widget(wxWindow* parent, ogStaticText* *StaticTex return sizer; } +#if ENABLE_PROJECT_DIRTY_STATE +bool Tab::saved_preset_is_dirty() const { return m_presets->saved_is_dirty(); } +void Tab::update_saved_preset_from_current_preset() { m_presets->update_saved_preset_from_current_preset(); } +bool Tab::current_preset_is_dirty() const { return m_presets->current_is_dirty(); } +#else bool Tab::current_preset_is_dirty() { return m_presets->current_is_dirty(); } +#endif // ENABLE_PROJECT_DIRTY_STATE void TabPrinter::build() { @@ -3141,8 +3150,8 @@ void Tab::select_preset(std::string preset_name, bool delete_current /*=false*/, if (preset_name.empty()) { if (delete_current) { // Find an alternate preset to be selected after the current preset is deleted. - const std::deque &presets = this->m_presets->get_presets(); - size_t idx_current = this->m_presets->get_idx_selected(); + const std::deque &presets = m_presets->get_presets(); + size_t idx_current = m_presets->get_idx_selected(); // Find the next visible preset. size_t idx_new = idx_current + 1; if (idx_new < presets.size()) diff --git a/src/slic3r/GUI/Tab.hpp b/src/slic3r/GUI/Tab.hpp index 9ccbcda28..601995ea7 100644 --- a/src/slic3r/GUI/Tab.hpp +++ b/src/slic3r/GUI/Tab.hpp @@ -270,7 +270,11 @@ public: Preset::Type type() const { return m_type; } // The tab is already constructed. bool completed() const { return m_completed; } - virtual bool supports_printer_technology(const PrinterTechnology tech) = 0; +#if ENABLE_PROJECT_DIRTY_STATE + virtual bool supports_printer_technology(const PrinterTechnology tech) const = 0; +#else + virtual bool supports_printer_technology(const PrinterTechnology tech) = 0; +#endif // ENABLE_PROJECT_DIRTY_STATE void create_preset_tab(); void add_scaled_button(wxWindow* parent, ScalableButton** btn, const std::string& icon_name, @@ -333,7 +337,13 @@ public: Field* get_field(const t_config_option_key &opt_key, Page** selected_page, int opt_index = -1); void toggle_option(const std::string& opt_key, bool toggle, int opt_index = -1); wxSizer* description_line_widget(wxWindow* parent, ogStaticText** StaticText, wxString text = wxEmptyString); +#if ENABLE_PROJECT_DIRTY_STATE + bool current_preset_is_dirty() const; + bool saved_preset_is_dirty() const; + void update_saved_preset_from_current_preset(); +#else bool current_preset_is_dirty(); +#endif // ENABLE_PROJECT_DIRTY_STATE DynamicPrintConfig* get_config() { return m_config; } PresetCollection* get_presets() { return m_presets; } @@ -377,8 +387,8 @@ class TabPrint : public Tab { public: TabPrint(wxNotebook* parent) : -// Tab(parent, _(L("Print Settings")), L("print")) {} - Tab(parent, _(L("Print Settings")), Slic3r::Preset::TYPE_PRINT) {} +// Tab(parent, _L("Print Settings"), L("print")) {} + Tab(parent, _L("Print Settings"), Slic3r::Preset::TYPE_PRINT) {} ~TabPrint() {} void build() override; @@ -387,7 +397,11 @@ public: void toggle_options() override; void update() override; void clear_pages() override; - bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptFFF; } +#if ENABLE_PROJECT_DIRTY_STATE + bool supports_printer_technology(const PrinterTechnology tech) const override { return tech == ptFFF; } +#else + bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptFFF; } +#endif // ENABLE_PROJECT_DIRTY_STATE private: ogStaticText* m_recommended_thin_wall_thickness_description_line = nullptr; @@ -407,8 +421,8 @@ private: std::map m_overrides_options; public: TabFilament(wxNotebook* parent) : -// Tab(parent, _(L("Filament Settings")), L("filament")) {} - Tab(parent, _(L("Filament Settings")), Slic3r::Preset::TYPE_FILAMENT) {} +// Tab(parent, _L("Filament Settings"), L("filament")) {} + Tab(parent, _L("Filament Settings"), Slic3r::Preset::TYPE_FILAMENT) {} ~TabFilament() {} void build() override; @@ -417,7 +431,11 @@ public: void toggle_options() override; void update() override; void clear_pages() override; - bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptFFF; } +#if ENABLE_PROJECT_DIRTY_STATE + bool supports_printer_technology(const PrinterTechnology tech) const override { return tech == ptFFF; } +#else + bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptFFF; } +#endif // ENABLE_PROJECT_DIRTY_STATE }; class TabPrinter : public Tab @@ -450,7 +468,7 @@ public: // TabPrinter(wxNotebook* parent) : Tab(parent, _(L("Printer Settings")), L("printer")) {} TabPrinter(wxNotebook* parent) : - Tab(parent, _(L("Printer Settings")), Slic3r::Preset::TYPE_PRINTER) {} + Tab(parent, _L("Printer Settings"), Slic3r::Preset::TYPE_PRINTER) {} ~TabPrinter() {} void build() override; @@ -472,7 +490,11 @@ public: void init_options_list() override; void msw_rescale() override; void sys_color_changed() override; - bool supports_printer_technology(const PrinterTechnology /* tech */) override { return true; } +#if ENABLE_PROJECT_DIRTY_STATE + bool supports_printer_technology(const PrinterTechnology /* tech */) const override { return true; } +#else + bool supports_printer_technology(const PrinterTechnology /* tech */) override { return true; } +#endif // ENABLE_PROJECT_DIRTY_STATE wxSizer* create_bed_shape_widget(wxWindow* parent); void cache_extruder_cnt(); @@ -483,8 +505,8 @@ class TabSLAMaterial : public Tab { public: TabSLAMaterial(wxNotebook* parent) : -// Tab(parent, _(L("Material Settings")), L("sla_material")) {} - Tab(parent, _(L("Material Settings")), Slic3r::Preset::TYPE_SLA_MATERIAL) {} +// Tab(parent, _L("Material Settings"), L("sla_material")) {} + Tab(parent, _L("Material Settings"), Slic3r::Preset::TYPE_SLA_MATERIAL) {} ~TabSLAMaterial() {} void build() override; @@ -492,15 +514,19 @@ public: void toggle_options() override {}; void update() override; void init_options_list() override; - bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptSLA; } +#if ENABLE_PROJECT_DIRTY_STATE + bool supports_printer_technology(const PrinterTechnology tech) const override { return tech == ptSLA; } +#else + bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptSLA; } +#endif // ENABLE_PROJECT_DIRTY_STATE }; class TabSLAPrint : public Tab { public: TabSLAPrint(wxNotebook* parent) : -// Tab(parent, _(L("Print Settings")), L("sla_print")) {} - Tab(parent, _(L("Print Settings")), Slic3r::Preset::TYPE_SLA_PRINT) {} +// Tab(parent, _L("Print Settings"), L("sla_print")) {} + Tab(parent, _L("Print Settings"), Slic3r::Preset::TYPE_SLA_PRINT) {} ~TabSLAPrint() {} ogStaticText* m_support_object_elevation_description_line = nullptr; @@ -511,7 +537,11 @@ public: void toggle_options() override; void update() override; void clear_pages() override; - bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptSLA; } +#if ENABLE_PROJECT_DIRTY_STATE + bool supports_printer_technology(const PrinterTechnology tech) const override { return tech == ptSLA; } +#else + bool supports_printer_technology(const PrinterTechnology tech) override { return tech == ptSLA; } +#endif // ENABLE_PROJECT_DIRTY_STATE }; } // GUI diff --git a/src/slic3r/GUI/UnsavedChangesDialog.cpp b/src/slic3r/GUI/UnsavedChangesDialog.cpp index 0a0a3dc60..dc2c56246 100644 --- a/src/slic3r/GUI/UnsavedChangesDialog.cpp +++ b/src/slic3r/GUI/UnsavedChangesDialog.cpp @@ -1694,6 +1694,9 @@ void DiffPresetDialog::update_compatibility(const std::string& preset_name, Pres technology_changed = old_printer_technology != new_printer_technology; } + // select preset + presets->select_preset_by_name(preset_name, false); + // Mark the print & filament enabled if they are compatible with the currently selected preset. // The following method should not discard changes of current print or filament presets on change of a printer profile, // if they are compatible with the current printer. diff --git a/src/slic3r/Utils/UndoRedo.cpp b/src/slic3r/Utils/UndoRedo.cpp index 697c1209d..6d6753ea2 100644 --- a/src/slic3r/Utils/UndoRedo.cpp +++ b/src/slic3r/Utils/UndoRedo.cpp @@ -755,7 +755,7 @@ namespace UndoRedo { template std::shared_ptr& ImmutableObjectHistory::shared_ptr(StackImpl &stack) { - if (m_shared_object.get() == nullptr && ! this->m_serialized.empty()) { + if (m_shared_object.get() == nullptr && ! m_serialized.empty()) { // Deserialize the object. std::istringstream iss(m_serialized); { @@ -897,7 +897,7 @@ void StackImpl::load_snapshot(size_t timestamp, Slic3r::Model& model, Slic3r::GU this->load_mutable_object(gizmos.id(), gizmos); // Sort the volumes so that we may use binary search. std::sort(m_selection.volumes_and_instances.begin(), m_selection.volumes_and_instances.end()); - this->m_active_snapshot_time = timestamp; + m_active_snapshot_time = timestamp; assert(this->valid()); } diff --git a/t/flow.t b/t/flow.t index 4d7ee5ca2..50c491604 100644 --- a/t/flow.t +++ b/t/flow.t @@ -21,7 +21,7 @@ use Slic3r::Test; $config->set('fill_density', 0.4); $config->set('bottom_solid_layers', 1); $config->set('first_layer_extrusion_width', 2); - $config->set('first_layer_height', '100%'); + $config->set('first_layer_height', $config->layer_height); $config->set('filament_diameter', [ 3.0 ]); $config->set('nozzle_diameter', [ 0.5 ]); diff --git a/t/layers.t b/t/layers.t index a9f7dfe39..4d958808a 100644 --- a/t/layers.t +++ b/t/layers.t @@ -49,7 +49,7 @@ use Slic3r::Test qw(_eq); $config->set('first_layer_height', 0.2); ok $test->(), "absolute first layer height"; - $config->set('first_layer_height', '60%'); + $config->set('first_layer_height', 0.6 * $config->layer_height); ok $test->(), "relative first layer height"; $config->set('z_offset', 0.9); diff --git a/t/multi.t b/t/multi.t index 8e7225bec..e74a7a1a8 100644 --- a/t/multi.t +++ b/t/multi.t @@ -181,7 +181,7 @@ use Slic3r::Test; my $config = Slic3r::Config::new_from_defaults; $config->set('nozzle_diameter', [0.6,0.6,0.6,0.6]); $config->set('layer_height', 0.4); - $config->set('first_layer_height', '100%'); + $config->set('first_layer_height', $config->layer_height); $config->set('skirts', 0); my $print = Slic3r::Test::init_print($model, config => $config); diff --git a/t/perimeters.t b/t/perimeters.t index d0657cb23..d3f96f122 100644 --- a/t/perimeters.t +++ b/t/perimeters.t @@ -395,8 +395,8 @@ use Slic3r::Test; return scalar keys %z_with_bridges; }; ok $test->(Slic3r::Test::init_print('V', config => $config)) == 1, - 'no overhangs printed with bridge speed'; # except for the first internal solid layers above void - ok $test->(Slic3r::Test::init_print('V', config => $config, scale_xyz => [3,1,1])) > 1, + 'no overhangs printed with bridge speed'; # except for the two internal solid layers above void + ok $test->(Slic3r::Test::init_print('V', config => $config, scale_xyz => [3,1,1])) > 2, 'overhangs printed with bridge speed'; } diff --git a/t/shells.t b/t/shells.t index 47b5c8881..29bc0b5f0 100644 --- a/t/shells.t +++ b/t/shells.t @@ -84,7 +84,7 @@ use Slic3r::Test; { my $config = Slic3r::Config::new_from_defaults; $config->set('layer_height', 0.3); - $config->set('first_layer_height', '100%'); + $config->set('first_layer_height', $config->layer_height); $config->set('bottom_solid_layers', 0); $config->set('top_solid_layers', 3); $config->set('cooling', [ 0 ]); @@ -119,7 +119,7 @@ use Slic3r::Test; $config->set('cooling', [ 0 ]); # prevent speed alteration $config->set('first_layer_speed', '100%'); # prevent speed alteration $config->set('layer_height', 0.4); - $config->set('first_layer_height', '100%'); + $config->set('first_layer_height', $config->layer_height); $config->set('extrusion_width', 0.55); $config->set('bottom_solid_layers', 3); $config->set('top_solid_layers', 0); @@ -142,7 +142,7 @@ use Slic3r::Test; $config->set('cooling', [ 0 ]); # prevent speed alteration $config->set('first_layer_speed', '100%'); # prevent speed alteration $config->set('layer_height', 0.4); - $config->set('first_layer_height', '100%'); + $config->set('first_layer_height', $config->layer_height); $config->set('bottom_solid_layers', 3); $config->set('top_solid_layers', 3); $config->set('solid_infill_speed', 99); @@ -170,7 +170,7 @@ use Slic3r::Test; $config->set('spiral_vase', 1); $config->set('bottom_solid_layers', 0); $config->set('skirts', 0); - $config->set('first_layer_height', '100%'); + $config->set('first_layer_height', $config->layer_height); $config->set('start_gcode', ''); $config->set('temperature', [200]); $config->set('first_layer_temperature', [205]); @@ -231,8 +231,8 @@ use Slic3r::Test; $config->set('bottom_solid_layers', 0); $config->set('retract_layer_change', [0]); $config->set('skirts', 0); - $config->set('first_layer_height', '100%'); $config->set('layer_height', 0.4); + $config->set('first_layer_height', $config->layer_height); $config->set('start_gcode', ''); # $config->set('use_relative_e_distances', 1); $config->validate; @@ -310,7 +310,7 @@ use Slic3r::Test; # $config->set('spiral_vase', 1); # $config->set('bottom_solid_layers', 0); # $config->set('skirts', 0); -# $config->set('first_layer_height', '100%'); +# $config->set('first_layer_height', $config->layer_height); # $config->set('start_gcode', ''); # # my $print = Slic3r::Test::init_print('two_hollow_squares', config => $config); diff --git a/t/thin.t b/t/thin.t index 9147236ee..50e7abc95 100644 --- a/t/thin.t +++ b/t/thin.t @@ -18,7 +18,7 @@ use Slic3r::Test; if (0) { my $config = Slic3r::Config::new_from_defaults; $config->set('layer_height', 0.2); - $config->set('first_layer_height', '100%'); + $config->set('first_layer_height', $config->layer_height); $config->set('extrusion_width', 0.5); $config->set('first_layer_extrusion_width', '200%'); # check this one too $config->set('skirts', 0); diff --git a/tests/fff_print/test_fill.cpp b/tests/fff_print/test_fill.cpp index 222e94d99..8e311282e 100644 --- a/tests/fff_print/test_fill.cpp +++ b/tests/fff_print/test_fill.cpp @@ -456,7 +456,7 @@ bool test_if_solid_surface_filled(const ExPolygon& expolygon, double flow_spacin }); // Shrink the initial expolygon a bit, this simulates the infill / perimeter overlap that we usually apply. - ExPolygons uncovered = diff_ex(offset(expolygon, - float(0.2 * scale_(flow_spacing))), grown_paths, true); + ExPolygons uncovered = diff_ex(offset(expolygon, - float(0.2 * scale_(flow_spacing))), grown_paths, ApplySafetyOffset::Yes); // ignore very small dots const double scaled_flow_spacing = std::pow(scale_(flow_spacing), 2); diff --git a/tests/fff_print/test_flow.cpp b/tests/fff_print/test_flow.cpp index 08ba15a84..dc73f4b6e 100644 --- a/tests/fff_print/test_flow.cpp +++ b/tests/fff_print/test_flow.cpp @@ -24,7 +24,7 @@ SCENARIO("Extrusion width specifics", "[Flow]") { { "skirts", 1 }, { "perimeters", 3 }, { "fill_density", "40%" }, - { "first_layer_height", "100%" } + { "first_layer_height", 0.3 } }); WHEN("first layer width set to 2mm") { diff --git a/tests/fff_print/test_support_material.cpp b/tests/fff_print/test_support_material.cpp index 1b85532d3..442db7654 100644 --- a/tests/fff_print/test_support_material.cpp +++ b/tests/fff_print/test_support_material.cpp @@ -29,7 +29,7 @@ SCENARIO("SupportMaterial: support_layers_z and contact_distance", "[SupportMate { ConstSupportLayerPtrsAdaptor support_layers = print.objects().front()->support_layers(); - first_support_layer_height_ok = support_layers.front()->print_z == print.default_object_config().first_layer_height.value; + first_support_layer_height_ok = support_layers.front()->print_z == print.config().first_layer_height.value; layer_height_minimum_ok = true; layer_height_maximum_ok = true; diff --git a/tests/libnest2d/CMakeLists.txt b/tests/libnest2d/CMakeLists.txt index d4f684dd3..bcb759452 100644 --- a/tests/libnest2d/CMakeLists.txt +++ b/tests/libnest2d/CMakeLists.txt @@ -4,4 +4,4 @@ target_link_libraries(${_TEST_NAME}_tests test_common libnest2d ) set_property(TARGET ${_TEST_NAME}_tests PROPERTY FOLDER "tests") # catch_discover_tests(${_TEST_NAME}_tests TEST_PREFIX "${_TEST_NAME}: ") -add_test(${_TEST_NAME}_tests ${_TEST_NAME}_tests ${CATCH_EXTRA_ARGS}) +add_test(${_TEST_NAME}_tests ${_TEST_NAME}_tests "${CATCH_EXTRA_ARGS} exclude:[NotWorking]") diff --git a/tests/libnest2d/libnest2d_tests_main.cpp b/tests/libnest2d/libnest2d_tests_main.cpp index e3ffe9c6e..97c7ef99d 100644 --- a/tests/libnest2d/libnest2d_tests_main.cpp +++ b/tests/libnest2d/libnest2d_tests_main.cpp @@ -44,12 +44,74 @@ struct NfpImpl } } +namespace { +using namespace libnest2d; + +template +void exportSVG(const char *loc, It from, It to) { + + static const char* svg_header = + R"raw( + + +)raw"; + + // for(auto r : result) { + std::fstream out(loc, std::fstream::out); + if(out.is_open()) { + out << svg_header; + // Item rbin( RectangleItem(bin.width(), bin.height()) ); + // for(unsigned j = 0; j < rbin.vertexCount(); j++) { + // auto v = rbin.vertex(j); + // setY(v, -getY(v)/SCALE + 500 ); + // setX(v, getX(v)/SCALE); + // rbin.setVertex(j, v); + // } + // out << shapelike::serialize(rbin.rawShape()) << std::endl; + for(auto it = from; it != to; ++it) { + const Item &itm = *it; + Item tsh(itm.transformedShape()); + for(unsigned j = 0; j < tsh.vertexCount(); j++) { + auto v = tsh.vertex(j); + setY(v, -getY(v)/SCALE + 500); + setX(v, getX(v)/SCALE); + tsh.setVertex(j, v); + } + out << shapelike::serialize(tsh.rawShape()) << std::endl; + } + out << "\n" << std::endl; + } + out.close(); + + // i++; + // } +} + +template +void exportSVG(std::vector>& result, int idx = 0) { + exportSVG((std::string("out") + std::to_string(idx) + ".svg").c_str(), + result.begin(), result.end()); +} +} + static std::vector& prusaParts() { - static std::vector ret; + using namespace libnest2d; + + static std::vector ret; if(ret.empty()) { ret.reserve(PRINTER_PART_POLYGONS.size()); - for(auto& inp : PRINTER_PART_POLYGONS) ret.emplace_back(inp); + for(auto& inp : PRINTER_PART_POLYGONS) { + auto inp_cpy = inp; + + if (ClosureTypeV == Closure::OPEN) + inp_cpy.points.pop_back(); + + if constexpr (!libnest2d::is_clockwise()) + std::reverse(inp_cpy.begin(), inp_cpy.end()); + + ret.emplace_back(inp_cpy); + } } return ret; @@ -140,15 +202,15 @@ TEST_CASE("boundingCircle", "[Geometry]") { PolygonImpl p = {{{0, 10}, {10, 0}, {0, -10}, {0, 10}}, {}}; Circle c = boundingCircle(p); - REQUIRE(c.center().X == 0); - REQUIRE(c.center().Y == 0); + REQUIRE(getX(c.center()) == 0); + REQUIRE(getY(c.center()) == 0); REQUIRE(c.radius() == Approx(10)); shapelike::translate(p, PointImpl{10, 10}); c = boundingCircle(p); - REQUIRE(c.center().X == 10); - REQUIRE(c.center().Y == 10); + REQUIRE(getX(c.center()) == 10); + REQUIRE(getY(c.center()) == 10); REQUIRE(c.radius() == Approx(10)); auto parts = prusaParts(); @@ -243,7 +305,7 @@ TEST_CASE("Area", "[Geometry]") { {61, 97} }; - REQUIRE(shapelike::area(item.transformedShape()) > 0 ); + REQUIRE(std::abs(shapelike::area(item.transformedShape())) > 0 ); } TEST_CASE("IsPointInsidePolygon", "[Geometry]") { @@ -296,30 +358,36 @@ TEST_CASE("LeftAndDownPolygon", "[Geometry]") Box bin(100, 100); BottomLeftPlacer placer(bin); - Item item = {{70, 75}, {88, 60}, {65, 50}, {60, 30}, {80, 20}, {42, 20}, - {35, 35}, {35, 55}, {40, 75}, {70, 75}}; + PathImpl pitem = {{70, 75}, {88, 60}, {65, 50}, {60, 30}, {80, 20}, + {42, 20}, {35, 35}, {35, 55}, {40, 75}}; - Item leftControl = { {40, 75}, - {35, 55}, - {35, 35}, - {42, 20}, - {0, 20}, - {0, 75}, - {40, 75}}; + PathImpl pleftControl = {{40, 75}, {35, 55}, {35, 35}, + {42, 20}, {0, 20}, {0, 75}}; - Item downControl = {{88, 60}, - {88, 0}, - {35, 0}, - {35, 35}, - {42, 20}, - {80, 20}, - {60, 30}, - {65, 50}, - {88, 60}}; + PathImpl pdownControl = {{88, 60}, {88, 0}, {35, 0}, {35, 35}, + {42, 20}, {80, 20}, {60, 30}, {65, 50}}; + if constexpr (!is_clockwise()) { + std::reverse(sl::begin(pitem), sl::end(pitem)); + std::reverse(sl::begin(pleftControl), sl::end(pleftControl)); + std::reverse(sl::begin(pdownControl), sl::end(pdownControl)); + } + + if constexpr (ClosureTypeV == Closure::CLOSED) { + sl::addVertex(pitem, sl::front(pitem)); + sl::addVertex(pleftControl, sl::front(pleftControl)); + sl::addVertex(pdownControl, sl::front(pdownControl)); + } + + Item item{pitem}, leftControl{pleftControl}, downControl{pdownControl}; Item leftp(placer.leftPoly(item)); - REQUIRE(shapelike::isValid(leftp.rawShape()).first); + auto valid = sl::isValid(leftp.rawShape()); + + std::vector> to_export{ leftp, leftControl }; + exportSVG<1>("leftp.svg", to_export.begin(), to_export.end()); + + REQUIRE(valid.first); REQUIRE(leftp.vertexCount() == leftControl.vertexCount()); for(unsigned long i = 0; i < leftControl.vertexCount(); i++) { @@ -338,7 +406,7 @@ TEST_CASE("LeftAndDownPolygon", "[Geometry]") } } -TEST_CASE("ArrangeRectanglesTight", "[Nesting]") +TEST_CASE("ArrangeRectanglesTight", "[Nesting][NotWorking]") { using namespace libnest2d; @@ -390,6 +458,8 @@ TEST_CASE("ArrangeRectanglesTight", "[Nesting]") // check for no intersections, no containment: + // exportSVG<1>("arrangeRectanglesTight.svg", rects.begin(), rects.end()); + bool valid = true; for(Item& r1 : rects) { for(Item& r2 : rects) { @@ -470,57 +540,7 @@ TEST_CASE("ArrangeRectanglesLoose", "[Nesting]") } -namespace { -using namespace libnest2d; - -template -void exportSVG(const char *loc, It from, It to) { - - static const char* svg_header = -R"raw( - - -)raw"; - - // for(auto r : result) { - std::fstream out(loc, std::fstream::out); - if(out.is_open()) { - out << svg_header; -// Item rbin( RectangleItem(bin.width(), bin.height()) ); -// for(unsigned j = 0; j < rbin.vertexCount(); j++) { -// auto v = rbin.vertex(j); -// setY(v, -getY(v)/SCALE + 500 ); -// setX(v, getX(v)/SCALE); -// rbin.setVertex(j, v); -// } -// out << shapelike::serialize(rbin.rawShape()) << std::endl; - for(auto it = from; it != to; ++it) { - const Item &itm = *it; - Item tsh(itm.transformedShape()); - for(unsigned j = 0; j < tsh.vertexCount(); j++) { - auto v = tsh.vertex(j); - setY(v, -getY(v)/SCALE + 500); - setX(v, getX(v)/SCALE); - tsh.setVertex(j, v); - } - out << shapelike::serialize(tsh.rawShape()) << std::endl; - } - out << "\n" << std::endl; - } - out.close(); - - // i++; - // } -} - -template -void exportSVG(std::vector>& result, int idx = 0) { - exportSVG((std::string("out") + std::to_string(idx) + ".svg").c_str(), - result.begin(), result.end()); -} -} - -TEST_CASE("BottomLeftStressTest", "[Geometry]") { +TEST_CASE("BottomLeftStressTest", "[Geometry][NotWorking]") { using namespace libnest2d; const Coord SCALE = 1000000; @@ -563,7 +583,7 @@ TEST_CASE("BottomLeftStressTest", "[Geometry]") { TEST_CASE("convexHull", "[Geometry]") { using namespace libnest2d; - ClipperLib::Path poly = PRINTER_PART_POLYGONS[0]; + PathImpl poly = PRINTER_PART_POLYGONS[0]; auto chull = sl::convexHull(poly); @@ -597,7 +617,7 @@ TEST_CASE("PrusaPartsShouldFitIntoTwoBins", "[Nesting]") { })); // Gather the items into piles of arranged polygons... - using Pile = TMultiShape; + using Pile = TMultiShape; std::vector piles(bins); for (auto &itm : input) @@ -609,6 +629,20 @@ TEST_CASE("PrusaPartsShouldFitIntoTwoBins", "[Nesting]") { auto bb = sl::boundingBox(pile); REQUIRE(sl::isInside(bb, bin)); } + + // Check the area of merged pile vs the sum of area of all the parts + // They should match, otherwise there is an overlap which should not happen. + for (auto &pile : piles) { + double area_sum = 0.; + + for (auto &obj : pile) + area_sum += sl::area(obj); + + auto pile_m = nfp::merge(pile); + double area_merge = sl::area(pile_m); + + REQUIRE(area_sum == Approx(area_merge)); + } } TEST_CASE("EmptyItemShouldBeUntouched", "[Nesting]") { @@ -616,7 +650,7 @@ TEST_CASE("EmptyItemShouldBeUntouched", "[Nesting]") { std::vector items; items.emplace_back(Item{}); // Emplace empty item - items.emplace_back(Item{0, 200, 0}); // Emplace zero area item + items.emplace_back(Item{ {0, 200} }); // Emplace zero area item size_t bins = libnest2d::nest(items, bin); @@ -661,12 +695,12 @@ TEST_CASE("Items can be preloaded", "[Nesting]") { REQUIRE(bins == 1); REQUIRE(fixed_rect.binId() == 0); - REQUIRE(fixed_rect.translation().X == bin.center().X); - REQUIRE(fixed_rect.translation().Y == bin.center().Y); + REQUIRE(getX(fixed_rect.translation()) == getX(bin.center())); + REQUIRE(getY(fixed_rect.translation()) == getY(bin.center())); REQUIRE(movable_rect.binId() == 0); - REQUIRE(movable_rect.translation().X != bin.center().X); - REQUIRE(movable_rect.translation().Y != bin.center().Y); + REQUIRE(getX(movable_rect.translation()) != getX(bin.center())); + REQUIRE(getY(movable_rect.translation()) != getY(bin.center())); } SECTION("Preloaded Item should not affect free bins") { @@ -677,14 +711,14 @@ TEST_CASE("Items can be preloaded", "[Nesting]") { REQUIRE(bins == 2); REQUIRE(fixed_rect.binId() == 1); - REQUIRE(fixed_rect.translation().X == bin.center().X); - REQUIRE(fixed_rect.translation().Y == bin.center().Y); + REQUIRE(getX(fixed_rect.translation()) == getX(bin.center())); + REQUIRE(getY(fixed_rect.translation()) == getY(bin.center())); REQUIRE(movable_rect.binId() == 0); auto bb = movable_rect.boundingBox(); - REQUIRE(bb.center().X == bin.center().X); - REQUIRE(bb.center().Y == bin.center().Y); + REQUIRE(getX(bb.center()) == getX(bin.center())); + REQUIRE(getY(bb.center()) == getY(bin.center())); } } @@ -700,15 +734,13 @@ std::vector nfp_testdata = { { {80, 50}, {100, 70}, - {120, 50}, - {80, 50} + {120, 50} }, { {10, 10}, {10, 40}, {40, 40}, - {40, 10}, - {10, 10} + {40, 10} } }, { @@ -718,15 +750,13 @@ std::vector nfp_testdata = { {80, 90}, {120, 90}, {140, 70}, - {120, 50}, - {80, 50} + {120, 50} }, { {10, 10}, {10, 40}, {40, 40}, - {40, 10}, - {10, 10} + {40, 10} } }, { @@ -738,15 +768,13 @@ std::vector nfp_testdata = { {30, 40}, {40, 40}, {50, 30}, - {50, 20}, - {40, 10} + {50, 20} }, { {80, 0}, {80, 30}, {110, 30}, - {110, 0}, - {80, 0} + {110, 0} } }, { @@ -766,9 +794,8 @@ std::vector nfp_testdata = { {122, 97}, {120, 98}, {118, 101}, - {117, 103}, - {117, 107} - }, + {117, 103} + }, { {102, 116}, {111, 126}, @@ -777,9 +804,8 @@ std::vector nfp_testdata = { {148, 100}, {148, 85}, {147, 84}, - {102, 84}, - {102, 116}, - } + {102, 84} + } }, { { @@ -793,9 +819,8 @@ std::vector nfp_testdata = { {139, 68}, {111, 68}, {108, 70}, - {99, 102}, - {99, 122}, - }, + {99, 102} + }, { {107, 124}, {128, 125}, @@ -810,9 +835,8 @@ std::vector nfp_testdata = { {136, 86}, {134, 85}, {108, 85}, - {107, 86}, - {107, 124}, - } + {107, 86} + } }, { { @@ -825,9 +849,8 @@ std::vector nfp_testdata = { {156, 66}, {133, 57}, {132, 57}, - {91, 98}, - {91, 100}, - }, + {91, 98} + }, { {101, 90}, {103, 98}, @@ -843,9 +866,8 @@ std::vector nfp_testdata = { {145, 84}, {105, 84}, {102, 87}, - {101, 89}, - {101, 90}, - } + {101, 89} + } } }; @@ -860,10 +882,9 @@ std::vector nfp_testdata = { {533659, 157607}, {538669, 160091}, {537178, 142155}, - {534959, 143386}, - {533726, 142141}, - } - }, + {534959, 143386} + } + }, { { {118305, 11603}, @@ -884,8 +905,7 @@ std::vector nfp_testdata = { {209315, 17080}, {205326, 17080}, {203334, 13629}, - {204493, 11616}, - {118305, 11603}, + {204493, 11616} } }, } @@ -957,6 +977,14 @@ void testNfp(const std::vector& testdata) { for(auto& td : testdata) { auto orbiter = td.orbiter; auto stationary = td.stationary; + if (!libnest2d::is_clockwise()) { + auto porb = orbiter.rawShape(); + auto pstat = stationary.rawShape(); + std::reverse(sl::begin(porb), sl::end(porb)); + std::reverse(sl::begin(pstat), sl::end(pstat)); + orbiter = Item{porb}; + stationary = Item{pstat}; + } onetest(orbiter, stationary, tidx++); } @@ -964,6 +992,14 @@ void testNfp(const std::vector& testdata) { for(auto& td : testdata) { auto orbiter = td.stationary; auto stationary = td.orbiter; + if (!libnest2d::is_clockwise()) { + auto porb = orbiter.rawShape(); + auto pstat = stationary.rawShape(); + std::reverse(sl::begin(porb), sl::end(porb)); + std::reverse(sl::begin(pstat), sl::end(pstat)); + orbiter = Item{porb}; + stationary = Item{pstat}; + } onetest(orbiter, stationary, tidx++); } } @@ -1073,7 +1109,7 @@ using Ratio = boost::rational; TEST_CASE("MinAreaBBWithRotatingCalipers", "[Geometry]") { long double err_epsilon = 500e6l; - for(ClipperLib::Path rinput : PRINTER_PART_POLYGONS) { + for(PathImpl rinput : PRINTER_PART_POLYGONS) { PolygonImpl poly(rinput); long double arearef = refMinAreaBox(poly); @@ -1085,8 +1121,8 @@ TEST_CASE("MinAreaBBWithRotatingCalipers", "[Geometry]") { REQUIRE(succ); } - for(ClipperLib::Path rinput : STEGOSAUR_POLYGONS) { - rinput.pop_back(); + for(PathImpl rinput : STEGOSAUR_POLYGONS) { +// rinput.pop_back(); std::reverse(rinput.begin(), rinput.end()); PolygonImpl poly(removeCollinearPoints(rinput, 1000000)); @@ -1116,7 +1152,7 @@ template MultiPolygon merged_pile(It from, It to, int bin_id) TEST_CASE("Test for bed center distance optimization", "[Nesting], [NestKernels]") { - static const constexpr ClipperLib::cInt W = 10000000; + static const constexpr Slic3r::ClipperLib::cInt W = 10000000; // Get the input items and define the bin. std::vector input(9, {W, W}); @@ -1151,7 +1187,7 @@ TEST_CASE("Test for bed center distance optimization", "[Nesting], [NestKernels] TEST_CASE("Test for biggest bounding box area", "[Nesting], [NestKernels]") { - static const constexpr ClipperLib::cInt W = 10000000; + static const constexpr Slic3r::ClipperLib::cInt W = 10000000; static const constexpr size_t N = 100; // Get the input items and define the bin. diff --git a/tests/libslic3r/test_clipper_utils.cpp b/tests/libslic3r/test_clipper_utils.cpp index a660b29cb..bbf76ea18 100644 --- a/tests/libslic3r/test_clipper_utils.cpp +++ b/tests/libslic3r/test_clipper_utils.cpp @@ -22,7 +22,7 @@ SCENARIO("Various Clipper operations - xs/t/11_clipper.t", "[ClipperUtils]") { THEN("offset matches") { REQUIRE(result == Polygons { { { 205, 205 }, { 95, 205 }, { 95, 95 }, { 205, 95 }, }, - { { 145, 145 }, { 145, 155 }, { 155, 155 }, { 155, 145 } } }); + { { 155, 145 }, { 145, 145 }, { 145, 155 }, { 155, 155 } } }); } } WHEN("offset_ex") { @@ -56,7 +56,7 @@ SCENARIO("Various Clipper operations - xs/t/11_clipper.t", "[ClipperUtils]") { } GIVEN("square and hole") { WHEN("diff_ex") { - ExPolygons result = Slic3r::diff_ex({ square }, { hole_in_square }); + ExPolygons result = Slic3r::diff_ex(Polygons{ square }, Polygons{ hole_in_square }); THEN("hole is created") { REQUIRE(result.size() == 1); REQUIRE(square_with_hole.area() == result.front().area()); @@ -77,7 +77,7 @@ SCENARIO("Various Clipper operations - xs/t/11_clipper.t", "[ClipperUtils]") { } } WHEN("diff_pl") { - Polylines result = Slic3r::diff_pl({ polyline }, { square, hole_in_square }); + Polylines result = Slic3r::diff_pl({ polyline }, Polygons{ square, hole_in_square }); THEN("correct number of result lines") { REQUIRE(result.size() == 3); } @@ -180,7 +180,7 @@ SCENARIO("Various Clipper operations - t/clipper.t", "[ClipperUtils]") { // CW oriented contour Slic3r::Polygon hole_in_square { { 14, 14 }, { 14, 16 }, { 16, 16 }, { 16, 14 } }; WHEN("intersection_ex with another square") { - ExPolygons intersection = Slic3r::intersection_ex({ square, hole_in_square }, { square2 }); + ExPolygons intersection = Slic3r::intersection_ex(Polygons{ square, hole_in_square }, Polygons{ square2 }); THEN("intersection area matches (hole is preserved)") { ExPolygon match({ { 20, 18 }, { 10, 18 }, { 10, 12 }, { 20, 12 } }, { { 14, 16 }, { 16, 16 }, { 16, 14 }, { 14, 14 } }); @@ -203,7 +203,7 @@ SCENARIO("Various Clipper operations - t/clipper.t", "[ClipperUtils]") { } } WHEN("diff_ex with another square") { - ExPolygons diff = Slic3r::diff_ex({ square, square2 }, { hole }); + ExPolygons diff = Slic3r::diff_ex(Polygons{ square, square2 }, Polygons{ hole }); THEN("difference of a cw from two ccw is a contour with one hole") { REQUIRE(diff.size() == 1); REQUIRE(diff.front().area() == Approx(ExPolygon({ {40, 40}, {0, 40}, {0, 0}, {40, 0} }, { {15, 25}, {25, 25}, {25, 15}, {15, 15} }).area())); @@ -214,7 +214,7 @@ SCENARIO("Various Clipper operations - t/clipper.t", "[ClipperUtils]") { Slic3r::Polygon square { { 10, 10 }, { 20, 10 }, { 20, 20 }, { 10, 20 } }; Slic3r::Polyline square_pl = square.split_at_first_point(); WHEN("no-op diff_pl") { - Slic3r::Polylines res = Slic3r::diff_pl({ square_pl }, {}); + Slic3r::Polylines res = Slic3r::diff_pl({ square_pl }, Polygons{}); THEN("returns the right number of polylines") { REQUIRE(res.size() == 1); } diff --git a/tests/libslic3r/test_elephant_foot_compensation.cpp b/tests/libslic3r/test_elephant_foot_compensation.cpp index 4e340c37a..09ad33f41 100644 --- a/tests/libslic3r/test_elephant_foot_compensation.cpp +++ b/tests/libslic3r/test_elephant_foot_compensation.cpp @@ -15,22 +15,6 @@ using namespace Slic3r; namespace Slic3r { ClipperLib::Path mittered_offset_path_scaled(const Points& contour, const std::vector& deltas, double miter_limit); - -#if 0 - static Points mittered_offset_path_scaled_points(const Points& contour, const std::vector& deltas, double miter_limit) - { - Points out; - ClipperLib::Path scaled = mittered_offset_path_scaled(contour, deltas, miter_limit); - for (ClipperLib::IntPoint& pt : scaled) { - pt.X += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA; - pt.Y += CLIPPER_OFFSET_SCALE_ROUNDING_DELTA; - pt.X >>= CLIPPER_OFFSET_POWER_OF_2; - pt.Y >>= CLIPPER_OFFSET_POWER_OF_2; - out.emplace_back(coord_t(pt.X), coord_t(pt.Y)); - } - return out; - } -#endif } static ExPolygon spirograph_gear_1mm() diff --git a/tests/libslic3r/test_placeholder_parser.cpp b/tests/libslic3r/test_placeholder_parser.cpp index e632dc705..8c56afc6d 100644 --- a/tests/libslic3r/test_placeholder_parser.cpp +++ b/tests/libslic3r/test_placeholder_parser.cpp @@ -14,9 +14,12 @@ SCENARIO("Placeholder parser scripting", "[PlaceholderParser]") { { "nozzle_diameter", "0.6;0.6;0.6;0.6" }, { "temperature", "357;359;363;378" } }); - // To test the "first_layer_extrusion_width" over "first_layer_heigth" over "layer_height" chain. - config.option("first_layer_height")->value = 150.; - config.option("first_layer_height")->percent = true; + // To test the "first_layer_extrusion_width" over "first_layer_heigth". + // "first_layer_heigth" over "layer_height" is no more supported after first_layer_height was moved from PrintObjectConfig to PrintConfig. +// config.option("first_layer_height")->value = 150.; +// config.option("first_layer_height")->percent = true; + config.option("first_layer_height")->value = 1.5 * config.opt_float("layer_height"); + config.option("first_layer_height")->percent = false; // To let the PlaceholderParser throw when referencing first_layer_speed if it is set to percent, as the PlaceholderParser does not know // a percent to what. config.option("first_layer_speed")->value = 50.; @@ -50,7 +53,7 @@ SCENARIO("Placeholder parser scripting", "[PlaceholderParser]") { SECTION("math: int(-13.4)") { REQUIRE(parser.process("{int(-13.4)}") == "-13"); } // Test the "coFloatOrPercent" and "xxx_extrusion_width" substitutions. - // first_layer_extrusion_width ratio_over first_layer_heigth ratio_over layer_height + // first_layer_extrusion_width ratio_over first_layer_heigth. SECTION("perimeter_extrusion_width") { REQUIRE(std::stod(parser.process("{perimeter_extrusion_width}")) == Approx(0.67500001192092896)); } SECTION("first_layer_extrusion_width") { REQUIRE(std::stod(parser.process("{first_layer_extrusion_width}")) == Approx(0.9)); } SECTION("support_material_xy_spacing") { REQUIRE(std::stod(parser.process("{support_material_xy_spacing}")) == Approx(0.3375)); } diff --git a/tests/libslic3r/test_polygon.cpp b/tests/libslic3r/test_polygon.cpp index d45e37fb1..f2c78cace 100644 --- a/tests/libslic3r/test_polygon.cpp +++ b/tests/libslic3r/test_polygon.cpp @@ -5,6 +5,112 @@ using namespace Slic3r; +SCENARIO("Converted Perl tests", "[Polygon]") { + GIVEN("ccw_square") { + Polygon ccw_square{ { 100, 100 }, { 200, 100 }, { 200, 200 }, { 100, 200 } }; + Polygon cw_square(ccw_square); + cw_square.reverse(); + + THEN("ccw_square is valid") { + REQUIRE(ccw_square.is_valid()); + } + THEN("cw_square is valid") { + REQUIRE(cw_square.is_valid()); + } + THEN("ccw_square.area") { + REQUIRE(ccw_square.area() == 100 * 100); + } + THEN("cw_square.area") { + REQUIRE(cw_square.area() == - 100 * 100); + } + THEN("ccw_square.centroid") { + REQUIRE(ccw_square.centroid() == Point { 150, 150 }); + } + THEN("cw_square.centroid") { + REQUIRE(cw_square.centroid() == Point { 150, 150 }); + } + THEN("ccw_square.contains_point(150, 150)") { + REQUIRE(ccw_square.contains({ 150, 150 })); + } + THEN("cw_square.contains_point(150, 150)") { + REQUIRE(cw_square.contains({ 150, 150 })); + } + THEN("conversion to lines") { + REQUIRE(ccw_square.lines() == Lines{ + { { 100, 100 }, { 200, 100 } }, + { { 200, 100 }, { 200, 200 } }, + { { 200, 200 }, { 100, 200 } }, + { { 100, 200 }, { 100, 100 } } }); + } + THEN("split_at_first_point") { + REQUIRE(ccw_square.split_at_first_point() == Polyline { ccw_square[0], ccw_square[1], ccw_square[2], ccw_square[3], ccw_square[0] }); + } + THEN("split_at_index(2)") { + REQUIRE(ccw_square.split_at_index(2) == Polyline { ccw_square[2], ccw_square[3], ccw_square[0], ccw_square[1], ccw_square[2] }); + } + THEN("split_at_vertex(ccw_square[2])") { + REQUIRE(ccw_square.split_at_vertex(ccw_square[2]) == Polyline { ccw_square[2], ccw_square[3], ccw_square[0], ccw_square[1], ccw_square[2] }); + } + THEN("is_counter_clockwise") { + REQUIRE(ccw_square.is_counter_clockwise()); + } + THEN("! is_counter_clockwise") { + REQUIRE(! cw_square.is_counter_clockwise()); + } + THEN("make_counter_clockwise") { + cw_square.make_counter_clockwise(); + REQUIRE(cw_square.is_counter_clockwise()); + } + THEN("make_counter_clockwise^2") { + cw_square.make_counter_clockwise(); + cw_square.make_counter_clockwise(); + REQUIRE(cw_square.is_counter_clockwise()); + } + THEN("first_point") { + REQUIRE(&ccw_square.first_point() == &ccw_square.points.front()); + } + } + GIVEN("Triangulating hexagon") { + Polygon hexagon{ { 100, 0 } }; + for (size_t i = 1; i < 6; ++ i) { + Point p = hexagon.points.front(); + p.rotate(PI / 3 * i); + hexagon.points.emplace_back(p); + } + Polygons triangles; + hexagon.triangulate_convex(&triangles); + THEN("right number of triangles") { + REQUIRE(triangles.size() == 4); + } + THEN("all triangles are ccw") { + auto it = std::find_if(triangles.begin(), triangles.end(), [](const Polygon &tri) { return tri.is_clockwise(); }); + REQUIRE(it == triangles.end()); + } + } + GIVEN("General triangle") { + Polygon polygon { { 50000000, 100000000 }, { 300000000, 102000000 }, { 50000000, 104000000 } }; + Line line { { 175992032, 102000000 }, { 47983964, 102000000 } }; + Point intersection; + bool has_intersection = polygon.intersection(line, &intersection); + THEN("Intersection with line") { + REQUIRE(has_intersection); + REQUIRE(intersection == Point { 50000000, 102000000 }); + } + } +} + +TEST_CASE("Centroid of Trapezoid must be inside", "[Polygon][Utils]") +{ + Slic3r::Polygon trapezoid { + { 4702134, 1124765853 }, + { -4702134, 1124765853 }, + { -9404268, 1049531706 }, + { 9404268, 1049531706 }, + }; + Point centroid = trapezoid.centroid(); + CHECK(trapezoid.contains(centroid)); +} + // This test currently only covers remove_collinear_points. // All remaining tests are to be ported from xs/t/06_polygon.t diff --git a/xs/t/06_polygon.t b/xs/t/06_polygon.t index 779c7deec..7bbcd5356 100644 --- a/xs/t/06_polygon.t +++ b/xs/t/06_polygon.t @@ -3,11 +3,8 @@ use strict; use warnings; -use List::Util qw(first); use Slic3r::XS; -use Test::More tests => 21; - -use constant PI => 4 * atan2(1, 1); +use Test::More tests => 3; my $square = [ # ccw [100, 100], @@ -17,81 +14,8 @@ my $square = [ # ccw ]; my $polygon = Slic3r::Polygon->new(@$square); -my $cw_polygon = $polygon->clone; -$cw_polygon->reverse; - -ok $polygon->is_valid, 'is_valid'; -is_deeply $polygon->pp, $square, 'polygon roundtrip'; - is ref($polygon->arrayref), 'ARRAY', 'polygon arrayref is unblessed'; isa_ok $polygon->[0], 'Slic3r::Point::Ref', 'polygon point is blessed'; - -my $lines = $polygon->lines; -is_deeply [ map $_->pp, @$lines ], [ - [ [100, 100], [200, 100] ], - [ [200, 100], [200, 200] ], - [ [200, 200], [100, 200] ], - [ [100, 200], [100, 100] ], -], 'polygon lines'; - -is_deeply $polygon->split_at_first_point->pp, [ @$square[0,1,2,3,0] ], 'split_at_first_point'; -is_deeply $polygon->split_at_index(2)->pp, [ @$square[2,3,0,1,2] ], 'split_at_index'; -is_deeply $polygon->split_at_vertex(Slic3r::Point->new(@{$square->[2]}))->pp, [ @$square[2,3,0,1,2] ], 'split_at'; -is $polygon->area, 100*100, 'area'; - -ok $polygon->is_counter_clockwise, 'is_counter_clockwise'; -ok !$cw_polygon->is_counter_clockwise, 'is_counter_clockwise'; -{ - my $clone = $polygon->clone; - $clone->reverse; - ok !$clone->is_counter_clockwise, 'is_counter_clockwise'; - $clone->make_counter_clockwise; - ok $clone->is_counter_clockwise, 'make_counter_clockwise'; - $clone->make_counter_clockwise; - ok $clone->is_counter_clockwise, 'make_counter_clockwise'; -} - ok ref($polygon->first_point) eq 'Slic3r::Point', 'first_point'; -ok $polygon->contains_point(Slic3r::Point->new(150,150)), 'ccw contains_point'; -ok $cw_polygon->contains_point(Slic3r::Point->new(150,150)), 'cw contains_point'; - -{ - my @points = (Slic3r::Point->new(100,0)); - foreach my $i (1..5) { - my $point = $points[0]->clone; - $point->rotate(PI/3*$i, [0,0]); - push @points, $point; - } - my $hexagon = Slic3r::Polygon->new(@points); - my $triangles = $hexagon->triangulate_convex; - is scalar(@$triangles), 4, 'right number of triangles'; - ok !(defined first { $_->is_clockwise } @$triangles), 'all triangles are ccw'; -} - -{ - is_deeply $polygon->centroid->pp, [150,150], 'centroid'; -} - -{ - my $polygon = Slic3r::Polygon->new( - [50000000, 100000000], - [300000000, 102000000], - [50000000, 104000000], - ); - my $line = Slic3r::Line->new([175992032,102000000], [47983964,102000000]); - my $intersection = $polygon->intersection($line); - is_deeply $intersection->pp, [50000000, 102000000], 'polygon-line intersection'; -} - -# this is not a test: this just demonstrates bad usage, where $polygon->clone gets -# DESTROY'ed before the derived object ($point), causing bad memory access -if (0) { - my $point; - { - $point = $polygon->clone->[0]; - } - $point->scale(2); -} - __END__ diff --git a/xs/t/15_config.t b/xs/t/15_config.t index 55b679101..4d032019c 100644 --- a/xs/t/15_config.t +++ b/xs/t/15_config.t @@ -4,7 +4,7 @@ use strict; use warnings; use Slic3r::XS; -use Test::More tests => 147; +use Test::More tests => 143; foreach my $config (Slic3r::Config->new, Slic3r::Config::Static::new_FullPrintConfig) { $config->set('layer_height', 0.3); @@ -70,10 +70,11 @@ foreach my $config (Slic3r::Config->new, Slic3r::Config::Static::new_FullPrintCo ok abs($config->get('first_layer_height') - 0.3) < 1e-4, 'set/get absolute floatOrPercent'; is $config->opt_serialize('first_layer_height'), '0.3', 'serialize absolute floatOrPercent'; - $config->set('first_layer_height', '50%'); - $config->get_abs_value('first_layer_height'); - ok abs($config->get_abs_value('first_layer_height') - 0.15) < 1e-4, 'set/get relative floatOrPercent'; - is $config->opt_serialize('first_layer_height'), '50%', 'serialize relative floatOrPercent'; +# This is no more supported after first_layer_height was moved from PrintObjectConfig to PrintConfig. +# $config->set('first_layer_height', $config->get('layer_height')); +# $config->get_abs_value('first_layer_height'); +# ok abs($config->get_abs_value('first_layer_height') - 0.15) < 1e-4, 'set/get relative floatOrPercent'; +# is $config->opt_serialize('first_layer_height'), '50%', 'serialize relative floatOrPercent'; # Uh-oh, we have no point option to test at the moment #ok $config->set('print_center', [50,80]), 'valid point coordinates'; diff --git a/xs/xsp/Clipper.xsp b/xs/xsp/Clipper.xsp index 277b59825..bae6a103e 100644 --- a/xs/xsp/Clipper.xsp +++ b/xs/xsp/Clipper.xsp @@ -2,7 +2,6 @@ %{ #include -#include "clipper.hpp" #include "libslic3r/ClipperUtils.hpp" %} @@ -21,10 +20,10 @@ _constant() OUTPUT: RETVAL Polygons -offset(polygons, delta, joinType = ClipperLib::jtMiter, miterLimit = 3) +offset(polygons, delta, joinType = Slic3r::ClipperLib::jtMiter, miterLimit = 3) Polygons polygons const float delta - ClipperLib::JoinType joinType + Slic3r::ClipperLib::JoinType joinType double miterLimit CODE: RETVAL = offset(polygons, delta, joinType, miterLimit); @@ -32,34 +31,22 @@ offset(polygons, delta, joinType = ClipperLib::jtMiter, miterLimit = 3) RETVAL ExPolygons -offset_ex(polygons, delta, joinType = ClipperLib::jtMiter, miterLimit = 3) +offset_ex(polygons, delta, joinType = Slic3r::ClipperLib::jtMiter, miterLimit = 3) Polygons polygons const float delta - ClipperLib::JoinType joinType + Slic3r::ClipperLib::JoinType joinType double miterLimit CODE: RETVAL = offset_ex(polygons, delta, joinType, miterLimit); OUTPUT: RETVAL -Polygons -offset2(polygons, delta1, delta2, joinType = ClipperLib::jtMiter, miterLimit = 3) - Polygons polygons - const float delta1 - const float delta2 - ClipperLib::JoinType joinType - double miterLimit - CODE: - RETVAL = offset2(polygons, delta1, delta2, joinType, miterLimit); - OUTPUT: - RETVAL - ExPolygons -offset2_ex(polygons, delta1, delta2, joinType = ClipperLib::jtMiter, miterLimit = 3) +offset2_ex(polygons, delta1, delta2, joinType = Slic3r::ClipperLib::jtMiter, miterLimit = 3) Polygons polygons const float delta1 const float delta2 - ClipperLib::JoinType joinType + Slic3r::ClipperLib::JoinType joinType double miterLimit CODE: RETVAL = offset2_ex(polygons, delta1, delta2, joinType, miterLimit); @@ -72,7 +59,7 @@ diff(subject, clip, safety_offset = false) Polygons clip bool safety_offset CODE: - RETVAL = diff(subject, clip, safety_offset); + RETVAL = diff(subject, clip, safety_offset ? ApplySafetyOffset::Yes : ApplySafetyOffset::No); OUTPUT: RETVAL @@ -82,7 +69,7 @@ diff_ex(subject, clip, safety_offset = false) Polygons clip bool safety_offset CODE: - RETVAL = diff_ex(subject, clip, safety_offset); + RETVAL = diff_ex(subject, clip, safety_offset ? ApplySafetyOffset::Yes : ApplySafetyOffset::No); OUTPUT: RETVAL @@ -101,7 +88,7 @@ intersection(subject, clip, safety_offset = false) Polygons clip bool safety_offset CODE: - RETVAL = intersection(subject, clip, safety_offset); + RETVAL = intersection(subject, clip, safety_offset ? ApplySafetyOffset::Yes : ApplySafetyOffset::No); OUTPUT: RETVAL @@ -111,7 +98,7 @@ intersection_ex(subject, clip, safety_offset = false) Polygons clip bool safety_offset CODE: - RETVAL = intersection_ex(subject, clip, safety_offset); + RETVAL = intersection_ex(subject, clip, safety_offset ? ApplySafetyOffset::Yes : ApplySafetyOffset::No); OUTPUT: RETVAL @@ -129,7 +116,7 @@ union(subject, safety_offset = false) Polygons subject bool safety_offset CODE: - RETVAL = union_(subject, safety_offset); + RETVAL = safety_offset ? union_safety_offset(subject) : union_(subject); OUTPUT: RETVAL @@ -138,7 +125,7 @@ union_ex(subject, safety_offset = false) Polygons subject bool safety_offset CODE: - RETVAL = union_ex(subject, safety_offset); + RETVAL = safety_offset ? union_safety_offset_ex(subject) : union_ex(subject); OUTPUT: RETVAL diff --git a/xs/xsp/Config.xsp b/xs/xsp/Config.xsp index d8b60bc84..52a5e7d83 100644 --- a/xs/xsp/Config.xsp +++ b/xs/xsp/Config.xsp @@ -108,7 +108,7 @@ std::string get_extrusion_axis() %code{% if (GCodeConfig* config = dynamic_cast(THIS)) { - RETVAL = config->get_extrusion_axis(); + RETVAL = get_extrusion_axis(*config); } else { CONFESS("This StaticConfig object does not provide get_extrusion_axis()"); } diff --git a/xs/xsp/Layer.xsp b/xs/xsp/Layer.xsp index 50ddfd9a1..b97e340bd 100644 --- a/xs/xsp/Layer.xsp +++ b/xs/xsp/Layer.xsp @@ -10,7 +10,8 @@ // owned by Layer, no constructor/destructor Ref layer(); - Ref region(); + Ref region() + %code%{ RETVAL = &THIS->region(); %}; Ref slices() %code%{ RETVAL = &THIS->slices; %}; diff --git a/xs/xsp/Polyline.xsp b/xs/xsp/Polyline.xsp index 0dbd0e572..10bbb263f 100644 --- a/xs/xsp/Polyline.xsp +++ b/xs/xsp/Polyline.xsp @@ -79,9 +79,9 @@ Polyline::rotate(angle, center_sv) THIS->rotate(angle, center); Polygons -Polyline::grow(delta, joinType = ClipperLib::jtSquare, miterLimit = 3) +Polyline::grow(delta, joinType = Slic3r::ClipperLib::jtSquare, miterLimit = 3) const float delta - ClipperLib::JoinType joinType + Slic3r::ClipperLib::JoinType joinType double miterLimit CODE: RETVAL = offset(*THIS, delta, joinType, miterLimit); diff --git a/xs/xsp/Print.xsp b/xs/xsp/Print.xsp index 9e632bd53..8aef9e7a3 100644 --- a/xs/xsp/Print.xsp +++ b/xs/xsp/Print.xsp @@ -32,15 +32,11 @@ _constant() Ref config() %code%{ RETVAL = &THIS->config(); %}; - Ref print(); }; %name{Slic3r::Print::Object} class PrintObject { // owned by Print, no constructor/destructor - int region_count() - %code%{ RETVAL = THIS->print()->regions().size(); %}; - Ref print(); Ref model_object(); Ref config() @@ -99,11 +95,7 @@ _constant() %code%{ RETVAL = THIS->objects().size(); %}; PrintRegionPtrs* regions() - %code%{ RETVAL = const_cast(&THIS->regions_mutable()); %}; - Ref get_region(int idx) - %code%{ RETVAL = THIS->regions_mutable()[idx]; %}; - size_t region_count() - %code%{ RETVAL = THIS->regions().size(); %}; + %code%{ RETVAL = const_cast(&THIS->print_regions_mutable()); %}; bool step_done(PrintStep step) %code%{ RETVAL = THIS->is_step_done(step); %}; @@ -113,7 +105,7 @@ _constant() SV* filament_stats() %code%{ HV* hv = newHV(); - for (std::map::const_iterator it = THIS->print_statistics().filament_stats.begin(); it != THIS->print_statistics().filament_stats.end(); ++it) { + for (std::map::const_iterator it = THIS->print_statistics().filament_stats.begin(); it != THIS->print_statistics().filament_stats.end(); ++it) { // stringify extruder_id std::ostringstream ss; ss << it->first; @@ -123,7 +115,6 @@ _constant() RETVAL = newRV_noinc((SV*)hv); } %}; - double max_allowed_layer_height() const; bool has_support_material() const; void auto_assign_extruders(ModelObject* model_object); std::string output_filepath(std::string path = "") diff --git a/xs/xsp/Surface.xsp b/xs/xsp/Surface.xsp index 379774f0a..49d988333 100644 --- a/xs/xsp/Surface.xsp +++ b/xs/xsp/Surface.xsp @@ -85,7 +85,7 @@ Surface::polygons() Surfaces Surface::offset(delta, joinType = ClipperLib::jtMiter, miterLimit = 3) const float delta - ClipperLib::JoinType joinType + Slic3r::ClipperLib::JoinType joinType double miterLimit CODE: surfaces_append(RETVAL, offset_ex(THIS->expolygon, delta, joinType, miterLimit), *THIS); diff --git a/xs/xsp/my.map b/xs/xsp/my.map index 2ecff6e3f..54e686ae3 100644 --- a/xs/xsp/my.map +++ b/xs/xsp/my.map @@ -211,8 +211,8 @@ FlowRole T_UV PrintStep T_UV PrintObjectStep T_UV SurfaceType T_UV -ClipperLib::JoinType T_UV -ClipperLib::PolyFillType T_UV +Slic3r::ClipperLib::JoinType T_UV +Slic3r::ClipperLib::PolyFillType T_UV # we return these types whenever we want the items to be cloned Points T_ARRAYREF