diff --git a/MANIFEST b/MANIFEST index a2eccc24..e4980408 100644 --- a/MANIFEST +++ b/MANIFEST @@ -24,6 +24,7 @@ lib/Slic3r/Format/STL.pm lib/Slic3r/Geometry.pm lib/Slic3r/Geometry/Clipper.pm lib/Slic3r/GUI.pm +lib/Slic3r/GUI/Dashboard.pm lib/Slic3r/GUI/OptionsGroup.pm lib/Slic3r/GUI/SkeinPanel.pm lib/Slic3r/Layer.pm @@ -33,7 +34,6 @@ lib/Slic3r/Polygon.pm lib/Slic3r/Polyline.pm lib/Slic3r/Print.pm lib/Slic3r/Print/Object.pm -lib/Slic3r/Skein.pm lib/Slic3r/Surface.pm lib/Slic3r/SVG.pm lib/Slic3r/TriangleMesh.pm diff --git a/README.markdown b/README.markdown index 2bd0beda..8e25787b 100644 --- a/README.markdown +++ b/README.markdown @@ -50,7 +50,7 @@ Roadmap includes the following goals: * output some statistics; * support material for internal perimeters; -* new and better GUI; +* more GUI work; * more fill patterns. ## Is it usable already? Any known limitation? @@ -95,7 +95,7 @@ The author is Alessandro Ranellucci (me). --post-process Generated G-code will be processed with the supplied script; call this more than once to process through multiple scripts. --export-svg Export a SVG file containing slices instead of G-code. - --merge If multiple files are supplied, they will be composed into a single + -m, --merge If multiple files are supplied, they will be composed into a single print rather than processed individually. Printer options: diff --git a/lib/Slic3r.pm b/lib/Slic3r.pm index adb615ca..3b77246b 100644 --- a/lib/Slic3r.pm +++ b/lib/Slic3r.pm @@ -33,7 +33,6 @@ use Slic3r::Polygon; use Slic3r::Polyline; use Slic3r::Print; use Slic3r::Print::Object; -use Slic3r::Skein; use Slic3r::Surface; use Slic3r::TriangleMesh; use Slic3r::TriangleMesh::IntersectionLine; diff --git a/lib/Slic3r/Config.pm b/lib/Slic3r/Config.pm index e504171a..2647c995 100644 --- a/lib/Slic3r/Config.pm +++ b/lib/Slic3r/Config.pm @@ -16,8 +16,8 @@ our $Options = { cli => 'notes=s', type => 's', multiline => 1, - width => 350, - height => 300, + width => 220, + height => 130, serialize => sub { join '\n', split /\R/, $_[0] }, deserialize => sub { join "\n", split /\\n/, $_[0] }, }, @@ -408,7 +408,7 @@ our $Options = { type => 'i', }, 'bed_size' => { - label => 'Bed size for autoarrange (mm)', + label => 'Bed size (mm)', cli => 'bed-size=s', type => 'point', serialize => sub { join ',', @{$_[0]} }, diff --git a/lib/Slic3r/Fill.pm b/lib/Slic3r/Fill.pm index 520278aa..677f3c5f 100644 --- a/lib/Slic3r/Fill.pm +++ b/lib/Slic3r/Fill.pm @@ -11,7 +11,7 @@ use Slic3r::Fill::Line; use Slic3r::Fill::OctagramSpiral; use Slic3r::Fill::PlanePath; use Slic3r::Fill::Rectilinear; -use Slic3r::Geometry qw(scale shortest_path); +use Slic3r::Geometry qw(X Y scale shortest_path); use Slic3r::Geometry::Clipper qw(union_ex diff_ex); @@ -34,7 +34,8 @@ sub BUILD { $self->fillers->{$_} ||= $FillTypes{$_}->new(print => $self->print) for ('rectilinear', $Slic3r::fill_pattern, $Slic3r::solid_fill_pattern); - my $max_print_dimension = $self->print->max_length * sqrt(2); + my $print_size = $self->print->size; + my $max_print_dimension = ($print_size->[X] > $print_size->[Y] ? $print_size->[X] : $print_size->[Y]) * sqrt(2); $_->max_print_dimension($max_print_dimension) for values %{$self->fillers}; } diff --git a/lib/Slic3r/Fill/Honeycomb.pm b/lib/Slic3r/Fill/Honeycomb.pm index 8f76bfd9..aa54cb04 100644 --- a/lib/Slic3r/Fill/Honeycomb.pm +++ b/lib/Slic3r/Fill/Honeycomb.pm @@ -39,7 +39,8 @@ sub fill_surface { # adjust actual bounding box to the nearest multiple of our hex pattern # and align it so that it matches across layers - my $bounding_box = [ 0, 0, $self->print->total_x_length, $self->print->total_y_length ]; + my $print_bounding_box = $self->print->bounding_box; + my $bounding_box = [ 0, 0, $print_bounding_box->[X2], $print_bounding_box->[Y2] ]; { my $bb_polygon = Slic3r::Polygon->new([ [ $bounding_box->[X1], $bounding_box->[Y1] ], diff --git a/lib/Slic3r/GUI.pm b/lib/Slic3r/GUI.pm index 5a24cbfe..b441036a 100644 --- a/lib/Slic3r/GUI.pm +++ b/lib/Slic3r/GUI.pm @@ -4,6 +4,7 @@ use warnings; use utf8; use FindBin; +use Slic3r::GUI::Dashboard; use Slic3r::GUI::OptionsGroup; use Slic3r::GUI::SkeinPanel; @@ -65,4 +66,22 @@ sub About { Wx::AboutBox($info); } +sub catch_error { + my ($self, $cb) = @_; + if (my $err = $@) { + $cb->() if $cb; + Wx::MessageDialog->new($self, $err, 'Error', &Wx::wxOK | &Wx::wxICON_ERROR)->ShowModal; + return 1; + } + return 0; +} + +sub warning_catcher { + my ($self) = @_; + return sub { + my $message = shift; + Wx::MessageDialog->new($self, $message, 'Warning', &Wx::wxOK | &Wx::wxICON_WARNING)->ShowModal; + }; +} + 1; diff --git a/lib/Slic3r/GUI/Dashboard.pm b/lib/Slic3r/GUI/Dashboard.pm new file mode 100644 index 00000000..dd9ee77c --- /dev/null +++ b/lib/Slic3r/GUI/Dashboard.pm @@ -0,0 +1,544 @@ +package Slic3r::GUI::Dashboard; +use strict; +use warnings; +use utf8; + +use File::Basename qw(basename dirname); +use Math::ConvexHull qw(convex_hull); +use Slic3r::Geometry qw(X Y X1 Y1 X2 Y2 scale unscale); +use Wx qw(:sizer :progressdialog wxOK wxICON_INFORMATION wxICON_WARNING wxICON_ERROR wxICON_QUESTION + wxOK wxCANCEL wxID_OK wxFD_OPEN wxFD_SAVE wxDEFAULT wxNORMAL); +use Wx::Event qw(EVT_BUTTON EVT_PAINT EVT_MOUSE_EVENTS EVT_LIST_ITEM_SELECTED EVT_LIST_ITEM_DESELECTED); +use base 'Wx::Panel'; + +sub new { + my $class = shift; + my ($parent) = @_; + my $self = $class->SUPER::new($parent, -1); + + $self->{canvas} = Wx::Panel->new($self, -1, [-1, -1], [300, 300]); + $self->{canvas}->SetBackgroundColour(Wx::wxWHITE); + EVT_PAINT($self->{canvas}, \&repaint); + EVT_MOUSE_EVENTS($self->{canvas}, \&mouse_event); + + $self->{objects_brush} = Wx::Brush->new(Wx::Colour->new(210,210,210), &Wx::wxSOLID); + $self->{selected_brush} = Wx::Brush->new(Wx::Colour->new(255,128,128), &Wx::wxSOLID); + $self->{transparent_brush} = Wx::Brush->new(Wx::Colour->new(0,0,0), &Wx::wxTRANSPARENT); + $self->{grid_pen} = Wx::Pen->new(Wx::Colour->new(230,230,230), 1, &Wx::wxSOLID); + $self->{skirt_pen} = Wx::Pen->new(Wx::Colour->new(150,150,150), 1, &Wx::wxSOLID); + + $self->{list} = Wx::ListView->new($self, -1, [-1, -1], [-1, 180], &Wx::wxLC_SINGLE_SEL | &Wx::wxLC_REPORT | &Wx::wxBORDER_DEFAULT); + $self->{list}->InsertColumn(0, "Name", &Wx::wxLIST_FORMAT_LEFT, 300); + $self->{list}->InsertColumn(1, "Copies", &Wx::wxLIST_FORMAT_CENTER, 50); + $self->{list}->InsertColumn(2, "Scale", &Wx::wxLIST_FORMAT_CENTER, 50); + EVT_LIST_ITEM_SELECTED($self, $self->{list}, \&list_item_selected); + EVT_LIST_ITEM_DESELECTED($self, $self->{list}, \&list_item_deselected); + + $self->{btn_load} = Wx::Button->new($self, -1, "Add…"); + $self->{btn_remove} = Wx::Button->new($self, -1, "Remove"); + $self->{btn_increase} = Wx::Button->new($self, -1, "+1 copy"); + $self->{btn_decrease} = Wx::Button->new($self, -1, "-1 copy"); + $self->{btn_rotate45cw} = Wx::Button->new($self, -1, "Rotate by 45° (cw)"); + $self->{btn_rotate45ccw} = Wx::Button->new($self, -1, "Rotate by 45° (ccw)"); + $self->{btn_reset} = Wx::Button->new($self, -1, "Clean"); + $self->{btn_arrange} = Wx::Button->new($self, -1, "Autoarrange"); + $self->{btn_changescale} = Wx::Button->new($self, -1, "Change Scale…"); + $self->{btn_export_gcode} = Wx::Button->new($self, -1, "Export G-code…"); + $self->{btn_export_gcode}->SetDefault; + $self->{$_}->SetWindowVariant(&Wx::wxWINDOW_VARIANT_SMALL) for grep /^btn_/, keys %$self; + $self->selection_changed(0); + $self->object_list_changed; + EVT_BUTTON($self, $self->{btn_load}, \&load); + EVT_BUTTON($self, $self->{btn_remove}, \&remove); + EVT_BUTTON($self, $self->{btn_increase}, \&increase); + EVT_BUTTON($self, $self->{btn_decrease}, \&decrease); + EVT_BUTTON($self, $self->{btn_rotate45cw}, sub { $_[0]->rotate(45) }); + EVT_BUTTON($self, $self->{btn_rotate45ccw}, sub { $_[0]->rotate(-45) }); + EVT_BUTTON($self, $self->{btn_reset}, \&reset); + EVT_BUTTON($self, $self->{btn_arrange}, \&arrange); + EVT_BUTTON($self, $self->{btn_changescale}, \&changescale); + EVT_BUTTON($self, $self->{btn_export_gcode}, \&export_gcode); + + $self->SetDropTarget(Slic3r::GUI::Dashboard::DropTarget->new($self)); + + # calculate scaling factor for preview + { + # supposing the preview canvas is square, calculate the scaling factor + # to constrain print bed area inside preview + my $canvas_side = $self->{canvas}->GetSize->GetWidth; + my $bed_largest_side = $Slic3r::bed_size->[X] > $Slic3r::bed_size->[Y] + ? $Slic3r::bed_size->[Y] : $Slic3r::bed_size->[X]; + $self->{scaling_factor} = $canvas_side / $bed_largest_side; + } + + $self->{print} = Slic3r::Print->new; + $self->{thumbnails} = []; # polygons, each one aligned to 0,0 + $self->{scale} = []; + $self->{object_previews} = []; # [ obj_idx, copy_idx, positioned polygon ] + $self->{selected_objects} = []; + $self->recenter; + + { + my $buttons1 = Wx::BoxSizer->new(wxVERTICAL); + $buttons1->Add($self->{"btn_$_"}) + for qw(load remove reset arrange export_gcode); + + my $buttons2 = Wx::BoxSizer->new(wxVERTICAL); + $buttons2->Add($self->{"btn_$_"}) + for qw(increase decrease rotate45cw rotate45ccw changescale); + + my $buttons_sizer = Wx::BoxSizer->new(wxHORIZONTAL); + $buttons_sizer->Add($_) for ($buttons1, $buttons2); + + my $vertical_sizer = Wx::BoxSizer->new(wxVERTICAL); + $vertical_sizer->Add($self->{list}, 0, wxEXPAND | wxALL); + $vertical_sizer->Add($buttons_sizer); + + my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); + $sizer->Add($self->{canvas}, 0, wxALL, 10); + $sizer->Add($vertical_sizer, 1, wxEXPAND | wxALL, 10); + $sizer->SetSizeHints($self); + $self->SetSizer($sizer); + } + return $self; +} + +sub load { + my $self = shift; + + my $dir = $Slic3r::GUI::SkeinPanel::last_skein_dir || $Slic3r::GUI::SkeinPanel::last_config_dir || ""; + my $dialog = Wx::FileDialog->new($self, 'Choose a STL or AMF file:', $dir, "", $Slic3r::GUI::SkeinPanel::model_wildcard, wxFD_OPEN); + if ($dialog->ShowModal != wxID_OK) { + $dialog->Destroy; + return; + } + my $input_file = $dialog->GetPaths; + $dialog->Destroy; + return $self->load_file($input_file); +} + +sub load_file { + my $self = shift; + my ($input_file) = @_; + + $Slic3r::GUI::SkeinPanel::last_input_file = $input_file; + + local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self); + my $object = $self->{print}->add_object_from_file($input_file); + my $obj_idx = $#{$self->{print}->objects}; + $self->{print}->arrange_objects; + + $self->{list}->InsertStringItem($obj_idx, basename($input_file)); + $self->{list}->SetItem($obj_idx, 1, "1"); + $self->{list}->SetItem($obj_idx, 2, "100%"); + $self->{list}->Select($obj_idx, 0); + push @{$self->{scale}}, 1; + + $self->make_thumbnail($obj_idx); + $self->recenter; + $self->{canvas}->Refresh; + $self->{list}->Update; + $self->{list}->Select($obj_idx, 1); + $self->object_list_changed; +} + +sub remove { + my $self = shift; + + foreach my $pobj (@{$self->{selected_objects}}) { + my ($obj_idx, $copy_idx) = ($pobj->[0], $pobj->[1]); + $self->{print}->copies->[$obj_idx][$copy_idx] = undef; + } + + my @objects_to_remove = (); + for my $obj_idx (0 .. $#{$self->{print}->objects}) { + my $copies = $self->{print}->copies->[$obj_idx]; + + # filter out removed copies + @$copies = grep defined $_, @$copies; + + # update copies count in list + $self->{list}->SetItem($obj_idx, 1, scalar @$copies); + + # if no copies are left, remove the object itself + push @objects_to_remove, $obj_idx if !@$copies; + } + for my $obj_idx (sort { $b <=> $a } @objects_to_remove) { + splice @{$self->{print}->objects}, $obj_idx, 1; + splice @{$self->{print}->copies}, $obj_idx, 1; + splice @{$self->{thumbnails}}, $obj_idx, 1; + splice @{$self->{scale}}, $obj_idx, 1; + $self->{list}->DeleteItem($obj_idx); + } + + $self->{selected_objects} = []; + $self->selection_changed(0); + $self->object_list_changed; + $self->recenter; + $self->{canvas}->Refresh; +} + +sub reset { + my $self = shift; + + @{$self->{print}->objects} = (); + @{$self->{print}->copies} = (); + @{$self->{thumbnails}} = (); + @{$self->{scale}} = (); + $self->{list}->DeleteAllItems; + + $self->{selected_objects} = []; + $self->selection_changed(0); + $self->object_list_changed; + $self->{canvas}->Refresh; +} + +sub increase { + my $self = shift; + + my $obj_idx = $self->selected_object_idx; + my $copies = $self->{print}->copies->[$obj_idx]; + push @$copies, [ $copies->[-1]->[X] + scale 10, $copies->[-1]->[Y] + scale 10 ]; + $self->{list}->SetItem($obj_idx, 1, scalar @$copies); + $self->arrange; +} + +sub decrease { + my $self = shift; + + my $obj_idx = $self->selected_object_idx; + $self->{selected_objects} = [ +(grep { $_->[0] == $obj_idx } @{$self->{object_previews}})[-1] ]; + $self->remove; + + if ($self->{print}->objects->[$obj_idx]) { + $self->{list}->Select($obj_idx, 0); + $self->{list}->Select($obj_idx, 1); + } +} + +sub rotate { + my $self = shift; + my ($angle) = @_; + + my $obj_idx = $self->selected_object_idx; + my $object = $self->{print}->objects->[$obj_idx]; + + # rotate, realign to 0,0 and update size + $object->mesh->rotate($angle); + $object->mesh->align_to_origin; + my @size = $object->mesh->size; + $object->x_length($size[X]); + $object->y_length($size[Y]); + + $self->make_thumbnail($obj_idx); + $self->arrange; + $self->recenter; + $self->{canvas}->Refresh; +} + +sub arrange { + my $self = shift; + + $self->{print}->arrange_objects; + $self->recenter; + $self->{canvas}->Refresh; +} + +sub changescale { + my $self = shift; + + my $obj_idx = $self->selected_object_idx; + my $scale = $self->{scale}[$obj_idx]; + $scale = Wx::GetNumberFromUser("", "Enter the scale % for the selected object:", "Scale", $scale*100, 0, 1000, $self); + return if !$scale || $scale == -1; + + my $object = $self->{print}->objects->[$obj_idx]; + my $mesh = $object->mesh; + $mesh->scale($scale/100 / $self->{scale}[$obj_idx]); + $object->mesh->align_to_origin; + my @size = $object->mesh->size; + $object->x_length($size[X]); + $object->y_length($size[Y]); + + $self->{scale}[$obj_idx] = $scale/100; + $self->{list}->SetItem($obj_idx, 2, "$scale%"); + + $self->{print}->arrange_objects; + $self->make_thumbnail($obj_idx); + $self->recenter; + $self->{canvas}->Refresh; +} + +sub export_gcode { + my $self = shift; + + my $process_dialog; + eval { + # validate configuration + Slic3r::Config->validate; + + my $print = $self->{print}; + + # select output file + my $output_file = $main::opt{output}; + { + $output_file = $print->expanded_output_filepath($output_file); + my $dlg = Wx::FileDialog->new($self, 'Save G-code file as:', dirname($output_file), + basename($output_file), $Slic3r::GUI::SkeinPanel::gcode_wildcard, wxFD_SAVE); + if ($dlg->ShowModal != wxID_OK) { + $dlg->Destroy; + return; + } + $output_file = $Slic3r::GUI::SkeinPanel::last_output_file = $dlg->GetPath; + $dlg->Destroy; + } + + # show processbar dialog + $process_dialog = Wx::ProgressDialog->new('Slicing...', "Processing input file...", + 100, $self, 0); + $process_dialog->Pulse; + + { + my @warnings = (); + local $SIG{__WARN__} = sub { push @warnings, $_[0] }; + my %params = ( + output_file => $output_file, + status_cb => sub { + my ($percent, $message) = @_; + if (&Wx::wxVERSION_STRING =~ / 2\.(8\.|9\.[2-9])/) { + $process_dialog->Update($percent, "$message..."); + } + }, + keep_meshes => 1, + ); + if ($params{export_svg}) { + $print->export_svg(%params); + } else { + $print->export_gcode(%params); + } + Slic3r::GUI::warning_catcher($self)->($_) for @warnings; + } + $process_dialog->Destroy; + undef $process_dialog; + + my $message = "Your files were successfully sliced"; + $message .= sprintf " in %d minutes and %.3f seconds", + int($print->processing_time/60), + $print->processing_time - int($print->processing_time/60)*60 + if $print->processing_time; + $message .= "."; + eval { + $self->{growler}->notify(Event => 'SKEIN_DONE', Title => 'Slicing Done!', Message => $message) + if ($self->{growler}); + }; + Wx::MessageDialog->new($self, $message, 'Done!', + wxOK | wxICON_INFORMATION)->ShowModal; + }; + Slic3r::GUI::catch_error($self, sub { $process_dialog->Destroy if $process_dialog }); +} + +sub make_thumbnail { + my $self = shift; + my ($obj_idx) = @_; + + my $object = $self->{print}->objects->[$obj_idx]; + my @points = map [ @$_[X,Y] ], @{$object->mesh->vertices}; + my $convex_hull = Slic3r::Polygon->new(convex_hull(\@points)); + for (@$convex_hull) { + @$_ = map $self->to_pixel($_), @$_; + } + $convex_hull->simplify(0.3); + $self->{thumbnails}->[$obj_idx] = $convex_hull; +} + +sub recenter { + my $self = shift; + + # calculate displacement needed to center the print + my @print_bb = $self->{print}->bounding_box; + @print_bb = (0,0,0,0) if !defined $print_bb[0]; + $self->{shift} = [ + ($self->{canvas}->GetSize->GetWidth - ($self->to_pixel($print_bb[X2] + $print_bb[X1]))) / 2, + ($self->{canvas}->GetSize->GetHeight - ($self->to_pixel($print_bb[Y2] + $print_bb[Y1]))) / 2, + ]; +} + +sub repaint { + my ($self, $event) = @_; + my $parent = $self->GetParent; + my $print = $parent->{print}; + + my $dc = Wx::PaintDC->new($self); + my $size = $self->GetSize; + my @size = ($size->GetWidth, $size->GetHeight); + + # draw grid + $dc->SetPen($parent->{grid_pen}); + my $step = 10 * $parent->{scaling_factor}; + for (my $x = $step; $x <= $size[X]; $x += $step) { + $dc->DrawLine($x, 0, $x, $size[Y]); + } + for (my $y = $step; $y <= $size[Y]; $y += $step) { + $dc->DrawLine(0, $y, $size[X], $y); + } + + # draw frame + $dc->SetPen(Wx::wxBLACK_PEN); + $dc->SetBrush($parent->{transparent_brush}); + $dc->DrawRectangle(0, 0, @size); + + # draw text if plate is empty + if (!@{$print->objects}) { + $dc->SetTextForeground(Wx::Colour->new(150,50,50)); + $dc->DrawLabel("Drag your objects here", Wx::Rect->new(0, 0, $self->GetSize->GetWidth, $self->GetSize->GetHeight), &Wx::wxALIGN_CENTER_HORIZONTAL | &Wx::wxALIGN_CENTER_VERTICAL); + } + + # draw thumbnails + $dc->SetPen(Wx::wxBLACK_PEN); + @{$parent->{object_previews}} = (); + for my $obj_idx (0 .. $#{$print->objects}) { + for my $copy_idx (0 .. $#{$print->copies->[$obj_idx]}) { + my $copy = $print->copies->[$obj_idx][$copy_idx]; + push @{$parent->{object_previews}}, [ $obj_idx, $copy_idx, $parent->{thumbnails}[$obj_idx]->clone ]; + $parent->{object_previews}->[-1][2]->translate(map $parent->to_pixel($copy->[$_]) + $parent->{shift}[$_], (X,Y)); + + if (grep { $_->[0] == $obj_idx } @{$parent->{selected_objects}}) { + $dc->SetBrush($parent->{selected_brush}); + } else { + $dc->SetBrush($parent->{objects_brush}); + } + $dc->DrawPolygon($parent->_y($parent->{object_previews}->[-1][2]), 0, 0); + } + } + + # draw skirt + if (@{$parent->{object_previews}} && $Slic3r::skirts) { + my $convex_hull = Slic3r::Polygon->new(convex_hull([ map @{$_->[2]}, @{$parent->{object_previews}} ])); + $convex_hull = +($convex_hull->offset($Slic3r::skirt_distance * $parent->{scaling_factor}, 1))[0]; + $dc->SetPen($parent->{skirt_pen}); + $dc->SetBrush($parent->{transparent_brush}); + $dc->DrawPolygon($parent->_y($convex_hull), 0, 0) if $convex_hull; + } + + $event->Skip; +} + +sub mouse_event { + my ($self, $event) = @_; + my $parent = $self->GetParent; + my $print = $parent->{print}; + + my $point = $event->GetPosition; + my $pos = $parent->_y([[$point->x, $point->y]])->[0]; #]] + if ($event->ButtonDown(&Wx::wxMOUSE_BTN_LEFT)) { + $parent->{selected_objects} = []; + $parent->{list}->Select($parent->{list}->GetFirstSelected, 0); + $parent->selection_changed(0); + for my $preview (@{$parent->{object_previews}}) { + if ($preview->[2]->encloses_point($pos)) { + $parent->{selected_objects} = [$preview]; + $parent->{list}->Select($preview->[0], 1); + $parent->selection_changed(1); + my $copy = $print->copies->[ $preview->[0] ]->[ $preview->[1] ]; + $self->{drag_start_pos} = [ map $pos->[$_] - $parent->{shift}[$_] - $parent->to_pixel($copy->[$_]), X,Y ]; # displacement between the click and the copy's origin + $self->{drag_object} = $preview; + } + } + $parent->Refresh; + } elsif ($event->ButtonUp(&Wx::wxMOUSE_BTN_LEFT)) { + $parent->recenter; + $parent->Refresh; + $self->{drag_start_pos} = undef; + $self->{drag_object} = undef; + } elsif ($event->Dragging) { + return if !$self->{drag_start_pos}; # concurrency problems + for my $obj ($self->{drag_object}) { + my $copy = $print->copies->[ $obj->[0] ]->[ $obj->[1] ]; + $copy->[$_] = $parent->to_scaled($pos->[$_] - $self->{drag_start_pos}[$_] - $parent->{shift}[$_]) for X,Y; + $parent->Refresh; + } + } +} + +sub list_item_deselected { + my ($self, $event) = @_; + + if ($self->{list}->GetFirstSelected == -1) { + $self->{selected_objects} = []; + $self->{canvas}->Refresh; + $self->selection_changed(0); + } +} + +sub list_item_selected { + my ($self, $event) = @_; + + my $obj_idx = $event->GetIndex; + $self->{selected_objects} = [ grep $_->[0] == $obj_idx, @{$self->{object_previews}} ]; + $self->{canvas}->Refresh; + $self->selection_changed(1); +} + +sub object_list_changed { + my $self = shift; + + my $method = $self->{print} && @{$self->{print}->objects} ? 'Enable' : 'Disable'; + $self->{$_}->$method + for qw(btn_reset btn_arrange btn_export_gcode); +} + +sub selection_changed { + my $self = shift; + my ($have_sel) = @_; + + my $method = $have_sel ? 'Enable' : 'Disable'; + $self->{$_}->$method + for qw(btn_remove btn_increase btn_decrease btn_rotate45cw btn_rotate45ccw btn_changescale); +} + +sub selected_object_idx { + my $self = shift; + return $self->{selected_objects}[0][0] || $self->{list}->GetFirstSelected; +} + +sub to_pixel { + my $self = shift; + return unscale $_[0] * $self->{scaling_factor}; +} + +sub to_scaled { + my $self = shift; + return scale $_[0] / $self->{scaling_factor}; +} + +sub _y { + my $self = shift; + my ($points) = @_; + my $height = $self->{canvas}->GetSize->GetHeight; + return [ map [ $_->[X], $height - $_->[Y] ], @$points ]; +} + +package Slic3r::GUI::Dashboard::DropTarget; + +use Wx::DND; +use base 'Wx::FileDropTarget'; + +sub new { + my $class = shift; + my ($window) = @_; + my $self = $class->SUPER::new; + $self->{window} = $window; + return $self; +} + +sub OnDropFiles { + my $self = shift; + my ($x, $y, $filenames) = @_; + + # only accept STL and AMF files + return 0 if grep !/\.(?:stl|amf(?:\.xml)?)$/i, @$filenames; + + $self->{window}->load_file($_) for @$filenames; +} + +1; diff --git a/lib/Slic3r/GUI/OptionsGroup.pm b/lib/Slic3r/GUI/OptionsGroup.pm index a695fe9b..99311775 100644 --- a/lib/Slic3r/GUI/OptionsGroup.pm +++ b/lib/Slic3r/GUI/OptionsGroup.pm @@ -8,7 +8,7 @@ use base 'Wx::StaticBoxSizer'; # not very elegant, but this solution is temporary waiting for a better GUI -our @reload_callbacks = (\&update_duplicate_controls); +our @reload_callbacks = (); our %fields = (); # $key => [$control] sub new { @@ -83,7 +83,6 @@ sub new { $field = Wx::Choice->new($parent, -1, Wx::wxDefaultPosition, Wx::wxDefaultSize, $opt->{labels} || $opt->{values}); EVT_CHOICE($parent, $field, sub { Slic3r::Config->set($opt_key, $opt->{values}[$field->GetSelection]); - update_duplicate_controls() if $opt_key eq 'duplicate_mode'; }); push @reload_callbacks, sub { my $value = Slic3r::Config->get($opt_key); @@ -102,19 +101,4 @@ sub new { return $self; } -sub update_duplicate_controls { - # prevent infinite loops when calling ourselves - return if +(caller 1)[3] =~ /::update_duplicate_controls$/; - - my $value = Slic3r::Config->get('duplicate_mode'); - $_->Enable($value eq 'autoarrange') for @{$fields{duplicate}}; - $_->Enable($value eq 'autoarrange') for @{$fields{bed_size}}; - $_->Enable($value eq 'grid') for @{$fields{duplicate_grid}}; - $_->Enable($value ne 'no') for @{$fields{duplicate_distance}}; - Slic3r::Config->set('duplicate', 1) if $value ne 'autoarrange'; - Slic3r::Config->set('duplicate_grid', [1,1]) if $value ne 'grid'; - $fields{duplicate}[0]->GetParent->Refresh; - $_->() for @reload_callbacks; # apply new values -} - 1; diff --git a/lib/Slic3r/GUI/SkeinPanel.pm b/lib/Slic3r/GUI/SkeinPanel.pm index 5f7eff21..f4331240 100644 --- a/lib/Slic3r/GUI/SkeinPanel.pm +++ b/lib/Slic3r/GUI/SkeinPanel.pm @@ -10,10 +10,10 @@ use Wx qw(:sizer :progressdialog wxOK wxICON_INFORMATION wxICON_WARNING wxICON_E use Wx::Event qw(EVT_BUTTON); use base 'Wx::Panel'; -my $last_skein_dir; -my $last_config_dir; -my $last_input_file; -my $last_output_file; +our $last_skein_dir; +our $last_config_dir; +our $last_input_file; +our $last_output_file; our $last_config; sub new { @@ -24,7 +24,7 @@ sub new { my %panels = ( printer => { title => 'Printer', - options => [qw(nozzle_diameter print_center z_offset gcode_flavor use_relative_e_distances)], + options => [qw(nozzle_diameter bed_size print_center z_offset gcode_flavor use_relative_e_distances)], }, filament => { title => 'Filament', @@ -59,12 +59,8 @@ sub new { title => 'Skirt', options => [qw(skirts skirt_distance skirt_height)], }, - transform => { - title => 'Transform', - options => [qw(scale rotate duplicate_mode duplicate bed_size duplicate_grid duplicate_distance)], - }, gcode => { - title => 'Custom G-code', + title => 'G-code', options => [qw(start_gcode end_gcode layer_gcode gcode_comments post_process)], }, extrusion => { @@ -110,26 +106,25 @@ sub new { }; my @tabs = ( - $make_tab->([qw(transform accuracy skirt)], [qw(print retract)]), + $make_tab->([qw(accuracy skirt retract)], [qw(print notes)]), $make_tab->([qw(cooling)]), $make_tab->([qw(printer filament)], [qw(print_speed speed)]), $make_tab->([qw(gcode)]), - $make_tab->([qw(notes)]), $make_tab->([qw(extrusion)], [qw(output)]), ); + $tabpanel->AddPage(Slic3r::GUI::Dashboard->new($tabpanel), "Dashboard"); $tabpanel->AddPage($tabs[0], "Print Settings"); $tabpanel->AddPage($tabs[1], "Cooling"); $tabpanel->AddPage($tabs[2], "Printer and Filament"); - $tabpanel->AddPage($tabs[3], "Custom G-code"); - $tabpanel->AddPage($tabs[4], "Notes"); - $tabpanel->AddPage($tabs[5], "Advanced"); + $tabpanel->AddPage($tabs[3], "G-code"); + $tabpanel->AddPage($tabs[4], "Advanced"); my $buttons_sizer; { $buttons_sizer = Wx::BoxSizer->new(wxHORIZONTAL); - my $slice_button = Wx::Button->new($self, -1, "Slice..."); + my $slice_button = Wx::Button->new($self, -1, "Quick slice…"); $slice_button->SetDefault(); $buttons_sizer->Add($slice_button, 0, wxRIGHT, 20); EVT_BUTTON($self, $slice_button, sub { $self->do_slice }); @@ -161,9 +156,9 @@ sub new { return $self; } -my $model_wildcard = "STL files (*.stl)|*.stl;*.STL|AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"; -my $ini_wildcard = "INI files *.ini|*.ini;*.INI"; -my $gcode_wildcard = "G-code files *.gcode|*.gcode;*.GCODE"; +our $model_wildcard = "STL files (*.stl)|*.stl;*.STL|AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"; +our $ini_wildcard = "INI files *.ini|*.ini;*.INI"; +our $gcode_wildcard = "G-code files *.gcode|*.gcode;*.GCODE"; sub do_slice { my $self = shift; @@ -212,24 +207,15 @@ sub do_slice { my $input_file_basename = basename($input_file); $last_skein_dir = dirname($input_file); - my $skein = Slic3r::Skein->new( - input_file => $input_file, - output_file => $main::opt{output}, - status_cb => sub { - my ($percent, $message) = @_; - if (&Wx::wxVERSION_STRING =~ / 2\.(8\.|9\.[2-9])/) { - $process_dialog->Update($percent, "$message..."); - } - }, - ); + my $print = Slic3r::Print->new; + $print->add_object_from_file($input_file); # select output file + my $output_file = $main::opt{output}; if ($params{reslice}) { - if (defined $last_output_file) { - $skein->output_file($last_output_file); - } + $output_file = $last_output_file if defined $last_output_file; } elsif ($params{save_as}) { - my $output_file = $skein->expanded_output_filepath; + $output_file = $print->expanded_output_filepath($output_file); $output_file =~ s/\.gcode$/.svg/i if $params{export_svg}; my $dlg = Wx::FileDialog->new($self, 'Save ' . ($params{export_svg} ? 'SVG' : 'G-code') . ' file as:', dirname($output_file), basename($output_file), $gcode_wildcard, wxFD_SAVE); @@ -237,8 +223,7 @@ sub do_slice { $dlg->Destroy; return; } - $skein->output_file($dlg->GetPath); - $last_output_file = $dlg->GetPath; + $output_file = $last_output_file = $dlg->GetPath; $dlg->Destroy; } @@ -250,21 +235,30 @@ sub do_slice { { my @warnings = (); local $SIG{__WARN__} = sub { push @warnings, $_[0] }; + my %params = ( + output_file => $output_file, + status_cb => sub { + my ($percent, $message) = @_; + if (&Wx::wxVERSION_STRING =~ / 2\.(8\.|9\.[2-9])/) { + $process_dialog->Update($percent, "$message..."); + } + }, + ); if ($params{export_svg}) { - $skein->export_svg; + $print->export_svg(%params); } else { - $skein->go; + $print->export_gcode(%params); } - $self->catch_warning->($_) for @warnings; + Slic3r::GUI::warning_catcher($self)->($_) for @warnings; } $process_dialog->Destroy; undef $process_dialog; my $message = "$input_file_basename was successfully sliced"; $message .= sprintf " in %d minutes and %.3f seconds", - int($skein->processing_time/60), - $skein->processing_time - int($skein->processing_time/60)*60 - if $skein->processing_time; + int($print->processing_time/60), + $print->processing_time - int($print->processing_time/60)*60 + if $print->processing_time; $message .= "."; eval { $self->{growler}->notify(Event => 'SKEIN_DONE', Title => 'Slicing Done!', Message => $message) @@ -273,7 +267,7 @@ sub do_slice { Wx::MessageDialog->new($self, $message, 'Done!', wxOK | wxICON_INFORMATION)->ShowModal; }; - $self->catch_error(sub { $process_dialog->Destroy if $process_dialog }); + Slic3r::GUI::catch_error($self, sub { $process_dialog->Destroy if $process_dialog }); } sub save_config { @@ -284,7 +278,7 @@ sub save_config { # validate configuration Slic3r::Config->validate; }; - $self->catch_error(sub { $process_dialog->Destroy if $process_dialog }) and return; + Slic3r::GUI::catch_error($self, sub { $process_dialog->Destroy if $process_dialog }) and return; my $dir = $last_config ? dirname($last_config) : $last_config_dir || $last_skein_dir || ""; my $filename = $last_config ? basename($last_config) : "config.ini"; @@ -310,7 +304,7 @@ sub load_config { $last_config_dir = dirname($file); $last_config = $file; eval { - local $SIG{__WARN__} = $self->catch_warning; + local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self); Slic3r::Config->load($file); }; $self->catch_error(); @@ -319,22 +313,4 @@ sub load_config { $dlg->Destroy; } -sub catch_error { - my ($self, $cb) = @_; - if (my $err = $@) { - $cb->() if $cb; - Wx::MessageDialog->new($self, $err, 'Error', wxOK | wxICON_ERROR)->ShowModal; - return 1; - } - return 0; -} - -sub catch_warning { - my ($self) = @_; - return sub { - my $message = shift; - Wx::MessageDialog->new($self, $message, 'Warning', wxOK | wxICON_WARNING)->ShowModal; - }; -}; - 1; diff --git a/lib/Slic3r/Geometry.pm b/lib/Slic3r/Geometry.pm index 7a30499b..304a0fec 100644 --- a/lib/Slic3r/Geometry.pm +++ b/lib/Slic3r/Geometry.pm @@ -875,4 +875,112 @@ sub douglas_peucker2 { return [ map $points->[$_], sort keys %keep ]; } +sub arrange { + my ($total_parts, $partx, $party, $areax, $areay, $dist) = @_; + + my $linint = sub { + my ($value, $oldmin, $oldmax, $newmin, $newmax) = @_; + return ($value - $oldmin) * ($newmax - $newmin) / ($oldmax - $oldmin) + $newmin; + }; + + # use actual part size (the largest) plus separation distance (half on each side) in spacing algorithm + $partx += $dist; + $party += $dist; + + # margin needed for the skirt + my $skirt_margin; + if ($Slic3r::skirts > 0) { + $skirt_margin = ($Slic3r::flow_spacing * $Slic3r::skirts + $Slic3r::skirt_distance) * 2; + } else { + $skirt_margin = 0; + } + + # this is how many cells we have available into which to put parts + my $cellw = int(($areax - $skirt_margin + $dist) / $partx); + my $cellh = int(($areay - $skirt_margin + $dist) / $party); + + die "$total_parts parts won't fit in your print area!\n" if $total_parts > ($cellw * $cellh); + + # width and height of space used by cells + my $w = $cellw * $partx; + my $h = $cellh * $party; + + # left and right border positions of space used by cells + my $l = ($areax - $w) / 2; + my $r = $l + $w; + + # top and bottom border positions + my $t = ($areay - $h) / 2; + my $b = $t + $h; + + # list of cells, sorted by distance from center + my @cellsorder; + + # work out distance for all cells, sort into list + for my $i (0..$cellw-1) { + for my $j (0..$cellh-1) { + my $cx = $linint->($i + 0.5, 0, $cellw, $l, $r); + my $cy = $linint->($j + 0.5, 0, $cellh, $t, $b); + + my $xd = abs(($areax / 2) - $cx); + my $yd = abs(($areay / 2) - $cy); + + my $c = { + location => [$cx, $cy], + index => [$i, $j], + distance => $xd * $xd + $yd * $yd - abs(($cellw / 2) - ($i + 0.5)), + }; + + BINARYINSERTIONSORT: { + my $index = $c->{distance}; + my $low = 0; + my $high = @cellsorder; + while ($low < $high) { + my $mid = ($low + (($high - $low) / 2)) | 0; + my $midval = $cellsorder[$mid]->[0]; + + if ($midval < $index) { + $low = $mid + 1; + } elsif ($midval > $index) { + $high = $mid; + } else { + splice @cellsorder, $mid, 0, [$index, $c]; + last BINARYINSERTIONSORT; + } + } + splice @cellsorder, $low, 0, [$index, $c]; + } + } + } + + # the extents of cells actually used by objects + my ($lx, $ty, $rx, $by) = (0, 0, 0, 0); + + # now find cells actually used by objects, map out the extents so we can position correctly + for my $i (1..$total_parts) { + my $c = $cellsorder[$i - 1]; + my $cx = $c->[1]->{index}->[0]; + my $cy = $c->[1]->{index}->[1]; + if ($i == 1) { + $lx = $rx = $cx; + $ty = $by = $cy; + } else { + $rx = $cx if $cx > $rx; + $lx = $cx if $cx < $lx; + $by = $cy if $cy > $by; + $ty = $cy if $cy < $ty; + } + } + # now we actually place objects into cells, positioned such that the left and bottom borders are at 0 + my @positions = (); + for (1..$total_parts) { + my $c = shift @cellsorder; + my $cx = $c->[1]->{index}->[0] - $lx; + my $cy = $c->[1]->{index}->[1] - $ty; + + push @positions, [$cx * $partx, $cy * $party]; + } + return @positions; +} + 1; diff --git a/lib/Slic3r/Print.pm b/lib/Slic3r/Print.pm index e3faa9bb..b6970d97 100644 --- a/lib/Slic3r/Print.pm +++ b/lib/Slic3r/Print.pm @@ -1,15 +1,16 @@ package Slic3r::Print; use Moo; +use File::Basename qw(basename fileparse); use Math::ConvexHull 1.0.4 qw(convex_hull); -use Slic3r::Geometry qw(X Y Z PI scale unscale move_points); +use Slic3r::Geometry qw(X Y Z X1 Y1 X2 Y2 PI scale unscale move_points); use Slic3r::Geometry::Clipper qw(diff_ex union_ex offset JT_ROUND); +use Time::HiRes qw(gettimeofday tv_interval); -has 'objects' => (is => 'rw', default => sub {[]}); -has 'copies' => (is => 'rw', default => sub {[]}); # obj_idx => [copies...] -has 'total_x_length' => (is => 'rw'); # including duplicates -has 'total_y_length' => (is => 'rw'); # including duplicates +has 'objects' => (is => 'rw', default => sub {[]}); +has 'copies' => (is => 'rw', default => sub {[]}); # obj_idx => [copies...] has 'total_extrusion_length' => (is => 'rw'); +has 'processing_time' => (is => 'rw', required => 0); # ordered collection of extrusion paths to build skirt loops has 'skirt' => ( @@ -18,6 +19,26 @@ has 'skirt' => ( default => sub { [] }, ); +sub add_object_from_file { + my $self = shift; + my ($input_file) = @_; + + my $object; + if ($input_file =~ /\.stl$/i) { + my $mesh = Slic3r::Format::STL->read_file($input_file); + $mesh->check_manifoldness; + $object = $self->add_object_from_mesh($mesh); + } elsif ( $input_file =~ /\.amf(\.xml)?$/i) { + my ($materials, $meshes_by_material) = Slic3r::Format::AMF->read_file($input_file); + $_->check_manifoldness for values %$meshes_by_material; + $object = $self->add_object_from_mesh($meshes_by_material->{_} || +(values %$meshes_by_material)[0]); + } else { + die "Input file must have .stl or .amf(.xml) extension\n"; + } + $object->input_file($input_file); + return $object; +} + sub add_object_from_mesh { my $self = shift; my ($mesh) = @_; @@ -29,123 +50,13 @@ sub add_object_from_mesh { # initialize print object my @size = $mesh->size; my $object = Slic3r::Print::Object->new( + mesh => $mesh, x_length => $size[X], y_length => $size[Y], ); - # process facets - { - my $apply_lines = sub { - my $lines = shift; - foreach my $layer_id (keys %$lines) { - my $layer = $object->layer($layer_id); - $layer->add_line($_) for @{ $lines->{$layer_id} }; - } - }; - Slic3r::parallelize( - disable => ($#{$mesh->facets} < 500), # don't parallelize when too few facets - items => [ 0..$#{$mesh->facets} ], - thread_cb => sub { - my $q = shift; - my $result_lines = {}; - while (defined (my $facet_id = $q->dequeue)) { - my $lines = $mesh->slice_facet($object, $facet_id); - foreach my $layer_id (keys %$lines) { - $result_lines->{$layer_id} ||= []; - push @{ $result_lines->{$layer_id} }, @{ $lines->{$layer_id} }; - } - } - return $result_lines; - }, - collect_cb => sub { - $apply_lines->($_[0]); - }, - no_threads_cb => sub { - for (0..$#{$mesh->facets}) { - my $lines = $mesh->slice_facet($object, $_); - $apply_lines->($lines); - } - }, - ); - } - die "Invalid input file\n" if !@{$object->layers}; - - # remove last layer if empty - # (we might have created it because of the $max_layer = ... + 1 code below) - pop @{$object->layers} if !@{$object->layers->[-1]->surfaces} && !@{$object->layers->[-1]->lines}; - - foreach my $layer (@{ $object->layers }) { - Slic3r::debugf "Making surfaces for layer %d (slice z = %f):\n", - $layer->id, unscale $layer->slice_z if $Slic3r::debug; - - # layer currently has many lines representing intersections of - # model facets with the layer plane. there may also be lines - # that we need to ignore (for example, when two non-horizontal - # facets share a common edge on our plane, we get a single line; - # however that line has no meaning for our layer as it's enclosed - # inside a closed polyline) - - # build surfaces from sparse lines - $layer->make_surfaces($mesh->make_loops($layer)); - - # free memory - $layer->lines(undef); - } - - # detect slicing errors - my $warning_thrown = 0; - for my $i (0 .. $#{$object->layers}) { - my $layer = $object->layers->[$i]; - next unless $layer->slicing_errors; - if (!$warning_thrown) { - warn "The model has overlapping or self-intersecting facets. I tried to repair it, " - . "however you might want to check the results or repair the input file and retry.\n"; - $warning_thrown = 1; - } - - # try to repair the layer surfaces by merging all contours and all holes from - # neighbor layers - Slic3r::debugf "Attempting to repair layer %d\n", $i; - - my (@upper_surfaces, @lower_surfaces); - for (my $j = $i+1; $j <= $#{$object->layers}; $j++) { - if (!$object->layers->[$j]->slicing_errors) { - @upper_surfaces = @{$object->layers->[$j]->slices}; - last; - } - } - for (my $j = $i-1; $j >= 0; $j--) { - if (!$object->layers->[$j]->slicing_errors) { - @lower_surfaces = @{$object->layers->[$j]->slices}; - last; - } - } - - my $union = union_ex([ - map $_->expolygon->contour, @upper_surfaces, @lower_surfaces, - ]); - my $diff = diff_ex( - [ map @$_, @$union ], - [ map $_->expolygon->holes, @upper_surfaces, @lower_surfaces, ], - ); - - @{$layer->slices} = map Slic3r::Surface->new - (expolygon => $_, surface_type => 'internal'), - @$diff; - } - - # remove empty layers from bottom - while (@{$object->layers} && !@{$object->layers->[0]->slices} && !@{$object->layers->[0]->thin_walls}) { - shift @{$object->layers}; - for (my $i = 0; $i <= $#{$object->layers}; $i++) { - $object->layers->[$i]->id($i); - } - } - - warn "No layers were detected. You might want to repair your STL file and retry.\n" - if !@{$object->layers}; - push @{$self->objects}, $object; + push @{$self->copies}, [[0, 0]]; return $object; } @@ -158,21 +69,18 @@ sub layer_count { return $count; } -sub arrange_objects { +sub duplicate { my $self = shift; - my $dist = scale $Slic3r::duplicate_distance; - if ($Slic3r::duplicate_grid->[X] > 1 || $Slic3r::duplicate_grid->[Y] > 1) { if (@{$self->objects} > 1) { die "Grid duplication is not supported with multiple objects\n"; } my $object = $self->objects->[0]; - $self->total_x_length($object->x_length * $Slic3r::duplicate_grid->[X] + $dist * ($Slic3r::duplicate_grid->[X] - 1)); - $self->total_y_length($object->y_length * $Slic3r::duplicate_grid->[Y] + $dist * ($Slic3r::duplicate_grid->[Y] - 1)); # generate offsets for copies - push @{$self->copies}, []; + my $dist = scale $Slic3r::duplicate_distance; + @{$self->copies->[0]} = (); for my $x_copy (1..$Slic3r::duplicate_grid->[X]) { for my $y_copy (1..$Slic3r::duplicate_grid->[Y]) { push @{$self->copies->[0]}, [ @@ -181,132 +89,247 @@ sub arrange_objects { ]; } } - } elsif ($Slic3r::duplicate > 1 || @{$self->objects} > 1) { - my $total_parts = @{$self->objects} * $Slic3r::duplicate; - my $linint = sub { - my ($value, $oldmin, $oldmax, $newmin, $newmax) = @_; - return ($value - $oldmin) * ($newmax - $newmin) / ($oldmax - $oldmin) + $newmin; - }; - - # use actual part size (the largest) plus separation distance (half on each side) in spacing algorithm - my $partx = my $party = 0; - foreach my $object (@{$self->objects}) { - $partx = $object->x_length if $object->x_length > $partx; - $party = $object->y_length if $object->y_length > $party; + } elsif ($Slic3r::duplicate > 1) { + foreach my $copies (@{$self->copies}) { + @$copies = map [0,0], 1..$Slic3r::duplicate; } - $partx = unscale($partx) + $Slic3r::duplicate_distance; - $party = unscale($party) + $Slic3r::duplicate_distance; - - # margin needed for the skirt - my $skirt_margin; - if ($Slic3r::skirts > 0) { - $skirt_margin = ($Slic3r::flow_spacing * $Slic3r::skirts + $Slic3r::skirt_distance) * 2; - } else { - $skirt_margin = 0; - } - - # this is how many cells we have available into which to put parts - my $cellw = int(($Slic3r::bed_size->[X] - $skirt_margin + $Slic3r::duplicate_distance) / $partx); - my $cellh = int(($Slic3r::bed_size->[Y] - $skirt_margin + $Slic3r::duplicate_distance) / $party); - - die "$total_parts parts won't fit in your print area!\n" if $total_parts > ($cellw * $cellh); - - # width and height of space used by cells - my $w = $cellw * $partx; - my $h = $cellh * $party; - - # left and right border positions of space used by cells - my $l = ($Slic3r::bed_size->[X] - $w) / 2; - my $r = $l + $w; - - # top and bottom border positions - my $t = ($Slic3r::bed_size->[Y] - $h) / 2; - my $b = $t + $h; - - # list of cells, sorted by distance from center - my @cellsorder; - - # work out distance for all cells, sort into list - for my $i (0..$cellw-1) { - for my $j (0..$cellh-1) { - my $cx = $linint->($i + 0.5, 0, $cellw, $l, $r); - my $cy = $linint->($j + 0.5, 0, $cellh, $t, $b); - - my $xd = abs(($Slic3r::bed_size->[X] / 2) - $cx); - my $yd = abs(($Slic3r::bed_size->[Y] / 2) - $cy); - - my $c = { - location => [$cx, $cy], - index => [$i, $j], - distance => $xd * $xd + $yd * $yd - abs(($cellw / 2) - ($i + 0.5)), - }; - - BINARYINSERTIONSORT: { - my $index = $c->{distance}; - my $low = 0; - my $high = @cellsorder; - while ($low < $high) { - my $mid = ($low + (($high - $low) / 2)) | 0; - my $midval = $cellsorder[$mid]->[0]; - - if ($midval < $index) { - $low = $mid + 1; - } elsif ($midval > $index) { - $high = $mid; - } else { - splice @cellsorder, $mid, 0, [$index, $c]; - last BINARYINSERTIONSORT; - } - } - splice @cellsorder, $low, 0, [$index, $c]; - } - } - } - - # the extents of cells actually used by objects - my ($lx, $ty, $rx, $by) = (0, 0, 0, 0); - - # now find cells actually used by objects, map out the extents so we can position correctly - for my $i (1..$total_parts) { - my $c = $cellsorder[$i - 1]; - my $cx = $c->[1]->{index}->[0]; - my $cy = $c->[1]->{index}->[1]; - if ($i == 1) { - $lx = $rx = $cx; - $ty = $by = $cy; - } else { - $rx = $cx if $cx > $rx; - $lx = $cx if $cx < $lx; - $by = $cy if $cy > $by; - $ty = $cy if $cy < $ty; - } - } - # now we actually place objects into cells, positioned such that the left and bottom borders are at 0 - for (0..$#{$self->objects}) { - my @copies = (); - for (1..$Slic3r::duplicate) { - my $c = shift @cellsorder; - my $cx = $c->[1]->{index}->[0] - $lx; - my $cy = $c->[1]->{index}->[1] - $ty; - - push @copies, [scale($cx * $partx), scale($cy * $party)]; - } - push @{$self->copies}, [@copies]; - } - - # save size of area used - $self->total_x_length(scale(($rx - $lx + 1) * $partx - $Slic3r::duplicate_distance)); - $self->total_y_length(scale(($by - $ty + 1) * $party - $Slic3r::duplicate_distance)); - } else { - $self->total_x_length($self->objects->[0]->x_length); - $self->total_y_length($self->objects->[0]->y_length); - push @{$self->copies}, [[0, 0]]; + $self->arrange_objects; } } -sub max_length { +sub arrange_objects { my $self = shift; - return ($self->total_x_length > $self->total_y_length) ? $self->total_x_length : $self->total_y_length; + + my $total_parts = scalar map @$_, @{$self->copies}; + my $partx = my $party = 0; + foreach my $object (@{$self->objects}) { + $partx = $object->x_length if $object->x_length > $partx; + $party = $object->y_length if $object->y_length > $party; + } + my @positions = Slic3r::Geometry::arrange + ($total_parts, $partx, $party, (map scale $_, @$Slic3r::bed_size), scale $Slic3r::duplicate_distance); + + for my $obj_idx (0..$#{$self->objects}) { + @{$self->copies->[$obj_idx]} = splice @positions, 0, scalar @{$self->copies->[$obj_idx]}; + } +} + +sub bounding_box { + my $self = shift; + + my @points = (); + foreach my $obj_idx (0 .. $#{$self->objects}) { + my $object = $self->objects->[$obj_idx]; + foreach my $copy (@{$self->copies->[$obj_idx]}) { + push @points, + [ $copy->[X], $copy->[Y] ], + [ $copy->[X] + $object->x_length, $copy->[Y] ], + [ $copy->[X] + $object->x_length, $copy->[Y] + $object->y_length ], + [ $copy->[X], $copy->[Y] + $object->y_length ]; + } + } + return Slic3r::Geometry::bounding_box(\@points); +} + +sub size { + my $self = shift; + + my @bb = $self->bounding_box; + return [ $bb[X2] - $bb[X1], $bb[Y2] - $bb[Y1] ]; +} + +sub export_gcode { + my $self = shift; + my %params = @_; + + my $status_cb = $params{status_cb} || sub {}; + my $t0 = [gettimeofday]; + + # skein the STL into layers + # each layer has surfaces with holes + $status_cb->(5, "Processing input file"); + $status_cb->(10, "Processing triangulated mesh"); + $_->slice for @{$self->objects}; + unless ($params{keep_meshes}) { + $_->mesh(undef) for @{$self->objects}; # free memory + } + + # make perimeters + # this will add a set of extrusion loops to each layer + # as well as generate infill boundaries + $status_cb->(20, "Generating perimeters"); + $_->make_perimeters for map @{$_->layers}, @{$self->objects}; + + # this will clip $layer->surfaces to the infill boundaries + # and split them in top/bottom/internal surfaces; + $status_cb->(30, "Detecting solid surfaces"); + $_->detect_surfaces_type for @{$self->objects}; + + # decide what surfaces are to be filled + $status_cb->(35, "Preparing infill surfaces"); + $_->prepare_fill_surfaces for map @{$_->layers}, @{$self->objects}; + + # this will remove unprintable surfaces + # (those that are too tight for extrusion) + $status_cb->(40, "Cleaning up"); + $_->remove_small_surfaces for map @{$_->layers}, @{$self->objects}; + + # this will detect bridges and reverse bridges + # and rearrange top/bottom/internal surfaces + $status_cb->(45, "Detect bridges"); + $_->process_bridges for map @{$_->layers}, @{$self->objects}; + + # this will remove unprintable perimeter loops + # (those that are too tight for extrusion) + $status_cb->(50, "Cleaning up the perimeters"); + $_->remove_small_perimeters for map @{$_->layers}, @{$self->objects}; + + # detect which fill surfaces are near external layers + # they will be split in internal and internal-solid surfaces + $status_cb->(60, "Generating horizontal shells"); + $_->discover_horizontal_shells for @{$self->objects}; + + # free memory + @{$_->surfaces} = () for map @{$_->layers}, @{$self->objects}; + + # combine fill surfaces to honor the "infill every N layers" option + $status_cb->(70, "Combining infill"); + $_->infill_every_layers for @{$self->objects}; + + # this will generate extrusion paths for each layer + $status_cb->(80, "Infilling layers"); + { + my $fill_maker = Slic3r::Fill->new('print' => $self); + + my @items = (); # [obj_idx, layer_id] + foreach my $obj_idx (0 .. $#{$self->objects}) { + push @items, map [$obj_idx, $_], 0..$#{$self->objects->[$obj_idx]->layers}; + } + Slic3r::parallelize( + items => [@items], + thread_cb => sub { + my $q = shift; + $Slic3r::Geometry::Clipper::clipper = Math::Clipper->new; + my $fills = {}; + while (defined (my $obj_layer = $q->dequeue)) { + my ($obj_idx, $layer_id) = @$obj_layer; + $fills->{$obj_idx} ||= {}; + $fills->{$obj_idx}{$layer_id} = [ $fill_maker->make_fill($self->objects->[$obj_idx]->layers->[$layer_id]) ]; + } + return $fills; + }, + collect_cb => sub { + my $fills = shift; + foreach my $obj_idx (keys %$fills) { + foreach my $layer_id (keys %{$fills->{$obj_idx}}) { + @{$self->objects->[$obj_idx]->layers->[$layer_id]->fills} = @{$fills->{$obj_idx}{$layer_id}}; + } + } + }, + no_threads_cb => sub { + foreach my $layer (map @{$_->layers}, @{$self->objects}) { + @{$layer->fills} = $fill_maker->make_fill($layer); + } + }, + ); + } + + # generate support material + if ($Slic3r::support_material) { + $status_cb->(85, "Generating support material"); + $_->generate_support_material for @{$self->objects}; + } + + # free memory (note that support material needs fill_surfaces) + @{$_->fill_surfaces} = () for map @{$_->layers}, @{$self->objects}; + + # make skirt + $status_cb->(88, "Generating skirt"); + $self->make_skirt; + + # output everything to a G-code file + my $output_file = $self->expanded_output_filepath($params{output_file}); + $status_cb->(90, "Exporting G-code to $output_file"); + $self->write_gcode($output_file); + + # run post-processing scripts + if (@$Slic3r::post_process) { + $status_cb->(95, "Running post-processing scripts"); + for (@$Slic3r::post_process) { + Slic3r::debugf " '%s' '%s'\n", $_, $output_file; + system($_, $output_file); + } + } + + # output some statistics + $self->processing_time(tv_interval($t0)); + printf "Done. Process took %d minutes and %.3f seconds\n", + int($self->processing_time/60), + $self->processing_time - int($self->processing_time/60)*60; + + # TODO: more statistics! + printf "Filament required: %.1fmm (%.1fcm3)\n", + $self->total_extrusion_length, $self->total_extrusion_volume; +} + +sub export_svg { + my $self = shift; + my %params = @_; + + $_->slice for @{$self->objects}; + unless ($params{keep_meshes}) { + $_->mesh(undef) for @{$self->objects}; # free memory + } + $self->arrange_objects; + + my $output_file = $self->expanded_output_filepath($params{output_file}); + $output_file =~ s/\.gcode$/.svg/i; + + open my $fh, ">", $output_file or die "Failed to open $output_file for writing\n"; + print "Exporting to $output_file..."; + my $print_size = $self->size; + print $fh sprintf <<"EOF", unscale($print_size->[X]), unscale($print_size->[Y]); + + + + +EOF + + my $print_polygon = sub { + my ($polygon, $type) = @_; + printf $fh qq{ \n}, + $type, (join ' ', map { join ',', map unscale $_, @$_ } @$polygon), + ($type eq 'contour' ? 'black' : 'white'); + }; + + for my $layer_id (0..$self->layer_count-1) { + my @layers = map $_->layers->[$layer_id], @{$self->objects}; + printf $fh qq{ \n}, $layer_id, unscale +(grep defined $_, @layers)[0]->slice_z; + + for my $obj_idx (0 .. $#layers) { + my $layer = $layers[$layer_id] or next; + + # sort slices so that the outermost ones come first + my @slices = sort { $a->expolygon->contour->encloses_point($b->expolygon->contour->[0]) ? 0 : 1 } @{$layer->slices}; + + foreach my $copy (@{$self->copies->[$obj_idx]}) { + foreach my $slice (@slices) { + my $expolygon = $slice->expolygon->clone; + $expolygon->translate(@$copy); + $print_polygon->($expolygon->contour, 'contour'); + $print_polygon->($_, 'hole') for $expolygon->holes; + } + } + } + print $fh qq{ \n}; + } + + print $fh "\n"; + close $fh; + print "Done.\n"; } sub make_skirt { @@ -344,7 +367,7 @@ sub make_skirt { push @{$self->skirt}, @skirt; } -sub export_gcode { +sub write_gcode { my $self = shift; my ($file) = @_; @@ -394,9 +417,10 @@ sub export_gcode { } # calculate X,Y shift to center print around specified origin + my @print_bb = $self->bounding_box; my @shift = ( - $Slic3r::print_center->[X] - (unscale $self->total_x_length / 2), - $Slic3r::print_center->[Y] - (unscale $self->total_y_length / 2), + $Slic3r::print_center->[X] - (unscale ($print_bb[X2] - $print_bb[X1]) / 2) - unscale $print_bb[X1], + $Slic3r::print_center->[Y] - (unscale ($print_bb[Y2] - $print_bb[Y1]) / 2) - unscale $print_bb[Y1], ); # set up our extruder object @@ -523,4 +547,24 @@ sub total_extrusion_volume { return $self->total_extrusion_length * ($Slic3r::filament_diameter**2) * PI/4 / 1000; } +# this method will return the value of $self->output_file after expanding its +# format variables with their values +sub expanded_output_filepath { + my $self = shift; + my ($path) = @_; + + # if no explicit output file was defined, we take the input + # file directory and append the specified filename format + my $input_file = $self->objects->[0]->input_file; + $path ||= (fileparse($input_file))[1] . $Slic3r::output_filename_format; + + my $input_filename = my $input_filename_base = basename($input_file); + $input_filename_base =~ s/\.(?:stl|amf(?:\.xml)?)$//i; + + return Slic3r::Config->replace_options($path, { + input_filename => $input_filename, + input_filename_base => $input_filename_base, + }); +} + 1; diff --git a/lib/Slic3r/Print/Object.pm b/lib/Slic3r/Print/Object.pm index e280b8d3..2784acc8 100644 --- a/lib/Slic3r/Print/Object.pm +++ b/lib/Slic3r/Print/Object.pm @@ -4,8 +4,10 @@ use Moo; use Slic3r::Geometry qw(scale); use Slic3r::Geometry::Clipper qw(diff_ex intersection_ex union_ex); -has 'x_length' => (is => 'ro', required => 1); -has 'y_length' => (is => 'ro', required => 1); +has 'input_file' => (is => 'rw', required => 0); +has 'mesh' => (is => 'rw', required => 0); +has 'x_length' => (is => 'rw', required => 1); +has 'y_length' => (is => 'rw', required => 1); has 'layers' => ( traits => ['Array'], @@ -34,6 +36,122 @@ sub layer { return $self->layers->[$layer_id]; } +sub slice { + my $self = shift; + + # process facets + { + my $apply_lines = sub { + my $lines = shift; + foreach my $layer_id (keys %$lines) { + my $layer = $self->layer($layer_id); + $layer->add_line($_) for @{ $lines->{$layer_id} }; + } + }; + Slic3r::parallelize( + disable => ($#{$self->mesh->facets} < 500), # don't parallelize when too few facets + items => [ 0..$#{$self->mesh->facets} ], + thread_cb => sub { + my $q = shift; + my $result_lines = {}; + while (defined (my $facet_id = $q->dequeue)) { + my $lines = $self->mesh->slice_facet($self, $facet_id); + foreach my $layer_id (keys %$lines) { + $result_lines->{$layer_id} ||= []; + push @{ $result_lines->{$layer_id} }, @{ $lines->{$layer_id} }; + } + } + return $result_lines; + }, + collect_cb => sub { + $apply_lines->($_[0]); + }, + no_threads_cb => sub { + for (0..$#{$self->mesh->facets}) { + my $lines = $self->mesh->slice_facet($self, $_); + $apply_lines->($lines); + } + }, + ); + } + die "Invalid input file\n" if !@{$self->layers}; + + # remove last layer if empty + # (we might have created it because of the $max_layer = ... + 1 code below) + pop @{$self->layers} if !@{$self->layers->[-1]->surfaces} && !@{$self->layers->[-1]->lines}; + + foreach my $layer (@{ $self->layers }) { + Slic3r::debugf "Making surfaces for layer %d (slice z = %f):\n", + $layer->id, unscale $layer->slice_z if $Slic3r::debug; + + # layer currently has many lines representing intersections of + # model facets with the layer plane. there may also be lines + # that we need to ignore (for example, when two non-horizontal + # facets share a common edge on our plane, we get a single line; + # however that line has no meaning for our layer as it's enclosed + # inside a closed polyline) + + # build surfaces from sparse lines + $layer->make_surfaces($self->mesh->make_loops($layer)); + + # free memory + $layer->lines(undef); + } + + # detect slicing errors + my $warning_thrown = 0; + for my $i (0 .. $#{$self->layers}) { + my $layer = $self->layers->[$i]; + next unless $layer->slicing_errors; + if (!$warning_thrown) { + warn "The model has overlapping or self-intersecting facets. I tried to repair it, " + . "however you might want to check the results or repair the input file and retry.\n"; + $warning_thrown = 1; + } + + # try to repair the layer surfaces by merging all contours and all holes from + # neighbor layers + Slic3r::debugf "Attempting to repair layer %d\n", $i; + + my (@upper_surfaces, @lower_surfaces); + for (my $j = $i+1; $j <= $#{$self->layers}; $j++) { + if (!$self->layers->[$j]->slicing_errors) { + @upper_surfaces = @{$self->layers->[$j]->slices}; + last; + } + } + for (my $j = $i-1; $j >= 0; $j--) { + if (!$self->layers->[$j]->slicing_errors) { + @lower_surfaces = @{$self->layers->[$j]->slices}; + last; + } + } + + my $union = union_ex([ + map $_->expolygon->contour, @upper_surfaces, @lower_surfaces, + ]); + my $diff = diff_ex( + [ map @$_, @$union ], + [ map $_->expolygon->holes, @upper_surfaces, @lower_surfaces, ], + ); + + @{$layer->slices} = map Slic3r::Surface->new + (expolygon => $_, surface_type => 'internal'), + @$diff; + } + + # remove empty layers from bottom + while (@{$self->layers} && !@{$self->layers->[0]->slices} && !@{$self->layers->[0]->thin_walls}) { + shift @{$self->layers}; + for (my $i = 0; $i <= $#{$self->layers}; $i++) { + $self->layers->[$i]->id($i); + } + } + + warn "No layers were detected. You might want to repair your STL file and retry.\n" + if !@{$self->layers}; +} + sub detect_surfaces_type { my $self = shift; Slic3r::debugf "Detecting solid surfaces...\n"; diff --git a/lib/Slic3r/Skein.pm b/lib/Slic3r/Skein.pm deleted file mode 100644 index fbcf5c2a..00000000 --- a/lib/Slic3r/Skein.pm +++ /dev/null @@ -1,236 +0,0 @@ -package Slic3r::Skein; -use Moo; - -use Config; -use File::Basename qw(basename fileparse); -use Slic3r::Geometry qw(PI unscale); -use Time::HiRes qw(gettimeofday tv_interval); - -# full path (relative or absolute) to the input file -has 'input_file' => (is => 'ro', required => 1); -has 'additional_input_files' => (is => 'ro', required => 0, default => sub {[]}); - -# full path (relative or absolute) to the output file; it may contain -# formatting variables like [layer_height] etc. -has 'output_file' => (is => 'rw', required => 0); - -has 'status_cb' => (is => 'rw', required => 0, default => sub { sub {} }); -has 'processing_time' => (is => 'rw', required => 0); - -sub slice_input { - my $self = shift; - - my $print = Slic3r::Print->new; - foreach my $input_file ($self->input_file, @{$self->additional_input_files}) { - if ($input_file =~ /\.stl$/i) { - my $mesh = Slic3r::Format::STL->read_file($input_file); - $mesh->check_manifoldness; - $print->add_object_from_mesh($mesh); - } elsif ( $input_file =~ /\.amf(\.xml)?$/i) { - my ($materials, $meshes_by_material) = Slic3r::Format::AMF->read_file($input_file); - $_->check_manifoldness for values %$meshes_by_material; - $print->add_object_from_mesh($meshes_by_material->{_} || +(values %$meshes_by_material)[0]); - } else { - die "Input file must have .stl or .amf(.xml) extension\n"; - } - } - return $print; -} - -sub go { - my $self = shift; - my $t0 = [gettimeofday]; - - # skein the STL into layers - # each layer has surfaces with holes - $self->status_cb->(5, "Processing input file " . $self->input_file); - $self->status_cb->(10, "Processing triangulated mesh"); - my $print = $self->slice_input; - $print->arrange_objects; - - # make perimeters - # this will add a set of extrusion loops to each layer - # as well as generate infill boundaries - $self->status_cb->(20, "Generating perimeters"); - $_->make_perimeters for map @{$_->layers}, @{$print->objects}; - - # this will clip $layer->surfaces to the infill boundaries - # and split them in top/bottom/internal surfaces; - $self->status_cb->(30, "Detecting solid surfaces"); - $_->detect_surfaces_type for @{$print->objects}; - - # decide what surfaces are to be filled - $self->status_cb->(35, "Preparing infill surfaces"); - $_->prepare_fill_surfaces for map @{$_->layers}, @{$print->objects}; - - # this will remove unprintable surfaces - # (those that are too tight for extrusion) - $self->status_cb->(40, "Cleaning up"); - $_->remove_small_surfaces for map @{$_->layers}, @{$print->objects}; - - # this will detect bridges and reverse bridges - # and rearrange top/bottom/internal surfaces - $self->status_cb->(45, "Detect bridges"); - $_->process_bridges for map @{$_->layers}, @{$print->objects}; - - # this will remove unprintable perimeter loops - # (those that are too tight for extrusion) - $self->status_cb->(50, "Cleaning up the perimeters"); - $_->remove_small_perimeters for map @{$_->layers}, @{$print->objects}; - - # detect which fill surfaces are near external layers - # they will be split in internal and internal-solid surfaces - $self->status_cb->(60, "Generating horizontal shells"); - $_->discover_horizontal_shells for @{$print->objects}; - - # free memory - @{$_->surfaces} = () for map @{$_->layers}, @{$print->objects}; - - # combine fill surfaces to honor the "infill every N layers" option - $self->status_cb->(70, "Combining infill"); - $_->infill_every_layers for @{$print->objects}; - - # this will generate extrusion paths for each layer - $self->status_cb->(80, "Infilling layers"); - { - my $fill_maker = Slic3r::Fill->new('print' => $print); - - my @items = (); # [obj_idx, layer_id] - foreach my $obj_idx (0 .. $#{$print->objects}) { - push @items, map [$obj_idx, $_], 0..$#{$print->objects->[$obj_idx]->layers}; - } - Slic3r::parallelize( - items => [@items], - thread_cb => sub { - my $q = shift; - $Slic3r::Geometry::Clipper::clipper = Math::Clipper->new; - my $fills = {}; - while (defined (my $obj_layer = $q->dequeue)) { - my ($obj_idx, $layer_id) = @$obj_layer; - $fills->{$obj_idx} ||= {}; - $fills->{$obj_idx}{$layer_id} = [ $fill_maker->make_fill($print->objects->[$obj_idx]->layers->[$layer_id]) ]; - } - return $fills; - }, - collect_cb => sub { - my $fills = shift; - foreach my $obj_idx (keys %$fills) { - foreach my $layer_id (keys %{$fills->{$obj_idx}}) { - @{$print->objects->[$obj_idx]->layers->[$layer_id]->fills} = @{$fills->{$obj_idx}{$layer_id}}; - } - } - }, - no_threads_cb => sub { - foreach my $layer (map @{$_->layers}, @{$print->objects}) { - @{$layer->fills} = $fill_maker->make_fill($layer); - } - }, - ); - } - - # generate support material - if ($Slic3r::support_material) { - $self->status_cb->(85, "Generating support material"); - $_->generate_support_material for @{$print->objects}; - } - - # free memory (note that support material needs fill_surfaces) - @{$_->fill_surfaces} = () for map @{$_->layers}, @{$print->objects}; - - # make skirt - $self->status_cb->(88, "Generating skirt"); - $print->make_skirt; - - # output everything to a G-code file - my $output_file = $self->expanded_output_filepath; - $self->status_cb->(90, "Exporting G-code to $output_file"); - $print->export_gcode($output_file); - - # run post-processing scripts - if (@$Slic3r::post_process) { - $self->status_cb->(95, "Running post-processing scripts"); - for (@$Slic3r::post_process) { - Slic3r::debugf " '%s' '%s'\n", $_, $output_file; - system($_, $output_file); - } - } - - # output some statistics - $self->processing_time(tv_interval($t0)); - printf "Done. Process took %d minutes and %.3f seconds\n", - int($self->processing_time/60), - $self->processing_time - int($self->processing_time/60)*60; - - # TODO: more statistics! - printf "Filament required: %.1fmm (%.1fcm3)\n", - $print->total_extrusion_length, $print->total_extrusion_volume; -} - -sub export_svg { - my $self = shift; - - my $print = $self->slice_input; - my $output_file = $self->expanded_output_filepath; - $output_file =~ s/\.gcode$/.svg/i; - - open my $fh, ">", $output_file or die "Failed to open $output_file for writing\n"; - print "Exporting to $output_file..."; - print $fh sprintf <<"EOF", unscale($print->total_x_length), unscale($print->total_y_length); - - - - -EOF - - my $print_polygon = sub { - my ($polygon, $type) = @_; - printf $fh qq{ \n}, - $type, (join ' ', map { join ',', map unscale $_, @$_ } @$polygon), - ($type eq 'contour' ? 'black' : 'white'); - }; - - foreach my $layer (@{$print->layers}) { - printf $fh qq{ \n}, $layer->id, unscale $layer->slice_z; - # sort slices so that the outermost ones come first - my @slices = sort { $a->expolygon->contour->encloses_point($b->expolygon->contour->[0]) ? 0 : 1 } @{$layer->slices}; - - foreach my $copy (@{$print->copies}) { - foreach my $slice (@slices) { - my $expolygon = $slice->expolygon->clone; - $expolygon->translate(@$copy); - $print_polygon->($expolygon->contour, 'contour'); - $print_polygon->($_, 'hole') for $expolygon->holes; - } - } - print $fh qq{ \n}; - } - - print $fh "\n"; - close $fh; - print "Done.\n"; -} - -# this method will return the value of $self->output_file after expanding its -# format variables with their values -sub expanded_output_filepath { - my $self = shift; - - my $path = $self->output_file; - - # if no explicit output file was defined, we take the input - # file directory and append the specified filename format - $path ||= (fileparse($self->input_file))[1] . $Slic3r::output_filename_format; - - my $input_filename = my $input_filename_base = basename($self->input_file); - $input_filename_base =~ s/\.(?:stl|amf(?:\.xml)?)$//i; - - return Slic3r::Config->replace_options($path, { - input_filename => $input_filename, - input_filename_base => $input_filename_base, - }); -} - -1; diff --git a/lib/Slic3r/TriangleMesh.pm b/lib/Slic3r/TriangleMesh.pm index 63917c77..142ff5c1 100644 --- a/lib/Slic3r/TriangleMesh.pm +++ b/lib/Slic3r/TriangleMesh.pm @@ -4,7 +4,7 @@ use Moo; use Slic3r::Geometry qw(X Y Z A B unscale same_point); # public -has 'vertices' => (is => 'ro', required => 1); # id => [ [$x1,$y1],[$x2,$y2],[$x3,$y3] ] +has 'vertices' => (is => 'ro', required => 1); # id => [$x,$y,$z] has 'facets' => (is => 'ro', required => 1); # id => [ $normal, $v1_id, $v2_id, $v3_id ] # private diff --git a/slic3r.pl b/slic3r.pl index dce403ac..68ed125c 100755 --- a/slic3r.pl +++ b/slic3r.pl @@ -74,9 +74,13 @@ if (!@ARGV && !$opt{save} && eval "require Slic3r::GUI; 1") { if (@ARGV) { while (my $input_file = shift @ARGV) { - my $skein = Slic3r::Skein->new( - input_file => $input_file, - additional_input_files => $opt{merge} ? [ splice @ARGV, 0 ] : [], + my $print = Slic3r::Print->new; + $print->add_object_from_file($input_file); + if ($opt{merge}) { + $print->add_object_from_file($_) for splice @ARGV, 0; + } + $print->duplicate; + my %params = ( output_file => $opt{output}, status_cb => sub { my ($percent, $message) = @_; @@ -84,9 +88,9 @@ if (@ARGV) { }, ); if ($opt{export_svg}) { - $skein->export_svg; + $print->export_svg(%params); } else { - $skein->go; + $print->export_gcode(%params); } } } else { @@ -125,7 +129,7 @@ $j --post-process Generated G-code will be processed with the supplied script; call this more than once to process through multiple scripts. --export-svg Export a SVG file containing slices instead of G-code. - --merge If multiple files are supplied, they will be composed into a single + -m, --merge If multiple files are supplied, they will be composed into a single print rather than processed individually. Printer options: