~ubuntu-branches/ubuntu/utopic/slic3r/utopic

« back to all changes in this revision

Viewing changes to lib/Slic3r/GUI/Plater.pm

  • Committer: Package Import Robot
  • Author(s): Chow Loong Jin
  • Date: 2014-06-17 01:27:26 UTC
  • Revision ID: package-import@ubuntu.com-20140617012726-2wrs4zdo251nr4vg
Tags: upstream-1.1.4+dfsg
Import upstream version 1.1.4+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package Slic3r::GUI::Plater;
 
2
use strict;
 
3
use warnings;
 
4
use utf8;
 
5
 
 
6
use File::Basename qw(basename dirname);
 
7
use List::Util qw(max sum first);
 
8
use Slic3r::Geometry::Clipper qw(offset JT_ROUND);
 
9
use Slic3r::Geometry qw(X Y Z MIN MAX convex_hull scale unscale);
 
10
use threads::shared qw(shared_clone);
 
11
use Wx qw(:bitmap :brush :button :cursor :dialog :filedialog :font :keycode :icon :id :listctrl :misc :panel :pen :sizer :toolbar :window);
 
12
use Wx::Event qw(EVT_BUTTON EVT_COMMAND EVT_KEY_DOWN EVT_LIST_ITEM_ACTIVATED EVT_LIST_ITEM_DESELECTED EVT_LIST_ITEM_SELECTED EVT_MOUSE_EVENTS EVT_PAINT EVT_TOOL EVT_CHOICE);
 
13
use base 'Wx::Panel';
 
14
 
 
15
use constant TB_ADD             => &Wx::NewId;
 
16
use constant TB_REMOVE          => &Wx::NewId;
 
17
use constant TB_RESET           => &Wx::NewId;
 
18
use constant TB_ARRANGE         => &Wx::NewId;
 
19
use constant TB_EXPORT_GCODE    => &Wx::NewId;
 
20
use constant TB_EXPORT_STL      => &Wx::NewId;
 
21
use constant TB_MORE    => &Wx::NewId;
 
22
use constant TB_FEWER   => &Wx::NewId;
 
23
use constant TB_45CW    => &Wx::NewId;
 
24
use constant TB_45CCW   => &Wx::NewId;
 
25
use constant TB_ROTATE  => &Wx::NewId;
 
26
use constant TB_SCALE   => &Wx::NewId;
 
27
use constant TB_SPLIT   => &Wx::NewId;
 
28
use constant TB_VIEW    => &Wx::NewId;
 
29
use constant TB_SETTINGS => &Wx::NewId;
 
30
 
 
31
# package variables to avoid passing lexicals to threads
 
32
our $THUMBNAIL_DONE_EVENT    : shared = Wx::NewEventType;
 
33
our $PROGRESS_BAR_EVENT      : shared = Wx::NewEventType;
 
34
our $MESSAGE_DIALOG_EVENT    : shared = Wx::NewEventType;
 
35
our $EXPORT_COMPLETED_EVENT  : shared = Wx::NewEventType;
 
36
our $EXPORT_FAILED_EVENT     : shared = Wx::NewEventType;
 
37
 
 
38
use constant CANVAS_SIZE => [335,335];
 
39
use constant CANVAS_TEXT => join('-', +(localtime)[3,4]) eq '13-8'
 
40
    ? 'What do you want to print today? ™' # Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap.
 
41
    : 'Drag your objects here';
 
42
use constant FILAMENT_CHOOSERS_SPACING => 3;
 
43
 
 
44
my $PreventListEvents = 0;
 
