Fixed conflicts after merge with master

This commit is contained in:
enricoturri1966 2021-12-02 11:23:39 +01:00
commit 6bb2fbb3d2
65 changed files with 20066 additions and 7124 deletions

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,5 @@
min_slic3r_version = 2.4.0-beta2
1.4.0-beta3 Added material profiles for Prusament Resins.
1.4.0-beta2 Added SLA material colors. Updated BASF filament profiles.
min_slic3r_version = 2.4.0-beta0
1.4.0-beta1 Updated pad wall slope angle for SLA printers. Updated Filatech Filacarbon profile for Prusa MINI.
@ -17,6 +18,8 @@ min_slic3r_version = 2.4.0-alpha0
1.3.0-alpha1 Added Prusament PCCF. Increased travel acceleration for Prusa MINI. Updated start g-code for Prusa MINI. Added multiple add:north and Extrudr filament profiles. Updated Z travel speed values.
1.3.0-alpha0 Disabled thick bridges, updated support settings.
min_slic3r_version = 2.3.2-alpha0
1.3.5 Added material profiles for Prusament Resins.
1.3.4 Added material profiles for new Prusament Resins. Added profiles for multiple BASF filaments.
1.3.3 Added multiple profiles for Filatech filaments. Added material profiles for SL1S SPEED. Updated SLA print settings.
1.3.2 Added material profiles for Prusament Resin.
1.3.1 Added multiple add:north and Extrudr filament profiles. Updated support head settings (SL1S).

View file

@ -5,7 +5,7 @@
name = Prusa Research
# 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 = 1.4.0-beta2
config_version = 1.4.0-beta3
# Where to get the updates from?
config_update_url = https://files.prusa3d.com/wp-content/uploads/repository/PrusaSlicer-settings-master/live/PrusaResearch/
changelog_url = https://files.prusa3d.com/?latest=slicer-profiles&lng=%1%
@ -2925,7 +2925,6 @@ bridge_fan_speed = 100
filament_type = PET
disable_fan_first_layers = 1
full_fan_speed_layer = 3
filament_notes = "BASF Forward AM Ultrafuse PET\nMaterial profile version 1.0\n\nMaterial Description\nUltrafuse PET is made from a premium PET and prints as easy as PLA, but is much stronger. The filament has a large operating window for printing (temperature vs. speed), so it can be used on every 3D-printer. PET will give you outstanding printing results: a good layer adhesion, a high resolution and it is easy to handle. Ultrafuse PET can be 100% recycled, is watertight and has great colors and finish.\n\nPrinting Recommendations:\nUltrafuse PET can be printed directly onto a clean build plate. For challenging prints, use 3dLac to improve adhesion.\n"
filament_retract_length = 2
filament_retract_speed = 40
@ -4836,6 +4835,46 @@ material_type = Tough
material_vendor = Prusa Polymers
material_colour = #808080
[sla_material:Prusament Resin Tough Sandstone Model @0.025]
inherits = *common 0.025*
exposure_time = 4
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F7D190
[sla_material:Prusament Resin Tough Terra Brown @0.025]
inherits = *common 0.025*
exposure_time = 4
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #7A5C45
[sla_material:Prusament Resin Tough Brick Red @0.025]
inherits = *common 0.025*
exposure_time = 4
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #B46056
[sla_material:Prusament Resin Tough Grass Green @0.025]
inherits = *common 0.025*
exposure_time = 4
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #37823F
[sla_material:Prusament Resin Tough Bright Yellow @0.025]
inherits = *common 0.025*
exposure_time = 4
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F9DB4C
## Prusa 0.025
[sla_material:Prusa Orange Tough @0.025]
@ -5649,6 +5688,46 @@ material_type = Tough
material_vendor = Prusa Polymers
material_colour = #C0C0C0
[sla_material:Prusament Resin Tough Sandstone Model @0.05]
inherits = *common 0.05*
exposure_time = 6
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F7D190
[sla_material:Prusament Resin Tough Terra Brown @0.05]
inherits = *common 0.05*
exposure_time = 6
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #7A5C45
[sla_material:Prusament Resin Tough Brick Red @0.05]
inherits = *common 0.05*
exposure_time = 6
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #B46056
[sla_material:Prusament Resin Tough Grass Green @0.05]
inherits = *common 0.05*
exposure_time = 6
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #37823F
[sla_material:Prusament Resin Tough Bright Yellow @0.05]
inherits = *common 0.05*
exposure_time = 6
initial_exposure_time = 35
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F9DB4C
## Prusa 0.05
[sla_material:Prusa Beige Tough @0.05]
@ -5965,6 +6044,46 @@ material_type = Tough
material_vendor = Prusa Polymers
material_colour = #808080
[sla_material:Prusament Resin Tough Sandstone Model @0.1]
inherits = *common 0.1*
exposure_time = 13
initial_exposure_time = 45
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F7D190
[sla_material:Prusament Resin Tough Terra Brown @0.1]
inherits = *common 0.1*
exposure_time = 13
initial_exposure_time = 45
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #7A5C45
[sla_material:Prusament Resin Tough Brick Red @0.1]
inherits = *common 0.1*
exposure_time = 13
initial_exposure_time = 45
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #B46056
[sla_material:Prusament Resin Tough Grass Green @0.1]
inherits = *common 0.1*
exposure_time = 13
initial_exposure_time = 45
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #37823F
[sla_material:Prusament Resin Tough Bright Yellow @0.1]
inherits = *common 0.1*
exposure_time = 13
initial_exposure_time = 45
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F9DB4C
## Prusa 0.1
[sla_material:Prusa Orange Tough @0.1]
@ -6085,6 +6204,46 @@ material_type = Tough
material_vendor = Prusa Polymers
material_colour = #808080
[sla_material:Prusament Resin Tough Sandstone Model @0.025 SL1S]
inherits = *0.025_sl1s*
exposure_time = 2
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F7D190
[sla_material:Prusament Resin Tough Terra Brown @0.025 SL1S]
inherits = *0.025_sl1s*
exposure_time = 1.8
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #7A5C45
[sla_material:Prusament Resin Tough Brick Red @0.025 SL1S]
inherits = *0.025_sl1s*
exposure_time = 1.8
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #B46056
[sla_material:Prusament Resin Tough Grass Green @0.025 SL1S]
inherits = *0.025_sl1s*
exposure_time = 1.8
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #37823F
[sla_material:Prusament Resin Tough Bright Yellow @0.025 SL1S]
inherits = *0.025_sl1s*
exposure_time = 1.8
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F9DB4C
## Made for Prusa 0.025
[sla_material:Prusa Orange Tough @0.025 SL1S]
@ -6331,6 +6490,46 @@ material_type = Tough
material_vendor = Prusa Polymers
material_colour = #808080
[sla_material:Prusament Resin Tough Sandstone Model @0.05 SL1S]
inherits = *0.05_sl1s*
exposure_time = 2.4
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F7D190
[sla_material:Prusament Resin Tough Terra Brown @0.05 SL1S]
inherits = *0.05_sl1s*
exposure_time = 2
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #7A5C45
[sla_material:Prusament Resin Tough Brick Red @0.05 SL1S]
inherits = *0.05_sl1s*
exposure_time = 2
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #B46056
[sla_material:Prusament Resin Tough Grass Green @0.05 SL1S]
inherits = *0.05_sl1s*
exposure_time = 2
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #37823F
[sla_material:Prusament Resin Tough Bright Yellow @0.05 SL1S]
inherits = *0.05_sl1s*
exposure_time = 2
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F9DB4C
## Made for Prusa 0.05
[sla_material:Prusa Orange Tough @0.05 SL1S]
@ -6577,6 +6776,46 @@ material_type = Tough
material_vendor = Prusa Polymers
material_colour = #808080
[sla_material:Prusament Resin Tough Sandstone Model @0.1 SL1S]
inherits = *0.1_sl1s*
exposure_time = 3
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F7D190
[sla_material:Prusament Resin Tough Terra Brown @0.1 SL1S]
inherits = *0.1_sl1s*
exposure_time = 2.6
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #7A5C45
[sla_material:Prusament Resin Tough Brick Red @0.1 SL1S]
inherits = *0.1_sl1s*
exposure_time = 2.6
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #B46056
[sla_material:Prusament Resin Tough Grass Green @0.1 SL1S]
inherits = *0.1_sl1s*
exposure_time = 2.6
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #37823F
[sla_material:Prusament Resin Tough Bright Yellow @0.1 SL1S]
inherits = *0.1_sl1s*
exposure_time = 2.6
initial_exposure_time = 25
material_type = Tough
material_vendor = Prusa Polymers
material_colour = #F9DB4C
## Made for Prusa 0.1
[sla_material:Prusa Orange Tough @0.1 SL1S]

View file

