<commit_before>package Slic3r::GCode;
use Moo;

use List::Util qw(min max first);
use Slic3r::ExtrusionPath ':roles';
use Slic3r::Geometry qw(scale unscale scaled_epsilon points_coincide PI X Y B);
use Slic3r::Geometry::Clipper qw(union_ex);
use Slic3r::Surface ':types';

has 'config'             => (is => 'ro', required => 1);
has 'multiple_extruders' => (is => 'ro', default => sub {0} );
has 'layer_count'        => (is => 'ro', required => 1 );
has 'layer'              => (is => 'rw');
has '_layer_overhangs'   => (is => 'rw');
has 'move_z_callback'    => (is => 'rw');
has 'shift_x'            => (is => 'rw', default => sub {0} );
has 'shift_y'            => (is => 'rw', default => sub {0} );
has 'z'                  => (is => 'rw');
has 'speed'              => (is => 'rw');

has 'speeds'             => (is => 'lazy');  # mm/min
has 'external_mp'        => (is => 'rw');
has 'layer_mp'           => (is => 'rw');
has 'new_object'         => (is => 'rw', default => sub {0});
has 'straight_once'      => (is => 'rw', default => sub {1});
has 'extruder'           => (is => 'rw');
has 'elapsed_time'       => (is => 'rw', default => sub {0} );  # seconds
has 'total_extrusion_length' => (is => 'rw', default => sub {0} );
has 'lifted'             => (is => 'rw', default => sub {0} );
has 'last_pos'           => (is => 'rw', default => sub { Slic3r::Point->new(0,0) } );
has 'last_speed'         => (is => 'rw', default => sub {""});
has 'last_f'             => (is => 'rw', default => sub {""});
has 'last_fan_speed'     => (is => 'rw', default => sub {0});
has 'wipe_path'          => (is => 'rw');
has 'dec'                => (is => 'ro', default => sub { 3 } );

# used for vibration limit:
has 'last_dir'           => (is => 'ro', default => sub { [0,0] });
has 'dir_time'           => (is => 'ro', default => sub { [0,0] });

sub _build_speeds {
    my $self = shift;
    return {
        map { $_ => 60 * $self->config->get_value("${_}_speed") }
            qw(travel perimeter small_perimeter external_perimeter infill
                solid_infill top_solid_infill support_material bridge gap_fill retract),
    };
}

# assign speeds to roles
my %role_speeds = (
    &EXTR_ROLE_PERIMETER                    => 'perimeter',
    &EXTR_ROLE_EXTERNAL_PERIMETER           => 'external_perimeter',
    &EXTR_ROLE_OVERHANG_PERIMETER           => 'external_perimeter',
    &EXTR_ROLE_CONTOUR_INTERNAL_PERIMETER   => 'perimeter',
    &EXTR_ROLE_FILL                         => 'infill',
    &EXTR_ROLE_SOLIDFILL                    => 'solid_infill',
    &EXTR_ROLE_TOPSOLIDFILL                 => 'top_solid_infill',
    &EXTR_ROLE_BRIDGE                       => 'bridge',
    &EXTR_ROLE_INTERNALBRIDGE               => 'solid_infill',
    &EXTR_ROLE_SKIRT                        => 'perimeter',
    &EXTR_ROLE_SUPPORTMATERIAL              => 'support_material',
    &EXTR_ROLE_GAPFILL                      => 'gap_fill',
);

sub set_shift {
    my $self = shift;
    my @shift = @_;
    
    # if shift increases (goes towards right), last_pos decreases because it goes towards left
    my @translate = (
        scale ($self->shift_x - $shift[X]),
        scale ($self->shift_y - $shift[Y]),
    );
    $self->last_pos->translate(@translate);
    $self->wipe_path->translate(@translate) if $self->wipe_path;
    
    $self->shift_x($shift[X]);
    $self->shift_y($shift[Y]);
}

sub change_layer {
    my $self = shift;
    my ($layer) = @_;
    
    $self->layer($layer);
    $self->_layer_overhangs(
        $layer->id > 0
            ? [ map $_->expolygon, grep $_->surface_type == S_TYPE_BOTTOM, map @{$_->slices}, @{$layer->regions} ]
            : []
        );
    if ($self->config->avoid_crossing_perimeters) {
        $self->layer_mp(Slic3r::GCode::MotionPlanner->new(
            islands => union_ex([ map @$_, @{$layer->slices} ], undef, 1),
        ));
    }
    
    my $gcode = "";
    if ($self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/) {
        $gcode .= sprintf "M73 P%s%s\n",
            int(99 * ($layer->id / ($self->layer_count - 1))),
            ($self->config->gcode_comments ? ' ; update progress' : '');
    }
    return $gcode;
}

# this method accepts Z in scaled coordinates
sub move_z {
    my $self = shift;
    my ($z, $comment) = @_;
    
    $z *= &Slic3r::SCALING_FACTOR;
    $z += $self->config->z_offset;
    
    my $gcode = "";
    my $current_z = $self->z;
    if (!defined $current_z || $current_z != ($z + $self->lifted)) {
        $gcode .= $self->retract(move_z => $z) if $self->extruder->retract_layer_change;
        $self->speed('travel');
        $gcode .= $self->G0(undef, $z, 0, $comment || ('move to next layer (' . $self->layer->id . ')'))
            unless ($current_z // -1) != ($self->z // -1);
        $gcode .= $self->move_z_callback->() if defined $self->move_z_callback;
    }
    
    return $gcode;
}

sub extrude {
    my $self = shift;
    
    ($_[0]->isa('Slic3r::ExtrusionLoop') || $_[0]->isa('Slic3r::ExtrusionLoop::Packed'))
        ? $self->extrude_loop(@_)
        : $self->extrude_path(@_);
}

sub extrude_loop {
    my $self = shift;
    my ($loop, $description) = @_;
    
    # extrude all loops ccw
    $loop = $loop->unpack if $loop->isa('Slic3r::ExtrusionLoop::Packed');
    my $was_clockwise = $loop->polygon->make_counter_clockwise;
    
    # find the point of the loop that is closest to the current extruder position
    # or randomize if requested
    my $last_pos = $self->last_pos;
    if ($self->config->randomize_start && $loop->role == EXTR_ROLE_CONTOUR_INTERNAL_PERIMETER) {
        $last_pos = Slic3r::Point->new(scale $self->config->print_center->[X], scale $self->config->bed_size->[Y]);
        $last_pos->rotate(rand(2*PI), $self->config->print_center);
    }
    my $start_index = $loop->nearest_point_index_to($last_pos);
    
    # split the loop at the starting point and make a path
    my $extrusion_path = $loop->split_at_index($start_index);
    
    # clip the path to avoid the extruder to get exactly on the first point of the loop;
    # if polyline was shorter than the clipping distance we'd get a null polyline, so
    # we discard it in that case
    $extrusion_path->clip_end(scale $extrusion_path->flow_spacing * &Slic3r::LOOP_CLIPPING_LENGTH_OVER_SPACING);
    return '' if !@{$extrusion_path->polyline};
    
    my @paths = ();
    # detect overhanging/bridging perimeters
    if ($extrusion_path->is_perimeter && @{$self->_layer_overhangs}) {
        # get non-overhang paths by subtracting overhangs from the loop
        push @paths,
            $extrusion_path->subtract_expolygons($self->_layer_overhangs);
        
        # get overhang paths by intersecting overhangs with the loop
        push @paths,
            map { $_->role(EXTR_ROLE_OVERHANG_PERIMETER); $_ }
            $extrusion_path->intersect_expolygons($self->_layer_overhangs);
        
        # reapply the nearest point search for starting point
        # (TODO: choose the nearest point not on an overhang)
        @paths = Slic3r::ExtrusionPath::Collection
            ->new(paths => [@paths])
            ->chained_path($last_pos);
    } else {
        push @paths, $extrusion_path;
    }
    
    # extrude along the path
    my $gcode = join '', map $self->extrude_path($_, $description), @paths;
    $self->wipe_path($extrusion_path->polyline);
    
    # make a little move inwards before leaving loop
    if ($loop->role == EXTR_ROLE_EXTERNAL_PERIMETER && $self->config->perimeters > 1) {
        # detect angle between last and first segment
        # the side depends on the original winding order of the polygon (left for contours, right for holes)
        my @points = $was_clockwise ? (-2, 1) : (1, -2);
        my $angle = Slic3r::Geometry::angle3points(@{$extrusion_path->polyline}[0, @points]) / 3;
        $angle *= -1 if $was_clockwise;
        
        # create the destination point along the first segment and rotate it
        # we make sure we don't exceed the segment length because we don't know
        # the rotation of the second segment so we might cross the object boundary
        my $first_segment = Slic3r::Line->new(@{$extrusion_path->polyline}[0,1]);
        my $distance = min(scale $extrusion_path->flow_spacing, $first_segment->length);
        my $point = Slic3r::Geometry::point_along_segment(@$first_segment, $distance);<commit_msg>Note to self in code<commit_after>package Slic3r::GCode;
use Moo;

use List::Util qw(min max first);
use Slic3r::ExtrusionPath ':roles';
use Slic3r::Geometry qw(scale unscale scaled_epsilon points_coincide PI X Y B);
use Slic3r::Geometry::Clipper qw(union_ex);
use Slic3r::Surface ':types';

has 'config'             => (is => 'ro', required => 1);
has 'multiple_extruders' => (is => 'ro', default => sub {0} );
has 'layer_count'        => (is => 'ro', required => 1 );
has 'layer'              => (is => 'rw');
has '_layer_overhangs'   => (is => 'rw');
has 'move_z_callback'    => (is => 'rw');
has 'shift_x'            => (is => 'rw', default => sub {0} );
has 'shift_y'            => (is => 'rw', default => sub {0} );
has 'z'                  => (is => 'rw');
has 'speed'              => (is => 'rw');

has 'speeds'             => (is => 'lazy');  # mm/min
has 'external_mp'        => (is => 'rw');
has 'layer_mp'           => (is => 'rw');
has 'new_object'         => (is => 'rw', default => sub {0});
has 'straight_once'      => (is => 'rw', default => sub {1});
has 'extruder'           => (is => 'rw');
has 'elapsed_time'       => (is => 'rw', default => sub {0} );  # seconds
has 'total_extrusion_length' => (is => 'rw', default => sub {0} );
has 'lifted'             => (is => 'rw', default => sub {0} );
has 'last_pos'           => (is => 'rw', default => sub { Slic3r::Point->new(0,0) } );
has 'last_speed'         => (is => 'rw', default => sub {""});
has 'last_f'             => (is => 'rw', default => sub {""});
has 'last_fan_speed'     => (is => 'rw', default => sub {0});
has 'wipe_path'          => (is => 'rw');
has 'dec'                => (is => 'ro', default => sub { 3 } );

# used for vibration limit:
has 'last_dir'           => (is => 'ro', default => sub { [0,0] });
has 'dir_time'           => (is => 'ro', default => sub { [0,0] });

sub _build_speeds {
    my $self = shift;
    return {
        map { $_ => 60 * $self->config->get_value("${_}_speed") }
            qw(travel perimeter small_perimeter external_perimeter infill
                solid_infill top_solid_infill support_material bridge gap_fill retract),
    };
}

# assign speeds to roles
my %role_speeds = (
    &EXTR_ROLE_PERIMETER                    => 'perimeter',
    &EXTR_ROLE_EXTERNAL_PERIMETER           => 'external_perimeter',
    &EXTR_ROLE_OVERHANG_PERIMETER           => 'external_perimeter',
    &EXTR_ROLE_CONTOUR_INTERNAL_PERIMETER   => 'perimeter',
    &EXTR_ROLE_FILL                         => 'infill',
    &EXTR_ROLE_SOLIDFILL                    => 'solid_infill',
    &EXTR_ROLE_TOPSOLIDFILL                 => 'top_solid_infill',
    &EXTR_ROLE_BRIDGE                       => 'bridge',
    &EXTR_ROLE_INTERNALBRIDGE               => 'solid_infill',
    &EXTR_ROLE_SKIRT                        => 'perimeter',
    &EXTR_ROLE_SUPPORTMATERIAL              => 'support_material',
    &EXTR_ROLE_GAPFILL                      => 'gap_fill',
);

sub set_shift {
    my $self = shift;
    my @shift = @_;
    
    # if shift increases (goes towards right), last_pos decreases because it goes towards left
    my @translate = (
        scale ($self->shift_x - $shift[X]),
        scale ($self->shift_y - $shift[Y]),
    );
    $self->last_pos->translate(@translate);
    $self->wipe_path->translate(@translate) if $self->wipe_path;
    
    $self->shift_x($shift[X]);
    $self->shift_y($shift[Y]);
}

sub change_layer {
    my $self = shift;
    my ($layer) = @_;
    
    $self->layer($layer);
    $self->_layer_overhangs(
        $layer->id > 0
            ? [ map $_->expolygon, grep $_->surface_type == S_TYPE_BOTTOM, map @{$_->slices}, @{$layer->regions} ]
            : []
        );
    if ($self->config->avoid_crossing_perimeters) {
        $self->layer_mp(Slic3r::GCode::MotionPlanner->new(
            islands => union_ex([ map @$_, @{$layer->slices} ], undef, 1),
        ));
    }
    
    my $gcode = "";
    if ($self->config->gcode_flavor =~ /^(?:makerware|sailfish)$/) {
        $gcode .= sprintf "M73 P%s%s\n",
            int(99 * ($layer->id / ($self->layer_count - 1))),
            ($self->config->gcode_comments ? ' ; update progress' : '');
    }
    return $gcode;
}

# this method accepts Z in scaled coordinates
sub move_z {
    my $self = shift;
    my ($z, $comment) = @_;
    
    $z *= &Slic3r::SCALING_FACTOR;
    $z += $self->config->z_offset;
    
    my $gcode = "";
    my $current_z = $self->z;
    if (!defined $current_z || $current_z != ($z + $self->lifted)) {
        $gcode .= $self->retract(move_z => $z) if $self->extruder->retract_layer_change;
        $self->speed('travel');
        $gcode .= $self->G0(undef, $z, 0, $comment || ('move to next layer (' . $self->layer->id . ')'))
            unless ($current_z // -1) != ($self->z // -1);
        $gcode .= $self->move_z_callback->() if defined $self->move_z_callback;
    }
    
    return $gcode;
}

sub extrude {
    my $self = shift;
    
    ($_[0]->isa('Slic3r::ExtrusionLoop') || $_[0]->isa('Slic3r::ExtrusionLoop::Packed'))
        ? $self->extrude_loop(@_)
        : $self->extrude_path(@_);
}

sub extrude_loop {
    my $self = shift;
    my ($loop, $description) = @_;
    
    # extrude all loops ccw
    $loop = $loop->unpack if $loop->isa('Slic3r::ExtrusionLoop::Packed');
    my $was_clockwise = $loop->polygon->make_counter_clockwise;
    
    # find the point of the loop that is closest to the current extruder position
    # or randomize if requested
    my $last_pos = $self->last_pos;
    if ($self->config->randomize_start && $loop->role == EXTR_ROLE_CONTOUR_INTERNAL_PERIMETER) {
        $last_pos = Slic3r::Point->new(scale $self->config->print_center->[X], scale $self->config->bed_size->[Y]);
        $last_pos->rotate(rand(2*PI), $self->config->print_center);
    }
    my $start_index = $loop->nearest_point_index_to($last_pos);
    
    # split the loop at the starting point and make a path
    my $extrusion_path = $loop->split_at_index($start_index);
    
    # clip the path to avoid the extruder to get exactly on the first point of the loop;
    # if polyline was shorter than the clipping distance we'd get a null polyline, so
    # we discard it in that case
    $extrusion_path->clip_end(scale $extrusion_path->flow_spacing * &Slic3r::LOOP_CLIPPING_LENGTH_OVER_SPACING);
    return '' if !@{$extrusion_path->polyline};
    
    my @paths = ();
    # detect overhanging/bridging perimeters
    if ($extrusion_path->is_perimeter && @{$self->_layer_overhangs}) {
        # get non-overhang paths by subtracting overhangs from the loop
        push @paths,
            $extrusion_path->subtract_expolygons($self->_layer_overhangs);
        
        # get overhang paths by intersecting overhangs with the loop
        push @paths,
            map { $_->role(EXTR_ROLE_OVERHANG_PERIMETER); $_ }
            $extrusion_path->intersect_expolygons($self->_layer_overhangs);
        
        # reapply the nearest point search for starting point
        # (TODO: choose the nearest point not on an overhang - make sure wipe and
        # inwards move consider the new actual starting point)
        @paths = Slic3r::ExtrusionPath::Collection
            ->new(paths => [@paths])
            ->chained_path($last_pos);
    } else {
        push @paths, $extrusion_path;
    }
    
    # extrude along the path
    my $gcode = join '', map $self->extrude_path($_, $description), @paths;
    $self->wipe_path($extrusion_path->polyline);
    
    # make a little move inwards before leaving loop
    if ($loop->role == EXTR_ROLE_EXTERNAL_PERIMETER && $self->config->perimeters > 1) {
        # detect angle between last and first segment
        # the side depends on the original winding order of the polygon (left for contours, right for holes)
        my @points = $was_clockwise ? (-2, 1) : (1, -2);
        my $angle = Slic3r::Geometry::angle3points(@{$extrusion_path->polyline}[0, @points]) / 3;
        $angle *= -1 if $was_clockwise;
        
        # create the destination point along the first segment and rotate it
        # we make sure we don't exceed the segment length because we don't know
        # the rotation of the second segment so we might cross the object boundary
        my $first_segment = Slic3r::Line->new(@{$extrusion_path->polyline}[0,1]);
        my $distance = min(scale $extrusion_path->flow_spacing, $first_segment->length);
        my $point = Slic3r::Geometry::point_along_segment(@$first_segment, $distance);
{'fraction_non_alphanumeric': 0.16099585062240665, 'fraction_numerical': 0.0073503260225251926, 'mean_word_length': 2.6079982891360136, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 365, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3263125', 'n_tokens_mistral': 5735, 'n_tokens_neox': 5645, 'n_words': 1357}