45
 
 
46
sub new {
 
47
    my $class = shift;
 
48
    my ($parent) = @_;
 
49
    my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
 
50
    $self->{config} = Slic3r::Config->new_from_defaults(qw(
 
51
        bed_size print_center complete_objects extruder_clearance_radius skirts skirt_distance
 
52
    ));
 
53
    $self->{model} = Slic3r::Model->new;
 
54
    $self->{print} = Slic3r::Print->new;
 
55
    $self->{objects} = [];
 
56
    
 
57
    $self->{canvas} = Wx::Panel->new($self, -1, wxDefaultPosition, CANVAS_SIZE, wxTAB_TRAVERSAL);
 
58
    $self->{canvas}->SetBackgroundColour(Wx::wxWHITE);
 
59
    EVT_PAINT($self->{canvas}, \&repaint);
 
60
    EVT_MOUSE_EVENTS($self->{canvas}, \&mouse_event);
 
61
    
 
62
    $self->{objects_brush} = Wx::Brush->new(Wx::Colour->new(210,210,210), wxSOLID);
 
63
    $self->{selected_brush} = Wx::Brush->new(Wx::Colour->new(255,128,128), wxSOLID);
 
64
    $self->{dragged_brush} = Wx::Brush->new(Wx::Colour->new(128,128,255), wxSOLID);
 
65
    $self->{transparent_brush} = Wx::Brush->new(Wx::Colour->new(0,0,0), wxTRANSPARENT);
 
66
    $self->{grid_pen} = Wx::Pen->new(Wx::Colour->new(230,230,230), 1, wxSOLID);
 
67
    $self->{print_center_pen} = Wx::Pen->new(Wx::Colour->new(200,200,200), 1, wxSOLID);
 
68
    $self->{clearance_pen} = Wx::Pen->new(Wx::Colour->new(0,0,200), 1, wxSOLID);
 
69
    $self->{skirt_pen} = Wx::Pen->new(Wx::Colour->new(150,150,150), 1, wxSOLID);
 
70
    
 
71
    # toolbar for object manipulation
 
72
    if (!&Wx::wxMSW) {
 
73
        Wx::ToolTip::Enable(1);
 
74
        $self->{htoolbar} = Wx::ToolBar->new($self, -1, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxTB_TEXT | wxBORDER_SIMPLE | wxTAB_TRAVERSAL);
 
75
        $self->{htoolbar}->AddTool(TB_ADD, "Add…", Wx::Bitmap->new("$Slic3r::var/brick_add.png", wxBITMAP_TYPE_PNG), '');
 
76
        $self->{htoolbar}->AddTool(TB_REMOVE, "Delete", Wx::Bitmap->new("$Slic3r::var/brick_delete.png", wxBITMAP_TYPE_PNG), '');
 
77
        $self->{htoolbar}->AddTool(TB_RESET, "Delete All", Wx::Bitmap->new("$Slic3r::var/cross.png", wxBITMAP_TYPE_PNG), '');
 
78
        $self->{htoolbar}->AddTool(TB_ARRANGE, "Arrange", Wx::Bitmap->new("$Slic3r::var/bricks.png", wxBITMAP_TYPE_PNG), '');
 
79
        $self->{htoolbar}->AddSeparator;
 
80
        $self->{htoolbar}->AddTool(TB_MORE, "More", Wx::Bitmap->new("$Slic3r::var/add.png", wxBITMAP_TYPE_PNG), '');
 
81
        $self->{htoolbar}->AddTool(TB_FEWER, "Fewer", Wx::Bitmap->new("$Slic3r::var/delete.png", wxBITMAP_TYPE_PNG), '');
 
82
        $self->{htoolbar}->AddSeparator;
 
83
        $self->{htoolbar}->AddTool(TB_45CCW, "45° ccw", Wx::Bitmap->new("$Slic3r::var/arrow_rotate_anticlockwise.png", wxBITMAP_TYPE_PNG), '');
 
84
        $self->{htoolbar}->AddTool(TB_45CW, "45° cw", Wx::Bitmap->new("$Slic3r::var/arrow_rotate_clockwise.png", wxBITMAP_TYPE_PNG), '');
 
85
        $self->{htoolbar}->AddTool(TB_ROTATE, "Rotate…", Wx::Bitmap->new("$Slic3r::var/arrow_rotate_clockwise.png", wxBITMAP_TYPE_PNG), '');
 
86
        $self->{htoolbar}->AddTool(TB_SCALE, "Scale…", Wx::Bitmap->new("$Slic3r::var/arrow_out.png", wxBITMAP_TYPE_PNG), '');
 
87
        $self->{htoolbar}->AddTool(TB_SPLIT, "Split", Wx::Bitmap->new("$Slic3r::var/shape_ungroup.png", wxBITMAP_TYPE_PNG), '');
 
88
        $self->{htoolbar}->AddSeparator;
 
89
        $self->{htoolbar}->AddTool(TB_VIEW, "View/Cut…", Wx::Bitmap->new("$Slic3r::var/package.png", wxBITMAP_TYPE_PNG), '');
 
90
        $self->{htoolbar}->AddTool(TB_SETTINGS, "Settings…", Wx::Bitmap->new("$Slic3r::var/cog.png", wxBITMAP_TYPE_PNG), '');
 
91
    } else {
 
92
        my %tbar_buttons = (
 
93
            add             => "Add…",
 
94
            remove          => "Delete",
 
95
            reset           => "Delete All",
 
96
            arrange         => "Arrange",
 
97
            increase        => "",
 
98
            decrease        => "",
 
99
            rotate45ccw     => "",
 
100
            rotate45cw      => "",
 
101
            rotate          => "Rotate…",
 
102
            changescale     => "Scale…",
 
103
            split           => "Split",
 
104
            view            => "View/Cut…",
 
105
            settings        => "Settings…",
 
106
        );
 
107
        $self->{btoolbar} = Wx::BoxSizer->new(wxHORIZONTAL);
 
108
        for (qw(add remove reset arrange increase decrease rotate45ccw rotate45cw rotate changescale split view settings)) {
 
109
            $self->{"btn_$_"} = Wx::Button->new($self, -1, $tbar_buttons{$_}, wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
 
110
            $self->{btoolbar}->Add($self->{"btn_$_"});
 
111
        }
 
112
    }
 
113
 
 
114
    $self->{list} = Wx::ListView->new($self, -1, wxDefaultPosition, wxDefaultSize, wxLC_SINGLE_SEL | wxLC_REPORT | wxBORDER_SUNKEN | wxTAB_TRAVERSAL | wxWANTS_CHARS);
 
115
    $self->{list}->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 145);
 
116
    $self->{list}->InsertColumn(1, "Copies", wxLIST_FORMAT_CENTER, 45);
 
117
    $self->{list}->InsertColumn(2, "Scale", wxLIST_FORMAT_CENTER, wxLIST_AUTOSIZE_USEHEADER);
 
118
    EVT_LIST_ITEM_SELECTED($self, $self->{list}, \&list_item_selected);
 
119
    EVT_LIST_ITEM_DESELECTED($self, $self->{list}, \&list_item_deselected);
 
120
    EVT_LIST_ITEM_ACTIVATED($self, $self->{list}, \&list_item_activated);
 
121
    EVT_KEY_DOWN($self->{list}, sub {
 
122
        my ($list, $event) = @_;
 
123
        if ($event->GetKeyCode == WXK_TAB) {
 
124
            $list->Navigate($event->ShiftDown ? &Wx::wxNavigateBackward : &Wx::wxNavigateForward);
 
125
        } else {
 
126
            $event->Skip;
 
127
        }
 
128
    });
 
129
    
 
130
    # right pane buttons
 
131
    $self->{btn_export_gcode} = Wx::Button->new($self, -1, "Export G-code…", wxDefaultPosition, wxDefaultSize, wxBU_LEFT);
 
132
    $self->{btn_export_stl} = Wx::Button->new($self, -1, "Export STL…", wxDefaultPosition, wxDefaultSize, wxBU_LEFT);
 
133
    $self->{btn_export_gcode}->SetFont($Slic3r::GUI::small_font);
 
134
    $self->{btn_export_stl}->SetFont($Slic3r::GUI::small_font);
 
135
    
 
136
    if ($Slic3r::GUI::have_button_icons) {
 
137
        my %icons = qw(
 
138
            add             brick_add.png
 
139
            remove          brick_delete.png
 
140
            reset           cross.png
 
141
            arrange         bricks.png
 
142
            export_gcode    cog_go.png
 
143
            export_stl      brick_go.png
 
144
            
 
145
            increase        add.png
 
146
            decrease        delete.png
 
147
            rotate45cw      arrow_rotate_clockwise.png
 
148
            rotate45ccw     arrow_rotate_anticlockwise.png
 
149
            rotate          arrow_rotate_clockwise.png
 
150
            changescale     arrow_out.png
 
151
            split           shape_ungroup.png
 
152
            view            package.png
 
153
            settings        cog.png
 
154
        );
 
155
        for (grep $self->{"btn_$_"}, keys %icons) {
 
156
            $self->{"btn_$_"}->SetBitmap(Wx::Bitmap->new("$Slic3r::var/$icons{$_}", wxBITMAP_TYPE_PNG));
 
157
        }
 
158
    }
 
159
    $self->selection_changed(0);
 
160
    $self->object_list_changed;
 
161
    EVT_BUTTON($self, $self->{btn_export_gcode}, \&export_gcode);
 
162
    EVT_BUTTON($self, $self->{btn_export_stl}, \&export_stl);
 
163
    
 
164
    if ($self->{htoolbar}) {
 
165
        EVT_TOOL($self, TB_ADD, \&add);
 
166
        EVT_TOOL($self, TB_REMOVE, sub { $self->remove() }); # explicitly pass no argument to remove
 
167
        EVT_TOOL($self, TB_RESET, \&reset);
 
168
        EVT_TOOL($self, TB_ARRANGE, \&arrange);
 
169
        EVT_TOOL($self, TB_MORE, \&increase);
 
170
        EVT_TOOL($self, TB_FEWER, \&decrease);
 
171
        EVT_TOOL($self, TB_45CW, sub { $_[0]->rotate(-45) });
 
172
        EVT_TOOL($self, TB_45CCW, sub { $_[0]->rotate(45) });
 
173
        EVT_TOOL($self, TB_ROTATE, sub { $_[0]->rotate(undef) });
 
174
        EVT_TOOL($self, TB_SCALE, \&changescale);
 
175
        EVT_TOOL($self, TB_SPLIT, \&split_object);
 
176
        EVT_TOOL($self, TB_VIEW, sub { $_[0]->object_cut_dialog });
 
177
        EVT_TOOL($self, TB_SETTINGS, sub { $_[0]->object_settings_dialog });
 
178
    } else {
 
179
        EVT_BUTTON($self, $self->{btn_add}, \&add);
 
180
        EVT_BUTTON($self, $self->{btn_remove}, sub { $self->remove() }); # explicitly pass no argument to remove
 
181
        EVT_BUTTON($self, $self->{btn_reset}, \&reset);
 
182
        EVT_BUTTON($self, $self->{btn_arrange}, \&arrange);
 
183
        EVT_BUTTON($self, $self->{btn_increase}, \&increase);
 
184
        EVT_BUTTON($self, $self->{btn_decrease}, \&decrease);
 
185
        EVT_BUTTON($self, $self->{btn_rotate45cw}, sub { $_[0]->rotate(-45) });
 
186
        EVT_BUTTON($self, $self->{btn_rotate45ccw}, sub { $_[0]->rotate(45) });
 
187
        EVT_BUTTON($self, $self->{btn_changescale}, \&changescale);
 
188
        EVT_BUTTON($self, $self->{btn_rotate}, sub { $_[0]->rotate(undef) });
 
189
        EVT_BUTTON($self, $self->{btn_split}, \&split_object);
 
190
        EVT_BUTTON($self, $self->{btn_view}, sub { $_[0]->object_cut_dialog });
 
191
        EVT_BUTTON($self, $self->{btn_settings}, sub { $_[0]->object_settings_dialog });
 
192
    }
 
193
    
 
194
    $_->SetDropTarget(Slic3r::GUI::Plater::DropTarget->new($self))
 
195
        for $self, $self->{canvas}, $self->{list};
 
196
    
 
197
    EVT_COMMAND($self, -1, $THUMBNAIL_DONE_EVENT, sub {
 
198
        my ($self, $event) = @_;
 
199
        my ($obj_idx) = @{$event->GetData};
 
200
        return if !$self->{objects}[$obj_idx];  # object was deleted before thumbnail generation completed
 
201
        
 
202
        $self->on_thumbnail_made($obj_idx);
 
203
    });
 
204
    
 
205
    EVT_COMMAND($self, -1, $PROGRESS_BAR_EVENT, sub {
 
206
        my ($self, $event) = @_;
 
207
        my ($percent, $message) = @{$event->GetData};
 
208
        $self->statusbar->SetProgress($percent);
 
209
        $self->statusbar->SetStatusText("$message…");
 
210
    });
 
211
    
 
212
    EVT_COMMAND($self, -1, $MESSAGE_DIALOG_EVENT, sub {
 
213
        my ($self, $event) = @_;
 
214
        Wx::MessageDialog->new($self, @{$event->GetData})->ShowModal;
 
215
    });
 
216
    
 
217
    EVT_COMMAND($self, -1, $EXPORT_COMPLETED_EVENT, sub {
 
218
        my ($self, $event) = @_;
 
219
        $self->on_export_completed(@{$event->GetData});
 
220
    });
 
221
    
 
222
    EVT_COMMAND($self, -1, $EXPORT_FAILED_EVENT, sub {
 
223
        my ($self, $event) = @_;
 
224
        $self->on_export_failed;
 
225
    });
 
226
    
 
227
    $self->_update_bed_size;
 
228
    $self->update;
 
229
    
 
230
    {
 
231
        my $presets;
 
232
        if ($self->skeinpanel->{mode} eq 'expert') {
 
233
            $presets = Wx::BoxSizer->new(wxVERTICAL);
 
234
            my %group_labels = (
 
235
                print       => 'Print settings',
 
236
                filament    => 'Filament',
 
237
                printer     => 'Printer',
 
238
            );
 
239
            $self->{preset_choosers} = {};
 
240
            $self->{preset_choosers_sizers} = {};
 
241
            for my $group (qw(print filament printer)) {
 
242
                my $text = Wx::StaticText->new($self, -1, "$group_labels{$group}:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);
 
243
                $text->SetFont($Slic3r::GUI::small_font);
 
244
                my $choice = Wx::Choice->new($self, -1, wxDefaultPosition, [140, -1], []);
 
245
                $choice->SetFont($Slic3r::GUI::small_font);
 
246
                $self->{preset_choosers}{$group} = [$choice];
 
247
                EVT_CHOICE($choice, $choice, sub { $self->on_select_preset($group, @_) });
 
248
                
 
249
                $self->{preset_choosers_sizers}{$group} = Wx::BoxSizer->new(wxVERTICAL);
 
250
                $self->{preset_choosers_sizers}{$group}->Add($choice, 0, wxEXPAND | wxBOTTOM, FILAMENT_CHOOSERS_SPACING);
 
251
                
 
252
                $presets->Add($text, 0, wxALIGN_LEFT | wxRIGHT, 4);
 
253
                $presets->Add($self->{preset_choosers_sizers}{$group}, 0, wxALIGN_CENTER_VERTICAL | wxBOTTOM, 8);
 
254
            }
 
255
        }
 
256
        
 
257
        my $object_info_sizer;
 
258
        {
 
259
            my $box = Wx::StaticBox->new($self, -1, "Info");
 
260
            $object_info_sizer = Wx::StaticBoxSizer->new($box, wxVERTICAL);
 
261
            my $grid_sizer = Wx::FlexGridSizer->new(3, 4, 5, 5);
 
262
            $grid_sizer->SetFlexibleDirection(wxHORIZONTAL);
 
263
            $grid_sizer->AddGrowableCol(1, 1);
 
264
            $grid_sizer->AddGrowableCol(3, 1);
 
265
            $object_info_sizer->Add($grid_sizer, 0, wxEXPAND);
 
266
            
 
267
            my @info = (
 
268
                size        => "Size",
 
269
                volume      => "Volume",
 
270
                facets      => "Facets",
 
271
                materials   => "Materials",
 
272
                manifold    => "Manifold",
 
273
            );
 
274
            while (my $field = shift @info) {
 
275
                my $label = shift @info;
 
276
                my $text = Wx::StaticText->new($self, -1, "$label:", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
 
277
                $text->SetFont($Slic3r::GUI::small_font);
 
278
                $grid_sizer->Add($text, 0);
 
279
                
 
280
                $self->{"object_info_$field"} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
 
281
                $self->{"object_info_$field"}->SetFont($Slic3r::GUI::small_font);
 
282
                if ($field eq 'manifold') {
 
283
                    $self->{object_info_manifold_warning_icon} = Wx::StaticBitmap->new($self, -1, Wx::Bitmap->new("$Slic3r::var/error.png", wxBITMAP_TYPE_PNG));
 
284
                    $self->{object_info_manifold_warning_icon}->Hide;
 
285
                    
 
286
                    my $h_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
 
287
                    $h_sizer->Add($self->{object_info_manifold_warning_icon}, 0);
 
288
                    $h_sizer->Add($self->{"object_info_$field"}, 0);
 
289
                    $grid_sizer->Add($h_sizer, 0, wxEXPAND);
 
290
                } else {
 
291
                    $grid_sizer->Add($self->{"object_info_$field"}, 0);
 
292
                }
 
293
            }
 
294
        }
 
295
        
 
296
        my $right_buttons_sizer = Wx::BoxSizer->new(wxVERTICAL);
 
297
        $right_buttons_sizer->Add($presets, 0, wxEXPAND, 0) if defined $presets;
 
298
        $right_buttons_sizer->Add($self->{btn_export_gcode}, 0, wxEXPAND | wxTOP, 8);
 
299
        $right_buttons_sizer->Add($self->{btn_export_stl}, 0, wxEXPAND | wxTOP, 2);
 
300
        
 
301
        my $right_top_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
 
302
        $right_top_sizer->Add($self->{list}, 1, wxEXPAND | wxLEFT, 5);
 
303
        $right_top_sizer->Add($right_buttons_sizer, 0, wxEXPAND | wxALL, 10);
 
304
        
 
305
        my $right_sizer = Wx::BoxSizer->new(wxVERTICAL);
 
306
        $right_sizer->Add($right_top_sizer, 1, wxEXPAND | wxBOTTOM, 10);
 
307
        $right_sizer->Add($object_info_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, 5);
 
308
        
 
309
        my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL);
 
310
        $hsizer->Add($self->{canvas}, 0, wxTOP, 1);
 
311
        $hsizer->Add($right_sizer, 1, wxEXPAND | wxBOTTOM, 0);
 
312
        
 
313
        my $sizer = Wx::BoxSizer->new(wxVERTICAL);
 
314
        $sizer->Add($self->{htoolbar}, 0, wxEXPAND, 0) if $self->{htoolbar};
 
315
        $sizer->Add($self->{btoolbar}, 0, wxEXPAND, 0) if $self->{btoolbar};
 
316
        $sizer->Add($hsizer, 1, wxEXPAND, 0);
 
317
        
 
318
        $sizer->SetSizeHints($self);
 
319
        $self->SetSizer($sizer);
 
320
    }
 
321
    return $self;
 
322
}
 
323
 
 
324
sub on_select_preset {
 
325
        my $self = shift;
 
326
        my ($group, $choice) = @_;
 
327
        
 
328
        if ($group eq 'filament' && @{$self->{preset_choosers}{filament}} > 1) {
 
329
                my @filament_presets = $self->filament_presets;
 
330
                $Slic3r::GUI::Settings->{presets}{filament} = $choice->GetString($filament_presets[0]) . ".ini";
 
331
                $Slic3r::GUI::Settings->{presets}{"filament_${_}"} = $choice->GetString($filament_presets[$_])
 
332
                        for 1 .. $#filament_presets;
 
333
                Slic3r::GUI->save_settings;
 
334
                return;
 
335
        }
 
336
        $self->skeinpanel->{options_tabs}{$group}->select_preset($choice->GetSelection);
 
337
}
 
338
 
 
339
sub skeinpanel {
 
340
    my $self = shift;
 
341
    return $self->GetParent->GetParent;
 
342
}
 
343
 
 
344
sub update_presets {
 
345
    my $self = shift;
 
346
    my ($group, $items, $selected) = @_;
 
347
    
 
348
    foreach my $choice (@{ $self->{preset_choosers}{$group} }) {
 
349
        my $sel = $choice->GetSelection;
 
350
        $choice->Clear;
 
351
        $choice->Append($_) for @$items;
 
352
        $choice->SetSelection($sel) if $sel <= $#$items;
 
353
    }
 
354
    $self->{preset_choosers}{$group}[0]->SetSelection($selected);
 
355
}
 
356
 
 
357
sub filament_presets {
 
358
    my $self = shift;
 
359
    
 
360
    return map $_->GetSelection, @{ $self->{preset_choosers}{filament} };
 
361
}
 
362
 
 
363
sub add {
 
364
    my $self = shift;
 
365
    
 
366
    my @input_files = Slic3r::GUI::open_model($self);
 
367
    $self->load_file($_) for @input_files;
 
368
}
 
369
 
 
370
sub load_file {
 
371
    my $self = shift;
 
372
    my ($input_file) = @_;
 
373
    
 
374
    $Slic3r::GUI::Settings->{recent}{skein_directory} = dirname($input_file);
 
375
    Slic3r::GUI->save_settings;
 
376
    
 
377
    my $process_dialog = Wx::ProgressDialog->new('Loading…', "Processing input file…", 100, $self, 0);
 
378
    $process_dialog->Pulse;
 
379
    
 
380
    local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self);
 
381
    
 
382
    my $model = eval { Slic3r::Model->read_from_file($input_file) };
 
383
    Slic3r::GUI::show_error($self, $@) if $@;
 
384
    
 
385
    if (defined $model) {
 
386
        $self->load_model_objects(@{$model->objects});
 
387
        $self->statusbar->SetStatusText("Loaded " . basename($input_file));
 
388
    }
 
389
    
 
390
    $process_dialog->Destroy;
 
391
}
 
