Plater.pm 91 KB

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