Plater.pm 90 KB

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