392
 
 
393
sub load_model_objects {
 
394
    my ($self, @model_objects) = @_;
 
395
    
 
396
    my $need_arrange = 0;
 
397
    my @obj_idx = ();
 
398
    foreach my $model_object (@model_objects) {
 
399
        my $o = $self->{model}->add_object($model_object);
 
400
        
 
401
        push @{ $self->{objects} }, Slic3r::GUI::Plater::Object->new(
 
402
            name => basename($model_object->input_file),
 
403
        );
 
404
        push @obj_idx, $#{ $self->{objects} };
 
405
    
 
406
        if ($model_object->instances_count == 0) {
 
407
            # if object has no defined position(s) we need to rearrange everything after loading
 
408
            $need_arrange = 1;
 
409
        
 
410
            # add a default instance and center object around origin
 
411
            $o->center_around_origin;
 
412
            $o->add_instance(offset => Slic3r::Pointf->new(@{$self->{config}->print_center}));
 
413
        }
 
414
    
 
415
        $self->{print}->auto_assign_extruders($o);
 
416
        $self->{print}->add_model_object($o);
 
417
    }
 
418
    
 
419
    # if user turned autocentering off, automatic arranging would disappoint them
 
420
    if (!$Slic3r::GUI::Settings->{_}{autocenter}) {
 
421
        $need_arrange = 0;
 
422
    }
 
423
    
 
424
    $self->objects_loaded(\@obj_idx, no_arrange => !$need_arrange);
 
425
}
 
426
 
 
427
sub objects_loaded {
 
428
    my $self = shift;
 
429
    my ($obj_idxs, %params) = @_;
 
430
    
 
431
    foreach my $obj_idx (@$obj_idxs) {
 
432
        my $object = $self->{objects}[$obj_idx];
 
433
        my $model_object = $self->{model}->objects->[$obj_idx];
 
434
        $self->{list}->InsertStringItem($obj_idx, $object->name);
 
435
        $self->{list}->SetItemFont($obj_idx, Wx::Font->new(10, wxDEFAULT, wxNORMAL, wxNORMAL))
 
436
            if $self->{list}->can('SetItemFont');  # legacy code for wxPerl < 0.9918 not supporting SetItemFont()
 
437
    
 
438
        $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
 
439
        $self->{list}->SetItem($obj_idx, 2, ($model_object->instances->[0]->scaling_factor * 100) . "%");
 
440
    
 
441
        $self->make_thumbnail($obj_idx);
 
442
    }
 
443
    $self->arrange unless $params{no_arrange};
 
444
    $self->update;
 
445
    $self->{list}->Update;
 
446
    $self->{list}->Select($obj_idxs->[-1], 1);
 
447
    $self->object_list_changed;
 
448
}
 
449
 
 
450
sub remove {
 
451
    my $self = shift;
 
452
    my ($obj_idx) = @_;
 
453
    
 
454
    # if no object index is supplied, remove the selected one
 
455
    if (!defined $obj_idx) {
 
456
        ($obj_idx, undef) = $self->selected_object;
 
457
    }
 
458
    
 
459
    splice @{$self->{objects}}, $obj_idx, 1;
 
460
    $self->{model}->delete_object($obj_idx);
 
461
    $self->{print}->delete_object($obj_idx);
 
462
    $self->{list}->DeleteItem($obj_idx);
 
463
    $self->object_list_changed;
 
464
    
 
465
    $self->select_object(undef);
 
466
    $self->update;
 
467
    $self->{canvas}->Refresh;
 
468
}
 
469
 
 
470
sub reset {
 
471
    my $self = shift;
 
472
    
 
473
    @{$self->{objects}} = ();
 
474
    $self->{model}->clear_objects;
 
475
    $self->{print}->clear_objects;
 
476
    $self->{list}->DeleteAllItems;
 
477
    $self->object_list_changed;
 
478
    
 
479
    $self->select_object(undef);
 
480
    $self->{canvas}->Refresh;
 
481
}
 
482
 
 
483
sub increase {
 
484
    my $self = shift;
 
485
    
 
486
    my ($obj_idx, $object) = $self->selected_object;
 
487
    my $model_object = $self->{model}->objects->[$obj_idx];
 
488
    my $last_instance = $model_object->instances->[-1];
 
489
    my $i = $model_object->add_instance(
 
490
        offset          => Slic3r::Pointf->new(map 10+$_, @{$last_instance->offset}),
 
491
        scaling_factor  => $last_instance->scaling_factor,
 
492
        rotation        => $last_instance->rotation,
 
493
    );
 
494
    $self->{print}->objects->[$obj_idx]->add_copy(@{$i->offset});
 
495
    $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
 
496
    
 
497
    # only autoarrange if user has autocentering enabled
 
498
    if ($Slic3r::GUI::Settings->{_}{autocenter}) {
 
499
        $self->arrange;
 
500
    } else {
 
501
        $self->{canvas}->Refresh;
 
502
    }
 
503
}
 
504
 
 
505
sub decrease {
 
506
    my $self = shift;
 
507
    
 
508
    my ($obj_idx, $object) = $self->selected_object;
 
509
    my $model_object = $self->{model}->objects->[$obj_idx];
 
510
    if ($model_object->instances_count >= 2) {
 
511
        $model_object->delete_last_instance;
 
512
        $self->{print}->objects->[$obj_idx]->delete_last_copy;
 
513
        $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
 
514
    } else {
 
515
        $self->remove;
 
516
    }
 
517
    
 
518
    if ($self->{objects}[$obj_idx]) {
 
519
        $self->{list}->Select($obj_idx, 0);
 
520
        $self->{list}->Select($obj_idx, 1);
 
521
    }
 
522
    $self->update;
 
523
    $self->{canvas}->Refresh;
 
524
}
 
525
 
 
526
sub rotate {
 
527
    my $self = shift;
 
528
    my ($angle) = @_;
 
529
    
 
530
    my ($obj_idx, $object) = $self->selected_object;
 
531
    my $model_object = $self->{model}->objects->[$obj_idx];
 
532
    my $model_instance = $model_object->instances->[0];
 
533
    
 
534
    # we need thumbnail to be computed before allowing rotation
 
535
    return if !$object->thumbnail;
 
536
    
 
537
    if (!defined $angle) {
 
538
        $angle = Wx::GetNumberFromUser("", "Enter the rotation angle:", "Rotate", $model_instance->rotation, -364, 364, $self);
 
539
        return if !$angle || $angle == -1;
 
540
        $angle = 0 - $angle;  # rotate clockwise (be consistent with button icon)
 
541
    }
 
542
    
 
543
    {
 
544
        my $new_angle = $model_instance->rotation + $angle;
 
545
        $_->set_rotation($new_angle) for @{ $model_object->instances };
 
546
        $model_object->update_bounding_box;
 
547
        
 
548
        # update print
 
549
        $self->{print}->delete_object($obj_idx);
 
550
        $self->{print}->add_model_object($model_object, $obj_idx);
 
551
        
 
552
        $object->transform_thumbnail($self->{model}, $obj_idx);
 
553
    }
 
554
    $self->selection_changed;  # refresh info (size etc.)
 
555
    $self->update;
 
556
    $self->{canvas}->Refresh;
 
557
}
 
558
 
 
559
sub changescale {
 
560
    my $self = shift;
 
561
    
 
562
    my ($obj_idx, $object) = $self->selected_object;
 
563
    my $model_object = $self->{model}->objects->[$obj_idx];
 
564
    my $model_instance = $model_object->instances->[0];
 
565
    
 
566
    # we need thumbnail to be computed before allowing scaling
 
567
    return if !$object->thumbnail;
 
568
    
 
569
    # max scale factor should be above 2540 to allow importing files exported in inches
 
570
    my $scale = Wx::GetNumberFromUser("", "Enter the scale % for the selected object:", "Scale", $model_instance->scaling_factor*100, 0, 100000, $self);
 
571
    return if !$scale || $scale == -1;
 
572
    
 
573
    $self->{list}->SetItem($obj_idx, 2, "$scale%");
 
574
    $scale /= 100;  # turn percent into factor
 
575
    {
 
576
        my $variation = $scale / $model_instance->scaling_factor;
 
577
        foreach my $range (@{ $model_object->layer_height_ranges }) {
 
578
            $range->[0] *= $variation;
 
579
            $range->[1] *= $variation;
 
580
        }
 
581
        $_->set_scaling_factor($scale) for @{ $model_object->instances };
 
582
        $model_object->update_bounding_box;
 
583
        
 
584
        # update print
 
585
        $self->{print}->delete_object($obj_idx);
 
586
        $self->{print}->add_model_object($model_object, $obj_idx);
 
587
        
 
588
        $object->transform_thumbnail($self->{model}, $obj_idx);
 
589
    }
 
590
    $self->selection_changed(1);  # refresh info (size, volume etc.)
 
591
    $self->update;
 
592
    $self->{canvas}->Refresh;
 
593
}
 
594
 
 
595
sub arrange {
 
596
    my $self = shift;
 
597
    
 
598
    # get the bounding box of the model area shown in the viewport
 
599
    my $bb = Slic3r::Geometry::BoundingBox->new_from_points([
 
600
        Slic3r::Point->new(@{ $self->point_to_model_units([0,0]) }),
 
601
        Slic3r::Point->new(@{ $self->point_to_model_units(CANVAS_SIZE) }),
 
602
    ]);
 
603
    
 
604
    eval {
 
605
        $self->{model}->arrange_objects($self->skeinpanel->config->min_object_distance, $bb);
 
606
    };
 
607
    # ignore arrange failures on purpose: user has visual feedback and we don't need to warn him
 
608
    # when parts don't fit in print bed
 
609
    
 
610
    $self->update(1);
 
611
    $self->{canvas}->Refresh;
 
612
}
 
613
 
 
614
sub split_object {
 
615
    my $self = shift;
 
616
    
 
617
    my ($obj_idx, $current_object)  = $self->selected_object;
 
618
    my $current_model_object        = $self->{model}->objects->[$obj_idx];
 
619
    
 
620
    if (@{$current_model_object->volumes} > 1) {
 
621
        Slic3r::GUI::warning_catcher($self)->("The selected object couldn't be split because it contains more than one volume/material.");
 
622
        return;
 
623
    }
 
624
    
 
625
    my @new_meshes = @{$current_model_object->volumes->[0]->mesh->split};
 
626
    if (@new_meshes == 1) {
 
627
        Slic3r::GUI::warning_catcher($self)->("The selected object couldn't be split because it already contains a single part.");
 
628
        return;
 
629
    }
 
630
    
 
631
    # create a bogus Model object, we only need to instantiate the new Model::Object objects
 
632
    my $new_model = Slic3r::Model->new;
 
633
    
 
634
    my @model_objects = ();
 
635
    foreach my $mesh (@new_meshes) {
 
636
        $mesh->repair;
 
637
        
 
638
        my $model_object = $new_model->add_object(
 
639
            input_file              => $current_model_object->input_file,
 
640
            config                  => $current_model_object->config->clone,
 
641
            layer_height_ranges     => $current_model_object->layer_height_ranges,  # TODO: clone this
 
642
        );
 
643
        $model_object->add_volume(
 
644
            mesh        => $mesh,
 
645
            material_id => $current_model_object->volumes->[0]->material_id,
 
646
        );
 
647
        
 
648
        for my $instance_idx (0..$#{ $current_model_object->instances }) {
 
649
            my $current_instance = $current_model_object->instances->[$instance_idx];
 
650
            $model_object->add_instance(
 
651
                offset          => Slic3r::Pointf->new(
 
652
                    $current_instance->offset->[X] + ($instance_idx * 10),
 
653
                    $current_instance->offset->[Y] + ($instance_idx * 10),
 
654
                ),
 
655
                rotation        => $current_instance->rotation,
 
656
                scaling_factor  => $current_instance->scaling_factor,
 
657
            );
 
658
        }
 
659
        # we need to center this single object around origin
 
660
        $model_object->center_around_origin;
 
661
        push @model_objects, $model_object;
 
662
    }
 
663
 
 
664
    # remove the original object before spawning the object_loaded event, otherwise 
 
665
    # we'll pass the wrong $obj_idx to it (which won't be recognized after the
 
666
    # thumbnail thread returns)
 
667
    $self->remove($obj_idx);
 
668
    $current_object = $obj_idx = undef;
 
669
    
 
670
    # load all model objects at once, otherwise the plate would be rearranged after each one
 
671
    # causing original positions not to be kept
 
672
    $self->load_model_objects(@model_objects);
 
673
}
 
674
 
 
675
sub export_gcode {
 
676
    my $self = shift;
 
677
    
 
678
    if ($self->{export_thread}) {
 
679
        Wx::MessageDialog->new($self, "Another slicing job is currently running.", 'Error', wxOK | wxICON_ERROR)->ShowModal;
 
680
        return;
 
681
    }
 
682
    
 
683
    # It looks like declaring a local $SIG{__WARN__} prevents the ugly
 
684
    # "Attempt to free unreferenced scalar" warning...
 
685
    local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self);
 
686
    
 
687
    # apply config and validate print
 
688
    my $config = $self->skeinpanel->config;
 
689
    eval {
 
690
        # this will throw errors if config is not valid
 
691
        $config->validate;
 
692
        $self->{print}->apply_config($config);
 
693
        $self->{print}->validate;
 
694
    };
 
695
    Slic3r::GUI::catch_error($self) and return;
 
696
    
 
697
    # apply extra variables
 
698
    {
 
699
        my $extra = $self->skeinpanel->extra_variables;
 
700
        $self->{print}->placeholder_parser->set($_, $extra->{$_}) for keys %$extra;
 
701
    }
 
702
    
 
703
    # select output file
 
704
    $self->{output_file} = $main::opt{output};
 
705
    {
 
706
        my $output_file = $self->{print}->expanded_output_filepath($self->{output_file});
 
707
        my $dlg = Wx::FileDialog->new($self, 'Save G-code file as:', Slic3r::GUI->output_path(dirname($output_file)),
 
708
            basename($output_file), &Slic3r::GUI::SkeinPanel::FILE_WILDCARDS->{gcode}, wxFD_SAVE);
 
709
        if ($dlg->ShowModal != wxID_OK) {
 
710
            $dlg->Destroy;
 
711
            return;
 
712
        }
 
713
        $Slic3r::GUI::Settings->{_}{last_output_path} = dirname($dlg->GetPath);
 
714
        Slic3r::GUI->save_settings;
 
715
        $self->{output_file} = $Slic3r::GUI::SkeinPanel::last_output_file = $dlg->GetPath;
 
716
        $dlg->Destroy;
 
717
    }
 
718
    
 
719
    $self->statusbar->StartBusy;
 
720
    
 
721
    if ($Slic3r::have_threads) {
 
722
        @_ = ();
 
723
        
 
724
        # some perls (including 5.14.2) crash on threads->exit if we pass lexicals to the thread
 
725
        our $_thread_self = $self;
 
726
        
 
727
        $self->{export_thread} = threads->create(sub {
 
728
            $_thread_self->export_gcode2(
 
729
                $_thread_self->{output_file},
 
730
                progressbar     => sub { Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $PROGRESS_BAR_EVENT, shared_clone([@_]))) },
 
731
                message_dialog  => sub { Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $MESSAGE_DIALOG_EVENT, shared_clone([@_]))) },
 
732
                on_completed    => sub { Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, shared_clone([@_]))) },
 
733
                catch_error     => sub {
 
734
                    Slic3r::GUI::catch_error($_thread_self, $_[0], sub {
 
735
                        Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $MESSAGE_DIALOG_EVENT, shared_clone([@_])));
 
736
                        Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_FAILED_EVENT, undef));
 
737
                    });
 
738
                },
 
739
            );
 
740
            Slic3r::thread_cleanup();
 
741
        });
 
742
        $self->statusbar->SetCancelCallback(sub {
 
743
            $self->{export_thread}->kill('KILL')->join;
 
744
            $self->{export_thread} = undef;
 
745
            $self->statusbar->StopBusy;
 
746
            $self->statusbar->SetStatusText("Export cancelled");
 
747
        });
 
748
    } else {
 
749
        $self->export_gcode2(
 
750
            $self->{output_file},
 
751
            progressbar => sub {
 
752
                my ($percent, $message) = @_;
 
753
                $self->statusbar->SetProgress($percent);
 
754
                $self->statusbar->SetStatusText("$message…");
 
755
            },
 
756
            message_dialog => sub { Wx::MessageDialog->new($self, @_)->ShowModal },
 
757
            on_completed => sub { $self->on_export_completed(@_) },
 
758
            catch_error => sub { Slic3r::GUI::catch_error($self, @_) && $self->on_export_failed },
 
759
        );
 
760
    }
 
761
    
 
762
    # this method gets executed in a separate thread by wxWidgets since it's a button handler
 
763
    Slic3r::thread_cleanup() if $Slic3r::have_threads;
 
764
}
 
765
 
 
766
sub export_gcode2 {
 
767
    my $self = shift;
 
768
    my ($output_file, %params) = @_;
 
769
    local $SIG{'KILL'} = sub {
 
770
        Slic3r::debugf "Exporting cancelled; exiting thread...\n";
 
771
        Slic3r::thread_cleanup();
 
772
        threads->exit();
 
773
    } if $Slic3r::have_threads;
 
774
    
 
775
    my $print = $self->{print};
 
776
    
 
777
    eval {
 
778
        {
 
779
            my @warnings = ();
 
780
            local $SIG{__WARN__} = sub { push @warnings, $_[0] };
 
781
            
 
782
            $print->status_cb(sub { $params{progressbar}->(@_) });
 
783
            if ($params{export_svg}) {
 
784
                $print->export_svg(output_file => $output_file);
 
785
            } else {
 
786
                $print->process;
 
787
                $print->export_gcode(output_file => $output_file);
 
788
            }
 
789
            $print->status_cb(undef);
 
790
            Slic3r::GUI::warning_catcher($self, $Slic3r::have_threads ? sub {
 
791
                Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $MESSAGE_DIALOG_EVENT, shared_clone([@_])));
 
792
            } : undef)->($_) for @warnings;
 
793
        }
 
794
        
 
795
        $params{on_completed}->();
 
796
    };
 
797
    $params{catch_error}->();
 
798
}
 
799
 
 
800
sub on_export_completed {
 
801
    my $self = shift;
 
802
    
 
803
    $self->{export_thread}->detach if $self->{export_thread};
 
804
    $self->{export_thread} = undef;
 
805
    $self->statusbar->SetCancelCallback(undef);
 
806
    $self->statusbar->StopBusy;
 
807
    my $message = "G-code file exported to $self->{output_file}";
 
808
    $self->statusbar->SetStatusText($message);
 
809
    &Wx::wxTheApp->notify($message);
 
810
}
 
811
 
 
812
sub on_export_failed {
 
813
    my $self = shift;
 
814
    
 
815
    $self->{export_thread}->detach if $self->{export_thread};
 
816
    $self->{export_thread} = undef;
 
817
    $self->statusbar->SetCancelCallback(undef);
 
818
    $self->statusbar->StopBusy;
 
819
    $self->statusbar->SetStatusText("Export failed");
 
820
}
 
821
 
 
822
sub export_stl {
 
823
    my $self = shift;
 
824
        
 
825
    my $output_file = $self->_get_export_file('STL') or return;
 
826
    Slic3r::Format::STL->write_file($output_file, $self->{model}, binary => 1);
 
827
    $self->statusbar->SetStatusText("STL file exported to $output_file");
 
828
    
 
829
    # this method gets executed in a separate thread by wxWidgets since it's a button handler
 
830
    Slic3r::thread_cleanup() if $Slic3r::have_threads;
 
831
}
 
832
 
 
833
sub export_amf {
 
834
    my $self = shift;
 
835
        
 
836
    my $output_file = $self->_get_export_file('AMF') or return;
 
837
    Slic3r::Format::AMF->write_file($output_file, $self->{model});
 
838
    $self->statusbar->SetStatusText("AMF file exported to $output_file");
 
839
    
 
840
    # this method gets executed in a separate thread by wxWidgets since it's a menu handler
 
841
    Slic3r::thread_cleanup() if $Slic3r::have_threads;
 
842
}
 
843
 
 
844
sub _get_export_file {
 
845
    my $self = shift;
 
846
    my ($format) = @_;
 
847
    
 
848
    my $suffix = $format eq 'STL' ? '.stl' : '.amf.xml';
 
849
    
 
850
    my $output_file = $main::opt{output};
 
851
    {
 
852
        $output_file = $self->{print}->expanded_output_filepath($output_file);
 
853
        $output_file =~ s/\.gcode$/$suffix/i;
 
854
        my $dlg = Wx::FileDialog->new($self, "Save $format file as:", dirname($output_file),
 
855
            basename($output_file), &Slic3r::GUI::SkeinPanel::MODEL_WILDCARD, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
 
856
        if ($dlg->ShowModal != wxID_OK) {
 
857
            $dlg->Destroy;
 
858
            return undef;
 
859
        }
 
860
        $output_file = $Slic3r::GUI::SkeinPanel::last_output_file = $dlg->GetPath;
 
861
        $dlg->Destroy;
 
862
    }
 
863
    return $output_file;
 
864
}
 
865
 
 
866
sub make_thumbnail {
 
867
    my $self = shift;
 
868
    my ($obj_idx) = @_;
 
869
    
 
870
    my $plater_object = $self->{objects}[$obj_idx];
 
871
    $plater_object->thumbnail(Slic3r::ExPolygon::Collection->new);
 
872
    my $cb = sub {
 
873
        $plater_object->make_thumbnail($self->{model}, $obj_idx);
 
874
        
 
875
        if ($Slic3r::have_threads) {
 
876
            Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $THUMBNAIL_DONE_EVENT, shared_clone([ $obj_idx ])));
 
877
            Slic3r::thread_cleanup();
 
878
            threads->exit;
 
879
        } else {
 
880
            $self->on_thumbnail_made($obj_idx);
 
881
        }
 
882
    };
 