@ -1,26 +1,7 @@
#version 110
#define INTENSITY_CORRECTION 0.6
// normalized values for (-0.6/1.31, 0.6/1.31, 1./1.31)
const vec3 LIGHT_TOP_DIR = vec3(-0.4574957, 0.4574957, 0.7624929);
#define LIGHT_TOP_DIFFUSE (0.8 * INTENSITY_CORRECTION)
#define LIGHT_TOP_SPECULAR (0.125 * INTENSITY_CORRECTION)
#define LIGHT_TOP_SHININESS 20.0
// normalized values for (1./1.43, 0.2/1.43, 1./1.43)
const vec3 LIGHT_FRONT_DIR = vec3(0.6985074, 0.1397015, 0.6985074);
#define LIGHT_FRONT_DIFFUSE (0.3 * INTENSITY_CORRECTION)
#define INTENSITY_AMBIENT 0.3
const vec3 ZERO = vec3(0.0, 0.0, 0.0);
const vec3 GREEN = vec3(0.0, 0.7, 0.0);
const vec3 YELLOW = vec3(0.5, 0.7, 0.0);
const vec3 RED = vec3(0.7, 0.0, 0.0);
const vec3 WHITE = vec3(1.0, 1.0, 1.0);
const float EPSILON = 0.0001;
const float BANDS_WIDTH = 10.0;
struct PrintVolumeDetection
{

View file

@ -174,6 +174,9 @@ void AppConfig::set_defaults()
if (get("show_hints").empty())
set("show_hints", "1");
if (get("allow_ip_resolve").empty())
set("allow_ip_resolve", "1");
#ifdef _WIN32
if (get("use_legacy_3DConnexion").empty())
set("use_legacy_3DConnexion", "0");

View file

@ -126,7 +126,7 @@ static ConstPrintObjectPtrs get_top_level_objects_with_brim(const Print &print,
return top_level_objects_with_brim;
}
static Polygons top_level_outer_brim_islands(const ConstPrintObjectPtrs &top_level_objects_with_brim)
static Polygons top_level_outer_brim_islands(const ConstPrintObjectPtrs &top_level_objects_with_brim, const double scaled_resolution)
{
Polygons islands;
for (const PrintObject *object : top_level_objects_with_brim) {
@ -139,7 +139,7 @@ static Polygons top_level_outer_brim_islands(const ConstPrintObjectPtrs &top_lev
for (const ExPolygon &ex_poly : get_print_object_bottom_layer_expolygons(*object)) {
Polygons contour_offset = offset(ex_poly.contour, brim_separation, ClipperLib::jtSquare);
for (Polygon &poly : contour_offset)
poly.douglas_peucker(SCALED_RESOLUTION);
poly.douglas_peucker(scaled_resolution);
polygons_append(islands_object, std::move(contour_offset));
}
@ -359,13 +359,14 @@ static void make_inner_brim(const Print &print,
ExtrusionEntityCollection &brim)
{
assert(print.objects().size() == bottom_layers_expolygons.size());
const auto scaled_resolution = scaled<double>(print.config().gcode_resolution.value);
Flow flow = print.brim_flow();
ExPolygons islands_ex = inner_brim_area(print, top_level_objects_with_brim, bottom_layers_expolygons, float(flow.scaled_spacing()));
Polygons loops;
islands_ex = offset_ex(islands_ex, -0.5f * float(flow.scaled_spacing()), ClipperLib::jtSquare);
for (size_t i = 0; !islands_ex.empty(); ++i) {
for (ExPolygon &poly_ex : islands_ex)
poly_ex.douglas_peucker(SCALED_RESOLUTION);
poly_ex.douglas_peucker(scaled_resolution);
polygons_append(loops, to_polygons(islands_ex));
islands_ex = offset_ex(islands_ex, -float(flow.scaled_spacing()), ClipperLib::jtSquare);
}
@ -380,10 +381,11 @@ static void make_inner_brim(const Print &print,
// Collect islands_area to be merged into the final 1st layer convex hull.
ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cancel, Polygons &islands_area)
{
const auto scaled_resolution = scaled<double>(print.config().gcode_resolution.value);
Flow flow = print.brim_flow();
std::vector<ExPolygons> bottom_layers_expolygons = get_print_bottom_layers_expolygons(print);
ConstPrintObjectPtrs top_level_objects_with_brim = get_top_level_objects_with_brim(print, bottom_layers_expolygons);
Polygons islands = top_level_outer_brim_islands(top_level_objects_with_brim);
Polygons islands = top_level_outer_brim_islands(top_level_objects_with_brim, scaled_resolution);
ExPolygons islands_area_ex = top_level_outer_brim_area(print, top_level_objects_with_brim, bottom_layers_expolygons, float(flow.scaled_spacing()));
islands_area = to_polygons(islands_area_ex);
@ -393,7 +395,7 @@ ExtrusionEntityCollection make_brim(const Print &print, PrintTryCancel try_cance
try_cancel();
islands = expand(islands, float(flow.scaled_spacing()), ClipperLib::jtSquare);
for (Polygon &poly : islands)
poly.douglas_peucker(SCALED_RESOLUTION);
poly.douglas_peucker(scaled_resolution);
polygons_append(loops, shrink(islands, 0.5f * float(flow.scaled_spacing())));
}
loops = union_pt_chained_outside_in(loops);

View file

@ -67,6 +67,16 @@ add_library(libslic3r STATIC
Fill/FillPlanePath.hpp
Fill/FillLine.cpp
Fill/FillLine.hpp
Fill/FillLightning.cpp
Fill/FillLightning.hpp
Fill/Lightning/DistanceField.cpp
Fill/Lightning/DistanceField.hpp
Fill/Lightning/Generator.cpp
Fill/Lightning/Generator.hpp
Fill/Lightning/Layer.cpp
Fill/Lightning/Layer.hpp
Fill/Lightning/TreeNode.cpp
Fill/Lightning/TreeNode.hpp
Fill/FillRectilinear.cpp
Fill/FillRectilinear.hpp
Flow.cpp

View file

@ -330,6 +330,7 @@ void Layer::make_fills(FillAdaptive::Octree* adaptive_fill_octree, FillAdaptive:
std::vector<SurfaceFill> surface_fills = group_fills(*this);
const Slic3r::BoundingBox bbox = this->object()->bounding_box();
const auto resolution = this->object()->print()->config().gcode_resolution.value;
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
@ -371,6 +372,7 @@ void Layer::make_fills(FillAdaptive::Octree* adaptive_fill_octree, FillAdaptive:
params.dont_adjust = false; // surface_fill.params.dont_adjust;
params.anchor_length = surface_fill.params.anchor_length;
params.anchor_length_max = surface_fill.params.anchor_length_max;
params.resolution = resolution;
for (ExPolygon &expoly : surface_fill.expolygons) {
// Spacing is modified by the filler to indicate adjustments. Reset it for each expolygon.

View file

@ -19,6 +19,7 @@
#include "FillLine.hpp"
#include "FillRectilinear.hpp"
#include "FillAdaptive.hpp"
#include "FillLightning.hpp"
// #define INFILL_DEBUG_OUTPUT
@ -45,6 +46,9 @@ Fill* Fill::new_from_type(const InfillPattern type)
case ipAdaptiveCubic: return new FillAdaptive::Filler();
case ipSupportCubic: return new FillAdaptive::Filler();
case ipSupportBase: return new FillSupportBase();
#if HAS_LIGHTNING_INFILL
case ipLightning: return new FillLightning::Filler();
#endif // HAS_LIGHTNING_INFILL
default: throw Slic3r::InvalidArgument("unknown type");
}
}

View file

@ -13,10 +13,10 @@
#include "../BoundingBox.hpp"
#include "../Exception.hpp"
#include "../Utils.hpp"
#include "../ExPolygon.hpp"
namespace Slic3r {
class ExPolygon;
class Surface;
enum InfillPattern : int;
@ -44,6 +44,9 @@ struct FillParams
float anchor_length { 1000.f };
float anchor_length_max { 1000.f };
// G-code resolution.
double resolution { 0.0125 };
// Don't adjust spacing to fill the space evenly.
bool dont_adjust { true };

View file

@ -0,0 +1,29 @@
#include "../Print.hpp"
#include "FillLightning.hpp"
#include "Lightning/Generator.hpp"
#include "../Surface.hpp"
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <numeric>
namespace Slic3r::FillLightning {
Polylines Filler::fill_surface(const Surface *surface, const FillParams &params)
{
const Layer &layer = generator->getTreesForLayer(this->layer_id);
return layer.convertToLines(to_polygons(surface->expolygon), generator->infilll_extrusion_width());
}
void GeneratorDeleter::operator()(Generator *p) {
delete p;
}
GeneratorPtr build_generator(const PrintObject &print_object)
{
return GeneratorPtr(new Generator(print_object));
}
} // namespace Slic3r::FillAdaptive

View file

@ -0,0 +1,36 @@
#ifndef slic3r_FillLightning_hpp_
#define slic3r_FillLightning_hpp_
#include "FillBase.hpp"
namespace Slic3r {
class PrintObject;
namespace FillLightning {
class Generator;
// To keep the definition of Octree opaque, we have to define a custom deleter.
struct GeneratorDeleter { void operator()(Generator *p); };
using GeneratorPtr = std::unique_ptr<Generator, GeneratorDeleter>;
GeneratorPtr build_generator(const PrintObject &print_object);
class Filler : public Slic3r::Fill
{
public:
~Filler() override = default;
Generator *generator { nullptr };
protected:
Fill* clone() const override { return new Filler(*this); }
// Perform the fill.
Polylines fill_surface(const Surface *surface, const FillParams &params) override;
// Let the G-code export reoder the infill lines.
bool no_sort() const override { return false; }
};
} // namespace FillAdaptive
} // namespace Slic3r
#endif // slic3r_FillLightning_hpp_

View file

@ -31,7 +31,8 @@ void FillPlanePath::_fill_surface_single(
coord_t(ceil(coordf_t(bounding_box.min.x()) / distance_between_lines)),
coord_t(ceil(coordf_t(bounding_box.min.y()) / distance_between_lines)),
coord_t(ceil(coordf_t(bounding_box.max.x()) / distance_between_lines)),
coord_t(ceil(coordf_t(bounding_box.max.y()) / distance_between_lines)));
coord_t(ceil(coordf_t(bounding_box.max.y()) / distance_between_lines)),
params.resolution);
if (pts.size() >= 2) {
// Convert points to a polyline, upscale.
@ -58,7 +59,7 @@ void FillPlanePath::_fill_surface_single(
}
// Follow an Archimedean spiral, in polar coordinates: r=a+b\theta
Pointfs FillArchimedeanChords::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y)
Pointfs FillArchimedeanChords::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y, const double resolution)
{
// Radius to achieve.
coordf_t rmax = std::sqrt(coordf_t(max_x)*coordf_t(max_x)+coordf_t(max_y)*coordf_t(max_y)) * std::sqrt(2.) + 1.5;
@ -72,8 +73,8 @@ Pointfs FillArchimedeanChords::_generate(coord_t min_x, coord_t min_y, coord_t m
out.emplace_back(0, 0);
out.emplace_back(1, 0);
while (r < rmax) {
// Discretization angle to achieve a discretization error lower than RESOLUTION.
theta += 2. * acos(1. - RESOLUTION / r);
// Discretization angle to achieve a discretization error lower than resolution.
theta += 2. * acos(1. - resolution / r);
r = a + b * theta;
out.emplace_back(r * cos(theta), r * sin(theta));
}
@ -125,7 +126,7 @@ static inline Point hilbert_n_to_xy(const size_t n)
return Point(x, y);
}
Pointfs FillHilbertCurve::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y)
Pointfs FillHilbertCurve::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y, const double /* resolution */)
{
// Minimum power of two square to fit the domain.
size_t sz = 2;
@ -148,7 +149,7 @@ Pointfs FillHilbertCurve::_generate(coord_t min_x, coord_t min_y, coord_t max_x,
return line;
}
Pointfs FillOctagramSpiral::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y)
Pointfs FillOctagramSpiral::_generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y, const double /* resolution */)
{
// Radius to achieve.
coordf_t rmax = std::sqrt(coordf_t(max_x)*coordf_t(max_x)+coordf_t(max_y)*coordf_t(max_y)) * std::sqrt(2.) + 1.5;

View file

@ -28,7 +28,7 @@ protected:
float _layer_angle(size_t idx) const override { return 0.f; }
virtual bool _centered() const = 0;
virtual Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) = 0;
virtual Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y, const double resolution) = 0;
};
class FillArchimedeanChords : public FillPlanePath
@ -39,7 +39,7 @@ public:
protected:
bool _centered() const override { return true; }
Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) override;
Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y, const double resolution) override;
};
class FillHilbertCurve : public FillPlanePath
@ -50,7 +50,7 @@ public:
protected:
bool _centered() const override { return false; }
Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) override;
Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y, const double resolution) override;
};
class FillOctagramSpiral : public FillPlanePath
@ -61,7 +61,7 @@ public:
protected:
bool _centered() const override { return true; }
Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y) override;
Pointfs _generate(coord_t min_x, coord_t min_y, coord_t max_x, coord_t max_y, const double resolution) override;
};
} // namespace Slic3r

View file

@ -3041,5 +3041,40 @@ Polylines FillSupportBase::fill_surface(const Surface *surface, const FillParams
return polylines_out;
}
} // namespace Slic3r
Points sample_grid_pattern(const ExPolygon &expolygon, coord_t spacing)
{
ExPolygonWithOffset poly_with_offset(expolygon, 0, 0, 0);
BoundingBox bounding_box = poly_with_offset.bounding_box_src();
std::vector<SegmentedIntersectionLine> segs = slice_region_by_vertical_lines(
poly_with_offset,
(bounding_box.max.x() - bounding_box.min.x() + spacing - 1) / spacing,
bounding_box.min.x(),
spacing);
Points out;
for (const SegmentedIntersectionLine &sil : segs) {
for (size_t i = 0; i < sil.intersections.size(); i += 2) {
coord_t a = sil.intersections[i].pos();
coord_t b = sil.intersections[i + 1].pos();
for (coord_t y = a - (a % spacing) - spacing; y < b; y += spacing)
if (y > a)
out.emplace_back(sil.pos, y);
}
}
return out;
}
Points sample_grid_pattern(const ExPolygons &expolygons, coord_t spacing)
{
Points out;
for (const ExPolygon &expoly : expolygons)
append(out, sample_grid_pattern(expoly, spacing));
return out;
}
Points sample_grid_pattern(const Polygons &polygons, coord_t spacing)
{
return sample_grid_pattern(union_ex(polygons), spacing);
}
} // namespace Slic3r

View file

@ -109,6 +109,10 @@ protected:
float _layer_angle(size_t idx) const override { return 0.f; }
};
Points sample_grid_pattern(const ExPolygon &expolygon, coord_t spacing);
Points sample_grid_pattern(const ExPolygons &expolygons, coord_t spacing);
Points sample_grid_pattern(const Polygons &polygons, coord_t spacing);
} // namespace Slic3r
#endif // slic3r_FillRectilinear_hpp_

View file

@ -0,0 +1,99 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "DistanceField.hpp" //Class we're implementing.
#include "../FillRectilinear.hpp"
#include "../../ClipperUtils.hpp"
namespace Slic3r::FillLightning
{
constexpr coord_t radius_per_cell_size = 6; // The cell-size should be small compared to the radius, but not so small as to be inefficient.
DistanceField::DistanceField(const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang) :
m_cell_size(radius / radius_per_cell_size),
m_supporting_radius(radius)
{
m_supporting_radius2 = double(radius) * double(radius);
// Sample source polygons with a regular grid sampling pattern.
for (const ExPolygon &expoly : union_ex(current_outline)) {
for (const Point &p : sample_grid_pattern(expoly, m_cell_size)) {
// Find a squared distance to the source expolygon boundary.
double d2 = std::numeric_limits<double>::max();
for (size_t icontour = 0; icontour <= expoly.holes.size(); ++ icontour) {
const Polygon &contour = icontour == 0 ? expoly.contour : expoly.holes[icontour - 1];
if (contour.size() > 2) {
Point prev = contour.points.back();
for (const Point &p2 : contour.points) {
d2 = std::min(d2, Line::distance_to_squared(p, prev, p2));
prev = p2;
}
}
}
m_unsupported_points.emplace_back(p, sqrt(d2));
}
}
m_unsupported_points.sort([&radius](const UnsupportedCell &a, const UnsupportedCell &b) {
constexpr coord_t prime_for_hash = 191;
return std::abs(b.dist_to_boundary - a.dist_to_boundary) > radius ?
a.dist_to_boundary < b.dist_to_boundary :
(PointHash{}(a.loc) % prime_for_hash) < (PointHash{}(b.loc) % prime_for_hash);
});
for (auto it = m_unsupported_points.begin(); it != m_unsupported_points.end(); ++it) {
UnsupportedCell& cell = *it;
m_unsupported_points_grid.emplace(Point{ cell.loc.x() / m_cell_size, cell.loc.y() / m_cell_size }, it);
}
}
void DistanceField::update(const Point& to_node, const Point& added_leaf)
{
Vec2d v = (added_leaf - to_node).cast<double>();
auto l2 = v.squaredNorm();
Vec2d extent = Vec2d(-v.y(), v.x()) * m_supporting_radius / sqrt(l2);
BoundingBox grid;
{
Point diagonal(m_supporting_radius, m_supporting_radius);
Point iextent(extent.cast<coord_t>());
grid = BoundingBox(added_leaf - diagonal, added_leaf + diagonal);
grid.merge(to_node - iextent);
grid.merge(to_node + iextent);
grid.merge(added_leaf - iextent);
grid.merge(added_leaf + iextent);
grid.min /= m_cell_size;
grid.max /= m_cell_size;
}
Point grid_loc;
for (coord_t row = grid.min.y(); row <= grid.max.y(); ++ row) {
grid_loc.y() = row * m_cell_size;
for (coord_t col = grid.min.x(); col <= grid.max.y(); ++ col) {
grid_loc.x() = col * m_cell_size;
// Test inside a circle at the new leaf.
if ((grid_loc - added_leaf).cast<double>().squaredNorm() > m_supporting_radius2) {
// Not inside a circle at the end of the new leaf.
// Test inside a rotated rectangle.
Vec2d vx = (grid_loc - to_node).cast<double>();
double d = v.dot(vx);
if (d >= 0 && d <= l2) {
d = extent.dot(vx);
if (d < -1. || d > 1.)
// Not inside a rotated rectangle.
continue;
}
}
// Inside a circle at the end of the new leaf, or inside a rotated rectangle.
// Remove unsupported leafs at this grid location.
if (auto it = m_unsupported_points_grid.find(grid_loc); it != m_unsupported_points_grid.end()) {
std::list<UnsupportedCell>::iterator& list_it = it->second;
UnsupportedCell& cell = *list_it;
if ((cell.loc - added_leaf).cast<double>().squaredNorm() <= m_supporting_radius2) {
m_unsupported_points.erase(list_it);
m_unsupported_points_grid.erase(it);
}
}
}
}
}
} // namespace Slic3r::FillLightning

View file

