Plater.pm 92 KB

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