883
    
 
884
    @_ = ();
 
885
    $Slic3r::have_threads
 
886
        ? threads->create(sub { $cb->(); Slic3r::thread_cleanup(); })->detach
 
887
        : $cb->();
 
888
}
 
889
 
 
890
sub on_thumbnail_made {
 
891
    my $self = shift;
 
892
    my ($obj_idx) = @_;
 
893
    
 
894
    $self->{objects}[$obj_idx]->transform_thumbnail($self->{model}, $obj_idx);
 
895
    $self->update;
 
896
    $self->{canvas}->Refresh;
 
897
}
 
898
 
 
899
sub clean_instance_thumbnails {
 
900
    my ($self) = @_;
 
901
    
 
902
    foreach my $object (@{ $self->{objects} }) {
 
903
        @{ $object->instance_thumbnails } = ();
 
904
    }
 
905
}
 
906
 
 
907
# this method gets called whenever print center is changed or the objects' bounding box changes
 
908
# (i.e. when an object is added/removed/moved/rotated/scaled)
 
909
sub update {
 
910
    my ($self, $force_autocenter) = @_;
 
911
    
 
912
    if ($Slic3r::GUI::Settings->{_}{autocenter} || $force_autocenter) {
 
913
        $self->{model}->center_instances_around_point($self->{config}->print_center);
 
914
    }
 
915
    
 
916
    # sync model and print object instances
 
917
    for my $obj_idx (0..$#{$self->{objects}}) {
 
918
        my $model_object = $self->{model}->objects->[$obj_idx];
 
919
        my $print_object = $self->{print}->objects->[$obj_idx];
 
920
        
 
921
        $print_object->delete_all_copies;
 
922
        $print_object->add_copy(@{$_->offset}) for @{$model_object->instances};
 
923
    }
 
924
    
 
925
    $self->{canvas}->Refresh;
 
926
}
 