@ -0,0 +1,100 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#ifndef LIGHTNING_DISTANCE_FIELD_H
#define LIGHTNING_DISTANCE_FIELD_H
#include "../../Point.hpp"
#include "../../Polygon.hpp"
namespace Slic3r::FillLightning
{
/*!
* 2D field that maintains locations which need to be supported for Lightning
* Infill.
*
* This field contains a set of "cells", spaced out in a grid. Each cell
* maintains how far it is removed from the edge, which is used to determine
* how it gets supported by Lightning Infill.
*/
class DistanceField
{
public:
/*!
* Construct a new field to calculate Lightning Infill with.
* \param radius The radius of influence that an infill line is expected to
* support in the layer above.
* \param current_outline The total infill area on this layer.
* \param current_overhang The overhang that needs to be supported on this
* layer.
*/
DistanceField(const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang);
/*!
* Gets the next unsupported location to be supported by a new branch.
* \param p Output variable for the next point to support.
* \return ``true`` if successful, or ``false`` if there are no more points
* to consider.
*/
bool tryGetNextPoint(Point* p) const {
if (m_unsupported_points.empty())
return false;
*p = m_unsupported_points.front().loc;
return true;
}
/*!
* Update the distance field with a newly added branch.
*
* The branch is a line extending from \p to_node to \p added_leaf . This
* function updates the grid cells so that the distance field knows how far
* off it is from being supported by the current pattern. Grid points are
* updated with sampling points spaced out by the supporting radius along
* the line.
* \param to_node The node endpoint of the newly added branch.
* \param added_leaf The location of the leaf of the newly added branch,
* drawing a straight line to the node.
*/
void update(const Point& to_node, const Point& added_leaf);
protected:
/*!
* Spacing between grid points to consider supporting.
*/
coord_t m_cell_size;
/*!
* The radius of the area of the layer above supported by a point on a
* branch of a tree.
*/
coord_t m_supporting_radius;
double m_supporting_radius2;
/*!
* Represents a small discrete area of infill that needs to be supported.
*/
struct UnsupportedCell
{
UnsupportedCell(Point loc, coord_t dist_to_boundary) : loc(loc), dist_to_boundary(dist_to_boundary) {}
// The position of the center of this cell.
Point loc;
// How far this cell is removed from the ``current_outline`` polygon, the edge of the infill area.
coord_t dist_to_boundary;
};
/*!
* Cells which still need to be supported at some point.
*/
std::list<UnsupportedCell> m_unsupported_points;
/*!
* Links the unsupported points to a grid point, so that we can quickly look
* up the cell belonging to a certain position in the grid.
*/
std::unordered_map<Point, std::list<UnsupportedCell>::iterator, PointHash> m_unsupported_points_grid;
};
} // namespace Slic3r::FillLightning
#endif //LIGHTNING_DISTANCE_FIELD_H

View file

@ -0,0 +1,127 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "Generator.hpp"
#include "TreeNode.hpp"
#include "../../ClipperUtils.hpp"
#include "../../Layer.hpp"
#include "../../Print.hpp"
#include "../../Surface.hpp"
/* Possible future tasks/optimizations,etc.:
* - Improve connecting heuristic to favor connecting to shorter trees
* - Change which node of a tree is the root when that would be better in reconnectRoots.
* - (For implementation in Infill classes & elsewhere): Outline offset, infill-overlap & perimeter gaps.
* - Allow for polylines, i.e. merge Tims PR about polyline fixes
* - Unit Tests?
* - Optimization: let the square grid store the closest point on boundary
* - Optimization: only compute the closest dist to / point on boundary for the outer cells and flood-fill the rest
* - Make a pass with Arachne over the output. Somehow.
* - Generate all to-be-supported points at once instead of sequentially: See branch interlocking_gen PolygonUtils::spreadDots (Or work with sparse grids.)
* - Lots of magic values ... to many to parameterize. But are they the best?
* - Move more complex computations from Generator constructor to elsewhere.
*/
namespace Slic3r::FillLightning {
Generator::Generator(const PrintObject &print_object)
{
const PrintConfig &print_config = print_object.print()->config();
const PrintObjectConfig &object_config = print_object.config();
const PrintRegionConfig &region_config = print_object.shared_regions()->all_regions.front()->config();
const std::vector<double> &nozzle_diameters = print_config.nozzle_diameter.values;
double max_nozzle_diameter = *std::max_element(nozzle_diameters.begin(), nozzle_diameters.end());
// const int infill_extruder = region_config.infill_extruder.value;
const double default_infill_extrusion_width = Flow::auto_extrusion_width(FlowRole::frInfill, float(max_nozzle_diameter));
// Note: There's not going to be a layer below the first one, so the 'initial layer height' doesn't have to be taken into account.
const double layer_thickness = object_config.layer_height;
m_infill_extrusion_width = scaled<float>(region_config.infill_extrusion_width.percent ? default_infill_extrusion_width * 0.01 * region_config.infill_extrusion_width : region_config.infill_extrusion_width);
m_supporting_radius = scaled<coord_t>(m_infill_extrusion_width * 0.001 / region_config.fill_density);
const double lightning_infill_overhang_angle = M_PI / 4; // 45 degrees
const double lightning_infill_prune_angle = M_PI / 4; // 45 degrees
const double lightning_infill_straightening_angle = M_PI / 4; // 45 degrees
m_wall_supporting_radius = layer_thickness * std::tan(lightning_infill_overhang_angle);
m_prune_length = layer_thickness * std::tan(lightning_infill_prune_angle);
m_straightening_max_distance = layer_thickness * std::tan(lightning_infill_straightening_angle);
generateInitialInternalOverhangs(print_object);
generateTrees(print_object);
}
void Generator::generateInitialInternalOverhangs(const PrintObject &print_object)
{
m_overhang_per_layer.resize(print_object.layers().size());
const float infill_wall_offset = - m_infill_extrusion_width;
Polygons infill_area_above;
//Iterate from top to bottom, to subtract the overhang areas above from the overhang areas on the layer below, to get only overhang in the top layer where it is overhanging.
for (int layer_nr = print_object.layers().size() - 1; layer_nr >= 0; layer_nr--) {
Polygons infill_area_here;
for (const LayerRegion* layerm : print_object.get_layer(layer_nr)->regions())
for (const Surface& surface : layerm->fill_surfaces.surfaces)
if (surface.surface_type == stInternal)
append(infill_area_here, offset(surface.expolygon, infill_wall_offset));
//Remove the part of the infill area that is already supported by the walls.
Polygons overhang = diff(offset(infill_area_here, -m_wall_supporting_radius), infill_area_above);
m_overhang_per_layer[layer_nr] = overhang;
infill_area_above = std::move(infill_area_here);
}
}
const Layer& Generator::getTreesForLayer(const size_t& layer_id) const
{
assert(layer_id < m_lightning_layers.size());
return m_lightning_layers[layer_id];
}
void Generator::generateTrees(const PrintObject &print_object)
{
m_lightning_layers.resize(print_object.layers().size());
const coord_t infill_wall_offset = - m_infill_extrusion_width;
std::vector<Polygons> infill_outlines(print_object.layers().size(), Polygons());
// For-each layer from top to bottom:
for (int layer_id = print_object.layers().size() - 1; layer_id >= 0; layer_id--)
for (const LayerRegion *layerm : print_object.get_layer(layer_id)->regions())
for (const Surface &surface : layerm->fill_surfaces.surfaces)
if (surface.surface_type == stInternal)
append(infill_outlines[layer_id], offset(surface.expolygon, infill_wall_offset));
// For various operations its beneficial to quickly locate nearby features on the polygon:
const size_t top_layer_id = print_object.layers().size() - 1;
EdgeGrid::Grid outlines_locator(get_extents(infill_outlines[top_layer_id]).inflated(SCALED_EPSILON));
outlines_locator.create(infill_outlines[top_layer_id], locator_cell_size);
// For-each layer from top to bottom:
for (int layer_id = top_layer_id; layer_id >= 0; layer_id--)
{
Layer& current_lightning_layer = m_lightning_layers[layer_id];
Polygons& current_outlines = infill_outlines[layer_id];
// register all trees propagated from the previous layer as to-be-reconnected
std::vector<NodeSPtr> to_be_reconnected_tree_roots = current_lightning_layer.tree_roots;
current_lightning_layer.generateNewTrees(m_overhang_per_layer[layer_id], current_outlines, outlines_locator, m_supporting_radius, m_wall_supporting_radius);
current_lightning_layer.reconnectRoots(to_be_reconnected_tree_roots, current_outlines, outlines_locator, m_supporting_radius, m_wall_supporting_radius);
// Initialize trees for next lower layer from the current one.
if (layer_id == 0)
return;
const Polygons& below_outlines = infill_outlines[layer_id - 1];
outlines_locator.set_bbox(get_extents(below_outlines).inflated(SCALED_EPSILON));
outlines_locator.create(below_outlines, locator_cell_size);
std::vector<NodeSPtr>& lower_trees = m_lightning_layers[layer_id - 1].tree_roots;
for (auto& tree : current_lightning_layer.tree_roots)
tree->propagateToNextLayer(lower_trees, below_outlines, outlines_locator, m_prune_length, m_straightening_max_distance, locator_cell_size / 2);
}
}
} // namespace Slic3r::FillLightning

View file

@ -0,0 +1,132 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#ifndef LIGHTNING_GENERATOR_H
#define LIGHTNING_GENERATOR_H
#include "Layer.hpp"
#include <functional>
#include <memory>
#include <vector>
namespace Slic3r
{
class PrintObject;
namespace FillLightning
{
/*!
* Generates the Lightning Infill pattern.
*
* The lightning infill pattern is designed to use a minimal amount of material
* to support the top skin of the print, while still printing with reasonably
* consistently flowing lines. It sacrifices strength completely in favour of
* top surface quality and reduced print time / material usage.
*
* Lightning Infill is so named because the patterns it creates resemble a
* forked path with one main path and many small lines on the side. These paths
* grow out from the sides of the model just below where the top surface needs
* to be supported from the inside, so that minimal material is needed.
*
* This pattern is based on a paper called "Ribbed Support Vaults for 3D
* Printing of Hollowed Objects" by Tricard, Claux and Lefebvre:
* https://www.researchgate.net/publication/333808588_Ribbed_Support_Vaults_for_3D_Printing_of_Hollowed_Objects
*/
class Generator // "Just like Nicola used to make!"
{
public:
/*!
* Create a generator to fill a certain mesh with infill.
*
* This generator will pre-compute things in preparation of generating
* Lightning Infill for the infill areas in that mesh. The infill areas must
* already be calculated at this point.
* \param mesh The mesh to generate infill for.
*/
Generator(const PrintObject &print_object);
/*!
* Get a tree of paths generated for a certain layer of the mesh.
*
* This tree represents the paths that must be traced to print the infill.
* \param layer_id The layer number to get the path tree for. This is within
* the range of layers of the mesh (not the global layer numbers).
* \return A tree structure representing paths to print to create the
* Lightning Infill pattern.
*/
const Layer& getTreesForLayer(const size_t& layer_id) const;
float infilll_extrusion_width() const { return m_infill_extrusion_width; }
protected:
/*!
* Calculate the overhangs above the infill areas that need to be supported
* by infill.
*
* Normally, overhangs are only generated for the outside of the model and
* only when support is generated. For this pattern, we also need to
* generate overhang areas for the inside of the model.
*/
void generateInitialInternalOverhangs(const PrintObject &print_object);
/*!
* Calculate the tree structure of all layers.
*/
void generateTrees(const PrintObject &print_object);
float m_infill_extrusion_width;
/*!
* How far each piece of infill can support skin in the layer above.
*/
coord_t m_supporting_radius;
/*!
* How far a wall can support the wall above it. If a wall completely
* supports the wall above it, no infill needs to support that.
*
* This is similar to the overhang distance calculated for support. It is
* determined by the lightning_infill_overhang_angle setting.
*/
coord_t m_wall_supporting_radius;
/*!
* How far each piece of infill can support other infill in the layer above.
*
* This may be different than \ref supporting_radius, because the infill is
* printed with one end floating in mid-air. This endpoint will sag more, so
* an infill line may need to be supported more than a skin line.
*/
coord_t m_prune_length;
/*!
* How far a line may be shifted in order to straighten the line out.
*
* Straightening the line reduces material and time usage and reduces
* accelerations needed to print the pattern. However it makes the infill
* weak if lines are partially suspended next to the line on the previous
* layer.
*/
coord_t m_straightening_max_distance;
/*!
* For each layer, the overhang that needs to be supported by the pattern.
*
* This is generated by \ref generateInitialInternalOverhangs.
*/
std::vector<Polygons> m_overhang_per_layer;
/*!
* For each layer, the generated lightning paths.
*
* This is generated by \ref generateTrees.
*/
std::vector<Layer> m_lightning_layers;
};
} // namespace FillLightning
} // namespace Slic3r
#endif // LIGHTNING_GENERATOR_H

View file

