Plater.pm 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235
  1. # The "Plater" tab. It contains the "3D", "2D", "Preview" and "Layers" subtabs.
  2. package Slic3r::GUI::Plater;
  3. use strict;
  4. use warnings;
  5. use utf8;
  6. use File::Basename qw(basename dirname);
  7. use List::Util qw(sum first max);
  8. use Slic3r::Geometry qw(X Y Z MIN MAX scale unscale deg2rad rad2deg);
  9. use LWP::UserAgent;
  10. use threads::shared qw(shared_clone);
  11. use Wx qw(:button :colour :cursor :dialog :filedialog :keycode :icon :font :id :listctrl :misc
  12. :panel :sizer :toolbar :window wxTheApp :notebook :combobox wxNullBitmap);
  13. use Wx::Event qw(EVT_BUTTON EVT_TOGGLEBUTTON EVT_COMMAND EVT_KEY_DOWN EVT_LIST_ITEM_ACTIVATED
  14. EVT_LIST_ITEM_DESELECTED EVT_LIST_ITEM_SELECTED EVT_LEFT_DOWN EVT_MOUSE_EVENTS EVT_PAINT EVT_TOOL
  15. EVT_CHOICE EVT_COMBOBOX EVT_TIMER EVT_NOTEBOOK_PAGE_CHANGED);
  16. use base 'Wx::Panel';
  17. use constant TB_ADD => &Wx::NewId;
  18. use constant TB_REMOVE => &Wx::NewId;
  19. use constant TB_RESET => &Wx::NewId;
  20. use constant TB_ARRANGE => &Wx::NewId;
  21. use constant TB_EXPORT_GCODE => &Wx::NewId;
  22. use constant TB_EXPORT_STL => &Wx::NewId;
  23. use constant TB_MORE => &Wx::NewId;
  24. use constant TB_FEWER => &Wx::NewId;
  25. use constant TB_45CW => &Wx::NewId;
  26. use constant TB_45CCW => &Wx::NewId;
  27. use constant TB_SCALE => &Wx::NewId;
  28. use constant TB_SPLIT => &Wx::NewId;
  29. use constant TB_CUT => &Wx::NewId;
  30. use constant TB_SETTINGS => &Wx::NewId;
  31. use constant TB_LAYER_EDITING => &Wx::NewId;
  32. # package variables to avoid passing lexicals to threads
  33. our $PROGRESS_BAR_EVENT : shared = Wx::NewEventType;
  34. our $ERROR_EVENT : shared = Wx::NewEventType;
  35. # Emitted from the worker thread when the G-code export is finished.
  36. our $EXPORT_COMPLETED_EVENT : shared = Wx::NewEventType;
  37. our $PROCESS_COMPLETED_EVENT : shared = Wx::NewEventType;
  38. use constant FILAMENT_CHOOSERS_SPACING => 0;
  39. use constant PROCESS_DELAY => 0.5 * 1000; # milliseconds
  40. my $PreventListEvents = 0;
  41. sub new {
  42. my $class = shift;
  43. my ($parent) = @_;
  44. my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
  45. $self->{config} = Slic3r::Config->new_from_defaults(qw(
  46. bed_shape complete_objects extruder_clearance_radius skirts skirt_distance brim_width variable_layer_height
  47. serial_port serial_speed octoprint_host octoprint_apikey
  48. nozzle_diameter single_extruder_multi_material
  49. wipe_tower wipe_tower_x wipe_tower_y wipe_tower_width wipe_tower_per_color_wipe extruder_colour filament_colour
  50. ));
  51. # C++ Slic3r::Model with Perl extensions in Slic3r/Model.pm
  52. $self->{model} = Slic3r::Model->new;
  53. # C++ Slic3r::Print with Perl extensions in Slic3r/Print.pm
  54. $self->{print} = Slic3r::Print->new;
  55. # List of Perl objects Slic3r::GUI::Plater::Object, representing a 2D preview of the platter.
  56. $self->{objects} = [];
  57. $self->{print}->set_status_cb(sub {
  58. my ($percent, $message) = @_;
  59. if ($Slic3r::have_threads) {
  60. Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROGRESS_BAR_EVENT, shared_clone([$percent, $message])));
  61. } else {
  62. $self->on_progress_event($percent, $message);
  63. }
  64. });
  65. # Initialize preview notebook
  66. $self->{preview_notebook} = Wx::Notebook->new($self, -1, wxDefaultPosition, [335,335], wxNB_BOTTOM);
  67. # Initialize handlers for canvases
  68. my $on_select_object = sub {
  69. my ($obj_idx) = @_;
  70. # Ignore the special objects (the wipe tower proxy and such).
  71. $self->select_object((defined($obj_idx) && $obj_idx < 1000) ? $obj_idx : undef);
  72. };
  73. my $on_double_click = sub {
  74. $self->object_settings_dialog if $self->selected_object;
  75. };
  76. my $on_right_click = sub {
  77. my ($canvas, $click_pos) = @_;
  78. my ($obj_idx, $object) = $self->selected_object;
  79. return if !defined $obj_idx;
  80. my $menu = $self->object_menu;
  81. $canvas->PopupMenu($menu, $click_pos);
  82. $menu->Destroy;
  83. };
  84. my $on_instances_moved = sub {
  85. $self->update;
  86. };
  87. # Initialize 3D plater
  88. if ($Slic3r::GUI::have_OpenGL) {
  89. $self->{canvas3D} = Slic3r::GUI::Plater::3D->new($self->{preview_notebook}, $self->{objects}, $self->{model}, $self->{print}, $self->{config});
  90. $self->{preview_notebook}->AddPage($self->{canvas3D}, '3D');
  91. $self->{canvas3D}->set_on_select_object($on_select_object);
  92. $self->{canvas3D}->set_on_double_click($on_double_click);
  93. $self->{canvas3D}->set_on_right_click(sub { $on_right_click->($self->{canvas3D}, @_); });
  94. $self->{canvas3D}->set_on_instances_moved($on_instances_moved);
  95. $self->{canvas3D}->set_on_wipe_tower_moved(sub {
  96. my ($new_pos_3f) = @_;
  97. my $cfg = Slic3r::Config->new;
  98. $cfg->set('wipe_tower_x', $new_pos_3f->x);
  99. $cfg->set('wipe_tower_y', $new_pos_3f->y);
  100. $self->GetFrame->{options_tabs}{print}->load_config($cfg);
  101. });
  102. $self->{canvas3D}->set_on_model_update(sub {
  103. if ($Slic3r::GUI::Settings->{_}{background_processing}) {
  104. $self->schedule_background_process;
  105. } else {
  106. # Hide the print info box, it is no more valid.
  107. $self->{"print_info_box_show"}->(0);
  108. }
  109. });
  110. $self->{canvas3D}->on_viewport_changed(sub {
  111. $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D});
  112. });
  113. }
  114. # Initialize 2D preview canvas
  115. $self->{canvas} = Slic3r::GUI::Plater::2D->new($self->{preview_notebook}, wxDefaultSize, $self->{objects}, $self->{model}, $self->{config});
  116. $self->{preview_notebook}->AddPage($self->{canvas}, '2D');
  117. $self->{canvas}->on_select_object($on_select_object);
  118. $self->{canvas}->on_double_click($on_double_click);
  119. $self->{canvas}->on_right_click(sub { $on_right_click->($self->{canvas}, @_); });
  120. $self->{canvas}->on_instances_moved($on_instances_moved);
  121. # Initialize 3D toolpaths preview
  122. if ($Slic3r::GUI::have_OpenGL) {
  123. $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}, $self->{config});
  124. $self->{preview3D}->canvas->on_viewport_changed(sub {
  125. $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas);
  126. });
  127. $self->{preview_notebook}->AddPage($self->{preview3D}, 'Preview');
  128. $self->{preview3D_page_idx} = $self->{preview_notebook}->GetPageCount-1;
  129. }
  130. # Initialize toolpaths preview
  131. if ($Slic3r::GUI::have_OpenGL) {
  132. $self->{toolpaths2D} = Slic3r::GUI::Plater::2DToolpaths->new($self->{preview_notebook}, $self->{print});
  133. $self->{preview_notebook}->AddPage($self->{toolpaths2D}, 'Layers');
  134. }
  135. EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub {
  136. my $preview = $self->{preview_notebook}->GetCurrentPage;
  137. $self->{preview3D}->load_print(1) if ($preview == $self->{preview3D});
  138. $preview->OnActivate if $preview->can('OnActivate');
  139. });
  140. # toolbar for object manipulation
  141. if (!&Wx::wxMSW) {
  142. Wx::ToolTip::Enable(1);
  143. $self->{htoolbar} = Wx::ToolBar->new($self, -1, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxTB_TEXT | wxBORDER_SIMPLE | wxTAB_TRAVERSAL);
  144. $self->{htoolbar}->AddTool(TB_ADD, "Add…", Wx::Bitmap->new($Slic3r::var->("brick_add.png"), wxBITMAP_TYPE_PNG), '');
  145. $self->{htoolbar}->AddTool(TB_REMOVE, "Delete", Wx::Bitmap->new($Slic3r::var->("brick_delete.png"), wxBITMAP_TYPE_PNG), '');
  146. $self->{htoolbar}->AddTool(TB_RESET, "Delete All", Wx::Bitmap->new($Slic3r::var->("cross.png"), wxBITMAP_TYPE_PNG), '');
  147. $self->{htoolbar}->AddTool(TB_ARRANGE, "Arrange", Wx::Bitmap->new($Slic3r::var->("bricks.png"), wxBITMAP_TYPE_PNG), '');
  148. $self->{htoolbar}->AddSeparator;
  149. $self->{htoolbar}->AddTool(TB_MORE, "More", Wx::Bitmap->new($Slic3r::var->("add.png"), wxBITMAP_TYPE_PNG), '');
  150. $self->{htoolbar}->AddTool(TB_FEWER, "Fewer", Wx::Bitmap->new($Slic3r::var->("delete.png"), wxBITMAP_TYPE_PNG), '');
  151. $self->{htoolbar}->AddSeparator;
  152. $self->{htoolbar}->AddTool(TB_45CCW, "45° ccw", Wx::Bitmap->new($Slic3r::var->("arrow_rotate_anticlockwise.png"), wxBITMAP_TYPE_PNG), '');
  153. $self->{htoolbar}->AddTool(TB_45CW, "45° cw", Wx::Bitmap->new($Slic3r::var->("arrow_rotate_clockwise.png"), wxBITMAP_TYPE_PNG), '');
  154. $self->{htoolbar}->AddTool(TB_SCALE, "Scale…", Wx::Bitmap->new($Slic3r::var->("arrow_out.png"), wxBITMAP_TYPE_PNG), '');
  155. $self->{htoolbar}->AddTool(TB_SPLIT, "Split", Wx::Bitmap->new($Slic3r::var->("shape_ungroup.png"), wxBITMAP_TYPE_PNG), '');
  156. $self->{htoolbar}->AddTool(TB_CUT, "Cut…", Wx::Bitmap->new($Slic3r::var->("package.png"), wxBITMAP_TYPE_PNG), '');
  157. $self->{htoolbar}->AddSeparator;
  158. $self->{htoolbar}->AddTool(TB_SETTINGS, "Settings…", Wx::Bitmap->new($Slic3r::var->("cog.png"), wxBITMAP_TYPE_PNG), '');
  159. $self->{htoolbar}->AddTool(TB_LAYER_EDITING, 'Layer Editing', Wx::Bitmap->new($Slic3r::var->("variable_layer_height.png"), wxBITMAP_TYPE_PNG), wxNullBitmap, 1, 0, 'Layer Editing');
  160. } else {
  161. my %tbar_buttons = (
  162. add => "Add…",
  163. remove => "Delete",
  164. reset => "Delete All",
  165. arrange => "Arrange",
  166. increase => "",
  167. decrease => "",
  168. rotate45ccw => "",
  169. rotate45cw => "",
  170. changescale => "Scale…",
  171. split => "Split",
  172. cut => "Cut…",
  173. settings => "Settings…",
  174. layer_editing => "Layer editing",
  175. );
  176. $self->{btoolbar} = Wx::BoxSizer->new(wxHORIZONTAL);
  177. for (qw(add remove reset arrange increase decrease rotate45ccw rotate45cw changescale split cut settings)) {
  178. $self->{"btn_$_"} = Wx::Button->new($self, -1, $tbar_buttons{$_}, wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
  179. $self->{btoolbar}->Add($self->{"btn_$_"});
  180. }
  181. $self->{"btn_layer_editing"} = Wx::ToggleButton->new($self, -1, $tbar_buttons{'layer_editing'}, wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
  182. $self->{btoolbar}->Add($self->{"btn_layer_editing"});
  183. }
  184. $self->{list} = Wx::ListView->new($self, -1, wxDefaultPosition, wxDefaultSize,
  185. wxLC_SINGLE_SEL | wxLC_REPORT | wxBORDER_SUNKEN | wxTAB_TRAVERSAL | wxWANTS_CHARS );
  186. $self->{list}->InsertColumn(0, "Name", wxLIST_FORMAT_LEFT, 145);
  187. $self->{list}->InsertColumn(1, "Copies", wxLIST_FORMAT_CENTER, 45);
  188. $self->{list}->InsertColumn(2, "Scale", wxLIST_FORMAT_CENTER, wxLIST_AUTOSIZE_USEHEADER);
  189. EVT_LIST_ITEM_SELECTED($self, $self->{list}, \&list_item_selected);
  190. EVT_LIST_ITEM_DESELECTED($self, $self->{list}, \&list_item_deselected);
  191. EVT_LIST_ITEM_ACTIVATED($self, $self->{list}, \&list_item_activated);
  192. EVT_KEY_DOWN($self->{list}, sub {
  193. my ($list, $event) = @_;
  194. if ($event->GetKeyCode == WXK_TAB) {
  195. $list->Navigate($event->ShiftDown ? &Wx::wxNavigateBackward : &Wx::wxNavigateForward);
  196. } else {
  197. $event->Skip;
  198. }
  199. });
  200. # right pane buttons
  201. $self->{btn_export_gcode} = Wx::Button->new($self, -1, "Export G-code…", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  202. $self->{btn_reslice} = Wx::Button->new($self, -1, "Slice now", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  203. $self->{btn_print} = Wx::Button->new($self, -1, "Print…", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  204. $self->{btn_send_gcode} = Wx::Button->new($self, -1, "Send to printer", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  205. $self->{btn_export_stl} = Wx::Button->new($self, -1, "Export STL…", wxDefaultPosition, [-1, 30], wxBU_LEFT);
  206. #$self->{btn_export_gcode}->SetFont($Slic3r::GUI::small_font);
  207. #$self->{btn_export_stl}->SetFont($Slic3r::GUI::small_font);
  208. $self->{btn_print}->Hide;
  209. $self->{btn_send_gcode}->Hide;
  210. if ($Slic3r::GUI::have_button_icons) {
  211. my %icons = qw(
  212. add brick_add.png
  213. remove brick_delete.png
  214. reset cross.png
  215. arrange bricks.png
  216. export_gcode cog_go.png
  217. print arrow_up.png
  218. send_gcode arrow_up.png
  219. reslice reslice.png
  220. export_stl brick_go.png
  221. increase add.png
  222. decrease delete.png
  223. rotate45cw arrow_rotate_clockwise.png
  224. rotate45ccw arrow_rotate_anticlockwise.png
  225. changescale arrow_out.png
  226. split shape_ungroup.png
  227. cut package.png
  228. settings cog.png
  229. );
  230. for (grep $self->{"btn_$_"}, keys %icons) {
  231. $self->{"btn_$_"}->SetBitmap(Wx::Bitmap->new($Slic3r::var->($icons{$_}), wxBITMAP_TYPE_PNG));
  232. }
  233. }
  234. $self->selection_changed(0);
  235. $self->object_list_changed;
  236. EVT_BUTTON($self, $self->{btn_export_gcode}, sub {
  237. $self->export_gcode;
  238. });
  239. EVT_BUTTON($self, $self->{btn_print}, sub {
  240. $self->{print_file} = $self->export_gcode(Wx::StandardPaths::Get->GetTempDir());
  241. });
  242. EVT_BUTTON($self, $self->{btn_send_gcode}, sub {
  243. $self->{send_gcode_file} = $self->export_gcode(Wx::StandardPaths::Get->GetTempDir());
  244. });
  245. EVT_BUTTON($self, $self->{btn_reslice}, \&reslice);
  246. EVT_BUTTON($self, $self->{btn_export_stl}, \&export_stl);
  247. if ($self->{htoolbar}) {
  248. EVT_TOOL($self, TB_ADD, sub { $self->add; });
  249. EVT_TOOL($self, TB_REMOVE, sub { $self->remove() }); # explicitly pass no argument to remove
  250. EVT_TOOL($self, TB_RESET, sub { $self->reset; });
  251. EVT_TOOL($self, TB_ARRANGE, sub { $self->arrange; });
  252. EVT_TOOL($self, TB_MORE, sub { $self->increase; });
  253. EVT_TOOL($self, TB_FEWER, sub { $self->decrease; });
  254. EVT_TOOL($self, TB_45CW, sub { $_[0]->rotate(-45, Z, 'relative') });
  255. EVT_TOOL($self, TB_45CCW, sub { $_[0]->rotate(45, Z, 'relative') });
  256. EVT_TOOL($self, TB_SCALE, sub { $self->changescale(undef); });
  257. EVT_TOOL($self, TB_SPLIT, sub { $self->split_object; });
  258. EVT_TOOL($self, TB_CUT, sub { $_[0]->object_cut_dialog });
  259. EVT_TOOL($self, TB_SETTINGS, sub { $_[0]->object_settings_dialog });
  260. EVT_TOOL($self, TB_LAYER_EDITING, sub {
  261. my $state = $self->{canvas3D}->layer_editing_enabled;
  262. $self->{htoolbar}->ToggleTool(TB_LAYER_EDITING, ! $state);
  263. $self->on_layer_editing_toggled(! $state);
  264. });
  265. } else {
  266. EVT_BUTTON($self, $self->{btn_add}, sub { $self->add; });
  267. EVT_BUTTON($self, $self->{btn_remove}, sub { $self->remove() }); # explicitly pass no argument to remove
  268. EVT_BUTTON($self, $self->{btn_reset}, sub { $self->reset; });
  269. EVT_BUTTON($self, $self->{btn_arrange}, sub { $self->arrange; });
  270. EVT_BUTTON($self, $self->{btn_increase}, sub { $self->increase; });
  271. EVT_BUTTON($self, $self->{btn_decrease}, sub { $self->decrease; });
  272. EVT_BUTTON($self, $self->{btn_rotate45cw}, sub { $_[0]->rotate(-45, Z, 'relative') });
  273. EVT_BUTTON($self, $self->{btn_rotate45ccw}, sub { $_[0]->rotate(45, Z, 'relative') });
  274. EVT_BUTTON($self, $self->{btn_changescale}, sub { $self->changescale(undef); });
  275. EVT_BUTTON($self, $self->{btn_split}, sub { $self->split_object; });
  276. EVT_BUTTON($self, $self->{btn_cut}, sub { $_[0]->object_cut_dialog });
  277. EVT_BUTTON($self, $self->{btn_settings}, sub { $_[0]->object_settings_dialog });
  278. EVT_TOGGLEBUTTON($self, $self->{btn_layer_editing}, sub { $self->on_layer_editing_toggled($self->{btn_layer_editing}->GetValue); });
  279. }
  280. $_->SetDropTarget(Slic3r::GUI::Plater::DropTarget->new($self))
  281. for grep defined($_),
  282. $self, $self->{canvas}, $self->{canvas3D}, $self->{preview3D}, $self->{list};
  283. EVT_COMMAND($self, -1, $PROGRESS_BAR_EVENT, sub {
  284. my ($self, $event) = @_;
  285. my ($percent, $message) = @{$event->GetData};
  286. $self->on_progress_event($percent, $message);
  287. });
  288. EVT_COMMAND($self, -1, $ERROR_EVENT, sub {
  289. my ($self, $event) = @_;
  290. Slic3r::GUI::show_error($self, @{$event->GetData});
  291. });
  292. EVT_COMMAND($self, -1, $EXPORT_COMPLETED_EVENT, sub {
  293. my ($self, $event) = @_;
  294. $self->on_export_completed($event->GetData);
  295. });
  296. EVT_COMMAND($self, -1, $PROCESS_COMPLETED_EVENT, sub {
  297. my ($self, $event) = @_;
  298. $self->on_process_completed($event->GetData);
  299. });
  300. if ($Slic3r::have_threads) {
  301. my $timer_id = Wx::NewId();
  302. $self->{apply_config_timer} = Wx::Timer->new($self, $timer_id);
  303. EVT_TIMER($self, $timer_id, sub {
  304. my ($self, $event) = @_;
  305. $self->async_apply_config;
  306. });
  307. }
  308. $self->{canvas}->update_bed_size;
  309. if ($self->{canvas3D}) {
  310. $self->{canvas3D}->update_bed_size;
  311. $self->{canvas3D}->zoom_to_bed;
  312. }
  313. if ($self->{preview3D}) {
  314. $self->{preview3D}->set_bed_shape($self->{config}->bed_shape);
  315. }
  316. $self->update;
  317. {
  318. my $presets;
  319. {
  320. $presets = $self->{presets_sizer} = Wx::FlexGridSizer->new(3, 2, 1, 2);
  321. $presets->AddGrowableCol(1, 1);
  322. $presets->SetFlexibleDirection(wxHORIZONTAL);
  323. my %group_labels = (
  324. print => 'Print settings',
  325. filament => 'Filament',
  326. printer => 'Printer',
  327. );
  328. # UI Combo boxes for a print, multiple filaments, and a printer.
  329. # Initially a single filament combo box is created, but the number of combo boxes for the filament selection may increase,
  330. # once a printer preset with multiple extruders is activated.
  331. # $self->{preset_choosers}{$group}[$idx]
  332. $self->{preset_choosers} = {};
  333. # Boolean indicating whether the '- default -' preset is shown by the combo box.
  334. $self->{preset_choosers_default_suppressed} = {};
  335. for my $group (qw(print filament printer)) {
  336. my $text = Wx::StaticText->new($self, -1, "$group_labels{$group}:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);
  337. $text->SetFont($Slic3r::GUI::small_font);
  338. my $choice = Wx::BitmapComboBox->new($self, -1, "", wxDefaultPosition, wxDefaultSize, [], wxCB_READONLY);
  339. EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down(0, @_); } );
  340. $self->{preset_choosers}{$group} = [$choice];
  341. $self->{preset_choosers_default_suppressed}{$group} = 0;
  342. # setup the listener
  343. EVT_COMBOBOX($choice, $choice, sub {
  344. my ($choice) = @_;
  345. wxTheApp->CallAfter(sub {
  346. $self->_on_select_preset($group, $choice);
  347. });
  348. });
  349. $presets->Add($text, 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL | wxRIGHT, 4);
  350. $presets->Add($choice, 1, wxALIGN_CENTER_VERTICAL | wxEXPAND | wxBOTTOM, 0);
  351. }
  352. }
  353. my $object_info_sizer;
  354. {
  355. my $box = Wx::StaticBox->new($self, -1, "Info");
  356. $object_info_sizer = Wx::StaticBoxSizer->new($box, wxVERTICAL);
  357. $object_info_sizer->SetMinSize([350,-1]);
  358. my $grid_sizer = Wx::FlexGridSizer->new(3, 4, 5, 5);
  359. $grid_sizer->SetFlexibleDirection(wxHORIZONTAL);
  360. $grid_sizer->AddGrowableCol(1, 1);
  361. $grid_sizer->AddGrowableCol(3, 1);
  362. $object_info_sizer->Add($grid_sizer, 0, wxEXPAND);
  363. my @info = (
  364. size => "Size",
  365. volume => "Volume",
  366. facets => "Facets",
  367. materials => "Materials",
  368. manifold => "Manifold",
  369. );
  370. while (my $field = shift @info) {
  371. my $label = shift @info;
  372. my $text = Wx::StaticText->new($self, -1, "$label:", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
  373. $text->SetFont($Slic3r::GUI::small_font);
  374. $grid_sizer->Add($text, 0);
  375. $self->{"object_info_$field"} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
  376. $self->{"object_info_$field"}->SetFont($Slic3r::GUI::small_font);
  377. if ($field eq 'manifold') {
  378. $self->{object_info_manifold_warning_icon} = Wx::StaticBitmap->new($self, -1, Wx::Bitmap->new($Slic3r::var->("error.png"), wxBITMAP_TYPE_PNG));
  379. $self->{object_info_manifold_warning_icon}->Hide;
  380. my $h_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
  381. $h_sizer->Add($self->{object_info_manifold_warning_icon}, 0);
  382. $h_sizer->Add($self->{"object_info_$field"}, 0);
  383. $grid_sizer->Add($h_sizer, 0, wxEXPAND);
  384. } else {
  385. $grid_sizer->Add($self->{"object_info_$field"}, 0);
  386. }
  387. }
  388. }
  389. my $print_info_sizer;
  390. {
  391. my $box = Wx::StaticBox->new($self, -1, "Sliced Info");
  392. $print_info_sizer = Wx::StaticBoxSizer->new($box, wxVERTICAL);
  393. $print_info_sizer->SetMinSize([350,-1]);
  394. my $grid_sizer = Wx::FlexGridSizer->new(2, 2, 5, 5);
  395. $grid_sizer->SetFlexibleDirection(wxHORIZONTAL);
  396. $grid_sizer->AddGrowableCol(1, 1);
  397. $grid_sizer->AddGrowableCol(3, 1);
  398. $print_info_sizer->Add($grid_sizer, 0, wxEXPAND);
  399. my @info = (
  400. fil_mm3 => "Used Filament (mm^3)",
  401. fil_g => "Used Filament (g)",
  402. cost => "Cost",
  403. );
  404. while (my $field = shift @info) {
  405. my $label = shift @info;
  406. my $text = Wx::StaticText->new($self, -1, "$label:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);
  407. $text->SetFont($Slic3r::GUI::small_font);
  408. $grid_sizer->Add($text, 0);
  409. $self->{"print_info_$field"} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
  410. $self->{"print_info_$field"}->SetFont($Slic3r::GUI::small_font);
  411. $grid_sizer->Add($self->{"print_info_$field"}, 0);
  412. }
  413. }
  414. my $buttons_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
  415. $self->{buttons_sizer} = $buttons_sizer;
  416. $buttons_sizer->AddStretchSpacer(1);
  417. $buttons_sizer->Add($self->{btn_export_stl}, 0, wxALIGN_RIGHT, 0);
  418. $buttons_sizer->Add($self->{btn_reslice}, 0, wxALIGN_RIGHT, 0);
  419. $buttons_sizer->Add($self->{btn_print}, 0, wxALIGN_RIGHT, 0);
  420. $buttons_sizer->Add($self->{btn_send_gcode}, 0, wxALIGN_RIGHT, 0);
  421. $buttons_sizer->Add($self->{btn_export_gcode}, 0, wxALIGN_RIGHT, 0);
  422. my $right_sizer = Wx::BoxSizer->new(wxVERTICAL);
  423. $right_sizer->Add($presets, 0, wxEXPAND | wxTOP, 10) if defined $presets;
  424. $right_sizer->Add($buttons_sizer, 0, wxEXPAND | wxBOTTOM, 5);
  425. $right_sizer->Add($self->{list}, 1, wxEXPAND, 5);
  426. $right_sizer->Add($object_info_sizer, 0, wxEXPAND, 0);
  427. $right_sizer->Add($print_info_sizer, 0, wxEXPAND, 0);
  428. # Callback for showing / hiding the print info box.
  429. $self->{"print_info_box_show"} = sub {
  430. if ($right_sizer->IsShown(4) != $_[0]) {
  431. $right_sizer->Show(4, $_[0]);
  432. $self->Layout
  433. }
  434. };
  435. # Show the box initially, let it be shown after the slicing is finished.
  436. $self->{"print_info_box_show"}->(0);
  437. my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL);
  438. $hsizer->Add($self->{preview_notebook}, 1, wxEXPAND | wxTOP, 1);
  439. $hsizer->Add($right_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, 3);
  440. my $sizer = Wx::BoxSizer->new(wxVERTICAL);
  441. $sizer->Add($self->{htoolbar}, 0, wxEXPAND, 0) if $self->{htoolbar};
  442. $sizer->Add($self->{btoolbar}, 0, wxEXPAND, 0) if $self->{btoolbar};
  443. $sizer->Add($hsizer, 1, wxEXPAND, 0);
  444. $sizer->SetSizeHints($self);
  445. $self->SetSizer($sizer);
  446. }
  447. $self->update_ui_from_settings();
  448. return $self;
  449. }
  450. # sets the callback
  451. sub on_select_preset {
  452. my ($self, $cb) = @_;
  453. $self->{on_select_preset} = $cb;
  454. }
  455. sub _on_select_preset {
  456. my $self = shift;
  457. my ($group, $choice) = @_;
  458. # If user changed a filament preset and the selected machine is equipped with multiple extruders,
  459. # there are multiple filament selection combo boxes shown at the platter. In that case
  460. # don't propagate the filament selection changes to the tab.
  461. my $default_suppressed = $self->{preset_choosers_default_suppressed}{$group};
  462. if ($group eq 'filament' && @{$self->{preset_choosers}{filament}} > 1) {
  463. # Indices of the filaments selected.
  464. my @filament_presets = $self->filament_presets;
  465. $Slic3r::GUI::Settings->{presets}{filament} = $choice->GetString($filament_presets[0] - $default_suppressed) . ".ini";
  466. $Slic3r::GUI::Settings->{presets}{"filament_${_}"} = $choice->GetString($filament_presets[$_] - $default_suppressed)
  467. for 1 .. $#filament_presets;
  468. wxTheApp->save_settings;
  469. $self->update_filament_colors_preview($choice);
  470. } else {
  471. # call GetSelection() in scalar context as it's context-aware
  472. $self->{on_select_preset}->($group, scalar($choice->GetSelection) + $default_suppressed)
  473. if $self->{on_select_preset};
  474. }
  475. # get new config and generate on_config_change() event for updating plater and other things
  476. $self->on_config_change($self->GetFrame->config);
  477. }
  478. sub on_layer_editing_toggled {
  479. my ($self, $new_state) = @_;
  480. $self->{canvas3D}->layer_editing_enabled($new_state);
  481. if ($new_state && ! $self->{canvas3D}->layer_editing_enabled) {
  482. # Initialization of the OpenGL shaders failed. Disable the tool.
  483. if ($self->{htoolbar}) {
  484. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 0);
  485. $self->{htoolbar}->ToggleTool(TB_LAYER_EDITING, 0);
  486. } else {
  487. $self->{"btn_layer_editing"}->Disable;
  488. $self->{"btn_layer_editing"}->SetValue(0);
  489. }
  490. }
  491. $self->{canvas3D}->Refresh;
  492. $self->{canvas3D}->Update;
  493. }
  494. sub GetFrame {
  495. my ($self) = @_;
  496. return &Wx::GetTopLevelParent($self);
  497. }
  498. # Called after the Preferences dialog is closed and the program settings are saved.
  499. # Update the UI based on the current preferences.
  500. sub update_ui_from_settings
  501. {
  502. my ($self) = @_;
  503. if (defined($self->{btn_reslice}) && $self->{buttons_sizer}->IsShown($self->{btn_reslice}) != (! $Slic3r::GUI::Settings->{_}{background_processing})) {
  504. $self->{buttons_sizer}->Show($self->{btn_reslice}, ! $Slic3r::GUI::Settings->{_}{background_processing});
  505. $self->{buttons_sizer}->Layout;
  506. }
  507. }
  508. # Update preset combo boxes (Print settings, Filament, Printer) from their respective tabs.
  509. # Called by
  510. # Slic3r::GUI::Tab::Print::_on_presets_changed
  511. # Slic3r::GUI::Tab::Filament::_on_presets_changed
  512. # Slic3r::GUI::Tab::Printer::_on_presets_changed
  513. # when the presets are loaded or the user selects another preset.
  514. # For Print settings and Printer, synchronize the selection index with their tabs.
  515. # For Filament, synchronize the selection index for a single extruder printer only, otherwise keep the selection.
  516. sub update_presets {
  517. my $self = shift;
  518. # $presets: one of qw(print filament printer)
  519. # $selected: index of the selected preset in the array. This may not correspond
  520. # with the index of selection in the UI element, where not all items are displayed.
  521. my ($group, $presets, $default_suppressed, $selected, $is_dirty) = @_;
  522. my @choosers = @{ $self->{preset_choosers}{$group} };
  523. my $choice_idx = 0;
  524. foreach my $choice (@choosers) {
  525. if ($group eq 'filament' && @choosers > 1) {
  526. # if we have more than one filament chooser, keep our selection
  527. # instead of importing the one from the tab
  528. $selected = $choice->GetSelection + $self->{preset_choosers_default_suppressed}{$group};
  529. $is_dirty = 0;
  530. }
  531. $choice->Clear;
  532. foreach my $preset (@$presets) {
  533. next if ($preset->default && $default_suppressed);
  534. my $bitmap;
  535. if ($group eq 'filament') {
  536. $bitmap = Wx::Bitmap->new($Slic3r::var->("spool.png"), wxBITMAP_TYPE_PNG);
  537. } elsif ($group eq 'print') {
  538. $bitmap = Wx::Bitmap->new($Slic3r::var->("cog.png"), wxBITMAP_TYPE_PNG);
  539. } elsif ($group eq 'printer') {
  540. $bitmap = Wx::Bitmap->new($Slic3r::var->("printer_empty.png"), wxBITMAP_TYPE_PNG);
  541. }
  542. $choice->AppendString($preset->name, $bitmap);
  543. }
  544. if ($selected <= $#$presets) {
  545. my $idx = $selected - $default_suppressed;
  546. if ($idx >= 0) {
  547. if ($is_dirty) {
  548. $choice->SetString($idx, $choice->GetString($idx) . " (modified)");
  549. }
  550. # call SetSelection() only after SetString() otherwise the new string
  551. # won't be picked up as the visible string
  552. $choice->SetSelection($idx);
  553. }
  554. }
  555. $choice_idx += 1;
  556. }
  557. $self->{preset_choosers_default_suppressed}{$group} = $default_suppressed;
  558. wxTheApp->CallAfter(sub { $self->update_filament_colors_preview }) if $group eq 'filament' || $group eq 'printer';
  559. }
  560. # Update the color icon in front of each filament selection on the platter.
  561. # If the extruder has a preview color assigned, apply the extruder color to the active selection.
  562. # Always apply the filament color to the non-active selections.
  563. sub update_filament_colors_preview {
  564. my ($self, $extruder_idx) = shift;
  565. my @choosers = @{$self->{preset_choosers}{filament}};
  566. if (ref $extruder_idx) {
  567. # $extruder_idx is the chooser.
  568. foreach my $chooser (@choosers) {
  569. if ($extruder_idx == $chooser) {
  570. $extruder_idx = $chooser;
  571. last;
  572. }
  573. }
  574. }
  575. my @extruder_colors = @{$self->{config}->extruder_colour};
  576. my @extruder_list;
  577. if (defined $extruder_idx) {
  578. @extruder_list = ($extruder_idx);
  579. } else {
  580. # Collect extruder indices.
  581. @extruder_list = (0..$#extruder_colors);
  582. }
  583. my $filament_tab = $self->GetFrame->{options_tabs}{filament};
  584. my $presets = $filament_tab->{presets};
  585. my $default_suppressed = $filament_tab->{default_suppressed};
  586. foreach my $extruder_idx (@extruder_list) {
  587. my $chooser = $choosers[$extruder_idx];
  588. my $extruder_color = $self->{config}->extruder_colour->[$extruder_idx];
  589. my $preset_idx = 0;
  590. my $selection_idx = $chooser->GetSelection;
  591. foreach my $preset (@$presets) {
  592. my $bitmap;
  593. if ($preset->default) {
  594. next if $default_suppressed;
  595. } else {
  596. # Assign an extruder color to the selected item if the extruder color is defined.
  597. my $filament_rgb = $preset->config(['filament_colour'])->filament_colour->[0];
  598. my $extruder_rgb = ($preset_idx == $selection_idx && $extruder_color =~ m/^#[[:xdigit:]]{6}/) ? $extruder_color : $filament_rgb;
  599. $filament_rgb =~ s/^#//;
  600. $extruder_rgb =~ s/^#//;
  601. my $image = Wx::Image->new(24,16);
  602. if ($filament_rgb ne $extruder_rgb) {
  603. my @rgb = unpack 'C*', pack 'H*', $extruder_rgb;
  604. $image->SetRGB(Wx::Rect->new(0,0,16,16), @rgb);
  605. @rgb = unpack 'C*', pack 'H*', $filament_rgb;
  606. $image->SetRGB(Wx::Rect->new(16,0,8,16), @rgb);
  607. } else {
  608. my @rgb = unpack 'C*', pack 'H*', $filament_rgb;
  609. $image->SetRGB(Wx::Rect->new(0,0,24,16), @rgb);
  610. }
  611. $bitmap = Wx::Bitmap->new($image);
  612. }
  613. $chooser->SetItemBitmap($preset_idx, $bitmap) if $bitmap;
  614. $preset_idx += 1;
  615. }
  616. }
  617. }
  618. # Return a vector of indices of filaments selected by the $self->{preset_choosers}{filament} combo boxes.
  619. sub filament_presets {
  620. my $self = shift;
  621. # force scalar context for GetSelection() as it's context-aware
  622. return map scalar($_->GetSelection) + $self->{preset_choosers_default_suppressed}{filament}, @{ $self->{preset_choosers}{filament} };
  623. }
  624. sub add {
  625. my $self = shift;
  626. my @input_files = wxTheApp->open_model($self);
  627. $self->load_file($_) for @input_files;
  628. }
  629. sub load_file {
  630. my $self = shift;
  631. my ($input_file) = @_;
  632. $Slic3r::GUI::Settings->{recent}{skein_directory} = dirname($input_file);
  633. wxTheApp->save_settings;
  634. my $process_dialog = Wx::ProgressDialog->new('Loading…', "Processing input file…", 100, $self, 0);
  635. $process_dialog->Pulse;
  636. local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self);
  637. my $model = eval { Slic3r::Model->read_from_file($input_file, 0) };
  638. Slic3r::GUI::show_error($self, $@) if $@;
  639. my @obj_idx = ();
  640. if (defined $model) {
  641. if ($model->looks_like_multipart_object) {
  642. my $dialog = Wx::MessageDialog->new($self,
  643. "This file contains several objects positioned at multiple heights. "
  644. . "Instead of considering them as multiple objects, should I consider\n"
  645. . "this file as a single object having multiple parts?\n",
  646. 'Multi-part object detected', wxICON_WARNING | wxYES | wxNO);
  647. if ($dialog->ShowModal() == wxID_YES) {
  648. $model->convert_multipart_object;
  649. }
  650. }
  651. @obj_idx = $self->load_model_objects(@{$model->objects});
  652. $self->statusbar->SetStatusText("Loaded " . basename($input_file));
  653. }
  654. $process_dialog->Destroy;
  655. return @obj_idx;
  656. }
  657. sub load_model_objects {
  658. my ($self, @model_objects) = @_;
  659. my $bed_centerf = $self->bed_centerf;
  660. my $bed_shape = Slic3r::Polygon->new_scale(@{$self->{config}->bed_shape});
  661. my $bed_size = $bed_shape->bounding_box->size;
  662. my $need_arrange = 0;
  663. my $scaled_down = 0;
  664. my @obj_idx = ();
  665. foreach my $model_object (@model_objects) {
  666. my $o = $self->{model}->add_object($model_object);
  667. my $object_name = $model_object->name;
  668. $object_name = basename($model_object->input_file) if ($object_name eq '');
  669. push @{ $self->{objects} }, Slic3r::GUI::Plater::Object->new(name => $object_name);
  670. push @obj_idx, $#{ $self->{objects} };
  671. if ($model_object->instances_count == 0) {
  672. # if object has no defined position(s) we need to rearrange everything after loading
  673. $need_arrange = 1;
  674. # add a default instance and center object around origin
  675. $o->center_around_origin; # also aligns object to Z = 0
  676. $o->add_instance(offset => $bed_centerf);
  677. }
  678. {
  679. # if the object is too large (more than 5 times the bed), scale it down
  680. my $size = $o->bounding_box->size;
  681. my $ratio = max(@$size[X,Y]) / unscale(max(@$bed_size[X,Y]));
  682. if ($ratio > 5) {
  683. $_->set_scaling_factor(1/$ratio) for @{$o->instances};
  684. $scaled_down = 1;
  685. }
  686. }
  687. $self->{print}->auto_assign_extruders($o);
  688. $self->{print}->add_model_object($o);
  689. }
  690. # if user turned autocentering off, automatic arranging would disappoint them
  691. if (!$Slic3r::GUI::Settings->{_}{autocenter}) {
  692. $need_arrange = 0;
  693. }
  694. if ($scaled_down) {
  695. Slic3r::GUI::show_info(
  696. $self,
  697. 'Your object appears to be too large, so it was automatically scaled down to fit your print bed.',
  698. 'Object too large?',
  699. );
  700. }
  701. foreach my $obj_idx (@obj_idx) {
  702. my $object = $self->{objects}[$obj_idx];
  703. my $model_object = $self->{model}->objects->[$obj_idx];
  704. $self->{list}->InsertStringItem($obj_idx, $object->name);
  705. $self->{list}->SetItemFont($obj_idx, Wx::Font->new(10, wxDEFAULT, wxNORMAL, wxNORMAL))
  706. if $self->{list}->can('SetItemFont'); # legacy code for wxPerl < 0.9918 not supporting SetItemFont()
  707. $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
  708. $self->{list}->SetItem($obj_idx, 2, ($model_object->instances->[0]->scaling_factor * 100) . "%");
  709. $self->reset_thumbnail($obj_idx);
  710. }
  711. $self->arrange if $need_arrange;
  712. $self->update;
  713. # zoom to objects
  714. $self->{canvas3D}->zoom_to_volumes
  715. if $self->{canvas3D};
  716. $self->{list}->Update;
  717. $self->{list}->Select($obj_idx[-1], 1);
  718. $self->object_list_changed;
  719. $self->schedule_background_process;
  720. return @obj_idx;
  721. }
  722. sub bed_centerf {
  723. my ($self) = @_;
  724. my $bed_shape = Slic3r::Polygon->new_scale(@{$self->{config}->bed_shape});
  725. my $bed_center = $bed_shape->bounding_box->center;
  726. return Slic3r::Pointf->new(unscale($bed_center->x), unscale($bed_center->y)); #)
  727. }
  728. sub remove {
  729. my $self = shift;
  730. my ($obj_idx) = @_;
  731. $self->stop_background_process;
  732. # Prevent toolpaths preview from rendering while we modify the Print object
  733. $self->{toolpaths2D}->enabled(0) if $self->{toolpaths2D};
  734. $self->{preview3D}->enabled(0) if $self->{preview3D};
  735. # if no object index is supplied, remove the selected one
  736. if (!defined $obj_idx) {
  737. ($obj_idx, undef) = $self->selected_object;
  738. }
  739. splice @{$self->{objects}}, $obj_idx, 1;
  740. $self->{model}->delete_object($obj_idx);
  741. $self->{print}->delete_object($obj_idx);
  742. $self->{list}->DeleteItem($obj_idx);
  743. $self->object_list_changed;
  744. $self->select_object(undef);
  745. $self->update;
  746. $self->schedule_background_process;
  747. }
  748. sub reset {
  749. my $self = shift;
  750. $self->stop_background_process;
  751. # Prevent toolpaths preview from rendering while we modify the Print object
  752. $self->{toolpaths2D}->enabled(0) if $self->{toolpaths2D};
  753. $self->{preview3D}->enabled(0) if $self->{preview3D};
  754. @{$self->{objects}} = ();
  755. $self->{model}->clear_objects;
  756. $self->{print}->clear_objects;
  757. $self->{list}->DeleteAllItems;
  758. $self->object_list_changed;
  759. $self->select_object(undef);
  760. $self->update;
  761. }
  762. sub increase {
  763. my ($self, $copies) = @_;
  764. $copies //= 1;
  765. my ($obj_idx, $object) = $self->selected_object;
  766. my $model_object = $self->{model}->objects->[$obj_idx];
  767. my $instance = $model_object->instances->[-1];
  768. for my $i (1..$copies) {
  769. $instance = $model_object->add_instance(
  770. offset => Slic3r::Pointf->new(map 10+$_, @{$instance->offset}),
  771. scaling_factor => $instance->scaling_factor,
  772. rotation => $instance->rotation,
  773. );
  774. $self->{print}->objects->[$obj_idx]->add_copy($instance->offset);
  775. }
  776. $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
  777. # only autoarrange if user has autocentering enabled
  778. $self->stop_background_process;
  779. if ($Slic3r::GUI::Settings->{_}{autocenter}) {
  780. $self->arrange;
  781. } else {
  782. $self->update;
  783. }
  784. $self->schedule_background_process;
  785. }
  786. sub decrease {
  787. my ($self, $copies_asked) = @_;
  788. my $copies = $copies_asked // 1;
  789. $self->stop_background_process;
  790. my ($obj_idx, $object) = $self->selected_object;
  791. my $model_object = $self->{model}->objects->[$obj_idx];
  792. if ($model_object->instances_count > $copies) {
  793. for my $i (1..$copies) {
  794. $model_object->delete_last_instance;
  795. $self->{print}->objects->[$obj_idx]->delete_last_copy;
  796. }
  797. $self->{list}->SetItem($obj_idx, 1, $model_object->instances_count);
  798. } elsif (defined $copies_asked) {
  799. # The "decrease" came from the "set number of copies" dialog.
  800. $self->remove;
  801. } else {
  802. # The "decrease" came from the "-" button. Don't allow the object to disappear.
  803. $self->resume_background_process;
  804. return;
  805. }
  806. if ($self->{objects}[$obj_idx]) {
  807. $self->{list}->Select($obj_idx, 0);
  808. $self->{list}->Select($obj_idx, 1);
  809. }
  810. $self->update;
  811. $self->schedule_background_process;
  812. }
  813. sub set_number_of_copies {
  814. my ($self) = @_;
  815. $self->pause_background_process;
  816. # get current number of copies
  817. my ($obj_idx, $object) = $self->selected_object;
  818. my $model_object = $self->{model}->objects->[$obj_idx];
  819. # prompt user
  820. my $copies = Wx::GetNumberFromUser("", "Enter the number of copies of the selected object:", "Copies", $model_object->instances_count, 0, 1000, $self);
  821. my $diff = $copies - $model_object->instances_count;
  822. if ($diff == 0) {
  823. # no variation
  824. $self->resume_background_process;
  825. } elsif ($diff > 0) {
  826. $self->increase($diff);
  827. } elsif ($diff < 0) {
  828. $self->decrease(-$diff);
  829. }
  830. }
  831. sub _get_number_from_user {
  832. my ($self, $title, $prompt_message, $error_message, $default, $only_positive) = @_;
  833. for (;;) {
  834. my $value = Wx::GetTextFromUser($prompt_message, $title, $default, $self);
  835. # Accept both dashes and dots as a decimal separator.
  836. $value =~ s/,/./;
  837. # If scaling value is being entered, remove the trailing percent sign.
  838. $value =~ s/%$// if $only_positive;
  839. # User canceled the selection, return undef.
  840. return if $value eq '';
  841. # Validate a numeric value.
  842. return $value if ($value =~ /^-?\d*(?:\.\d*)?$/) && (! $only_positive || $value > 0);
  843. Wx::MessageBox(
  844. $error_message .
  845. (($only_positive && $value <= 0) ?
  846. ": $value\nNon-positive value." :
  847. ": $value\nNot a numeric value."),
  848. "Slic3r Error", wxOK | wxICON_EXCLAMATION, $self);
  849. $default = $value;
  850. }
  851. }
  852. sub rotate {
  853. my ($self, $angle, $axis, $relative_key) = @_;
  854. $relative_key //= 'absolute'; # relative or absolute coordinates
  855. $axis //= Z; # angle is in degrees
  856. my $relative = $relative_key eq 'relative';
  857. my ($obj_idx, $object) = $self->selected_object;
  858. return if !defined $obj_idx;
  859. my $model_object = $self->{model}->objects->[$obj_idx];
  860. my $model_instance = $model_object->instances->[0];
  861. if (!defined $angle) {
  862. my $axis_name = $axis == X ? 'X' : $axis == Y ? 'Y' : 'Z';
  863. my $default = $axis == Z ? rad2deg($model_instance->rotation) : 0;
  864. $angle = $self->_get_number_from_user("Enter the rotation angle:", "Rotate around $axis_name axis", "Invalid rotation angle entered", $default);
  865. return if $angle eq '';
  866. }
  867. $self->stop_background_process;
  868. if ($axis == Z) {
  869. my $new_angle = deg2rad($angle);
  870. $_->set_rotation(($relative ? $_->rotation : 0.) + $new_angle) for @{ $model_object->instances };
  871. $object->transform_thumbnail($self->{model}, $obj_idx);
  872. } else {
  873. # rotation around X and Y needs to be performed on mesh
  874. # so we first apply any Z rotation
  875. if ($model_instance->rotation != 0) {
  876. $model_object->rotate($model_instance->rotation, Z);
  877. $_->set_rotation(0) for @{ $model_object->instances };
  878. }
  879. $model_object->rotate(deg2rad($angle), $axis);
  880. # realign object to Z = 0
  881. $model_object->center_around_origin;
  882. $self->reset_thumbnail($obj_idx);
  883. }
  884. # update print and start background processing
  885. $self->{print}->add_model_object($model_object, $obj_idx);
  886. $self->selection_changed; # refresh info (size etc.)
  887. $self->update;
  888. $self->schedule_background_process;
  889. }
  890. sub mirror {
  891. my ($self, $axis) = @_;
  892. my ($obj_idx, $object) = $self->selected_object;
  893. return if !defined $obj_idx;
  894. my $model_object = $self->{model}->objects->[$obj_idx];
  895. my $model_instance = $model_object->instances->[0];
  896. # apply Z rotation before mirroring
  897. if ($model_instance->rotation != 0) {
  898. $model_object->rotate($model_instance->rotation, Z);
  899. $_->set_rotation(0) for @{ $model_object->instances };
  900. }
  901. $model_object->mirror($axis);
  902. # realign object to Z = 0
  903. $model_object->center_around_origin;
  904. $self->reset_thumbnail($obj_idx);
  905. # update print and start background processing
  906. $self->stop_background_process;
  907. $self->{print}->add_model_object($model_object, $obj_idx);
  908. $self->selection_changed; # refresh info (size etc.)
  909. $self->update;
  910. $self->schedule_background_process;
  911. }
  912. sub changescale {
  913. my ($self, $axis, $tosize) = @_;
  914. my ($obj_idx, $object) = $self->selected_object;
  915. return if !defined $obj_idx;
  916. my $model_object = $self->{model}->objects->[$obj_idx];
  917. my $model_instance = $model_object->instances->[0];
  918. my $object_size = $model_object->bounding_box->size;
  919. my $bed_size = Slic3r::Polygon->new_scale(@{$self->{config}->bed_shape})->bounding_box->size;
  920. if (defined $axis) {
  921. my $axis_name = $axis == X ? 'X' : $axis == Y ? 'Y' : 'Z';
  922. my $scale;
  923. if ($tosize) {
  924. my $cursize = $object_size->[$axis];
  925. my $newsize = $self->_get_number_from_user(
  926. sprintf('Enter the new size for the selected object (print bed: %smm):', $bed_size->[$axis]),
  927. "Scale along $axis_name", 'Invalid scaling value entered', $cursize, 1);
  928. return if $newsize eq '';
  929. $scale = $newsize / $cursize * 100;
  930. } else {
  931. $scale = $self->_get_number_from_user('Enter the scale % for the selected object:', "Scale along $axis_name", 'Invalid scaling value entered', 100, 1);
  932. return if $scale eq '';
  933. }
  934. # apply Z rotation before scaling
  935. if ($model_instance->rotation != 0) {
  936. $model_object->rotate($model_instance->rotation, Z);
  937. $_->set_rotation(0) for @{ $model_object->instances };
  938. }
  939. my $versor = [1,1,1];
  940. $versor->[$axis] = $scale/100;
  941. $model_object->scale_xyz(Slic3r::Pointf3->new(@$versor));
  942. #FIXME Scale the layer height profile when $axis == Z?
  943. #FIXME Scale the layer height ranges $axis == Z?
  944. # object was already aligned to Z = 0, so no need to realign it
  945. $self->reset_thumbnail($obj_idx);
  946. } else {
  947. my $scale;
  948. if ($tosize) {
  949. my $cursize = max(@$object_size);
  950. my $newsize = $self->_get_number_from_user('Enter the new max size for the selected object:', 'Scale', 'Invalid scaling value entered', $cursize, 1);
  951. return if $newsize eq '';
  952. $scale = $model_instance->scaling_factor * $newsize / $cursize * 100;
  953. } else {
  954. # max scale factor should be above 2540 to allow importing files exported in inches
  955. $scale = $self->_get_number_from_user('Enter the scale % for the selected object:', 'Scale', 'Invalid scaling value entered', $model_instance->scaling_factor*100, 1);
  956. return if $scale eq '';
  957. }
  958. $self->{list}->SetItem($obj_idx, 2, "$scale%");
  959. $scale /= 100; # turn percent into factor
  960. my $variation = $scale / $model_instance->scaling_factor;
  961. #FIXME Scale the layer height profile?
  962. foreach my $range (@{ $model_object->layer_height_ranges }) {
  963. $range->[0] *= $variation;
  964. $range->[1] *= $variation;
  965. }
  966. $_->set_scaling_factor($scale) for @{ $model_object->instances };
  967. $object->transform_thumbnail($self->{model}, $obj_idx);
  968. }
  969. # update print and start background processing
  970. $self->stop_background_process;
  971. $self->{print}->add_model_object($model_object, $obj_idx);
  972. $self->selection_changed(1); # refresh info (size, volume etc.)
  973. $self->update;
  974. $self->schedule_background_process;
  975. }
  976. sub arrange {
  977. my $self = shift;
  978. $self->pause_background_process;
  979. my $bb = Slic3r::Geometry::BoundingBoxf->new_from_points($self->{config}->bed_shape);
  980. my $success = $self->{model}->arrange_objects($self->GetFrame->config->min_object_distance, $bb);
  981. # ignore arrange failures on purpose: user has visual feedback and we don't need to warn him
  982. # when parts don't fit in print bed
  983. # Force auto center of the aligned grid of of objects on the print bed.
  984. $self->update(1);
  985. }
  986. sub split_object {
  987. my $self = shift;
  988. my ($obj_idx, $current_object) = $self->selected_object;
  989. # we clone model object because split_object() adds the split volumes
  990. # into the same model object, thus causing duplicates when we call load_model_objects()
  991. my $new_model = $self->{model}->clone; # store this before calling get_object()
  992. my $current_model_object = $new_model->get_object($obj_idx);
  993. if ($current_model_object->volumes_count > 1) {
  994. Slic3r::GUI::warning_catcher($self)->("The selected object can't be split because it contains more than one volume/material.");
  995. return;
  996. }
  997. $self->pause_background_process;
  998. my @model_objects = @{$current_model_object->split_object};
  999. if (@model_objects == 1) {
  1000. $self->resume_background_process;
  1001. Slic3r::GUI::warning_catcher($self)->("The selected object couldn't be split because it contains only one part.");
  1002. $self->resume_background_process;
  1003. return;
  1004. }
  1005. foreach my $object (@model_objects) {
  1006. $object->instances->[$_]->offset->translate($_ * 10, $_ * 10)
  1007. for 1..$#{ $object->instances };
  1008. # we need to center this single object around origin
  1009. $object->center_around_origin;
  1010. }
  1011. # remove the original object before spawning the object_loaded event, otherwise
  1012. # we'll pass the wrong $obj_idx to it (which won't be recognized after the
  1013. # thumbnail thread returns)
  1014. $self->remove($obj_idx);
  1015. $current_object = $obj_idx = undef;
  1016. # load all model objects at once, otherwise the plate would be rearranged after each one
  1017. # causing original positions not to be kept
  1018. $self->load_model_objects(@model_objects);
  1019. }
  1020. sub schedule_background_process {
  1021. my ($self) = @_;
  1022. if (defined $self->{apply_config_timer}) {
  1023. $self->{apply_config_timer}->Start(PROCESS_DELAY, 1); # 1 = one shot
  1024. }
  1025. }
  1026. # Executed asynchronously by a timer every PROCESS_DELAY (0.5 second).
  1027. # The timer is started by schedule_background_process(),
  1028. sub async_apply_config {
  1029. my ($self) = @_;
  1030. # pause process thread before applying new config
  1031. # since we don't want to touch data that is being used by the threads
  1032. $self->pause_background_process;
  1033. # apply new config
  1034. my $invalidated = $self->{print}->apply_config($self->GetFrame->config);
  1035. # Just redraw the 3D canvas without reloading the scene.
  1036. # $self->{canvas3D}->Refresh if ($invalidated && $self->{canvas3D}->layer_editing_enabled);
  1037. $self->{canvas3D}->Refresh if ($self->{canvas3D}->layer_editing_enabled);
  1038. # Hide the slicing results if the current slicing status is no more valid.
  1039. $self->{"print_info_box_show"}->(0) if $invalidated;
  1040. if ($Slic3r::GUI::Settings->{_}{background_processing}) {
  1041. if ($invalidated) {
  1042. # kill current thread if any
  1043. $self->stop_background_process;
  1044. } else {
  1045. $self->resume_background_process;
  1046. }
  1047. # schedule a new process thread in case it wasn't running
  1048. $self->start_background_process;
  1049. }
  1050. # Reset preview canvases. If the print has been invalidated, the preview canvases will be cleared.
  1051. # Otherwise they will be just refreshed.
  1052. if ($invalidated) {
  1053. $self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
  1054. $self->{preview3D}->reload_print if $self->{preview3D};
  1055. }
  1056. }
  1057. sub start_background_process {
  1058. my ($self) = @_;
  1059. return if !$Slic3r::have_threads;
  1060. return if !@{$self->{objects}};
  1061. return if $self->{process_thread};
  1062. # It looks like declaring a local $SIG{__WARN__} prevents the ugly
  1063. # "Attempt to free unreferenced scalar" warning...
  1064. local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self);
  1065. # don't start process thread if config is not valid
  1066. eval {
  1067. # this will throw errors if config is not valid
  1068. $self->GetFrame->config->validate;
  1069. $self->{print}->validate;
  1070. };
  1071. if ($@) {
  1072. $self->statusbar->SetStatusText($@);
  1073. return;
  1074. }
  1075. # apply extra variables
  1076. {
  1077. my $extra = $self->GetFrame->extra_variables;
  1078. $self->{print}->placeholder_parser->set($_, $extra->{$_}) for keys %$extra;
  1079. }
  1080. # start thread
  1081. @_ = ();
  1082. $self->{process_thread} = Slic3r::spawn_thread(sub {
  1083. eval {
  1084. $self->{print}->process;
  1085. };
  1086. if ($@) {
  1087. Slic3r::debugf "Background process error: $@\n";
  1088. Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, $@));
  1089. } else {
  1090. Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, undef));
  1091. }
  1092. Slic3r::thread_cleanup();
  1093. });
  1094. Slic3r::debugf "Background processing started.\n";
  1095. }
  1096. sub stop_background_process {
  1097. my ($self) = @_;
  1098. $self->{apply_config_timer}->Stop if defined $self->{apply_config_timer};
  1099. $self->statusbar->SetCancelCallback(undef);
  1100. $self->statusbar->StopBusy;
  1101. $self->statusbar->SetStatusText("");
  1102. $self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
  1103. $self->{preview3D}->reload_print if $self->{preview3D};
  1104. if ($self->{process_thread}) {
  1105. Slic3r::debugf "Killing background process.\n";
  1106. Slic3r::kill_all_threads();
  1107. $self->{process_thread} = undef;
  1108. } else {
  1109. Slic3r::debugf "No background process running.\n";
  1110. }
  1111. # if there's an export process, kill that one as well
  1112. if ($self->{export_thread}) {
  1113. Slic3r::debugf "Killing background export process.\n";
  1114. Slic3r::kill_all_threads();
  1115. $self->{export_thread} = undef;
  1116. }
  1117. }
  1118. sub pause_background_process {
  1119. my ($self) = @_;
  1120. if ($self->{process_thread} || $self->{export_thread}) {
  1121. Slic3r::pause_all_threads();
  1122. return 1;
  1123. } elsif (defined $self->{apply_config_timer} && $self->{apply_config_timer}->IsRunning) {
  1124. $self->{apply_config_timer}->Stop;
  1125. return 1;
  1126. }
  1127. return 0;
  1128. }
  1129. sub resume_background_process {
  1130. my ($self) = @_;
  1131. if ($self->{process_thread} || $self->{export_thread}) {
  1132. Slic3r::resume_all_threads();
  1133. }
  1134. }
  1135. sub reslice {
  1136. # explicitly cancel a previous thread and start a new one.
  1137. my ($self) = @_;
  1138. # Don't reslice if export of G-code or sending to OctoPrint is running.
  1139. if ($Slic3r::have_threads && ! defined($self->{export_gcode_output_file}) && ! defined($self->{send_gcode_file})) {
  1140. # Stop the background processing threads, stop the async update timer.
  1141. $self->stop_background_process;
  1142. # Rather perform one additional unnecessary update of the print object instead of skipping a pending async update.
  1143. $self->async_apply_config;
  1144. $self->statusbar->SetCancelCallback(sub {
  1145. $self->stop_background_process;
  1146. $self->statusbar->SetStatusText("Slicing cancelled");
  1147. # this updates buttons status
  1148. $self->object_list_changed;
  1149. });
  1150. $self->start_background_process;
  1151. }
  1152. }
  1153. sub export_gcode {
  1154. my ($self, $output_file) = @_;
  1155. return if !@{$self->{objects}};
  1156. if ($self->{export_gcode_output_file}) {
  1157. Wx::MessageDialog->new($self, "Another export job is currently running.", 'Error', wxOK | wxICON_ERROR)->ShowModal;
  1158. return;
  1159. }
  1160. # if process is not running, validate config
  1161. # (we assume that if it is running, config is valid)
  1162. eval {
  1163. # this will throw errors if config is not valid
  1164. $self->GetFrame->config->validate;
  1165. $self->{print}->validate;
  1166. };
  1167. Slic3r::GUI::catch_error($self) and return;
  1168. # apply config and validate print
  1169. my $config = $self->GetFrame->config;
  1170. eval {
  1171. # this will throw errors if config is not valid
  1172. $config->validate;
  1173. $self->{print}->apply_config($config);
  1174. $self->{print}->validate;
  1175. };
  1176. if (!$Slic3r::have_threads) {
  1177. Slic3r::GUI::catch_error($self) and return;
  1178. }
  1179. # select output file
  1180. if ($output_file) {
  1181. $self->{export_gcode_output_file} = $self->{print}->output_filepath($output_file);
  1182. } else {
  1183. my $default_output_file = $self->{print}->output_filepath($main::opt{output});
  1184. my $dlg = Wx::FileDialog->new($self, 'Save G-code file as:', wxTheApp->output_path(dirname($default_output_file)),
  1185. basename($default_output_file), &Slic3r::GUI::FILE_WILDCARDS->{gcode}, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
  1186. if ($dlg->ShowModal != wxID_OK) {
  1187. $dlg->Destroy;
  1188. return;
  1189. }
  1190. my $path = Slic3r::decode_path($dlg->GetPath);
  1191. $Slic3r::GUI::Settings->{_}{last_output_path} = dirname($path);
  1192. wxTheApp->save_settings;
  1193. $self->{export_gcode_output_file} = $path;
  1194. $dlg->Destroy;
  1195. }
  1196. $self->statusbar->StartBusy;
  1197. if ($Slic3r::have_threads) {
  1198. $self->statusbar->SetCancelCallback(sub {
  1199. $self->stop_background_process;
  1200. $self->statusbar->SetStatusText("Export cancelled");
  1201. $self->{export_gcode_output_file} = undef;
  1202. $self->{send_gcode_file} = undef;
  1203. # this updates buttons status
  1204. $self->object_list_changed;
  1205. });
  1206. # start background process, whose completion event handler
  1207. # will detect $self->{export_gcode_output_file} and proceed with export
  1208. $self->start_background_process;
  1209. } else {
  1210. eval {
  1211. $self->{print}->process;
  1212. $self->{print}->export_gcode(output_file => $self->{export_gcode_output_file});
  1213. };
  1214. my $result = !Slic3r::GUI::catch_error($self);
  1215. $self->on_export_completed($result);
  1216. }
  1217. # this updates buttons status
  1218. $self->object_list_changed;
  1219. return $self->{export_gcode_output_file};
  1220. }
  1221. # This gets called only if we have threads.
  1222. sub on_process_completed {
  1223. my ($self, $error) = @_;
  1224. $self->statusbar->SetCancelCallback(undef);
  1225. $self->statusbar->StopBusy;
  1226. $self->statusbar->SetStatusText($error // "");
  1227. Slic3r::debugf "Background processing completed.\n";
  1228. $self->{process_thread}->detach if $self->{process_thread};
  1229. $self->{process_thread} = undef;
  1230. # if we're supposed to perform an explicit export let's display the error in a dialog
  1231. if ($error && $self->{export_gcode_output_file}) {
  1232. $self->{export_gcode_output_file} = undef;
  1233. Slic3r::GUI::show_error($self, $error);
  1234. }
  1235. return if $error;
  1236. $self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
  1237. $self->{preview3D}->reload_print if $self->{preview3D};
  1238. # if we have an export filename, start a new thread for exporting G-code
  1239. if ($self->{export_gcode_output_file}) {
  1240. @_ = ();
  1241. # workaround for "Attempt to free un referenced scalar..."
  1242. our $_thread_self = $self;
  1243. $self->{export_thread} = Slic3r::spawn_thread(sub {
  1244. eval {
  1245. $_thread_self->{print}->export_gcode(output_file => $_thread_self->{export_gcode_output_file});
  1246. };
  1247. if ($@) {
  1248. Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $ERROR_EVENT, shared_clone([ $@ ])));
  1249. Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 0));
  1250. } else {
  1251. Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 1));
  1252. }
  1253. Slic3r::thread_cleanup();
  1254. });
  1255. Slic3r::debugf "Background G-code export started.\n";
  1256. }
  1257. }
  1258. # This gets called also if we have no threads.
  1259. sub on_progress_event {
  1260. my ($self, $percent, $message) = @_;
  1261. $self->statusbar->SetProgress($percent);
  1262. $self->statusbar->SetStatusText("$message…");
  1263. }
  1264. # Called when the G-code export finishes, either successfully or with an error.
  1265. # This gets called also if we don't have threads.
  1266. sub on_export_completed {
  1267. my ($self, $result) = @_;
  1268. $self->statusbar->SetCancelCallback(undef);
  1269. $self->statusbar->StopBusy;
  1270. $self->statusbar->SetStatusText("");
  1271. Slic3r::debugf "Background export process completed.\n";
  1272. $self->{export_thread}->detach if $self->{export_thread};
  1273. $self->{export_thread} = undef;
  1274. my $message;
  1275. my $send_gcode = 0;
  1276. my $do_print = 0;
  1277. if ($result) {
  1278. # G-code file exported successfully.
  1279. if ($self->{print_file}) {
  1280. $message = "File added to print queue";
  1281. $do_print = 1;
  1282. } elsif ($self->{send_gcode_file}) {
  1283. $message = "Sending G-code file to the OctoPrint server...";
  1284. $send_gcode = 1;
  1285. } else {
  1286. $message = "G-code file exported to " . $self->{export_gcode_output_file};
  1287. }
  1288. } else {
  1289. $message = "Export failed";
  1290. }
  1291. $self->{export_gcode_output_file} = undef;
  1292. $self->statusbar->SetStatusText($message);
  1293. wxTheApp->notify($message);
  1294. $self->do_print if $do_print;
  1295. # Send $self->{send_gcode_file} to OctoPrint.
  1296. $self->send_gcode if $send_gcode;
  1297. $self->{print_file} = undef;
  1298. $self->{send_gcode_file} = undef;
  1299. $self->{"print_info_cost"}->SetLabel(sprintf("%.2f" , $self->{print}->total_cost));
  1300. $self->{"print_info_fil_g"}->SetLabel(sprintf("%.2f" , $self->{print}->total_weight));
  1301. $self->{"print_info_fil_mm3"}->SetLabel(sprintf("%.2f" , $self->{print}->total_extruded_volume));
  1302. $self->{"print_info_box_show"}->(1);
  1303. # this updates buttons status
  1304. $self->object_list_changed;
  1305. }
  1306. sub do_print {
  1307. my ($self) = @_;
  1308. my $printer_tab = $self->GetFrame->{options_tabs}{printer};
  1309. my $printer_name = $printer_tab->get_current_preset->name;
  1310. my $controller = $self->GetFrame->{controller};
  1311. my $printer_panel = $controller->add_printer($printer_name, $printer_tab->config);
  1312. my $filament_stats = $self->{print}->filament_stats;
  1313. my @filament_names = $self->GetFrame->filament_preset_names;
  1314. $filament_stats = { map { $filament_names[$_] => $filament_stats->{$_} } keys %$filament_stats };
  1315. $printer_panel->load_print_job($self->{print_file}, $filament_stats);
  1316. $self->GetFrame->select_tab(1);
  1317. }
  1318. # Send $self->{send_gcode_file} to OctoPrint.
  1319. #FIXME Currently this call blocks the UI. Make it asynchronous.
  1320. sub send_gcode {
  1321. my ($self) = @_;
  1322. $self->statusbar->StartBusy;
  1323. my $ua = LWP::UserAgent->new;
  1324. $ua->timeout(180);
  1325. my $path = Slic3r::encode_path($self->{send_gcode_file});
  1326. my $res = $ua->post(
  1327. "http://" . $self->{config}->octoprint_host . "/api/files/local",
  1328. Content_Type => 'form-data',
  1329. 'X-Api-Key' => $self->{config}->octoprint_apikey,
  1330. Content => [
  1331. # OctoPrint doesn't like Windows paths so we use basename()
  1332. # Also, since we need to read from filesystem we process it through encode_path()
  1333. file => [ $path, basename($path) ],
  1334. ],
  1335. );
  1336. $self->statusbar->StopBusy;
  1337. if ($res->is_success) {
  1338. $self->statusbar->SetStatusText("G-code file successfully uploaded to the OctoPrint server");
  1339. } else {
  1340. my $message = "Error while uploading to the OctoPrint server: " . $res->status_line;
  1341. Slic3r::GUI::show_error($self, $message);
  1342. $self->statusbar->SetStatusText($message);
  1343. }
  1344. }
  1345. sub export_stl {
  1346. my $self = shift;
  1347. return if !@{$self->{objects}};
  1348. my $output_file = $self->_get_export_file('STL') or return;
  1349. $self->{model}->store_stl(Slic3r::encode_path($output_file), 1);
  1350. $self->statusbar->SetStatusText("STL file exported to $output_file");
  1351. }
  1352. sub reload_from_disk {
  1353. my ($self) = @_;
  1354. my ($obj_idx, $object) = $self->selected_object;
  1355. return if !defined $obj_idx;
  1356. my $model_object = $self->{model}->objects->[$obj_idx];
  1357. return if !$model_object->input_file
  1358. || !-e $model_object->input_file;
  1359. my @new_obj_idx = $self->load_file($model_object->input_file);
  1360. return if !@new_obj_idx;
  1361. foreach my $new_obj_idx (@new_obj_idx) {
  1362. my $o = $self->{model}->objects->[$new_obj_idx];
  1363. $o->clear_instances;
  1364. $o->add_instance($_) for @{$model_object->instances};
  1365. if ($o->volumes_count == $model_object->volumes_count) {
  1366. for my $i (0..($o->volumes_count-1)) {
  1367. $o->get_volume($i)->config->apply($model_object->get_volume($i)->config);
  1368. }
  1369. }
  1370. }
  1371. $self->remove($obj_idx);
  1372. }
  1373. sub export_object_stl {
  1374. my $self = shift;
  1375. my ($obj_idx, $object) = $self->selected_object;
  1376. return if !defined $obj_idx;
  1377. my $model_object = $self->{model}->objects->[$obj_idx];
  1378. my $output_file = $self->_get_export_file('STL') or return;
  1379. $model_object->mesh->write_binary(Slic3r::encode_path($output_file));
  1380. $self->statusbar->SetStatusText("STL file exported to $output_file");
  1381. }
  1382. sub export_amf {
  1383. my $self = shift;
  1384. return if !@{$self->{objects}};
  1385. my $output_file = $self->_get_export_file('AMF') or return;
  1386. $self->{model}->store_amf(Slic3r::encode_path($output_file));
  1387. $self->statusbar->SetStatusText("AMF file exported to $output_file");
  1388. }
  1389. sub _get_export_file {
  1390. my $self = shift;
  1391. my ($format) = @_;
  1392. my $suffix = $format eq 'STL' ? '.stl' : '.amf.xml';
  1393. my $output_file = $main::opt{output};
  1394. {
  1395. $output_file = $self->{print}->output_filepath($output_file);
  1396. $output_file =~ s/\.gcode$/$suffix/i;
  1397. my $dlg = Wx::FileDialog->new($self, "Save $format file as:", dirname($output_file),
  1398. basename($output_file), &Slic3r::GUI::MODEL_WILDCARD, wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
  1399. if ($dlg->ShowModal != wxID_OK) {
  1400. $dlg->Destroy;
  1401. return undef;
  1402. }
  1403. $output_file = Slic3r::decode_path($dlg->GetPath);
  1404. $dlg->Destroy;
  1405. }
  1406. return $output_file;
  1407. }
  1408. sub reset_thumbnail {
  1409. my ($self, $obj_idx) = @_;
  1410. $self->{objects}[$obj_idx]->thumbnail(undef);
  1411. }
  1412. # this method gets called whenever print center is changed or the objects' bounding box changes
  1413. # (i.e. when an object is added/removed/moved/rotated/scaled)
  1414. sub update {
  1415. my ($self, $force_autocenter) = @_;
  1416. if ($Slic3r::GUI::Settings->{_}{autocenter} || $force_autocenter) {
  1417. $self->{model}->center_instances_around_point($self->bed_centerf);
  1418. }
  1419. my $running = $self->pause_background_process;
  1420. my $invalidated = $self->{print}->reload_model_instances();
  1421. # The mere fact that no steps were invalidated when reloading model instances
  1422. # doesn't mean that all steps were done: for example, validation might have
  1423. # failed upon previous instance move, so we have no running thread and no steps
  1424. # are invalidated on this move, thus we need to schedule a new run.
  1425. if ($invalidated || !$running) {
  1426. $self->schedule_background_process;
  1427. } else {
  1428. $self->resume_background_process;
  1429. }
  1430. $self->{canvas}->reload_scene if $self->{canvas};
  1431. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1432. $self->{preview3D}->reload_print if $self->{preview3D};
  1433. }
  1434. # When a number of extruders changes, the UI needs to be updated to show a single filament selection combo box per extruder.
  1435. sub on_extruders_change {
  1436. my ($self, $num_extruders) = @_;
  1437. my $choices = $self->{preset_choosers}{filament};
  1438. while (@$choices < $num_extruders) {
  1439. # copy strings from first choice
  1440. my @presets = $choices->[0]->GetStrings;
  1441. # initialize new choice
  1442. my $choice = Wx::BitmapComboBox->new($self, -1, "", wxDefaultPosition, wxDefaultSize, [@presets], wxCB_READONLY);
  1443. my $extruder_idx = scalar @$choices;
  1444. EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down($extruder_idx, @_); } );
  1445. push @$choices, $choice;
  1446. # copy icons from first choice
  1447. $choice->SetItemBitmap($_, $choices->[0]->GetItemBitmap($_)) for 0..$#presets;
  1448. # insert new choice into sizer
  1449. $self->{presets_sizer}->Insert(4 + ($#$choices-1)*2, 0, 0);
  1450. $self->{presets_sizer}->Insert(5 + ($#$choices-1)*2, $choice, 0, wxEXPAND | wxBOTTOM, FILAMENT_CHOOSERS_SPACING);
  1451. # setup the listener
  1452. EVT_COMBOBOX($choice, $choice, sub {
  1453. my ($choice) = @_;
  1454. wxTheApp->CallAfter(sub {
  1455. $self->_on_select_preset('filament', $choice);
  1456. });
  1457. });
  1458. # initialize selection
  1459. my $i = first { $choice->GetString($_) eq ($Slic3r::GUI::Settings->{presets}{"filament_" . $#$choices} || '') } 0 .. $#presets;
  1460. $choice->SetSelection($i || 0);
  1461. }
  1462. # remove unused choices if any
  1463. while (@$choices > $num_extruders) {
  1464. $self->{presets_sizer}->Remove(4 + ($#$choices-1)*2); # label
  1465. $self->{presets_sizer}->Remove(4 + ($#$choices-1)*2); # wxChoice
  1466. $choices->[-1]->Destroy;
  1467. pop @$choices;
  1468. }
  1469. $self->Layout;
  1470. }
  1471. sub on_config_change {
  1472. my $self = shift;
  1473. my ($config) = @_;
  1474. my $update_scheduled;
  1475. foreach my $opt_key (@{$self->{config}->diff($config)}) {
  1476. $self->{config}->set($opt_key, $config->get($opt_key));
  1477. if ($opt_key eq 'bed_shape') {
  1478. $self->{canvas}->update_bed_size;
  1479. $self->{canvas3D}->update_bed_size if $self->{canvas3D};
  1480. $self->{preview3D}->set_bed_shape($self->{config}->bed_shape)
  1481. if $self->{preview3D};
  1482. $update_scheduled = 1;
  1483. } elsif ($opt_key =~ '^wipe_tower' || $opt_key eq 'single_extruder_multi_material') {
  1484. $update_scheduled = 1;
  1485. } elsif ($opt_key eq 'serial_port') {
  1486. $self->{btn_print}->Show($config->get('serial_port'));
  1487. $self->Layout;
  1488. } elsif ($opt_key eq 'octoprint_host') {
  1489. $self->{btn_send_gcode}->Show($config->get('octoprint_host'));
  1490. $self->Layout;
  1491. } elsif ($opt_key eq 'variable_layer_height') {
  1492. if ($config->get('variable_layer_height') != 1) {
  1493. if ($self->{htoolbar}) {
  1494. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 0);
  1495. $self->{htoolbar}->ToggleTool(TB_LAYER_EDITING, 0);
  1496. } else {
  1497. $self->{"btn_layer_editing"}->Disable;
  1498. $self->{"btn_layer_editing"}->SetValue(0);
  1499. }
  1500. $self->{canvas3D}->layer_editing_enabled(0);
  1501. $self->{canvas3D}->Refresh;
  1502. $self->{canvas3D}->Update;
  1503. } elsif ($self->{canvas3D}->layer_editing_allowed) {
  1504. # Want to allow the layer editing, but do it only if the OpenGL supports it.
  1505. if ($self->{htoolbar}) {
  1506. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 1);
  1507. } else {
  1508. $self->{"btn_layer_editing"}->Enable;
  1509. }
  1510. }
  1511. } elsif ($opt_key eq 'extruder_colour') {
  1512. $update_scheduled = 1;
  1513. my $extruder_colors = $config->get('extruder_colour');
  1514. $self->{preview3D}->set_number_extruders(scalar(@{$extruder_colors}));
  1515. }
  1516. }
  1517. $self->update if $update_scheduled;
  1518. return if !$self->GetFrame->is_loaded;
  1519. # (re)start timer
  1520. $self->schedule_background_process;
  1521. }
  1522. sub list_item_deselected {
  1523. my ($self, $event) = @_;
  1524. return if $PreventListEvents;
  1525. if ($self->{list}->GetFirstSelected == -1) {
  1526. $self->select_object(undef);
  1527. $self->{canvas}->Refresh;
  1528. #FIXME VBOs are being refreshed just to change a selection color?
  1529. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1530. }
  1531. }
  1532. sub list_item_selected {
  1533. my ($self, $event) = @_;
  1534. return if $PreventListEvents;
  1535. my $obj_idx = $event->GetIndex;
  1536. $self->select_object($obj_idx);
  1537. $self->{canvas}->Refresh;
  1538. #FIXME VBOs are being refreshed just to change a selection color?
  1539. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1540. }
  1541. sub list_item_activated {
  1542. my ($self, $event, $obj_idx) = @_;
  1543. $obj_idx //= $event->GetIndex;
  1544. $self->object_settings_dialog($obj_idx);
  1545. }
  1546. # Called when clicked on the filament preset combo box.
  1547. # When clicked on the icon, show the color picker.
  1548. sub filament_color_box_lmouse_down
  1549. {
  1550. my ($self, $extruder_idx, $combobox, $event) = @_;
  1551. my $pos = $event->GetLogicalPosition(Wx::ClientDC->new($combobox));
  1552. my( $x, $y ) = ( $pos->x, $pos->y );
  1553. if ($x > 24) {
  1554. # Let the combo box process the mouse click.
  1555. $event->Skip;
  1556. } else {
  1557. # Swallow the mouse click and open the color picker.
  1558. my $data = Wx::ColourData->new;
  1559. $data->SetChooseFull(1);
  1560. my $dialog = Wx::ColourDialog->new($self->GetFrame, $data);
  1561. if ($dialog->ShowModal == wxID_OK) {
  1562. my $cfg = Slic3r::Config->new;
  1563. my $colors = $self->GetFrame->config->get('extruder_colour');
  1564. $colors->[$extruder_idx] = $dialog->GetColourData->GetColour->GetAsString(wxC2S_HTML_SYNTAX);
  1565. $cfg->set('extruder_colour', $colors);
  1566. $self->GetFrame->{options_tabs}{printer}->load_config($cfg);
  1567. $self->update_filament_colors_preview($extruder_idx);
  1568. }
  1569. $dialog->Destroy();
  1570. }
  1571. }
  1572. sub object_cut_dialog {
  1573. my $self = shift;
  1574. my ($obj_idx) = @_;
  1575. if (!defined $obj_idx) {
  1576. ($obj_idx, undef) = $self->selected_object;
  1577. }
  1578. if (!$Slic3r::GUI::have_OpenGL) {
  1579. Slic3r::GUI::show_error($self, "Please install the OpenGL modules to use this feature (see build instructions).");
  1580. return;
  1581. }
  1582. my $dlg = Slic3r::GUI::Plater::ObjectCutDialog->new($self,
  1583. object => $self->{objects}[$obj_idx],
  1584. model_object => $self->{model}->objects->[$obj_idx],
  1585. );
  1586. return unless $dlg->ShowModal == wxID_OK;
  1587. if (my @new_objects = $dlg->NewModelObjects) {
  1588. $self->remove($obj_idx);
  1589. $self->load_model_objects(grep defined($_), @new_objects);
  1590. $self->arrange;
  1591. }
  1592. }
  1593. sub object_settings_dialog {
  1594. my $self = shift;
  1595. my ($obj_idx) = @_;
  1596. if (!defined $obj_idx) {
  1597. ($obj_idx, undef) = $self->selected_object;
  1598. }
  1599. my $model_object = $self->{model}->objects->[$obj_idx];
  1600. # validate config before opening the settings dialog because
  1601. # that dialog can't be closed if validation fails, but user
  1602. # can't fix any error which is outside that dialog
  1603. return unless $self->validate_config;
  1604. my $dlg = Slic3r::GUI::Plater::ObjectSettingsDialog->new($self,
  1605. object => $self->{objects}[$obj_idx],
  1606. model_object => $model_object,
  1607. config => $self->GetFrame->config,
  1608. );
  1609. $self->pause_background_process;
  1610. $dlg->ShowModal;
  1611. # update thumbnail since parts may have changed
  1612. if ($dlg->PartsChanged) {
  1613. # recenter and re-align to Z = 0
  1614. $model_object->center_around_origin;
  1615. $self->reset_thumbnail($obj_idx);
  1616. }
  1617. # update print
  1618. if ($dlg->PartsChanged || $dlg->PartSettingsChanged) {
  1619. $self->stop_background_process;
  1620. $self->{print}->reload_object($obj_idx);
  1621. $self->schedule_background_process;
  1622. $self->{canvas}->reload_scene if $self->{canvas};
  1623. $self->{canvas3D}->reload_scene if $self->{canvas3D};
  1624. } else {
  1625. $self->resume_background_process;
  1626. }
  1627. }
  1628. # Called to update various buttons depending on whether there are any objects or
  1629. # whether background processing (export of a G-code, sending to Octoprint, forced background re-slicing) is active.
  1630. sub object_list_changed {
  1631. my $self = shift;
  1632. # Enable/disable buttons depending on whether there are any objects on the platter.
  1633. my $have_objects = @{$self->{objects}} ? 1 : 0;
  1634. my $variable_layer_height_allowed = $self->{config}->variable_layer_height && $self->{canvas3D}->layer_editing_allowed;
  1635. if ($self->{htoolbar}) {
  1636. # On OSX or Linux
  1637. $self->{htoolbar}->EnableTool($_, $have_objects)
  1638. for (TB_RESET, TB_ARRANGE, TB_LAYER_EDITING);
  1639. $self->{htoolbar}->EnableTool(TB_LAYER_EDITING, 0) if (! $variable_layer_height_allowed);
  1640. } else {
  1641. # On MSW
  1642. my $method = $have_objects ? 'Enable' : 'Disable';
  1643. $self->{"btn_$_"}->$method
  1644. for grep $self->{"btn_$_"}, qw(reset arrange reslice export_gcode export_stl print send_gcode layer_editing);
  1645. $self->{"btn_layer_editing"}->Disable if (! $variable_layer_height_allowed);
  1646. }
  1647. my $export_in_progress = $self->{export_gcode_output_file} || $self->{send_gcode_file};
  1648. my $method = ($have_objects && ! $export_in_progress) ? 'Enable' : 'Disable';
  1649. $self->{"btn_$_"}->$method
  1650. for grep $self->{"btn_$_"}, qw(reslice export_gcode print send_gcode);
  1651. }
  1652. sub selection_changed {
  1653. my $self = shift;
  1654. my ($obj_idx, $object) = $self->selected_object;
  1655. my $have_sel = defined $obj_idx;
  1656. if ($self->{htoolbar}) {
  1657. # On OSX or Linux
  1658. $self->{htoolbar}->EnableTool($_, $have_sel)
  1659. for (TB_REMOVE, TB_MORE, TB_FEWER, TB_45CW, TB_45CCW, TB_SCALE, TB_SPLIT, TB_CUT, TB_SETTINGS);
  1660. } else {
  1661. # On MSW
  1662. my $method = $have_sel ? 'Enable' : 'Disable';
  1663. $self->{"btn_$_"}->$method
  1664. for grep $self->{"btn_$_"}, qw(remove increase decrease rotate45cw rotate45ccw changescale split cut settings);
  1665. }
  1666. if ($self->{object_info_size}) { # have we already loaded the info pane?
  1667. if ($have_sel) {
  1668. my $model_object = $self->{model}->objects->[$obj_idx];
  1669. $model_object->print_info;
  1670. my $model_instance = $model_object->instances->[0];
  1671. $self->{object_info_size}->SetLabel(sprintf("%.2f x %.2f x %.2f", @{$model_object->instance_bounding_box(0)->size}));
  1672. $self->{object_info_materials}->SetLabel($model_object->materials_count);
  1673. if (my $stats = $model_object->mesh_stats) {
  1674. $self->{object_info_volume}->SetLabel(sprintf('%.2f', $stats->{volume} * ($model_instance->scaling_factor**3)));
  1675. $self->{object_info_facets}->SetLabel(sprintf('%d (%d shells)', $model_object->facets_count, $stats->{number_of_parts}));
  1676. if (my $errors = sum(@$stats{qw(degenerate_facets edges_fixed facets_removed facets_added facets_reversed backwards_edges)})) {
  1677. $self->{object_info_manifold}->SetLabel(sprintf("Auto-repaired (%d errors)", $errors));
  1678. $self->{object_info_manifold_warning_icon}->Show;
  1679. # we don't show normals_fixed because we never provide normals
  1680. # to admesh, so it generates normals for all facets
  1681. my $message = sprintf '%d degenerate facets, %d edges fixed, %d facets removed, %d facets added, %d facets reversed, %d backwards edges',
  1682. @$stats{qw(degenerate_facets edges_fixed facets_removed facets_added facets_reversed backwards_edges)};
  1683. $self->{object_info_manifold}->SetToolTipString($message);
  1684. $self->{object_info_manifold_warning_icon}->SetToolTipString($message);
  1685. } else {
  1686. $self->{object_info_manifold}->SetLabel("Yes");
  1687. }
  1688. } else {
  1689. $self->{object_info_facets}->SetLabel($object->facets);
  1690. }
  1691. } else {
  1692. $self->{"object_info_$_"}->SetLabel("") for qw(size volume facets materials manifold);
  1693. $self->{object_info_manifold_warning_icon}->Hide;
  1694. $self->{object_info_manifold}->SetToolTipString("");
  1695. }
  1696. $self->Layout;
  1697. }
  1698. # prepagate the event to the frame (a custom Wx event would be cleaner)
  1699. $self->GetFrame->on_plater_selection_changed($have_sel);
  1700. }
  1701. sub select_object {
  1702. my ($self, $obj_idx) = @_;
  1703. $_->selected(0) for @{ $self->{objects} };
  1704. if (defined $obj_idx) {
  1705. $self->{objects}->[$obj_idx]->selected(1);
  1706. # We use this flag to avoid circular event handling
  1707. # Select() happens to fire a wxEVT_LIST_ITEM_SELECTED on Windows,
  1708. # whose event handler calls this method again and again and again
  1709. $PreventListEvents = 1;
  1710. $self->{list}->Select($obj_idx, 1);
  1711. $PreventListEvents = 0;
  1712. } else {
  1713. # TODO: deselect all in list
  1714. }
  1715. $self->selection_changed(1);
  1716. }
  1717. sub selected_object {
  1718. my $self = shift;
  1719. my $obj_idx = first { $self->{objects}[$_]->selected } 0..$#{ $self->{objects} };
  1720. return undef if !defined $obj_idx;
  1721. return ($obj_idx, $self->{objects}[$obj_idx]),
  1722. }
  1723. sub validate_config {
  1724. my $self = shift;
  1725. eval {
  1726. $self->GetFrame->config->validate;
  1727. };
  1728. return 0 if Slic3r::GUI::catch_error($self);
  1729. return 1;
  1730. }
  1731. sub statusbar {
  1732. my $self = shift;
  1733. return $self->GetFrame->{statusbar};
  1734. }
  1735. sub object_menu {
  1736. my ($self) = @_;
  1737. my $frame = $self->GetFrame;
  1738. my $menu = Wx::Menu->new;
  1739. $frame->_append_menu_item($menu, "Delete\tCtrl+Del", 'Remove the selected object', sub {
  1740. $self->remove;
  1741. }, undef, 'brick_delete.png');
  1742. $frame->_append_menu_item($menu, "Increase copies\tCtrl++", 'Place one more copy of the selected object', sub {
  1743. $self->increase;
  1744. }, undef, 'add.png');
  1745. $frame->_append_menu_item($menu, "Decrease copies\tCtrl+-", 'Remove one copy of the selected object', sub {
  1746. $self->decrease;
  1747. }, undef, 'delete.png');
  1748. $frame->_append_menu_item($menu, "Set number of copies…", 'Change the number of copies of the selected object', sub {
  1749. $self->set_number_of_copies;
  1750. }, undef, 'textfield.png');
  1751. $menu->AppendSeparator();
  1752. $frame->_append_menu_item($menu, "Rotate 45° clockwise", 'Rotate the selected object by 45° clockwise', sub {
  1753. $self->rotate(-45, Z, 'relative');
  1754. }, undef, 'arrow_rotate_clockwise.png');
  1755. $frame->_append_menu_item($menu, "Rotate 45° counter-clockwise", 'Rotate the selected object by 45° counter-clockwise', sub {
  1756. $self->rotate(+45, Z, 'relative');
  1757. }, undef, 'arrow_rotate_anticlockwise.png');
  1758. my $rotateMenu = Wx::Menu->new;
  1759. my $rotateMenuItem = $menu->AppendSubMenu($rotateMenu, "Rotate", 'Rotate the selected object by an arbitrary angle');
  1760. $frame->_set_menu_item_icon($rotateMenuItem, 'textfield.png');
  1761. $frame->_append_menu_item($rotateMenu, "Around X axis…", 'Rotate the selected object by an arbitrary angle around X axis', sub {
  1762. $self->rotate(undef, X);
  1763. }, undef, 'bullet_red.png');
  1764. $frame->_append_menu_item($rotateMenu, "Around Y axis…", 'Rotate the selected object by an arbitrary angle around Y axis', sub {
  1765. $self->rotate(undef, Y);
  1766. }, undef, 'bullet_green.png');
  1767. $frame->_append_menu_item($rotateMenu, "Around Z axis…", 'Rotate the selected object by an arbitrary angle around Z axis', sub {
  1768. $self->rotate(undef, Z);
  1769. }, undef, 'bullet_blue.png');
  1770. my $mirrorMenu = Wx::Menu->new;
  1771. my $mirrorMenuItem = $menu->AppendSubMenu($mirrorMenu, "Mirror", 'Mirror the selected object');
  1772. $frame->_set_menu_item_icon($mirrorMenuItem, 'shape_flip_horizontal.png');
  1773. $frame->_append_menu_item($mirrorMenu, "Along X axis…", 'Mirror the selected object along the X axis', sub {
  1774. $self->mirror(X);
  1775. }, undef, 'bullet_red.png');
  1776. $frame->_append_menu_item($mirrorMenu, "Along Y axis…", 'Mirror the selected object along the Y axis', sub {
  1777. $self->mirror(Y);
  1778. }, undef, 'bullet_green.png');
  1779. $frame->_append_menu_item($mirrorMenu, "Along Z axis…", 'Mirror the selected object along the Z axis', sub {
  1780. $self->mirror(Z);
  1781. }, undef, 'bullet_blue.png');
  1782. my $scaleMenu = Wx::Menu->new;
  1783. my $scaleMenuItem = $menu->AppendSubMenu($scaleMenu, "Scale", 'Scale the selected object along a single axis');
  1784. $frame->_set_menu_item_icon($scaleMenuItem, 'arrow_out.png');
  1785. $frame->_append_menu_item($scaleMenu, "Uniformly…", 'Scale the selected object along the XYZ axes', sub {
  1786. $self->changescale(undef);
  1787. });
  1788. $frame->_append_menu_item($scaleMenu, "Along X axis…", 'Scale the selected object along the X axis', sub {
  1789. $self->changescale(X);
  1790. }, undef, 'bullet_red.png');
  1791. $frame->_append_menu_item($scaleMenu, "Along Y axis…", 'Scale the selected object along the Y axis', sub {
  1792. $self->changescale(Y);
  1793. }, undef, 'bullet_green.png');
  1794. $frame->_append_menu_item($scaleMenu, "Along Z axis…", 'Scale the selected object along the Z axis', sub {
  1795. $self->changescale(Z);
  1796. }, undef, 'bullet_blue.png');
  1797. my $scaleToSizeMenu = Wx::Menu->new;
  1798. my $scaleToSizeMenuItem = $menu->AppendSubMenu($scaleToSizeMenu, "Scale to size", 'Scale the selected object along a single axis');
  1799. $frame->_set_menu_item_icon($scaleToSizeMenuItem, 'arrow_out.png');
  1800. $frame->_append_menu_item($scaleToSizeMenu, "Uniformly…", 'Scale the selected object along the XYZ axes', sub {
  1801. $self->changescale(undef, 1);
  1802. });
  1803. $frame->_append_menu_item($scaleToSizeMenu, "Along X axis…", 'Scale the selected object along the X axis', sub {
  1804. $self->changescale(X, 1);
  1805. }, undef, 'bullet_red.png');
  1806. $frame->_append_menu_item($scaleToSizeMenu, "Along Y axis…", 'Scale the selected object along the Y axis', sub {
  1807. $self->changescale(Y, 1);
  1808. }, undef, 'bullet_green.png');
  1809. $frame->_append_menu_item($scaleToSizeMenu, "Along Z axis…", 'Scale the selected object along the Z axis', sub {
  1810. $self->changescale(Z, 1);
  1811. }, undef, 'bullet_blue.png');
  1812. $frame->_append_menu_item($menu, "Split", 'Split the selected object into individual parts', sub {
  1813. $self->split_object;
  1814. }, undef, 'shape_ungroup.png');
  1815. $frame->_append_menu_item($menu, "Cut…", 'Open the 3D cutting tool', sub {
  1816. $self->object_cut_dialog;
  1817. }, undef, 'package.png');
  1818. $menu->AppendSeparator();
  1819. $frame->_append_menu_item($menu, "Settings…", 'Open the object editor dialog', sub {
  1820. $self->object_settings_dialog;
  1821. }, undef, 'cog.png');
  1822. $menu->AppendSeparator();
  1823. $frame->_append_menu_item($menu, "Reload from Disk", 'Reload the selected file from Disk', sub {
  1824. $self->reload_from_disk;
  1825. }, undef, 'arrow_refresh.png');
  1826. $frame->_append_menu_item($menu, "Export object as STL…", 'Export this single object as STL file', sub {
  1827. $self->export_object_stl;
  1828. }, undef, 'brick_go.png');
  1829. return $menu;
  1830. }
  1831. # Set a camera direction, zoom to all objects.
  1832. sub select_view {
  1833. my ($self, $direction) = @_;
  1834. my $idx_page = $self->{preview_notebook}->GetSelection;
  1835. my $page = ($idx_page == &Wx::wxNOT_FOUND) ? '3D' : $self->{preview_notebook}->GetPageText($idx_page);
  1836. if ($page eq 'Preview') {
  1837. $self->{preview3D}->canvas->select_view($direction);
  1838. $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas);
  1839. } else {
  1840. $self->{canvas3D}->select_view($direction);
  1841. $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D});
  1842. }
  1843. }
  1844. package Slic3r::GUI::Plater::DropTarget;
  1845. use Wx::DND;
  1846. use base 'Wx::FileDropTarget';
  1847. sub new {
  1848. my $class = shift;
  1849. my ($window) = @_;
  1850. my $self = $class->SUPER::new;
  1851. $self->{window} = $window;
  1852. return $self;
  1853. }
  1854. sub OnDropFiles {
  1855. my $self = shift;
  1856. my ($x, $y, $filenames) = @_;
  1857. # stop scalars leaking on older perl
  1858. # https://rt.perl.org/rt3/Public/Bug/Display.html?id=70602
  1859. @_ = ();
  1860. # only accept STL, OBJ and AMF files
  1861. return 0 if grep !/\.(?:stl|obj|amf(?:\.xml)?|prusa)$/i, @$filenames;
  1862. $self->{window}->load_file($_) for @$filenames;
  1863. }
  1864. # 2D preview of an object. Each object is previewed by its convex hull.
  1865. package Slic3r::GUI::Plater::Object;
  1866. use Moo;
  1867. use List::Util qw(first);
  1868. use Slic3r::Geometry qw(X Y Z MIN MAX deg2rad);
  1869. has 'name' => (is => 'rw', required => 1);
  1870. has 'thumbnail' => (is => 'rw'); # ExPolygon::Collection in scaled model units with no transforms
  1871. has 'transformed_thumbnail' => (is => 'rw');
  1872. 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
  1873. has 'selected' => (is => 'rw', default => sub { 0 });
  1874. sub make_thumbnail {
  1875. my ($self, $model, $obj_idx) = @_;
  1876. # make method idempotent
  1877. $self->thumbnail->clear;
  1878. # raw_mesh is the non-transformed (non-rotated, non-scaled, non-translated) sum of non-modifier object volumes.
  1879. my $mesh = $model->objects->[$obj_idx]->raw_mesh;
  1880. #FIXME The "correct" variant could be extremely slow.
  1881. # if ($mesh->facets_count <= 5000) {
  1882. # # remove polygons with area <= 1mm
  1883. # my $area_threshold = Slic3r::Geometry::scale 1;
  1884. # $self->thumbnail->append(
  1885. # grep $_->area >= $area_threshold,
  1886. # @{ $mesh->horizontal_projection }, # horizontal_projection returns scaled expolygons
  1887. # );
  1888. # $self->thumbnail->simplify(0.5);
  1889. # } else {
  1890. my $convex_hull = Slic3r::ExPolygon->new($mesh->convex_hull);
  1891. $self->thumbnail->append($convex_hull);
  1892. # }
  1893. return $self->thumbnail;
  1894. }
  1895. sub transform_thumbnail {
  1896. my ($self, $model, $obj_idx) = @_;
  1897. return unless defined $self->thumbnail;
  1898. my $model_object = $model->objects->[$obj_idx];
  1899. my $model_instance = $model_object->instances->[0];
  1900. # the order of these transformations MUST be the same everywhere, including
  1901. # in Slic3r::Print->add_model_object()
  1902. my $t = $self->thumbnail->clone;
  1903. $t->rotate($model_instance->rotation, Slic3r::Point->new(0,0));
  1904. $t->scale($model_instance->scaling_factor);
  1905. $self->transformed_thumbnail($t);
  1906. }
  1907. 1;