927
 
 
928
sub on_config_change {
 
929
    my $self = shift;
 
930
    my ($opt_key, $value) = @_;
 
931
    if ($opt_key eq 'extruders_count' && defined $value) {
 
932
        my $choices = $self->{preset_choosers}{filament};
 
933
        while (@$choices < $value) {
 
934
                my @presets = $choices->[0]->GetStrings;
 
935
            push @$choices, Wx::Choice->new($self, -1, wxDefaultPosition, [150, -1], [@presets]);
 
936
            $choices->[-1]->SetFont($Slic3r::GUI::small_font);
 
937
            $self->{preset_choosers_sizers}{filament}->Add($choices->[-1], 0, wxEXPAND | wxBOTTOM, FILAMENT_CHOOSERS_SPACING);
 
938
            EVT_CHOICE($choices->[-1], $choices->[-1], sub { $self->on_select_preset('filament', @_) });
 
939
            my $i = first { $choices->[-1]->GetString($_) eq ($Slic3r::GUI::Settings->{presets}{"filament_" . $#$choices} || '') } 0 .. $#presets;
 
940
                $choices->[-1]->SetSelection($i || 0);
 
941
        }
 
942
        while (@$choices > $value) {
 
943
            $self->{preset_choosers_sizers}{filament}->Remove(-1);
 
944
            $choices->[-1]->Destroy;
 
945
            pop @$choices;
 
946
        }
 
947
        $self->Layout;
 
948
    } elsif ($self->{config}->has($opt_key)) {
 
949
        $self->{config}->set($opt_key, $value);
 
950
        $self->_update_bed_size if $opt_key eq 'bed_size';
 
951
        $self->update if $opt_key eq 'print_center';
 
952
    }
 
953
}
 
954
 
 
955
sub _update_bed_size {
 
956
    my $self = shift;
 
957
    
 
958
    # supposing the preview canvas is square, calculate the scaling factor
 
959
    # to constrain print bed area inside preview
 
960
    # when the canvas is not rendered yet, its GetSize() method returns 0,0
 
961
    # scaling_factor is expressed in pixel / mm
 
962
    $self->{scaling_factor} = CANVAS_SIZE->[X] / max(@{ $self->{config}->bed_size });
 
963
    $self->update;
 
964
}
 
965
 
 
966
# this is called on the canvas
 
967
sub repaint {
 
968
    my ($self, $event) = @_;
 
969
    my $parent = $self->GetParent;
 
970
    
 
971
    my $dc = Wx::PaintDC->new($self);
 
972
    my $size = $self->GetSize;
 
973
    my @size = ($size->GetWidth, $size->GetHeight);
 
974
    
 
975
    # draw grid
 
976
    $dc->SetPen($parent->{grid_pen});
 
977
    my $step = 10 * $parent->{scaling_factor};
 
978
    for (my $x = $step; $x <= $size[X]; $x += $step) {
 
979
        $dc->DrawLine($x, 0, $x, $size[Y]);
 
980
    }
 
981
    for (my $y = $step; $y <= $size[Y]; $y += $step) {
 
982
        $dc->DrawLine(0, $y, $size[X], $y);
 
983
    }
 
984
    
 
985
    # draw print center
 
986
    if (@{$parent->{objects}}) {
 
987
        $dc->SetPen($parent->{print_center_pen});
 
988
        $dc->DrawLine($size[X]/2, 0, $size[X]/2, $size[Y]);
 
989
        $dc->DrawLine(0, $size[Y]/2, $size[X], $size[Y]/2);
 
990
        $dc->SetTextForeground(Wx::Colour->new(0,0,0));
 
991
        $dc->SetFont(Wx::Font->new(10, wxDEFAULT, wxNORMAL, wxNORMAL));
 
992
        $dc->DrawLabel("X = " . $parent->{config}->print_center->[X], Wx::Rect->new(0, 0, $self->GetSize->GetWidth, $self->GetSize->GetHeight), wxALIGN_CENTER_HORIZONTAL | wxALIGN_BOTTOM);
 
993
        $dc->DrawRotatedText("Y = " . $parent->{config}->print_center->[Y], 0, $size[Y]/2+15, 90);
 
994
    }
 
995
    
 
996
    # draw frame
 
997
    if (0) {
 
998
        $dc->SetPen(wxBLACK_PEN);
 
999
        $dc->SetBrush($parent->{transparent_brush});
 
1000
        $dc->DrawRectangle(0, 0, @size);
 
1001
    }
 
1002
    
 
1003
    # draw text if plate is empty
 
1004
    if (!@{$parent->{objects}}) {
 
1005
        $dc->SetTextForeground(Wx::Colour->new(150,50,50));
 
1006
        $dc->SetFont(Wx::Font->new(14, wxDEFAULT, wxNORMAL, wxNORMAL));
 
1007
        $dc->DrawLabel(CANVAS_TEXT, Wx::Rect->new(0, 0, $self->GetSize->GetWidth, $self->GetSize->GetHeight), wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL);
 
1008
    }
 
1009
    
 
1010
    # draw thumbnails
 
1011
    $dc->SetPen(wxBLACK_PEN);
 
1012
    $parent->clean_instance_thumbnails;
 
1013
    for my $obj_idx (0 .. $#{$parent->{objects}}) {
 
1014
        my $object = $parent->{objects}[$obj_idx];
 
1015
        my $model_object = $parent->{model}->objects->[$obj_idx];
 
1016
        next unless defined $object->thumbnail;
 
1017
        for my $instance_idx (0 .. $#{$model_object->instances}) {
 
1018
            my $instance = $model_object->instances->[$instance_idx];
 
1019
            next if !defined $object->transformed_thumbnail;
 
1020
            
 
1021
            my $thumbnail = $object->transformed_thumbnail->clone;      # in scaled model coordinates
 
1022
            $thumbnail->translate(map scale($_), @{$instance->offset});
 
1023
            
 
1024
            $object->instance_thumbnails->[$instance_idx] = $thumbnail;
 
1025
            
 
1026
            if (defined $self->{drag_object} && $self->{drag_object}[0] == $obj_idx && $self->{drag_object}[1] == $instance_idx) {
 
1027
                $dc->SetBrush($parent->{dragged_brush});
 
1028
            } elsif ($object->selected) {
 
1029
                $dc->SetBrush($parent->{selected_brush});
 
1030
            } else {
 
1031
                $dc->SetBrush($parent->{objects_brush});
 
1032
            }
 
1033
            foreach my $expolygon (@$thumbnail) {
 
1034
                foreach my $points (@{$expolygon->pp}) {
 
1035
                    $dc->DrawPolygon($parent->points_to_pixel($points, 1), 0, 0);
 
1036
                }
 
1037
            }
 
1038
            
 
1039
            if (0) {
 
1040
                # draw bounding box for debugging purposes
 
1041
                my $bb = $model_object->instance_bounding_box($instance_idx);
 
1042
                $bb->scale($parent->{scaling_factor});
 
1043
                # no need to translate by instance offset because instance_bounding_box() does that
 
1044
                my $points = $bb->polygon->pp;
 
1045
                $dc->SetPen($parent->{clearance_pen});
 
1046
                $dc->SetBrush($parent->{transparent_brush});
 
1047
                $dc->DrawPolygon($parent->_y($points), 0, 0);
 
1048
            }
 
1049
            
 
1050
            # if sequential printing is enabled and we have more than one object, draw clearance area
 
1051
            if ($parent->{config}->complete_objects && (map @{$_->instances}, @{$parent->{model}->objects}) > 1) {
 
1052
                my ($clearance) = @{offset([$thumbnail->convex_hull], (scale($parent->{config}->extruder_clearance_radius) / 2), 1, JT_ROUND, scale(0.1))};
 
1053
                $dc->SetPen($parent->{clearance_pen});
 
1054
                $dc->SetBrush($parent->{transparent_brush});
 
1055
                $dc->DrawPolygon($parent->points_to_pixel($clearance, 1), 0, 0);
 
1056
            }
 
1057
        }
 
1058
    }
 
1059
    
 
1060
    # draw skirt
 
1061
    if (@{$parent->{objects}} && $parent->{config}->skirts) {
 
1062
        my @points = map @{$_->contour}, map @$_, map @{$_->instance_thumbnails}, @{$parent->{objects}};
 
1063
        if (@points >= 3) {
 
1064
            my ($convex_hull) = @{offset([convex_hull(\@points)], scale($parent->{config}->skirt_distance), 1, JT_ROUND, scale(0.1))};
 
1065
            $dc->SetPen($parent->{skirt_pen});
 
1066
            $dc->SetBrush($parent->{transparent_brush});
 
1067
            $dc->DrawPolygon($parent->points_to_pixel($convex_hull, 1), 0, 0);
 
1068
        }
 
1069
    }
 
1070
    
 
1071
    $event->Skip;
 
1072
}
 
1073
 
 
1074
sub mouse_event {
 
1075
    my ($self, $event) = @_;
 
1076
    my $parent = $self->GetParent;
 
1077
    
 
1078
    my $point = $event->GetPosition;
 
1079
    my $pos = $parent->point_to_model_units([ $point->x, $point->y ]);  #]]
 
1080
    $pos = Slic3r::Point->new_scale(@$pos);
 
1081
    if ($event->ButtonDown(&Wx::wxMOUSE_BTN_LEFT)) {
 
1082
        $parent->select_object(undef);
 
1083
        for my $obj_idx (0 .. $#{$parent->{objects}}) {
 
1084
            my $object = $parent->{objects}->[$obj_idx];
 
1085
            for my $instance_idx (0 .. $#{ $object->instance_thumbnails }) {
 
1086
                my $thumbnail = $object->instance_thumbnails->[$instance_idx];
 
1087
                if (defined first { $_->contour->contains_point($pos) } @$thumbnail) {
 
1088
                    $parent->select_object($obj_idx);
 
1089
                    my $instance = $parent->{model}->objects->[$obj_idx]->instances->[$instance_idx];
 
1090
                    my $instance_origin = [ map scale($_), @{$instance->offset} ];
 
1091
                    $self->{drag_start_pos} = [   # displacement between the click and the instance origin in scaled model units
 
1092
                        $pos->x - $instance_origin->[X],
 
1093
                        $pos->y - $instance_origin->[Y],  #-
 
1094
                    ];
 
1095
                    $self->{drag_object} = [ $obj_idx, $instance_idx ];
 
1096
                }
 
1097
            }
 
1098
        }
 
1099
        $parent->Refresh;
 
1100
    } elsif ($event->ButtonUp(&Wx::wxMOUSE_BTN_LEFT)) {
 
1101
        $parent->update;
 
1102
        $parent->Refresh;
 
1103
        $self->{drag_start_pos} = undef;
 
1104
        $self->{drag_object} = undef;
 
1105
        $self->SetCursor(wxSTANDARD_CURSOR);
 
1106
    } elsif ($event->ButtonDClick) {
 
1107
        $parent->object_cut_dialog if $parent->selected_object;
 
1108
    } elsif ($event->Dragging) {
 
1109
        return if !$self->{drag_start_pos}; # concurrency problems
 
1110
        my ($obj_idx, $instance_idx) = @{ $self->{drag_object} };
 
1111
        my $model_object = $parent->{model}->objects->[$obj_idx];
 
1112
        $model_object->instances->[$instance_idx]->set_offset(
 
1113
            Slic3r::Pointf->new(
 
1114
                unscale($pos->[X] - $self->{drag_start_pos}[X]),
 
1115
                unscale($pos->[Y] - $self->{drag_start_pos}[Y]),
 
1116
            ));
 
1117
        $model_object->update_bounding_box;
 
1118
        $parent->Refresh;
 
1119
    } elsif ($event->Moving) {
 
1120
        my $cursor = wxSTANDARD_CURSOR;
 
1121
        if (defined first { $_->contour->contains_point($pos) } map @$_, map @{$_->instance_thumbnails}, @{ $parent->{objects} }) {
 
1122
            $cursor = Wx::Cursor->new(wxCURSOR_HAND);
 
1123
        }
 
1124
        $self->SetCursor($cursor);
 
1125
    }
 
1126
}
 
1127
 
 
1128
sub list_item_deselected {
 
1129
    my ($self, $event) = @_;
 
1130
    return if $PreventListEvents;
 
1131
    
 
1132
    if ($self->{list}->GetFirstSelected == -1) {
 
1133
        $self->select_object(undef);
 
1134
        $self->{canvas}->Refresh;
 
1135
    }
 
1136
}
 
1137
 
 
1138
sub list_item_selected {
 
1139
    my ($self, $event) = @_;
 
1140
    return if $PreventListEvents;
 
1141
    
 
1142
    my $obj_idx = $event->GetIndex;
 
1143
    $self->select_object($obj_idx);
 
1144
    $self->{canvas}->Refresh;
 
1145
}
 
1146
 
 
1147
sub list_item_activated {
 
1148
    my ($self, $event, $obj_idx) = @_;
 
1149
    
 
1150
    $obj_idx //= $event->GetIndex;
 
1151
        $self->object_cut_dialog($obj_idx);
 
1152
}
 
1153
 
 
1154
sub object_cut_dialog {
 
1155
    my $self = shift;
 
1156
    my ($obj_idx) = @_;
 
1157
    
 
1158
    if (!defined $obj_idx) {
 
1159
        ($obj_idx, undef) = $self->selected_object;
 
1160
    }
 
1161
    
 
1162
    if (!$Slic3r::GUI::have_OpenGL) {
 
1163
        Slic3r::GUI::show_error($self, "Please install the OpenGL modules to use this feature (see build instructions).");
 
1164
        return;
 
1165
    }
 
1166
    
 
1167
    my $dlg = Slic3r::GUI::Plater::ObjectCutDialog->new($self,
 
1168
                object              => $self->{objects}[$obj_idx],
 
1169
                model_object        => $self->{model}->objects->[$obj_idx],
 
1170
        );
 
1171
        $dlg->ShowModal;
 
1172
        
 
1173
        if (my @new_objects = $dlg->NewModelObjects) {
 
1174
            $self->remove($obj_idx);
 
1175
            $self->load_model_objects(@new_objects);
 
1176
            $self->arrange;
 
1177
        }
 
1178
}
 
1179
 
 
1180
sub object_settings_dialog {
 
1181
    my $self = shift;
 
1182
    my ($obj_idx) = @_;
 
1183
    
 
1184
    if (!defined $obj_idx) {
 
1185
        ($obj_idx, undef) = $self->selected_object;
 
1186
    }
 
1187
    my $model_object = $self->{model}->objects->[$obj_idx];
 
1188
    
 
1189
    # validate config before opening the settings dialog because
 
1190
    # that dialog can't be closed if validation fails, but user
 
1191
    # can't fix any error which is outside that dialog
 
1192
    return unless $self->validate_config;
 
1193
    
 
1194
    my $dlg = Slic3r::GUI::Plater::ObjectSettingsDialog->new($self,
 
1195
                object          => $self->{objects}[$obj_idx],
 
1196
                model_object    => $model_object,
 
1197
        );
 
1198
        $dlg->ShowModal;
 
1199
        
 
1200
        # update thumbnail since parts may have changed
 
1201
        if ($dlg->PartsChanged) {
 
1202
        $self->make_thumbnail($obj_idx);
 
1203
        }
 
1204
        
 
1205
        # update print
 
1206
        if ($dlg->PartsChanged || $dlg->PartSettingsChanged) {
 
1207
        $self->{print}->reload_object($obj_idx);
 
1208
    }
 
1209
}
 
1210
 
 
1211
sub object_list_changed {
 
1212
    my $self = shift;
 
1213
    
 
1214
    my $have_objects = @{$self->{objects}} ? 1 : 0;
 
1215
    my $method = $have_objects ? 'Enable' : 'Disable';
 
1216
    $self->{"btn_$_"}->$method
 
1217
        for grep $self->{"btn_$_"}, qw(reset arrange export_gcode export_stl);
 
1218
    
 
1219
    if ($self->{htoolbar}) {
 
1220
        $self->{htoolbar}->EnableTool($_, $have_objects)
 
1221
            for (TB_RESET, TB_ARRANGE);
 
1222
    }
 
1223
}
 
1224
 
 
1225
sub selection_changed {
 
1226
    my $self = shift;
 
1227
    
 
1228
    my ($obj_idx, $object) = $self->selected_object;
 
1229
    my $have_sel = defined $obj_idx;
 
1230
    
 
1231
    my $method = $have_sel ? 'Enable' : 'Disable';
 
1232
    $self->{"btn_$_"}->$method
 
1233
        for grep $self->{"btn_$_"}, qw(remove increase decrease rotate45cw rotate45ccw rotate changescale split view settings);
 
1234
    
 
1235
    if ($self->{htoolbar}) {
 
1236
        $self->{htoolbar}->EnableTool($_, $have_sel)
 
1237
            for (TB_REMOVE, TB_MORE, TB_FEWER, TB_45CW, TB_45CCW, TB_ROTATE, TB_SCALE, TB_SPLIT, TB_VIEW, TB_SETTINGS);
 
1238
    }
 
1239
    
 
1240
    if ($self->{object_info_size}) { # have we already loaded the info pane?
 
1241
        if ($have_sel) {
 
1242
            my $model_object = $self->{model}->objects->[$obj_idx];
 
1243
            my $model_instance = $model_object->instances->[0];
 
1244
            $self->{object_info_size}->SetLabel(sprintf("%.2f x %.2f x %.2f", @{$model_object->instance_bounding_box(0)->size}));
 
1245
            $self->{object_info_materials}->SetLabel($model_object->materials_count);
 
1246
            
 
1247
            if (my $stats = $model_object->mesh_stats) {
 
1248
                $self->{object_info_volume}->SetLabel(sprintf('%.2f', $stats->{volume} * ($model_instance->scaling_factor**3)));
 
1249
                $self->{object_info_facets}->SetLabel(sprintf('%d (%d shells)', $model_object->facets_count, $stats->{number_of_parts}));
 
1250
                if (my $errors = sum(@$stats{qw(degenerate_facets edges_fixed facets_removed facets_added facets_reversed backwards_edges)})) {
 
1251
                    $self->{object_info_manifold}->SetLabel(sprintf("Auto-repaired (%d errors)", $errors));
 
1252
                    $self->{object_info_manifold_warning_icon}->Show;
 
1253
                    
 
1254
                    # we don't show normals_fixed because we never provide normals
 
1255
                        # to admesh, so it generates normals for all facets
 
1256
                    my $message = sprintf '%d degenerate facets, %d edges fixed, %d facets removed, %d facets added, %d facets reversed, %d backwards edges',
 
1257
                        @$stats{qw(degenerate_facets edges_fixed facets_removed facets_added facets_reversed backwards_edges)};
 
1258
                    $self->{object_info_manifold}->SetToolTipString($message);
 
1259
                    $self->{object_info_manifold_warning_icon}->SetToolTipString($message);
 
1260
                } else {
 
1261
                    $self->{object_info_manifold}->SetLabel("Yes");
 
1262
                }
 
1263
            } else {
 
1264
                $self->{object_info_facets}->SetLabel($object->facets);
 
1265
            }
 
1266
        } else {
 
1267
            $self->{"object_info_$_"}->SetLabel("") for qw(size volume facets materials manifold);
 
1268
            $self->{object_info_manifold_warning_icon}->Hide;
 
1269
            $self->{object_info_manifold}->SetToolTipString("");
 
1270
        }
 
1271
        $self->Layout;
 
1272
    }
 
1273
}
 
1274
 
 
1275
sub select_object {
 
1276
    my ($self, $obj_idx) = @_;
 
1277
    
 
1278
    $_->selected(0) for @{ $self->{objects} };
 
1279
    if (defined $obj_idx) {
 
1280
        $self->{objects}->[$obj_idx]->selected(1);
 
1281
        
 
1282
        # We use this flag to avoid circular event handling
 
1283
        # Select() happens to fire a wxEVT_LIST_ITEM_SELECTED on Windows, 
 
1284
        # whose event handler calls this method again and again and again
 
1285
        $PreventListEvents = 1;
 
1286
        $self->{list}->Select($obj_idx, 1);
 
1287
        $PreventListEvents = 0;
 
1288
    } else {
 
1289
        # TODO: deselect all in list
 
1290
    }
 
1291
    $self->selection_changed(1);
 
1292
}
 
1293
 
 
1294
sub selected_object {
 
1295
    my $self = shift;
 
1296
    
 
1297
    my $obj_idx = first { $self->{objects}[$_]->selected } 0..$#{ $self->{objects} };
 
1298
    return undef if !defined $obj_idx;
 
1299
    return ($obj_idx, $self->{objects}[$obj_idx]),
 
1300
}
 
1301
 
 
1302
sub validate_config {
 
1303
    my $self = shift;
 
1304
    
 
1305
    eval {
 
1306
        $self->skeinpanel->config->validate;
 
1307
    };
 
1308
    return 0 if Slic3r::GUI::catch_error($self);    
 
1309
    return 1;
 
1310
}
 
1311
 
 
1312
sub statusbar {
 
1313
    my $self = shift;
 
1314
    return $self->skeinpanel->GetParent->{statusbar};
 
1315
}
 
1316
 
 
1317
# coordinates of the model origin (0,0) in pixels
 
1318
sub model_origin_to_pixel {
 
1319
    my ($self) = @_;
 
1320
    
 
1321
    return [
 
1322
        CANVAS_SIZE->[X]/2 - ($self->{config}->print_center->[X] * $self->{scaling_factor}),
 
1323
        CANVAS_SIZE->[Y]/2 - ($self->{config}->print_center->[Y] * $self->{scaling_factor}),
 
1324
    ];
 
1325
}
 
1326
 
 
1327
# convert a model coordinate into a pixel coordinate, assuming preview has square shape
 
1328
sub point_to_pixel {
 
1329
    my ($self, $point) = @_;
 
1330
    
 
1331
    my $canvas_height = $self->{canvas}->GetSize->GetHeight;
 
1332
    my $zero = $self->model_origin_to_pixel;
 
1333
    return [
 
1334
                          $point->[X] * $self->{scaling_factor} + $zero->[X],
 
1335
        $canvas_height - ($point->[Y] * $self->{scaling_factor} + $zero->[Y]),
 
1336
    ];
 
1337
}
 
1338
 
 
1339
sub points_to_pixel {
 
1340
    my ($self, $points, $unscale) = @_;
 
1341
    
 
1342
    my $result = [];
 
1343
    foreach my $point (@$points) {
 
1344
        $point = [ map unscale($_), @$point ] if $unscale;
 
1345
        push @$result, $self->point_to_pixel($point);
 
1346
    }
 
1347
    return $result;
 
1348
}
 
1349
 
 
1350
sub point_to_model_units {
 
1351
    my ($self, $point) = @_;
 
1352
    
 
1353
    my $canvas_height = $self->{canvas}->GetSize->GetHeight;
 
1354
    my $zero = $self->model_origin_to_pixel;
 
1355
    return [
 
1356
                          ($point->[X] - $zero->[X]) / $self->{scaling_factor},
 
1357
        (($canvas_height - $point->[Y] - $zero->[Y]) / $self->{scaling_factor}),
 
1358
    ];
 
1359
}
 
1360
 
 
1361
package Slic3r::GUI::Plater::DropTarget;
 
1362
use Wx::DND;
 
1363
use base 'Wx::FileDropTarget';
 
1364
 
 
1365
sub new {
 
1366
    my $class = shift;
 
1367
    my ($window) = @_;
 
1368
    my $self = $class->SUPER::new;
 
1369
    $self->{window} = $window;
 
1370
    return $self;
 
1371
}
 
1372
 
 
1373
sub OnDropFiles {
 
1374
    my $self = shift;
 
1375
    my ($x, $y, $filenames) = @_;
 
1376
    
 
1377
    # stop scalars leaking on older perl
 
1378
    # https://rt.perl.org/rt3/Public/Bug/Display.html?id=70602
 
1379
    @_ = ();
 
1380
    
 
1381
    # only accept STL, OBJ and AMF files
 
1382
    return 0 if grep !/\.(?:stl|obj|amf(?:\.xml)?)$/i, @$filenames;
 
1383
    
 
1384
    $self->{window}->load_file($_) for @$filenames;
 
1385
}
 
1386
 
 
1387
package Slic3r::GUI::Plater::Object;
 
1388
use Moo;
 
1389
 
 
1390
use List::Util qw(first);
 
1391
use Slic3r::Geometry qw(X Y Z MIN MAX deg2rad);
 
1392
 
 
1393
has 'name'                  => (is => 'rw', required => 1);
 
1394
has 'thumbnail'             => (is => 'rw'); # ExPolygon::Collection in scaled model units with no transforms
 
1395
has 'transformed_thumbnail' => (is => 'rw');
 
1396
has 'instance_thumbnails'   => (is => 'ro', default => sub { [] });  # array of ExPolygon::Collection objects, each one representing the actual placed thumbnail of each instance in pixel units
 
1397
has 'selected'              => (is => 'rw', default => sub { 0 });
 
1398
 
 
1399
sub make_thumbnail {
 
1400
    my ($self, $model, $obj_idx) = @_;
 
1401
    
 
1402
    my $mesh = $model->objects->[$obj_idx]->raw_mesh;
 
1403
    
 
1404
    if ($mesh->facets_count <= 5000) {
 
1405
        # remove polygons with area <= 1mm
 
1406
        my $area_threshold = Slic3r::Geometry::scale 1;
 
1407
        $self->thumbnail->append(
 
1408
            grep $_->area >= $area_threshold,
 
1409
            @{ $mesh->horizontal_projection },   # horizontal_projection returns scaled expolygons
 
1410
        );
 
1411
        $self->thumbnail->simplify(0.5);
 
1412
    } else {
 
1413
        my $convex_hull = Slic3r::ExPolygon->new($mesh->convex_hull);
 
1414
        $self->thumbnail->append($convex_hull);
 
1415
    }
 
1416
    
 
1417
    return $self->thumbnail;
 
1418
}
 
1419
 
 
1420
sub transform_thumbnail {
 
1421
    my ($self, $model, $obj_idx) = @_;
 
1422
    
 
1423
    return unless defined $self->thumbnail;
 
1424
    
 
1425
    my $model_object = $model->objects->[$obj_idx];
 
1426
    my $model_instance = $model_object->instances->[0];
 
1427
    
 
1428
    # the order of these transformations MUST be the same everywhere, including
 
1429
    # in Slic3r::Print->add_model_object()
 
1430
    my $t = $self->thumbnail->clone;
 
1431
    $t->rotate(deg2rad($model_instance->rotation), Slic3r::Point->new(0,0));
 
1432
    $t->scale($model_instance->scaling_factor);
 
1433
    
 
1434
    $self->transformed_thumbnail($t);
 
1435
}
 
1436
 
 
1437
1;