@ -0,0 +1,410 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "Layer.hpp" //The class we're implementing.
#include <iterator> // advance
#include "DistanceField.hpp"
#include "TreeNode.hpp"
#include "../../Geometry.hpp"
namespace Slic3r::FillLightning {
coord_t Layer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_location)
{
return coord_t((boundary_loc - unsupported_location).cast<double>().norm());
}
Point GroundingLocation::p() const
{
assert(tree_node || boundary_location);
return tree_node ? tree_node->getLocation() : *boundary_location;
}
void Layer::fillLocator(SparseNodeGrid &tree_node_locator)
{
std::function<void(NodeSPtr)> add_node_to_locator_func = [&tree_node_locator](NodeSPtr node) {
tree_node_locator.insert(std::make_pair(Point(node->getLocation().x() / locator_cell_size, node->getLocation().y() / locator_cell_size), node));
};
for (auto& tree : tree_roots)
tree->visitNodes(add_node_to_locator_func);
}
void Layer::generateNewTrees
(
const Polygons& current_overhang,
const Polygons& current_outlines,
const EdgeGrid::Grid& outlines_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
)
{
DistanceField distance_field(supporting_radius, current_outlines, current_overhang);
SparseNodeGrid tree_node_locator;
fillLocator(tree_node_locator);
// Until no more points need to be added to support all:
// Determine next point from tree/outline areas via distance-field
Point unsupported_location;
while (distance_field.tryGetNextPoint(&unsupported_location)) {
GroundingLocation grounding_loc = getBestGroundingLocation(
unsupported_location, current_outlines, outlines_locator, supporting_radius, wall_supporting_radius, tree_node_locator);
NodeSPtr new_parent;
NodeSPtr new_child;
this->attach(unsupported_location, grounding_loc, new_child, new_parent);
tree_node_locator.insert(std::make_pair(Point(new_child->getLocation().x() / locator_cell_size, new_child->getLocation().y() / locator_cell_size), new_child));
if (new_parent)
tree_node_locator.insert(std::make_pair(Point(new_parent->getLocation().x() / locator_cell_size, new_parent->getLocation().y() / locator_cell_size), new_parent));
// update distance field
distance_field.update(grounding_loc.p(), unsupported_location);
}
}
static bool polygonCollidesWithLineSegment(const Point from, const Point to, const EdgeGrid::Grid &loc_to_line)
{
struct Visitor {
explicit Visitor(const EdgeGrid::Grid &grid) : grid(grid) {}
bool operator()(coord_t iy, coord_t ix) {
// Called with a row and colum of the grid cell, which is intersected by a line.
auto cell_data_range = grid.cell_data_range(iy, ix);
for (auto it_contour_and_segment = cell_data_range.first; it_contour_and_segment != cell_data_range.second; ++ it_contour_and_segment) {
// End points of the line segment and their vector.
auto segment = grid.segment(*it_contour_and_segment);
if (Geometry::segments_intersect(segment.first, segment.second, line.a, line.b)) {
this->intersect = true;
return false;
}
}
// Continue traversing the grid along the edge.
return true;
}
const EdgeGrid::Grid& grid;
Line line;
bool intersect = false;
} visitor(loc_to_line);
loc_to_line.visit_cells_intersecting_line(from, to, visitor);
return visitor.intersect;
}
GroundingLocation Layer::getBestGroundingLocation
(
const Point& unsupported_location,
const Polygons& current_outlines,
const EdgeGrid::Grid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius,
const SparseNodeGrid& tree_node_locator,
const NodeSPtr& exclude_tree
)
{
// Closest point on current_outlines to unsupported_location:
Point node_location;
{
double d2 = std::numeric_limits<double>::max();
for (const Polygon &contour : current_outlines)
if (contour.size() > 2) {
Point prev = contour.points.back();
for (const Point &p2 : contour.points) {
if (double d = Line::distance_to_squared(unsupported_location, prev, p2); d < d2) {
d2 = d;
node_location = Geometry::foot_pt({ prev, p2 }, unsupported_location).cast<coord_t>();
}
prev = p2;
}
}
}
const auto within_dist = coord_t((node_location - unsupported_location).cast<double>().norm());
NodeSPtr sub_tree{ nullptr };
coord_t current_dist = getWeightedDistance(node_location, unsupported_location);
if (current_dist >= wall_supporting_radius) { // Only reconnect tree roots to other trees if they are not already close to the outlines.
const coord_t search_radius = std::min(current_dist, within_dist);
BoundingBox region(unsupported_location - Point(search_radius, search_radius), unsupported_location + Point(search_radius + locator_cell_size, search_radius + locator_cell_size));
region.min /= locator_cell_size;
region.max /= locator_cell_size;
Point grid_addr;
for (grid_addr.y() = region.min.y(); grid_addr.y() < region.max.y(); ++ grid_addr.y())
for (grid_addr.x() = region.min.x(); grid_addr.x() < region.max.x(); ++ grid_addr.x()) {
auto it_range = tree_node_locator.equal_range(grid_addr);
for (auto it = it_range.first; it != it_range.second; ++ it) {
auto candidate_sub_tree = it->second.lock();
if ((candidate_sub_tree && candidate_sub_tree != exclude_tree) &&
!(exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree)) &&
!polygonCollidesWithLineSegment(unsupported_location, candidate_sub_tree->getLocation(), outline_locator)) {
const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius);
if (candidate_dist < current_dist) {
current_dist = candidate_dist;
sub_tree = candidate_sub_tree;
}
}
}
}
}
return ! sub_tree ?
GroundingLocation{ nullptr, node_location } :
GroundingLocation{ sub_tree, std::optional<Point>() };
}
bool Layer::attach(
const Point& unsupported_location,
const GroundingLocation& grounding_loc,
NodeSPtr& new_child,
NodeSPtr& new_root)
{
// Update trees & distance fields.
if (grounding_loc.boundary_location) {
new_root = Node::create(grounding_loc.p(), std::make_optional(grounding_loc.p()));
new_child = new_root->addChild(unsupported_location);
tree_roots.push_back(new_root);
return true;
} else {
new_child = grounding_loc.tree_node->addChild(unsupported_location);
return false;
}
}
void Layer::reconnectRoots
(
std::vector<NodeSPtr>& to_be_reconnected_tree_roots,
const Polygons& current_outlines,
const EdgeGrid::Grid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
)
{
constexpr coord_t tree_connecting_ignore_offset = 100;
SparseNodeGrid tree_node_locator;
fillLocator(tree_node_locator);
const coord_t within_max_dist = outline_locator.resolution() * 2;
for (auto root_ptr : to_be_reconnected_tree_roots)
{
auto old_root_it = std::find(tree_roots.begin(), tree_roots.end(), root_ptr);
if (root_ptr->getLastGroundingLocation())
{
const Point& ground_loc = *root_ptr->getLastGroundingLocation();
if (ground_loc != root_ptr->getLocation())
{
Point new_root_pt;
// Find an intersection of the line segment from root_ptr->getLocation() to ground_loc, at within_max_dist from ground_loc.
if (lineSegmentPolygonsIntersection(root_ptr->getLocation(), ground_loc, outline_locator, new_root_pt, within_max_dist)) {
auto new_root = Node::create(new_root_pt, new_root_pt);
root_ptr->addChild(new_root);
new_root->reroot();
tree_node_locator.insert(std::make_pair(Point(new_root->getLocation().x() / locator_cell_size, new_root->getLocation().y() / locator_cell_size), new_root));
*old_root_it = std::move(new_root); // replace old root with new root
continue;
}
}
}
const coord_t tree_connecting_ignore_width = wall_supporting_radius - tree_connecting_ignore_offset; // Ideally, the boundary size in which the valence rule is ignored would be configurable.
GroundingLocation ground =
getBestGroundingLocation
(
root_ptr->getLocation(),
current_outlines,
outline_locator,
supporting_radius,
tree_connecting_ignore_width,
tree_node_locator,
root_ptr
);
if (ground.boundary_location)
{
if (*ground.boundary_location == root_ptr->getLocation())
continue; // Already on the boundary.
auto new_root = Node::create(ground.p(), ground.p());
auto attach_ptr = root_ptr->closestNode(new_root->getLocation());
attach_ptr->reroot();
new_root->addChild(attach_ptr);
tree_node_locator.insert(std::make_pair(new_root->getLocation(), new_root));
*old_root_it = std::move(new_root); // replace old root with new root
}
else
{
assert(ground.tree_node);
assert(ground.tree_node != root_ptr);
assert(!root_ptr->hasOffspring(ground.tree_node));
assert(!ground.tree_node->hasOffspring(root_ptr));
auto attach_ptr = root_ptr->closestNode(ground.tree_node->getLocation());
attach_ptr->reroot();
ground.tree_node->addChild(attach_ptr);
// remove old root
*old_root_it = std::move(tree_roots.back());
tree_roots.pop_back();
}
}
}
/*
* Implementation assumes moving inside, but moving outside should just as well be possible.
*/
static unsigned int moveInside(const Polygons& polygons, Point& from, int distance, int64_t maxDist2)
{
Point ret = from;
int64_t bestDist2 = std::numeric_limits<int64_t>::max();
unsigned int bestPoly = static_cast<unsigned int>(-1);
bool is_already_on_correct_side_of_boundary = false; // whether [from] is already on the right side of the boundary
for (unsigned int poly_idx = 0; poly_idx < polygons.size(); poly_idx++)
{
const Polygon &poly = polygons[poly_idx];
if (poly.size() < 2)
continue;
Point p0 = poly[poly.size() - 2];
Point p1 = poly.back();
// because we compare with vSize2 here (no division by zero), we also need to compare by vSize2 inside the loop
// to avoid integer rounding edge cases
bool projected_p_beyond_prev_segment = (p1 - p0).cast<int64_t>().dot((from - p0).cast<int64_t>()) >= (p1 - p0).cast<int64_t>().squaredNorm();
for (const Point& p2 : poly)
{
// X = A + Normal(B-A) * (((B-A) dot (P-A)) / VSize(B-A));
// = A + (B-A) * ((B-A) dot (P-A)) / VSize2(B-A);
// X = P projected on AB
const Point& a = p1;
const Point& b = p2;
const Point& p = from;
Point ab = b - a;
Point ap = p - a;
int64_t ab_length2 = ab.cast<int64_t>().squaredNorm();
if (ab_length2 <= 0) //A = B, i.e. the input polygon had two adjacent points on top of each other.
{
p1 = p2; //Skip only one of the points.
continue;
}
int64_t dot_prod = ab.cast<int64_t>().dot(ap.cast<int64_t>());
if (dot_prod <= 0) // x is projected to before ab
{
if (projected_p_beyond_prev_segment)
{ // case which looks like: > .
projected_p_beyond_prev_segment = false;
Point& x = p1;
int64_t dist2 = (x - p).cast<int64_t>().squaredNorm();
if (dist2 < bestDist2)
{
bestDist2 = dist2;
bestPoly = poly_idx;
if (distance == 0) {
ret = x;
} else {
// inward direction irrespective of sign of [distance]
Point inward_dir = perp((ab.cast<double>().normalized() * scaled<double>(10.0) + (p1 - p0).cast<double>().normalized() * scaled<double>(10.0)).eval()).cast<coord_t>();
// MM2INT(10.0) to retain precision for the eventual normalization
ret = x + (inward_dir.cast<double>().normalized() * distance).cast<coord_t>();
is_already_on_correct_side_of_boundary = inward_dir.cast<int64_t>().dot((p - x).cast<int64_t>()) * distance >= 0;
}
}
}
else
{
projected_p_beyond_prev_segment = false;
p0 = p1;
p1 = p2;
continue;
}
}
else if (dot_prod >= ab_length2) // x is projected to beyond ab
{
projected_p_beyond_prev_segment = true;
p0 = p1;
p1 = p2;
continue;
}
else
{ // x is projected to a point properly on the line segment (not onto a vertex). The case which looks like | .
projected_p_beyond_prev_segment = false;
Point x = a + ab * dot_prod / ab_length2;
int64_t dist2 = (p - x).cast<int64_t>().squaredNorm();
if (dist2 < bestDist2)
{
bestDist2 = dist2;
bestPoly = poly_idx;
if (distance == 0) { ret = x; }
else
{
// inward or outward depending on the sign of [distance]
Vec2d inward_dir = perp((ab.cast<double>().normalized() * distance).eval());
ret = x + inward_dir.cast<coord_t>();
is_already_on_correct_side_of_boundary = inward_dir.dot((p - x).cast<double>()) >= 0;
}
}
}
p0 = p1;
p1 = p2;
}
}
if (is_already_on_correct_side_of_boundary) // when the best point is already inside and we're moving inside, or when the best point is already outside and we're moving outside
{
if (bestDist2 < distance * distance)
{
from = ret;
}
else
{
// from = from; // original point stays unaltered. It is already inside by enough distance
}
return bestPoly;
}
else if (bestDist2 < maxDist2)
{
from = ret;
return bestPoly;
}
return static_cast<unsigned int>(-1);
}
// Returns 'added someting'.
Polylines Layer::convertToLines(const Polygons& limit_to_outline, const coord_t line_width) const
{
if (tree_roots.empty())
return {};
Polygons result_lines;
for (const auto& tree : tree_roots) {
// If even the furthest location in the tree is inside the polygon, the entire tree must be inside of the polygon.
// (Don't take the root as that may be on the edge and cause rounding errors to register as 'outside'.)
constexpr coord_t epsilon = 5;
Point should_be_inside = tree->getLocation();
moveInside(limit_to_outline, should_be_inside, epsilon, epsilon * epsilon);
if (inside(limit_to_outline, should_be_inside))
tree->convertToPolylines(result_lines, line_width);
}
// TODO: allow for polylines!
Polylines split_lines;
for (Polygon &line : result_lines) {
if (line.size() <= 1)
continue;
Point last = line[0];
for (size_t point_idx = 1; point_idx < line.size(); point_idx++) {
Point here = line[point_idx];
split_lines.push_back({ last, here });
last = here;
}
}
return split_lines;
}
} // namespace Slic3r::Lightning

View file

@ -0,0 +1,88 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#ifndef LIGHTNING_LAYER_H
#define LIGHTNING_LAYER_H
#include "../../EdgeGrid.hpp"
#include "../../Polygon.hpp"
#include <memory>
#include <vector>
#include <list>
#include <unordered_map>
#include <optional>
namespace Slic3r::FillLightning
{
class Node;
using NodeSPtr = std::shared_ptr<Node>;
using SparseNodeGrid = std::unordered_multimap<Point, std::weak_ptr<Node>, PointHash>;
struct GroundingLocation
{
NodeSPtr tree_node; //!< not null if the gounding location is on a tree
std::optional<Point> boundary_location; //!< in case the gounding location is on the boundary
Point p() const;
};
/*!
* A layer of the lightning fill.
*
* Contains the trees to be printed and propagated to the next layer below.
*/
class Layer
{
public:
std::vector<NodeSPtr> tree_roots;
void generateNewTrees
(
const Polygons& current_overhang,
const Polygons& current_outlines,
const EdgeGrid::Grid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
);
/*! Determine & connect to connection point in tree/outline.
* \param min_dist_from_boundary_for_tree If the unsupported point is closer to the boundary than this then don't consider connecting it to a tree
*/
GroundingLocation getBestGroundingLocation
(
const Point& unsupported_location,
const Polygons& current_outlines,
const EdgeGrid::Grid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius,
const SparseNodeGrid& tree_node_locator,
const NodeSPtr& exclude_tree = nullptr
);
/*!
* \param[out] new_child The new child node introduced
* \param[out] new_root The new root node if one had been made
* \return Whether a new root was added
*/
bool attach(const Point& unsupported_location, const GroundingLocation& ground, NodeSPtr& new_child, NodeSPtr& new_root);
void reconnectRoots
(
std::vector<NodeSPtr>& to_be_reconnected_tree_roots,
const Polygons& current_outlines,
const EdgeGrid::Grid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
);
Polylines convertToLines(const Polygons& limit_to_outline, const coord_t line_width) const;
coord_t getWeightedDistance(const Point& boundary_loc, const Point& unsupported_location);
void fillLocator(SparseNodeGrid& tree_node_locator);
};
} // namespace Slic3r::FillLightning
#endif // LIGHTNING_LAYER_H

View file

@ -0,0 +1,411 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "TreeNode.hpp"
#include "../../Geometry.hpp"
#include "../../ClipperUtils.hpp"
namespace Slic3r::FillLightning {
coord_t Node::getWeightedDistance(const Point& unsupported_location, const coord_t& supporting_radius) const
{
constexpr coord_t min_valence_for_boost = 0;
constexpr coord_t max_valence_for_boost = 4;
constexpr coord_t valence_boost_multiplier = 4;
const size_t valence = (!m_is_root) + m_children.size();
const coord_t valence_boost = (min_valence_for_boost < valence && valence < max_valence_for_boost) ? valence_boost_multiplier * supporting_radius : 0;
const auto dist_here = coord_t((getLocation() - unsupported_location).cast<double>().norm());
return dist_here - valence_boost;
}
bool Node::hasOffspring(const NodeSPtr& to_be_checked) const
{
if (to_be_checked == shared_from_this())
return true;
for (auto& child_ptr : m_children)
if (child_ptr->hasOffspring(to_be_checked))
return true;
return false;
}
NodeSPtr Node::addChild(const Point& child_loc)
{
assert(m_p != child_loc);
NodeSPtr child = Node::create(child_loc);
return addChild(child);
}
NodeSPtr Node::addChild(NodeSPtr& new_child)
{
assert(new_child != shared_from_this());
//assert(p != new_child->p); // NOTE: No problem for now. Issue to solve later. Maybe even afetr final. Low prio.
m_children.push_back(new_child);
new_child->m_parent = shared_from_this();
new_child->m_is_root = false;
return new_child;
}
void Node::propagateToNextLayer(
std::vector<NodeSPtr>& next_trees,
const Polygons& next_outlines,
const EdgeGrid::Grid& outline_locator,
const coord_t prune_distance,
const coord_t smooth_magnitude,
const coord_t max_remove_colinear_dist) const
{
auto tree_below = deepCopy();
tree_below->prune(prune_distance);
tree_below->straighten(smooth_magnitude, max_remove_colinear_dist);
if (tree_below->realign(next_outlines, outline_locator, next_trees))
next_trees.push_back(tree_below);
}
// NOTE: Depth-first, as currently implemented.
// Skips the root (because that has no root itself), but all initial nodes will have the root point anyway.
void Node::visitBranches(const std::function<void(const Point&, const Point&)>& visitor) const
{
for (const auto& node : m_children) {
assert(node->m_parent.lock() == shared_from_this());
visitor(m_p, node->m_p);
node->visitBranches(visitor);
}
}
// NOTE: Depth-first, as currently implemented.
void Node::visitNodes(const std::function<void(NodeSPtr)>& visitor)
{
visitor(shared_from_this());
for (const auto& node : m_children) {
assert(node->m_parent.lock() == shared_from_this());
node->visitNodes(visitor);
}
}
Node::Node(const Point& p, const std::optional<Point>& last_grounding_location /*= std::nullopt*/) :
m_is_root(true), m_p(p), m_last_grounding_location(last_grounding_location)
{}
NodeSPtr Node::deepCopy() const
{
NodeSPtr local_root = Node::create(m_p);
local_root->m_is_root = m_is_root;
if (m_is_root)
{
local_root->m_last_grounding_location = m_last_grounding_location.value_or(m_p);
}
local_root->m_children.reserve(m_children.size());
for (const auto& node : m_children)
{
NodeSPtr child = node->deepCopy();
child->m_parent = local_root;
local_root->m_children.push_back(child);
}
return local_root;
}
void Node::reroot(NodeSPtr new_parent /*= nullptr*/)
{
if (! m_is_root) {
auto old_parent = m_parent.lock();
old_parent->reroot(shared_from_this());
m_children.push_back(old_parent);
}
if (new_parent) {
m_children.erase(std::remove(m_children.begin(), m_children.end(), new_parent), m_children.end());
m_is_root = false;
m_parent = new_parent;
} else {
m_is_root = true;
m_parent.reset();
}
}
NodeSPtr Node::closestNode(const Point& loc)
{
NodeSPtr result = shared_from_this();
auto closest_dist2 = coord_t((m_p - loc).cast<double>().norm());
for (const auto& child : m_children) {
NodeSPtr candidate_node = child->closestNode(loc);
const auto child_dist2 = coord_t((candidate_node->m_p - loc).cast<double>().norm());
if (child_dist2 < closest_dist2) {
closest_dist2 = child_dist2;
result = candidate_node;
}
}
return result;
}
bool inside(const Polygons &polygons, const Point p)
{
int poly_count_inside = 0;
for (const Polygon &poly : polygons) {
const int is_inside_this_poly = ClipperLib::PointInPolygon(p, poly.points);
if (is_inside_this_poly == -1)
return true;
poly_count_inside += is_inside_this_poly;
}
return (poly_count_inside % 2) == 1;
}
bool lineSegmentPolygonsIntersection(const Point& a, const Point& b, const EdgeGrid::Grid& outline_locator, Point& result, const coord_t within_max_dist)
{
struct Visitor {
bool operator()(coord_t iy, coord_t ix) {
// Called with a row and colum of the grid cell, which is intersected by a line.
auto cell_data_range = grid.cell_data_range(iy, ix);
for (auto it_contour_and_segment = cell_data_range.first; it_contour_and_segment != cell_data_range.second; ++it_contour_and_segment) {
// End points of the line segment and their vector.
auto segment = grid.segment(*it_contour_and_segment);
if (Vec2d ip; Geometry::segment_segment_intersection(segment.first.cast<double>(), segment.second.cast<double>(), this->line_a, this->line_b, ip))
if (double d = (this->intersection_pt - this->line_b).squaredNorm(); d < d2min) {
this->d2min = d;
this->intersection_pt = ip;
}
}
// Continue traversing the grid along the edge.
return true;
}
const EdgeGrid::Grid& grid;
Vec2d line_a;
Vec2d line_b;
Vec2d intersection_pt;
double d2min { std::numeric_limits<double>::max() };
} visitor { outline_locator, a.cast<double>(), b.cast<double>() };
outline_locator.visit_cells_intersecting_line(a, b, visitor);
return visitor.d2min < within_max_dist * within_max_dist;
}
bool Node::realign(const Polygons& outlines, const EdgeGrid::Grid& outline_locator, std::vector<NodeSPtr>& rerooted_parts)
{
if (outlines.empty())
return false;
if (inside(outlines, m_p)) {
// Only keep children that have an unbroken connection to here, realign will put the rest in rerooted parts due to recursion:
Point coll;
bool reground_me = false;
m_children.erase(std::remove_if(m_children.begin(), m_children.end(), [&](const NodeSPtr &child) {
bool connect_branch = child->realign(outlines, outline_locator, rerooted_parts);
// Find an intersection of the line segment from p to child->p, at maximum outline_locator.resolution() * 2 distance from p.
if (connect_branch && lineSegmentPolygonsIntersection(child->m_p, m_p, outline_locator, coll, outline_locator.resolution() * 2)) {
child->m_last_grounding_location.reset();
child->m_parent.reset();
child->m_is_root = true;
rerooted_parts.push_back(child);
reground_me = true;
connect_branch = false;
}
return ! connect_branch;
}), m_children.end());
if (reground_me)
m_last_grounding_location.reset();
return true;
}
// 'Lift' any decendants out of this tree:
for (auto& child : m_children)
if (child->realign(outlines, outline_locator, rerooted_parts)) {
child->m_last_grounding_location = m_p;
child->m_parent.reset();
child->m_is_root = true;
rerooted_parts.push_back(child);
}
m_children.clear();
return false;
}
void Node::straighten(const coord_t magnitude, const coord_t max_remove_colinear_dist)
{
straighten(magnitude, m_p, 0, max_remove_colinear_dist * max_remove_colinear_dist);
}
Node::RectilinearJunction Node::straighten(
const coord_t magnitude,
const Point& junction_above,
const coord_t accumulated_dist,
const coord_t max_remove_colinear_dist2)
{
constexpr coord_t junction_magnitude_factor_numerator = 3;
constexpr coord_t junction_magnitude_factor_denominator = 4;
const coord_t junction_magnitude = magnitude * junction_magnitude_factor_numerator / junction_magnitude_factor_denominator;
if (m_children.size() == 1)
{
auto child_p = m_children.front();
auto child_dist = coord_t((m_p - child_p->m_p).cast<double>().norm());
RectilinearJunction junction_below = child_p->straighten(magnitude, junction_above, accumulated_dist + child_dist, max_remove_colinear_dist2);
coord_t total_dist_to_junction_below = junction_below.total_recti_dist;
Point a = junction_above;
Point b = junction_below.junction_loc;
if (a != b) // should always be true!
{
Point ab = b - a;
Point destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below);
if ((destination - m_p).cast<double>().squaredNorm() <= magnitude * magnitude)
m_p = destination;
else
m_p += ((destination - m_p).cast<double>().normalized() * magnitude).cast<coord_t>();
}
{ // remove nodes on linear segments
constexpr coord_t close_enough = 10;
child_p = m_children.front(); //recursive call to straighten might have removed the child
const NodeSPtr& parent_node = m_parent.lock();
if (parent_node &&
(child_p->m_p - parent_node->m_p).cast<double>().squaredNorm() < max_remove_colinear_dist2 &&
Line::distance_to_squared(m_p, parent_node->m_p, child_p->m_p) < close_enough * close_enough) {
child_p->m_parent = m_parent;
for (auto& sibling : parent_node->m_children)
{ // find this node among siblings
if (sibling == shared_from_this())
{
sibling = child_p; // replace this node by child
break;
}
}
}
}
return junction_below;
}
else
{
constexpr coord_t weight = 1000;
Point junction_moving_dir = ((junction_above - m_p).cast<double>().normalized() * weight).cast<coord_t>();
bool prevent_junction_moving = false;
for (auto& child_p : m_children)
{
const auto child_dist = coord_t((m_p - child_p->m_p).cast<double>().norm());
RectilinearJunction below = child_p->straighten(magnitude, m_p, child_dist, max_remove_colinear_dist2);
junction_moving_dir += ((below.junction_loc - m_p).cast<double>().normalized() * weight).cast<coord_t>();
if (below.total_recti_dist < magnitude) // TODO: make configurable?
{
prevent_junction_moving = true; // prevent flipflopping in branches due to straightening and junctoin moving clashing
}
}
if (junction_moving_dir != Point(0, 0) && ! m_children.empty() && ! m_is_root && ! prevent_junction_moving)
{
auto junction_moving_dir_len = coord_t(junction_moving_dir.norm());
if (junction_moving_dir_len > junction_magnitude)
{
junction_moving_dir = junction_moving_dir * junction_magnitude / junction_moving_dir_len;
}
m_p += junction_moving_dir;
}
return RectilinearJunction{ accumulated_dist, m_p };
}
}
// Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached.
coord_t Node::prune(const coord_t& pruning_distance)
{
if (pruning_distance <= 0)
return 0;
coord_t max_distance_pruned = 0;
for (auto child_it = m_children.begin(); child_it != m_children.end(); ) {
auto& child = *child_it;
coord_t dist_pruned_child = child->prune(pruning_distance);
if (dist_pruned_child >= pruning_distance)
{ // pruning is finished for child; dont modify further
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child);
++child_it;
} else {
const Point a = getLocation();
const Point b = child->getLocation();
const Point ba = a - b;
const auto ab_len = coord_t(ba.cast<double>().norm());
if (dist_pruned_child + ab_len <= pruning_distance) {
// we're still in the process of pruning
assert(child->m_children.empty() && "when pruning away a node all it's children must already have been pruned away");
max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child + ab_len);
child_it = m_children.erase(child_it);
} else {
// pruning stops in between this node and the child
const Point n = b + (ba.cast<double>().normalized() * (pruning_distance - dist_pruned_child)).cast<coord_t>();
assert(std::abs((n - b).cast<double>().norm() + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance");
max_distance_pruned = std::max(max_distance_pruned, pruning_distance);
child->setLocation(n);
++child_it;
}
}
}
return max_distance_pruned;
}
void Node::convertToPolylines(Polygons& output, const coord_t line_width) const
{
Polygons result;
output.emplace_back();
convertToPolylines(0, result);
removeJunctionOverlap(result, line_width);
append(output, std::move(result));
}
void Node::convertToPolylines(size_t long_line_idx, Polygons& output) const
{
if (m_children.empty()) {
output[long_line_idx].points.push_back(m_p);
return;
}
size_t first_child_idx = rand() % m_children.size();
m_children[first_child_idx]->convertToPolylines(long_line_idx, output);
output[long_line_idx].points.push_back(m_p);
for (size_t idx_offset = 1; idx_offset < m_children.size(); idx_offset++) {
size_t child_idx = (first_child_idx + idx_offset) % m_children.size();
const Node& child = *m_children[child_idx];
output.emplace_back();
size_t child_line_idx = output.size() - 1;
child.convertToPolylines(child_line_idx, output);
output[child_line_idx].points.emplace_back(m_p);
}
}
void Node::removeJunctionOverlap(Polygons& result_lines, const coord_t line_width) const
{
const coord_t reduction = line_width / 2; // TODO make configurable?
for (auto poly_it = result_lines.begin(); poly_it != result_lines.end(); ) {
Polygon &polyline = *poly_it;
if (polyline.size() <= 1) {
polyline = std::move(result_lines.back());
result_lines.pop_back();
continue;
}
coord_t to_be_reduced = reduction;
Point a = polyline.back();
for (int point_idx = polyline.size() - 2; point_idx >= 0; point_idx--) {
const Point b = polyline[point_idx];
const Point ab = b - a;
const auto ab_len = coord_t(ab.cast<double>().norm());
if (ab_len >= to_be_reduced) {
polyline.points.back() = a + (ab.cast<double>() * (double(to_be_reduced) / ab_len)).cast<coord_t>();
break;
} else {
to_be_reduced -= ab_len;
polyline.points.pop_back();
}
a = b;
}
if (polyline.size() <= 1) {
polyline = std::move(result_lines.back());
result_lines.pop_back();
} else
++ poly_it;
}
}
} // namespace Slic3r::FillLightning

View file

@ -0,0 +1,275 @@
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#ifndef LIGHTNING_TREE_NODE_H
#define LIGHTNING_TREE_NODE_H
#include <functional>
#include <memory>
#include <optional>
#include <vector>
#include "../../EdgeGrid.hpp"
#include "../../Polygon.hpp"
namespace Slic3r::FillLightning
{
constexpr auto locator_cell_size = scaled<coord_t>(4.);
class Node;
using NodeSPtr = std::shared_ptr<Node>;
// NOTE: As written, this struct will only be valid for a single layer, will have to be updated for the next.
// NOTE: Reasons for implementing this with some separate closures:
// - keep clear deliniation during development
// - possibility of multiple distance field strategies
/*!
* A single vertex of a Lightning Tree, the structure that determines the paths
* to be printed to form Lightning Infill.
*
* In essence these vertices are just a position linked to other positions in
* 2D. The nodes have a hierarchical structure of parents and children, forming
* a tree. The class also has some helper functions specific to Lightning Infill
* e.g. to straighten the paths around this node.
*/
class Node : public std::enable_shared_from_this<Node>
{
public:
// Workaround for private/protected constructors and 'make_shared': https://stackoverflow.com/a/27832765
template<typename ...Arg> NodeSPtr static create(Arg&&...arg)
{
struct EnableMakeShared : public Node
{
EnableMakeShared(Arg&&...arg) : Node(std::forward<Arg>(arg)...) {}
};
return std::make_shared<EnableMakeShared>(std::forward<Arg>(arg)...);
}
/*!
* Get the position on this layer that this node represents, a vertex of the
* path to print.
* \return The position that this node represents.
*/
const Point& getLocation() const { return m_p; }
/*!
* Change the position on this layer that the node represents.
* \param p The position that the node needs to represent.
*/
void setLocation(const Point& p) { m_p = p; }
/*!
* Construct a new ``Node`` instance and add it as a child of
* this node.
* \param p The location of the new node.
* \return A shared pointer to the new node.
*/
NodeSPtr addChild(const Point& p);
/*!
* Add an existing ``Node`` as a child of this node.
* \param new_child The node that must be added as a child.
* \return Always returns \p new_child.
*/
NodeSPtr addChild(NodeSPtr& new_child);
/*!
* Propagate this node's sub-tree to the next layer.
*
* Creates a copy of this tree, realign it to the new layer boundaries
* \p next_outlines and reduce (i.e. prune and straighten) it. A copy of
* this node and all of its descendant nodes will be added to the
* \p next_trees vector.
* \param next_trees A collection of tree nodes to use for the next layer.
* \param next_outlines The shape of the layer below, to make sure that the
* tree stays within the bounds of the infill area.
* \param prune_distance The maximum distance that a leaf node may be moved
* such that it still supports the current node.
* \param smooth_magnitude The maximum distance that a line may be shifted
* to straighten the tree's paths, such that it still supports the current
* paths.
* \param max_remove_colinear_dist The maximum distance of a line-segment
* from which straightening may remove a colinear point.
*/
void propagateToNextLayer
(
std::vector<NodeSPtr>& next_trees,
const Polygons& next_outlines,
const EdgeGrid::Grid& outline_locator,
const coord_t prune_distance,
const coord_t smooth_magnitude,
const coord_t max_remove_colinear_dist
) const;
/*!
* Executes a given function for every line segment in this node's sub-tree.
*
* The function takes two `Point` arguments. These arguments will be filled
* in with the higher-order node (closer to the root) first, and the
* downtree node (closer to the leaves) as the second argument. The segment
* from this node's parent to this node itself is not included.
* The order in which the segments are visited is depth-first.
* \param visitor A function to execute for every branch in the node's sub-
* tree.
*/
void visitBranches(const std::function<void(const Point&, const Point&)>& visitor) const;
/*!
* Execute a given function for every node in this node's sub-tree.
*
* The visitor function takes a node as input. This node is not const, so
* this can be used to change the tree.
* Nodes are visited in depth-first order. This node itself is visited as
* well (pre-order).
* \param visitor A function to execute for every node in this node's sub-
* tree.
*/
void visitNodes(const std::function<void(NodeSPtr)>& visitor);
/*!
* Get a weighted distance from an unsupported point to this node (given the current supporting radius).
*
* When attaching a unsupported location to a node, not all nodes have the same priority.
* (Eucludian) closer nodes are prioritised, but that's not the whole story.
* For instance, we give some nodes a 'valence boost' depending on the nr. of branches.
* \param unsupported_location The (unsuppported) location of which the weighted distance needs to be calculated.
* \param supporting_radius The maximum distance which can be bridged without (infill) supporting it.
* \return The weighted distance.
*/
coord_t getWeightedDistance(const Point& unsupported_location, const coord_t& supporting_radius) const;
/*!
* Returns whether this node is the root of a lightning tree. It is the root
* if it has no parents.
* \return ``true`` if this node is the root (no parents) or ``false`` if it
* is a child node of some other node.
*/
bool isRoot() const { return m_is_root; }
/*!
* Reverse the parent-child relationship all the way to the root, from this node onward.
* This has the effect of 're-rooting' the tree at the current node if no immediate parent is given as argument.
* That is, the current node will become the root, it's (former) parent if any, will become one of it's children.
* This is then recursively bubbled up until it reaches the (former) root, which then will become a leaf.
* \param new_parent The (new) parent-node of the root, useful for recursing or immediately attaching the node to another tree.
*/
void reroot(NodeSPtr new_parent = nullptr);
/*!
* Retrieves the closest node to the specified location.
* \param loc The specified location.
* \result The branch that starts at the position closest to the location within this tree.
*/
NodeSPtr closestNode(const Point& loc);
/*!
* Returns whether the given tree node is a descendant of this node.
*
* If this node itself is given, it is also considered to be a descendant.
* \param to_be_checked A node to find out whether it is a descendant of
* this node.
* \return ``true`` if the given node is a descendant or this node itself,
* or ``false`` if it is not in the sub-tree.
*/
bool hasOffspring(const NodeSPtr& to_be_checked) const;
protected:
Node() = delete; // Don't allow empty contruction
/*!
* Construct a new node, either for insertion in a tree or as root.
* \param p The physical location in the 2D layer that this node represents.
* Connecting other nodes to this node indicates that a line segment should
* be drawn between those two physical positions.
*/
Node(const Point& p, const std::optional<Point>& last_grounding_location = std::nullopt);
/*!
* Copy this node and its entire sub-tree.
* \return The equivalent of this node in the copy (the root of the new sub-
* tree).
*/
NodeSPtr deepCopy() const;
/*! Reconnect trees from the layer above to the new outlines of the lower layer.
* \return Wether or not the root is kept (false is no, true is yes).
*/
bool realign(const Polygons& outlines, const EdgeGrid::Grid& outline_locator, std::vector<NodeSPtr>& rerooted_parts);
struct RectilinearJunction
{
coord_t total_recti_dist; //!< rectilinear distance along the tree from the last junction above to the junction below
Point junction_loc; //!< junction location below
};
/*!
* Smoothen the tree to make it a bit more printable, while still supporting
* the trees above.
* \param magnitude The maximum allowed distance to move the node.
* \param max_remove_colinear_dist Maximum distance of the (compound) line-segment from which a co-linear point may be removed.
*/
void straighten(const coord_t magnitude, const coord_t max_remove_colinear_dist);
/*! Recursive part of \ref straighten(.)
* \param junction_above The last seen junction with multiple children above
* \param accumulated_dist The distance along the tree from the last seen junction to this node
* \param max_remove_colinear_dist2 Maximum distance _squared_ of the (compound) line-segment from which a co-linear point may be removed.
* \return the total distance along the tree from the last junction above to the first next junction below and the location of the next junction below
*/
RectilinearJunction straighten(const coord_t magnitude, const Point& junction_above, const coord_t accumulated_dist, const coord_t max_remove_colinear_dist2);
/*! Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached.
* \return The distance that has been pruned. If less than \p distance, then the whole tree was puned away.
*/
coord_t prune(const coord_t& distance);
public:
/*!
* Convert the tree into polylines
*
* At each junction one line is chosen at random to continue
*
* The lines start at a leaf and end in a junction
*
* \param output all branches in this tree connected into polylines
*/
void convertToPolylines(Polygons& output, const coord_t line_width) const;
/*! If this was ever a direct child of the root, it'll have a previous grounding location.
*
* This needs to be known when roots are reconnected, so that the last (higher) layer is supported by the next one.
*/
const std::optional<Point>& getLastGroundingLocation() const { return m_last_grounding_location; }
protected:
/*!
* Convert the tree into polylines
*
* At each junction one line is chosen at random to continue
*
* The lines start at a leaf and end in a junction
*
* \param long_line a reference to a polyline in \p output which to continue building on in the recursion
* \param output all branches in this tree connected into polylines
*/
void convertToPolylines(size_t long_line_idx, Polygons& output) const;
void removeJunctionOverlap(Polygons& polylines, const coord_t line_width) const;
bool m_is_root;
Point m_p;
std::weak_ptr<Node> m_parent;
std::vector<NodeSPtr> m_children;
std::optional<Point> m_last_grounding_location; //<! The last known grounding location, see 'getLastGroundingLocation()'.
};
bool inside(const Polygons &polygons, const Point p);
bool lineSegmentPolygonsIntersection(const Point& a, const Point& b, const EdgeGrid::Grid& outline_locator, Point& result, const coord_t within_max_dist);
} // namespace Slic3r::FillLightning
#endif // LIGHTNING_TREE_NODE_H

View file

@ -2414,6 +2414,7 @@ void GCode::apply_print_config(const PrintConfig &print_config)
{
m_writer.apply_print_config(print_config);
m_config.apply(print_config);
m_scaled_resolution = scaled<double>(print_config.gcode_resolution.value);
}
void GCode::append_full_config(const Print &print, std::string &str)
@ -2565,7 +2566,7 @@ std::string GCode::extrude_loop(ExtrusionLoop loop, std::string description, dou
for (ExtrusionPaths::iterator path = paths.begin(); path != paths.end(); ++path) {
// description += ExtrusionLoop::role_to_string(loop.loop_role());
// description += ExtrusionEntity::role_to_string(path->role);
path->simplify(SCALED_RESOLUTION);
path->simplify(m_scaled_resolution);
gcode += this->_extrude(*path, description, speed);
}
@ -2619,7 +2620,7 @@ std::string GCode::extrude_multi_path(ExtrusionMultiPath multipath, std::string
for (ExtrusionPath path : multipath.paths) {
// description += ExtrusionLoop::role_to_string(loop.loop_role());
// description += ExtrusionEntity::role_to_string(path->role);
path.simplify(SCALED_RESOLUTION);
path.simplify(m_scaled_resolution);
gcode += this->_extrude(path, description, speed);
}
if (m_wipe.enable) {
@ -2647,7 +2648,7 @@ std::string GCode::extrude_entity(const ExtrusionEntity &entity, std::string des
std::string GCode::extrude_path(ExtrusionPath path, std::string description, double speed)
{
// description += ExtrusionEntity::role_to_string(path.role());
path.simplify(SCALED_RESOLUTION);
path.simplify(m_scaled_resolution);
std::string gcode = this->_extrude(path, description, speed);
if (m_wipe.enable) {
m_wipe.path = std::move(path.polyline);

View file

@ -345,6 +345,8 @@ private:
methods. */
Vec2d m_origin;
FullPrintConfig m_config;
// scaled G-code resolution
double m_scaled_resolution;
GCodeWriter m_writer;
PlaceholderParser m_placeholder_parser;
// For random number generator etc.

View file

@ -254,7 +254,7 @@ static std::vector<Intersection> extend_for_closest_lines(const std::vector<Inte
};
std::vector<Intersection> new_intersections = intersections;
if (!intersections.empty() && !start_lines.empty()) {
if (!new_intersections.empty() && !start_lines.empty()) {
size_t cl_start_idx = get_closer(start_lines, new_intersections.front(), start);
if (cl_start_idx != std::numeric_limits<size_t>::max()) {
// If there is any ClosestLine around the start point closer to the Intersection, then replace this Intersection with ClosestLine.
@ -265,11 +265,13 @@ static std::vector<Intersection> extend_for_closest_lines(const std::vector<Inte
// vector of intersections. This allows in some cases when it is more than one around ClosestLine start point chose that one which
// minimizes the number of contours (also length of the detour) in result detour. If there doesn't exist any ClosestLine like this, then
// use the first one, which is the closest one to the start point.
size_t start_closest_lines_idx = find_closest_line_with_same_boundary_idx(start_lines, intersections, true);
size_t start_closest_lines_idx = find_closest_line_with_same_boundary_idx(start_lines, new_intersections, true);
const ClosestLine &cl_start = (start_closest_lines_idx != std::numeric_limits<size_t>::max()) ? start_lines[start_closest_lines_idx] : start_lines.front();
new_intersections.insert(new_intersections.begin(),{cl_start.border_idx, cl_start.line_idx, cl_start.point, compute_distance(cl_start)});
}
} else if (!intersections.empty() && !end_lines.empty()) {
}
if (!new_intersections.empty() && !end_lines.empty()) {
size_t cl_end_idx = get_closer(end_lines, new_intersections.back(), end);
if (cl_end_idx != std::numeric_limits<size_t>::max()) {
// If there is any ClosestLine around the end point closer to the Intersection, then replace this Intersection with ClosestLine.
@ -280,7 +282,7 @@ static std::vector<Intersection> extend_for_closest_lines(const std::vector<Inte
// vector of intersections. This allows in some cases when it is more than one around ClosestLine end point chose that one which
// minimizes the number of contours (also length of the detour) in result detour. If there doesn't exist any ClosestLine like this, then
// use the first one, which is the closest one to the end point.
size_t end_closest_lines_idx = find_closest_line_with_same_boundary_idx(end_lines, intersections, false);
size_t end_closest_lines_idx = find_closest_line_with_same_boundary_idx(end_lines, new_intersections, false);
const ClosestLine &cl_end = (end_closest_lines_idx != std::numeric_limits<size_t>::max()) ? end_lines[end_closest_lines_idx] : end_lines.front();
new_intersections.push_back({cl_end.border_idx, cl_end.line_idx, cl_end.point, compute_distance(cl_end)});
}

View file

@ -2,6 +2,7 @@
#include "libslic3r/Utils.hpp"
#include "libslic3r/format.hpp"
#include "libslic3r/I18N.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/log/trivial.hpp>
@ -184,6 +185,11 @@ static int run_script(const std::string &script, const std::string &gcode, std::
namespace Slic3r {
//! macro used to mark string used at localization,
//! return same string
#define L(s) (s)
#define _(s) Slic3r::I18N::translate(s)
// Run post processing script / scripts if defined.
// Returns true if a post-processing script was executed.
// Returns false if no post-processing script was defined.
@ -278,6 +284,15 @@ bool run_post_process_scripts(std::string &src_path, bool make_copy, const std::
delete_copy();
throw Slic3r::RuntimeError(msg);
}
if (! boost::filesystem::exists(gcode_file)) {
const std::string msg = (boost::format(_(L(
"Post-processing script %1% failed.\n\n"
"The post-processing script is expected to change the G-code file %2% in place, but the G-code file was deleted and likely saved under a new name.\n"
"Please adjust the post-processing script to change the G-code in place and consult the manual on how to optionally rename the post-processed G-code file.\n")))
% script % path).str();
BOOST_LOG_TRIVIAL(error) << msg;
throw Slic3r::RuntimeError(msg);
}
}
}
if (boost::filesystem::exists(path_output_name)) {

View file

@ -148,7 +148,8 @@ public:
return false;
}
void make_perimeters();
void make_fills() { this->make_fills(nullptr, nullptr); };
// Phony version of make_fills() without parameters for Perl integration only.
void make_fills() { this->make_fills(nullptr, nullptr); }
void make_fills(FillAdaptive::Octree* adaptive_fill_octree, FillAdaptive::Octree* support_fill_octree);
void make_ironing();

View file

@ -322,7 +322,7 @@ void PerimeterGenerator::process()
for (const Surface &surface : this->slices->surfaces) {
// detect how many perimeters must be generated for this island
int loop_number = this->config->perimeters + surface.extra_perimeters - 1; // 0-indexed loops
ExPolygons last = union_ex(surface.expolygon.simplify_p(SCALED_RESOLUTION));
ExPolygons last = union_ex(surface.expolygon.simplify_p(m_scaled_resolution));
ExPolygons gaps;
if (loop_number >= 0) {
// In case no perimeters are to be generated, loop_number will equal to -1.
@ -533,7 +533,7 @@ void PerimeterGenerator::process()
// simplify infill contours according to resolution
Polygons pp;
for (ExPolygon &ex : last)
ex.simplify_p(SCALED_RESOLUTION, &pp);
ex.simplify_p(m_scaled_resolution, &pp);
// collapse too narrow infill areas
coord_t min_perimeter_infill_spacing = coord_t(solid_infill_spacing * (1. - INSET_OVERLAP_TOLERANCE));
// append infill areas to fill_surfaces

View file

@ -50,6 +50,7 @@ public:
overhang_flow(flow), solid_infill_flow(flow),
config(config), object_config(object_config), print_config(print_config),
m_spiral_vase(spiral_vase),
m_scaled_resolution(scaled<double>(print_config->gcode_resolution.value)),
loops(loops), gap_fill(gap_fill), fill_surfaces(fill_surfaces),
m_ext_mm3_per_mm(-1), m_mm3_per_mm(-1), m_mm3_per_mm_overhang(-1)
{}
@ -63,6 +64,7 @@ public:
private:
bool m_spiral_vase;
double m_scaled_resolution;
double m_ext_mm3_per_mm;
double m_mm3_per_mm;
double m_mm3_per_mm_overhang;

View file

@ -255,7 +255,7 @@ namespace int128 {
// To be used by std::unordered_map, std::unordered_multimap and friends.
struct PointHash {
size_t operator()(const Vec2crd &pt) const {
return std::hash<coord_t>()(pt.x()) ^ std::hash<coord_t>()(pt.y());
return coord_t((89 * 31 + int64_t(pt.x())) * 31 + pt.y());
}
};

View file

@ -444,7 +444,7 @@ static std::vector<std::string> s_Preset_print_options {
"ooze_prevention", "standby_temperature_delta", "interface_shells", "extrusion_width", "first_layer_extrusion_width",
"perimeter_extrusion_width", "external_perimeter_extrusion_width", "infill_extrusion_width", "solid_infill_extrusion_width",
"top_infill_extrusion_width", "support_material_extrusion_width", "infill_overlap", "infill_anchor", "infill_anchor_max", "bridge_flow_ratio", "clip_multipart_objects",
"elefant_foot_compensation", "xy_size_compensation", "threads", "resolution", "wipe_tower", "wipe_tower_x", "wipe_tower_y",
"elefant_foot_compensation", "xy_size_compensation", "threads", "resolution", "gcode_resolution", "wipe_tower", "wipe_tower_x", "wipe_tower_y",
"wipe_tower_width", "wipe_tower_rotation_angle", "wipe_tower_brim_width", "wipe_tower_bridging", "single_extruder_multi_material_priming", "mmu_segmented_region_max_width",
"wipe_tower_no_sparse_layers", "compatible_printers", "compatible_printers_condition", "inherits"
};

View file

@ -214,7 +214,8 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n
} else if (
opt_key == "first_layer_extrusion_width"
|| opt_key == "min_layer_height"
|| opt_key == "max_layer_height") {
|| opt_key == "max_layer_height"
|| opt_key == "gcode_resolution") {
osteps.emplace_back(posPerimeters);
osteps.emplace_back(posInfill);
osteps.emplace_back(posSupportMaterial);

View file

@ -107,7 +107,10 @@ static t_config_enum_values s_keys_map_InfillPattern {
{ "archimedeanchords", ipArchimedeanChords },
{ "octagramspiral", ipOctagramSpiral },
{ "adaptivecubic", ipAdaptiveCubic },
{ "supportcubic", ipSupportCubic }
{ "supportcubic", ipSupportCubic },
#if HAS_LIGHTNING_INFILL
{ "lightning", ipLightning }
#endif // HAS_LIGHTNING_INFILL
};
CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(InfillPattern)
@ -1135,6 +1138,9 @@ void PrintConfigDef::init_fff_params()
def->enum_values.push_back("octagramspiral");
def->enum_values.push_back("adaptivecubic");
def->enum_values.push_back("supportcubic");
#if HAS_LIGHTNING_INFILL
def->enum_values.push_back("lightning");
#endif // HAS_LIGHTNING_INFILL
def->enum_labels.push_back(L("Rectilinear"));
def->enum_labels.push_back(L("Aligned Rectilinear"));
def->enum_labels.push_back(L("Grid"));
@ -1151,6 +1157,9 @@ void PrintConfigDef::init_fff_params()
def->enum_labels.push_back(L("Octagram Spiral"));
def->enum_labels.push_back(L("Adaptive Cubic"));
def->enum_labels.push_back(L("Support Cubic"));
#if HAS_LIGHTNING_INFILL
def->enum_labels.push_back(L("Lightning"));
#endif // HAS_LIGHTNING_INFILL
def->set_default_value(new ConfigOptionEnum<InfillPattern>(ipStars));
def = this->add("first_layer_acceleration", coFloat);
@ -2072,7 +2081,7 @@ void PrintConfigDef::init_fff_params()
def->set_default_value(new ConfigOptionInt(0));
def = this->add("resolution", coFloat);
def->label = L("Resolution");
def->label = L("Slice resolution");
def->tooltip = L("Minimum detail resolution, used to simplify the input file for speeding up "
"the slicing job and reducing memory usage. High-resolution models often carry "
"more detail than printers can render. Set to zero to disable any simplification "
@ -2082,6 +2091,18 @@ void PrintConfigDef::init_fff_params()
def->mode = comExpert;
def->set_default_value(new ConfigOptionFloat(0));
def = this->add("gcode_resolution", coFloat);
def->label = L("G-code resolution");
def->tooltip = L("Maximum deviation of exported G-code paths from their full resolution counterparts. "
"Very high resolution G-code requires huge amount of RAM to slice and preview, "
"also a 3D printer may stutter not being able to process a high resolution G-code in a timely manner. "
"On the other hand, a low resolution G-code will produce a low poly effect and because "
"the G-code reduction is performed at each layer independently, visible artifacts may be produced.");
def->sidetext = L("mm");
def->min = 0;
def->mode = comExpert;
def->set_default_value(new ConfigOptionFloat(0.0125));
def = this->add("retract_before_travel", coFloats);
def->label = L("Minimum travel after retraction");
def->tooltip = L("Retraction is not triggered when travel moves are shorter than this length.");
@ -3940,6 +3961,10 @@ void DynamicPrintConfig::normalize_fdm()
this->opt<ConfigOptionPercent>("fill_density", true)->value = 0;
}
}
if (auto *opt_gcode_resolution = this->opt<ConfigOptionFloat>("gcode_resolution", false); opt_gcode_resolution)
// Resolution will be above 1um.
opt_gcode_resolution->value = std::max(opt_gcode_resolution->value, 0.001);
}
void handle_legacy_sla(DynamicPrintConfig &config)

View file

@ -57,9 +57,15 @@ enum class FuzzySkinType {
All,
};
#define HAS_LIGHTNING_INFILL 0
enum InfillPattern : int {
ipRectilinear, ipMonotonic, ipAlignedRectilinear, ipGrid, ipTriangles, ipStars, ipCubic, ipLine, ipConcentric, ipHoneycomb, ip3DHoneycomb,
ipGyroid, ipHilbertCurve, ipArchimedeanChords, ipOctagramSpiral, ipAdaptiveCubic, ipSupportCubic, ipSupportBase, ipCount,
ipGyroid, ipHilbertCurve, ipArchimedeanChords, ipOctagramSpiral, ipAdaptiveCubic, ipSupportCubic, ipSupportBase,
#if HAS_LIGHTNING_INFILL
ipLightning,
#endif // HAS_LIGHTNING_INFILL
ipCount,
};
enum class IroningType {
@ -734,6 +740,7 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE(
((ConfigOptionString, printer_model))
((ConfigOptionString, printer_notes))
((ConfigOptionFloat, resolution))
((ConfigOptionFloat, gcode_resolution))
((ConfigOptionFloats, retract_before_travel))
((ConfigOptionBools, retract_layer_change))
((ConfigOptionFloat, skirt_distance))

View file

@ -47,9 +47,6 @@ static constexpr double EPSILON = 1e-4;
// int32_t fits an interval of (-2147.48mm, +2147.48mm)
// with int64_t we don't have to worry anymore about the size of the int.
static constexpr double SCALING_FACTOR = 0.000001;
// RESOLUTION, SCALED_RESOLUTION: Used as an error threshold for a Douglas-Peucker polyline simplification algorithm.
static constexpr double RESOLUTION = 0.0125;
#define SCALED_RESOLUTION (RESOLUTION / SCALING_FACTOR)
static constexpr double PI = 3.141592653589793238;
// When extruding a closed loop, the loop is interrupted and shortened a bit to reduce the seam.
static constexpr double LOOP_CLIPPING_LENGTH_OVER_NOZZLE_DIAMETER = 0.15;

View file

@ -139,7 +139,7 @@ Code flags --
REALfloat = 1 all numbers are 'float' type
= 0 all numbers are 'double' type
*/
#define REALfloat 1
#define REALfloat 0
#if (REALfloat == 1)
#define realT float

View file

@ -2713,7 +2713,9 @@ bool ConfigWizard::priv::apply_config(AppConfig *app_config, PresetBundle *prese
// if unsaved changes was not cheched till this moment
if (!check_unsaved_preset_changes) {
if ((check_unsaved_preset_changes = !first_added_filament.empty() || !first_added_sla_material.empty())) {
header = format_wxstr(_L("A new %1% was installed and it will be activated."), !first_added_filament.empty() ? _L("Filament") : _L("SLA material"));
header = !first_added_filament.empty() ?
_L("A new filament was installed and it will be activated.") :
_L("A new SLA material was installed and it will be activated.");
if (!wxGetApp().check_and_keep_current_preset_changes(caption, header, act_btns, &apply_keeped_changes))
return false;
}
@ -2721,7 +2723,7 @@ bool ConfigWizard::priv::apply_config(AppConfig *app_config, PresetBundle *prese
bool is_filaments_changed = app_config->get_section(AppConfig::SECTION_FILAMENTS) != appconfig_new.get_section(AppConfig::SECTION_FILAMENTS);
bool is_sla_materials_changed = app_config->get_section(AppConfig::SECTION_MATERIALS) != appconfig_new.get_section(AppConfig::SECTION_MATERIALS);
if ((check_unsaved_preset_changes = is_filaments_changed || is_sla_materials_changed)) {
header = format_wxstr(_L("Some %1% were uninstalled."), is_filaments_changed ? _L("Filaments") : _L("SLA materials"));
header = is_filaments_changed ? _L("Some filaments were uninstalled.") : _L("Some SLA materials were uninstalled.");
if (!wxGetApp().check_and_keep_current_preset_changes(caption, header, act_btns, &apply_keeped_changes))
return false;
}

View file

@ -1407,8 +1407,8 @@ wxString Control::get_tooltip(int tick/*=-1*/)
if (tick_code_it == m_ticks.ticks.end() && m_focus == fiActionIcon) // tick doesn't exist
{
if (m_draw_mode == dmSequentialFffPrint)
return _L("The sequential print is on.\n"
"It's impossible to apply any custom G-code for objects printing sequentually.\n");
return (_L("The sequential print is on.\n"
"It's impossible to apply any custom G-code for objects printing sequentually.") + "\n");
// Show mode as a first string of tooltop
tooltip = " " + _L("Print mode") + ": ";

View file

@ -1190,7 +1190,7 @@ void GCodeViewer::load_toolpaths(const GCodeProcessorResult& gcode_result)
vertices.push_back(normal.z());
};
if (prev.type != curr.type || !buffer.paths.back().matches(curr)) {
if (buffer.paths.empty() || prev.type != curr.type || !buffer.paths.back().matches(curr)) {
buffer.add_path(curr, vbuffer_id, vertices.size(), move_id - 1);
buffer.paths.back().sub_paths.back().first.position = prev.position;
}
@ -1281,7 +1281,7 @@ void GCodeViewer::load_toolpaths(const GCodeProcessorResult& gcode_result)
store_triangle(indices, v_offsets[4], v_offsets[5], v_offsets[6]);
};
if (prev.type != curr.type || !buffer.paths.back().matches(curr)) {
if (buffer.paths.empty() || prev.type != curr.type || !buffer.paths.back().matches(curr)) {
buffer.add_path(curr, ibuffer_id, indices.size(), move_id - 1);
buffer.paths.back().sub_paths.back().first.position = prev.position;
}
@ -2067,8 +2067,19 @@ void GCodeViewer::load_shells(const Print& print, bool initialized)
instance_ids[i] = i;
}
size_t current_volumes_count = m_shells.volumes.volumes.size();
m_shells.volumes.load_object(model_obj, object_id, instance_ids, "object", initialized);
// adjust shells' z if raft is present
const SlicingParameters& slicing_parameters = obj->slicing_parameters();
if (slicing_parameters.object_print_z_min != 0.0) {
const Vec3d z_offset = slicing_parameters.object_print_z_min * Vec3d::UnitZ();
for (size_t i = current_volumes_count; i < m_shells.volumes.volumes.size(); ++i) {
GLVolume* v = m_shells.volumes.volumes[i];
v->set_volume_offset(v->get_volume_offset() + z_offset);
}
}
++object_id;
}

View file

@ -503,17 +503,15 @@ static const FileWildcards file_wildcards_by_type[FT_SIZE] = {
// an extension from the provided initial file name and substitutes it with the default extension (the first one in the template).
wxString file_wildcards(FileType file_type, const std::string &custom_extension)
{
const FileWildcards data = file_wildcards_by_type[file_type];
const FileWildcards& data = file_wildcards_by_type[file_type];
std::string title;
std::string mask;
std::string custom_ext_lower;
if (! custom_extension.empty()) {
// Generate an extension into the title mask and into the list of extensions.
custom_ext_lower = custom_extension;
boost::to_lower(custom_ext_lower);
std::string custom_ext_upper = custom_extension;
boost::to_upper(custom_ext_upper);
custom_ext_lower = boost::to_lower_copy(custom_extension);
const std::string custom_ext_upper = boost::to_upper_copy(custom_extension);
if (custom_ext_lower == custom_extension) {
// Add a lower case version.
title = std::string("*") + custom_ext_lower;
@ -549,11 +547,9 @@ wxString file_wildcards(FileType file_type, const std::string &custom_extension)
mask += ext;
}
mask += ";*";
std::string ext_upper{ ext };
boost::to_upper(ext_upper);
mask += ext_upper;
mask += boost::to_upper_copy(std::string(ext));
}
return GUI::format("%s (%s)|%s", data.title, title, mask);
return GUI::format_wxstr("%s (%s)|%s", data.title, title, mask);
}
static std::string libslic3r_translate_callback(const char *s) { return wxGetTranslation(wxString(s, wxConvUTF8)).utf8_str().data(); }
@ -1039,7 +1035,7 @@ bool GUI_App::on_init_inner()
RichMessageDialog dlg(nullptr,
_L("You are running a 32 bit build of PrusaSlicer on 64-bit Windows."
"\n32 bit build of PrusaSlicer will likely not be able to utilize all the RAM available in the system."
"\nPlease download and install a 64 bit build of PrusaSlice from https://www.prusa3d.cz/prusaslicer/."
"\nPlease download and install a 64 bit build of PrusaSlicer from https://www.prusa3d.cz/prusaslicer/."
"\nDo you wish to continue?"),
"PrusaSlicer", wxICON_QUESTION | wxYES_NO);
if (dlg.ShowModal() != wxID_YES)

View file

@ -476,7 +476,7 @@ void GLGizmoSimplify::apply_simplify() {
int object_idx = selection.get_object_idx();
auto plater = wxGetApp().plater();
plater->take_snapshot(_u8L("Simplify ") + m_volume->name);
plater->take_snapshot(GUI::format(_u8L("Simplify %1%"), m_volume->name));
plater->clear_before_change_mesh(object_idx);
ModelVolume* mv = get_model_volume(selection, wxGetApp().model());

View file

@ -294,6 +294,10 @@ void HintDatabase::uninit()
write_used_binary(m_used_ids);
}
m_initialized = false;
m_loaded_hints.clear();
m_sorted_hints = false;
m_used_ids.clear();
m_used_ids_loaded = false;
}
void HintDatabase::init()
{
@ -336,7 +340,8 @@ void HintDatabase::load_hints_from_file(const boost::filesystem::path& path)
size_t weight = 1;
bool was_displayed = is_used(id_string);
//unescape text1
unescape_string_cstyle(_utf8(dict["text"]), fulltext);
unescape_string_cstyle(dict["text"], fulltext);
fulltext = _utf8(fulltext);
// replace <b> and </b> for imgui markers
std::string marker_s(1, ImGui::ColorMarkerStart);
std::string marker_e(1, ImGui::ColorMarkerEnd);

View file

@ -10,7 +10,7 @@ void PlaterJob::on_exception(const std::exception_ptr &eptr)
if (eptr)
std::rethrow_exception(eptr);
} catch (std::exception &e) {
show_error(m_plater, _(L("An unexpected error occured: ")) + e.what());
show_error(m_plater, _(L("An unexpected error occured")) + ": "+ e.what());
}
}

View file

@ -468,7 +468,7 @@ void PreferencesDialog::build(size_t selected_tab)
// Add "Dark Mode" tab
if (is_editor) {
// Add "Dark Mode" tab
m_optgroup_dark_mode = create_options_tab(_L("Dark mode IU (experimental)"), tabs);
m_optgroup_dark_mode = create_options_tab(_L("Dark mode (experimental)"), tabs);
m_optgroup_dark_mode->m_on_change = [this](t_config_option_key opt_key, boost::any value) {
m_values[opt_key] = boost::any_cast<bool>(value) ? "1" : "0";
};
@ -487,8 +487,7 @@ void PreferencesDialog::build(size_t selected_tab)
def.label = L("Use system menu for application");
def.type = coBool;
def.tooltip = L("If enabled, application will use the standart Windows system menu,\n"
"but on some combination od display scales it can look ugly. "
"If disabled, old UI will be used.");
"but on some combination of display scales it can looks ugly. If disabled, old UI will be used.");
def.set_default_value(new ConfigOptionBool{ app_config->get("sys_menu_enabled") == "1" });
option = Option(def, "sys_menu_enabled");
m_optgroup_dark_mode->append_single_option_line(option);

View file

@ -949,7 +949,7 @@ void Selection::rotate(const Vec3d& rotation, TransformationType transformation_
#else
else if (is_single_volume() || is_single_modifier()) {
if (transformation_type.independent())
v.set_volume_rotation(v.get_volume_rotation() + rotation);
v.set_volume_rotation(m_cache.volumes_data[i] + rotation);
else {
const Transform3d m = Geometry::assemble_transform(Vec3d::Zero(), rotation);
const Vec3d new_rotation = Geometry::extract_euler_angles(m * m_cache.volumes_data[i].get_volume_rotation_matrix());

View file

@ -70,7 +70,7 @@ public:
SendSystemInfoDialog(wxWindow* parent);
private:
wxString send_info();
bool send_info(wxString& message);
const std::string m_system_info_json;
wxButton* m_btn_show_data;
wxButton* m_btn_send;
@ -649,8 +649,11 @@ SendSystemInfoDialog::SendSystemInfoDialog(wxWindow* parent)
m_btn_send->Bind(wxEVT_BUTTON, [this](const wxEvent&)
{
if (wxString out = send_info(); !out.IsEmpty()) {
InfoDialog(nullptr, wxEmptyString, out).ShowModal();
wxString message;
bool success = send_info(message);
if (! message.IsEmpty())
InfoDialog(nullptr, wxEmptyString, message).ShowModal();
if (success) {
save_version();
EndModal(0);
}
@ -679,7 +682,7 @@ void SendSystemInfoDialog::on_dpi_changed(const wxRect&)
// This actually sends the info.
wxString SendSystemInfoDialog::send_info()
bool SendSystemInfoDialog::send_info(wxString& message)
{
std::atomic<int> job_done = false; // Flag to communicate between threads.
struct Result {
@ -723,9 +726,8 @@ wxString SendSystemInfoDialog::send_info()
job_done = true; // In case the user closed the dialog, let the other thread know
sending_thread.join(); // and wait until it terminates.
if (result.value == Result::Cancelled)
return "";
return result.str;
message = result.value == Result::Cancelled ? wxString("") : result.str;
return result.value == Result::Success;
}

View file

@ -1650,6 +1650,7 @@ void TabPrint::build()
optgroup->append_single_option_line("slice_closing_radius");
optgroup->append_single_option_line("slicing_mode");
optgroup->append_single_option_line("resolution");
optgroup->append_single_option_line("gcode_resolution");
optgroup->append_single_option_line("xy_size_compensation");
optgroup->append_single_option_line("elefant_foot_compensation", "elephant-foot-compensation_114487");

View file

@ -30,6 +30,14 @@ inline wxString format_wxstr(const wxString& fmt, TArgs&&... args) {
return format_wxstr(fmt.ToUTF8().data(), std::forward<TArgs>(args)...);
}
template<typename... TArgs>
inline std::string format(const char* fmt, TArgs&&... args) {
return Slic3r::format(fmt, std::forward<TArgs>(args)...);
}
template<typename... TArgs>
inline std::string format(const std::string& fmt, TArgs&&... args) {
return Slic3r::format(fmt, std::forward<TArgs>(args)...);
}
template<typename... TArgs>
inline std::string format(const wxString& fmt, TArgs&&... args) {
return Slic3r::format(fmt.ToUTF8().data(), std::forward<TArgs>(args)...);
}

View file

@ -15,6 +15,7 @@
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/GUI.hpp"
#include "Http.hpp"
#include "libslic3r/AppConfig.hpp"
namespace fs = boost::filesystem;
@ -23,6 +24,30 @@ namespace pt = boost::property_tree;
namespace Slic3r {
namespace {
std::string substitute_host(const std::string& orig_addr, const std::string sub_addr)
{
//URI = scheme ":"["//"[userinfo "@"] host [":" port]] path["?" query]["#" fragment]
std::string final_addr = orig_addr;
// http
size_t double_dash = orig_addr.find("//");
size_t host_start = (double_dash == std::string::npos ? 0 : double_dash + 2);
// userinfo
size_t at = orig_addr.find("@");
host_start = (at != std::string::npos && at > host_start ? at + 1 : host_start);
// end of host, could be port, subpath (could be query or fragment?)
size_t host_end = orig_addr.find_first_of(":/?#", host_start);
host_end = (host_end == std::string::npos ? orig_addr.length() : host_end);
// now host_start and host_end should mark where to put resolved addr
// check host_start. if its nonsense, lets just use original addr (or resolved addr?)
if (host_start >= orig_addr.length()) {
return final_addr;
}
final_addr.replace(host_start, host_end - host_start, sub_addr);
return final_addr;
}
} //namespace
OctoPrint::OctoPrint(DynamicPrintConfig *config) :
m_host(config->opt_string("print_host")),
m_apikey(config->opt_string("printhost_apikey")),
@ -115,8 +140,9 @@ bool OctoPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn, Erro
std::string url;
bool res = true;
if (m_host.find("https://") == 0 || test_msg.empty())
{
bool allow_ip_resolve = GUI::get_app_config()->get("allow_ip_resolve") == "1";
if (m_host.find("https://") == 0 || test_msg.empty() || !allow_ip_resolve) {
// If https is entered we assume signed ceritificate is being used
// IP resolving will not happen - it could resolve into address not being specified in cert
url = make_url("api/files/local");
@ -126,10 +152,13 @@ bool OctoPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn, Erro
// This new address returns in "test_msg" variable.
// Solves troubles of uploades failing with name address.
std::string resolved_addr = boost::nowide::narrow(test_msg);
// put ipv6 into [] brackets (there shouldn't be any http:// if its resolved addr)
// put ipv6 into [] brackets
if (resolved_addr.find(':') != std::string::npos && resolved_addr.at(0) != '[')
resolved_addr = "[" + resolved_addr + "]";
url = make_url("api/files/local", resolved_addr);
// in original address (m_host) replace host for resolved ip
std::string final_addr = substitute_host(m_host, resolved_addr);
BOOST_LOG_TRIVIAL(debug) << "Upload address after ip resolve: " << final_addr;
url = make_url("api/files/local", final_addr);
}
BOOST_LOG_TRIVIAL(info) << boost::format("%1%: Uploading file %2% at %3%, filename: %4%, path: %5%, print: %6%")