3DScene.pm 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  1. # Implements pure perl packages
  2. #
  3. # Slic3r::GUI::3DScene::Base;
  4. # Slic3r::GUI::3DScene;
  5. #
  6. # Slic3r::GUI::Plater::3D derives from Slic3r::GUI::3DScene,
  7. # Slic3r::GUI::Plater::3DPreview, Slic3r::GUI::Plater::3DToolpaths,
  8. # Slic3r::GUI::Plater::ObjectCutDialog and Slic3r::GUI::Plater::ObjectPartsPanel
  9. # own $self->{canvas} of the Slic3r::GUI::3DScene type.
  10. #
  11. # Therefore the 3DScene supports renderng of STLs, extrusions and cutting planes,
  12. # and camera manipulation.
  13. package Slic3r::GUI::3DScene::Base;
  14. use strict;
  15. use warnings;
  16. use Wx qw(:timer :bitmap :icon :dialog);
  17. use Wx::Event qw(EVT_PAINT EVT_SIZE EVT_ERASE_BACKGROUND EVT_IDLE EVT_MOUSEWHEEL EVT_MOUSE_EVENTS EVT_CHAR EVT_TIMER);
  18. # must load OpenGL *before* Wx::GLCanvas
  19. use OpenGL qw(:glconstants :glfunctions :glufunctions :gluconstants);
  20. use base qw(Wx::GLCanvas Class::Accessor);
  21. use Math::Trig qw(asin tan);
  22. use List::Util qw(reduce min max first);
  23. use Slic3r::Geometry qw(X Y normalize scale unscale scaled_epsilon);
  24. use Slic3r::Geometry::Clipper qw(offset_ex intersection_pl JT_ROUND);
  25. use Wx::GLCanvas qw(:all);
  26. use Slic3r::Geometry qw(PI);
  27. # _dirty: boolean flag indicating, that the screen has to be redrawn on EVT_IDLE.
  28. # volumes: reference to vector of Slic3r::GUI::3DScene::Volume.
  29. # _camera_type: 'perspective' or 'ortho'
  30. __PACKAGE__->mk_accessors( qw(_quat _dirty init
  31. enable_picking
  32. enable_moving
  33. use_plain_shader
  34. on_viewport_changed
  35. on_hover
  36. on_select
  37. on_double_click
  38. on_right_click
  39. on_move
  40. on_model_update
  41. volumes
  42. _sphi _stheta
  43. cutting_plane_z
  44. cut_lines_vertices
  45. bed_shape
  46. bed_triangles
  47. bed_grid_lines
  48. bed_polygon
  49. background
  50. origin
  51. _mouse_pos
  52. _hover_volume_idx
  53. _drag_volume_idx
  54. _drag_start_pos
  55. _drag_volume_center_offset
  56. _drag_start_xy
  57. _dragged
  58. _layer_height_edited
  59. _camera_type
  60. _camera_target
  61. _camera_distance
  62. _zoom
  63. ) );
  64. use constant TRACKBALLSIZE => 0.8;
  65. use constant TURNTABLE_MODE => 1;
  66. use constant GROUND_Z => -0.02;
  67. # For mesh selection: Not selected - bright yellow.
  68. use constant DEFAULT_COLOR => [1,1,0];
  69. # For mesh selection: Selected - bright green.
  70. use constant SELECTED_COLOR => [0,1,0,1];
  71. # For mesh selection: Mouse hovers over the object, but object not selected yet - dark green.
  72. use constant HOVER_COLOR => [0.4,0.9,0,1];
  73. # phi / theta angles to orient the camera.
  74. use constant VIEW_DEFAULT => [45.0,45.0];
  75. use constant VIEW_LEFT => [90.0,90.0];
  76. use constant VIEW_RIGHT => [-90.0,90.0];
  77. use constant VIEW_TOP => [0.0,0.0];
  78. use constant VIEW_BOTTOM => [0.0,180.0];
  79. use constant VIEW_FRONT => [0.0,90.0];
  80. use constant VIEW_REAR => [180.0,90.0];
  81. use constant MANIPULATION_IDLE => 0;
  82. use constant MANIPULATION_DRAGGING => 1;
  83. use constant MANIPULATION_LAYER_HEIGHT => 2;
  84. use constant GIMBALL_LOCK_THETA_MAX => 170;
  85. use constant VARIABLE_LAYER_THICKNESS_BAR_WIDTH => 70;
  86. use constant VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT => 22;
  87. # make OpenGL::Array thread-safe
  88. {
  89. no warnings 'redefine';
  90. *OpenGL::Array::CLONE_SKIP = sub { 1 };
  91. }
  92. sub new {
  93. my ($class, $parent) = @_;
  94. # We can only enable multi sample anti aliasing wih wxWidgets 3.0.3 and with a hacked Wx::GLCanvas,
  95. # which exports some new WX_GL_XXX constants, namely WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES.
  96. my $can_multisample =
  97. Wx::wxVERSION >= 3.000003 &&
  98. defined Wx::GLCanvas->can('WX_GL_SAMPLE_BUFFERS') &&
  99. defined Wx::GLCanvas->can('WX_GL_SAMPLES');
  100. my $attrib = [WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 24];
  101. if ($can_multisample) {
  102. # Request a window with multi sampled anti aliasing. This is a new feature in Wx 3.0.3 (backported from 3.1.0).
  103. # Use eval to avoid compilation, if the subs WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES are missing.
  104. eval 'push(@$attrib, (WX_GL_SAMPLE_BUFFERS, 1, WX_GL_SAMPLES, 4));';
  105. }
  106. # wxWidgets expect the attrib list to be ended by zero.
  107. push(@$attrib, 0);
  108. # we request a depth buffer explicitely because it looks like it's not created by
  109. # default on Linux, causing transparency issues
  110. my $self = $class->SUPER::new($parent, -1, Wx::wxDefaultPosition, Wx::wxDefaultSize, 0, "", $attrib);
  111. if (Wx::wxVERSION >= 3.000003) {
  112. # Wx 3.0.3 contains an ugly hack to support some advanced OpenGL attributes through the attribute list.
  113. # The attribute list is transferred between the wxGLCanvas and wxGLContext constructors using a single static array s_wglContextAttribs.
  114. # Immediatelly force creation of the OpenGL context to consume the static variable s_wglContextAttribs.
  115. $self->GetContext();
  116. }
  117. $self->{can_multisample} = $can_multisample;
  118. $self->background(1);
  119. $self->_quat((0, 0, 0, 1));
  120. $self->_stheta(45);
  121. $self->_sphi(45);
  122. $self->_zoom(1);
  123. $self->use_plain_shader(0);
  124. # Collection of GLVolume objects
  125. $self->volumes(Slic3r::GUI::_3DScene::GLVolume::Collection->new);
  126. # 3D point in model space
  127. $self->_camera_type('ortho');
  128. # $self->_camera_type('perspective');
  129. $self->_camera_target(Slic3r::Pointf3->new(0,0,0));
  130. $self->_camera_distance(0.);
  131. $self->layer_editing_enabled(0);
  132. $self->{layer_height_edit_band_width} = 2.;
  133. $self->{layer_height_edit_strength} = 0.005;
  134. $self->{layer_height_edit_last_object_id} = -1;
  135. $self->{layer_height_edit_last_z} = 0.;
  136. $self->{layer_height_edit_last_action} = 0;
  137. $self->reset_objects;
  138. EVT_PAINT($self, sub {
  139. my $dc = Wx::PaintDC->new($self);
  140. $self->Render($dc);
  141. });
  142. EVT_SIZE($self, sub { $self->_dirty(1) });
  143. EVT_IDLE($self, sub {
  144. return unless $self->_dirty;
  145. return if !$self->IsShownOnScreen;
  146. $self->Resize( $self->GetSizeWH );
  147. $self->Refresh;
  148. });
  149. EVT_MOUSEWHEEL($self, \&mouse_wheel_event);
  150. EVT_MOUSE_EVENTS($self, \&mouse_event);
  151. # EVT_KEY_DOWN($self, sub {
  152. EVT_CHAR($self, sub {
  153. my ($s, $event) = @_;
  154. if ($event->HasModifiers) {
  155. $event->Skip;
  156. } else {
  157. my $key = $event->GetKeyCode;
  158. if ($key == ord('0')) {
  159. $self->select_view('iso');
  160. } elsif ($key == ord('1')) {
  161. $self->select_view('top');
  162. } elsif ($key == ord('2')) {
  163. $self->select_view('bottom');
  164. } elsif ($key == ord('3')) {
  165. $self->select_view('front');
  166. } elsif ($key == ord('4')) {
  167. $self->select_view('rear');
  168. } elsif ($key == ord('5')) {
  169. $self->select_view('left');
  170. } elsif ($key == ord('6')) {
  171. $self->select_view('right');
  172. } else {
  173. $event->Skip;
  174. }
  175. }
  176. });
  177. $self->{layer_height_edit_timer_id} = &Wx::NewId();
  178. $self->{layer_height_edit_timer} = Wx::Timer->new($self, $self->{layer_height_edit_timer_id});
  179. EVT_TIMER($self, $self->{layer_height_edit_timer_id}, sub {
  180. my ($self, $event) = @_;
  181. return if $self->_layer_height_edited != 1;
  182. return if $self->{layer_height_edit_last_object_id} == -1;
  183. $self->_variable_layer_thickness_action(undef);
  184. });
  185. return $self;
  186. }
  187. sub Destroy {
  188. my ($self) = @_;
  189. $self->{layer_height_edit_timer}->Stop;
  190. $self->DestroyGL;
  191. return $self->SUPER::Destroy;
  192. }
  193. sub layer_editing_enabled {
  194. my ($self, $value) = @_;
  195. if (@_ == 2) {
  196. $self->{layer_editing_enabled} = $value;
  197. if ($value) {
  198. if (! $self->{layer_editing_initialized}) {
  199. # Enabling the layer editing for the first time. This triggers compilation of the necessary OpenGL shaders.
  200. # If compilation fails, a message box is shown with the error codes.
  201. $self->SetCurrent($self->GetContext);
  202. my $shader = new Slic3r::GUI::_3DScene::GLShader;
  203. my $error_message;
  204. if (! $shader->load($self->_fragment_shader_variable_layer_height, $self->_vertex_shader_variable_layer_height)) {
  205. # Compilation or linking of the shaders failed.
  206. $error_message = "Cannot compile an OpenGL Shader, therefore the Variable Layer Editing will be disabled.\n\n"
  207. . $shader->last_error;
  208. $shader = undef;
  209. } else {
  210. $self->{layer_height_edit_shader} = $shader;
  211. ($self->{layer_preview_z_texture_id}) = glGenTextures_p(1);
  212. glBindTexture(GL_TEXTURE_2D, $self->{layer_preview_z_texture_id});
  213. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  214. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  215. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  216. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
  217. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
  218. glBindTexture(GL_TEXTURE_2D, 0);
  219. }
  220. if (defined($error_message)) {
  221. # Don't enable the layer editing tool.
  222. $self->{layer_editing_enabled} = 0;
  223. # 2 means failed
  224. $self->{layer_editing_initialized} = 2;
  225. # Show the error message.
  226. Wx::MessageBox($error_message, "Slic3r Error", wxOK | wxICON_EXCLAMATION, $self);
  227. } else {
  228. $self->{layer_editing_initialized} = 1;
  229. }
  230. } elsif ($self->{layer_editing_initialized} == 2) {
  231. # Initilization failed before. Don't try to initialize and disable layer editing.
  232. $self->{layer_editing_enabled} = 0;
  233. }
  234. }
  235. }
  236. return $self->{layer_editing_enabled};
  237. }
  238. sub layer_editing_allowed {
  239. my ($self) = @_;
  240. # Allow layer editing if either the shaders were not initialized yet and we don't know
  241. # whether it will be possible to initialize them,
  242. # or if the initialization was done already and it failed.
  243. return ! (defined($self->{layer_editing_initialized}) && $self->{layer_editing_initialized} == 2);
  244. }
  245. sub _first_selected_object_id_for_variable_layer_height_editing {
  246. my ($self) = @_;
  247. for my $i (0..$#{$self->volumes}) {
  248. if ($self->volumes->[$i]->selected) {
  249. my $object_id = int($self->volumes->[$i]->select_group_id / 1000000);
  250. # Objects with object_id >= 1000 have a specific meaning, for example the wipe tower proxy.
  251. return ($object_id >= $self->{print}->object_count) ? -1 : $object_id
  252. if $object_id < 10000;
  253. }
  254. }
  255. return -1;
  256. }
  257. # Returns an array with (left, top, right, bottom) of the variable layer thickness bar on the screen.
  258. sub _variable_layer_thickness_bar_rect_screen {
  259. my ($self) = @_;
  260. my ($cw, $ch) = $self->GetSizeWH;
  261. return ($cw - VARIABLE_LAYER_THICKNESS_BAR_WIDTH, 0, $cw, $ch - VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT);
  262. }
  263. sub _variable_layer_thickness_bar_rect_viewport {
  264. my ($self) = @_;
  265. my ($cw, $ch) = $self->GetSizeWH;
  266. return ((0.5*$cw-VARIABLE_LAYER_THICKNESS_BAR_WIDTH)/$self->_zoom, (-0.5*$ch+VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT)/$self->_zoom, $cw/(2*$self->_zoom), $ch/(2*$self->_zoom));
  267. }
  268. # Returns an array with (left, top, right, bottom) of the variable layer thickness bar on the screen.
  269. sub _variable_layer_thickness_reset_rect_screen {
  270. my ($self) = @_;
  271. my ($cw, $ch) = $self->GetSizeWH;
  272. return ($cw - VARIABLE_LAYER_THICKNESS_BAR_WIDTH, $ch - VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT, $cw, $ch);
  273. }
  274. sub _variable_layer_thickness_reset_rect_viewport {
  275. my ($self) = @_;
  276. my ($cw, $ch) = $self->GetSizeWH;
  277. return ((0.5*$cw-VARIABLE_LAYER_THICKNESS_BAR_WIDTH)/$self->_zoom, -$ch/(2*$self->_zoom), $cw/(2*$self->_zoom), (-0.5*$ch+VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT)/$self->_zoom);
  278. }
  279. sub _variable_layer_thickness_bar_rect_mouse_inside {
  280. my ($self, $mouse_evt) = @_;
  281. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_bar_rect_screen;
  282. return $mouse_evt->GetX >= $bar_left && $mouse_evt->GetX <= $bar_right && $mouse_evt->GetY >= $bar_top && $mouse_evt->GetY <= $bar_bottom;
  283. }
  284. sub _variable_layer_thickness_reset_rect_mouse_inside {
  285. my ($self, $mouse_evt) = @_;
  286. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_reset_rect_screen;
  287. return $mouse_evt->GetX >= $bar_left && $mouse_evt->GetX <= $bar_right && $mouse_evt->GetY >= $bar_top && $mouse_evt->GetY <= $bar_bottom;
  288. }
  289. sub _variable_layer_thickness_bar_mouse_cursor_z_relative {
  290. my ($self) = @_;
  291. my $mouse_pos = $self->ScreenToClientPoint(Wx::GetMousePosition());
  292. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_bar_rect_screen;
  293. return ($mouse_pos->x >= $bar_left && $mouse_pos->x <= $bar_right && $mouse_pos->y >= $bar_top && $mouse_pos->y <= $bar_bottom) ?
  294. # Inside the bar.
  295. ($bar_bottom - $mouse_pos->y - 1.) / ($bar_bottom - $bar_top - 1) :
  296. # Outside the bar.
  297. -1000.;
  298. }
  299. sub _variable_layer_thickness_action {
  300. my ($self, $mouse_event, $do_modification) = @_;
  301. # A volume is selected. Test, whether hovering over a layer thickness bar.
  302. return if $self->{layer_height_edit_last_object_id} == -1;
  303. if (defined($mouse_event)) {
  304. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_bar_rect_screen;
  305. $self->{layer_height_edit_last_z} = unscale($self->{print}->get_object($self->{layer_height_edit_last_object_id})->size->z)
  306. * ($bar_bottom - $mouse_event->GetY - 1.) / ($bar_bottom - $bar_top);
  307. $self->{layer_height_edit_last_action} = $mouse_event->ShiftDown ? ($mouse_event->RightIsDown ? 3 : 2) : ($mouse_event->RightIsDown ? 0 : 1);
  308. }
  309. # Mark the volume as modified, so Print will pick its layer height profile? Where to mark it?
  310. # Start a timer to refresh the print? schedule_background_process() ?
  311. # The PrintObject::adjust_layer_height_profile() call adjusts the profile of its associated ModelObject, it does not modify the profile of the PrintObject itself.
  312. $self->{print}->get_object($self->{layer_height_edit_last_object_id})->adjust_layer_height_profile(
  313. $self->{layer_height_edit_last_z},
  314. $self->{layer_height_edit_strength},
  315. $self->{layer_height_edit_band_width},
  316. $self->{layer_height_edit_last_action});
  317. $self->volumes->[$self->{layer_height_edit_last_object_id}]->generate_layer_height_texture(
  318. $self->{print}->get_object($self->{layer_height_edit_last_object_id}), 1);
  319. $self->Refresh;
  320. # Automatic action on mouse down with the same coordinate.
  321. $self->{layer_height_edit_timer}->Start(100, wxTIMER_CONTINUOUS);
  322. }
  323. sub mouse_event {
  324. my ($self, $e) = @_;
  325. my $pos = Slic3r::Pointf->new($e->GetPositionXY);
  326. my $object_idx_selected = $self->{layer_height_edit_last_object_id} = ($self->layer_editing_enabled && $self->{print}) ? $self->_first_selected_object_id_for_variable_layer_height_editing : -1;
  327. if ($e->Entering && &Wx::wxMSW) {
  328. # wxMSW needs focus in order to catch mouse wheel events
  329. $self->SetFocus;
  330. $self->_drag_start_xy(undef);
  331. } elsif ($e->LeftDClick) {
  332. if ($object_idx_selected != -1 && $self->_variable_layer_thickness_bar_rect_mouse_inside($e)) {
  333. } elsif ($self->on_double_click) {
  334. $self->on_double_click->();
  335. }
  336. } elsif ($e->LeftDown || $e->RightDown) {
  337. # If user pressed left or right button we first check whether this happened
  338. # on a volume or not.
  339. my $volume_idx = $self->_hover_volume_idx // -1;
  340. $self->_layer_height_edited(0);
  341. if ($object_idx_selected != -1 && $self->_variable_layer_thickness_bar_rect_mouse_inside($e)) {
  342. # A volume is selected and the mouse is hovering over a layer thickness bar.
  343. # Start editing the layer height.
  344. $self->_layer_height_edited(1);
  345. $self->_variable_layer_thickness_action($e);
  346. } elsif ($object_idx_selected != -1 && $self->_variable_layer_thickness_reset_rect_mouse_inside($e)) {
  347. $self->{print}->get_object($object_idx_selected)->reset_layer_height_profile;
  348. # Index 2 means no editing, just wait for mouse up event.
  349. $self->_layer_height_edited(2);
  350. $self->Refresh;
  351. $self->Update;
  352. } else {
  353. # Select volume in this 3D canvas.
  354. # Don't deselect a volume if layer editing is enabled. We want the object to stay selected
  355. # during the scene manipulation.
  356. if ($self->enable_picking && ($volume_idx != -1 || ! $self->layer_editing_enabled)) {
  357. $self->deselect_volumes;
  358. $self->select_volume($volume_idx);
  359. if ($volume_idx != -1) {
  360. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  361. my @volumes;
  362. if ($group_id != -1) {
  363. $self->select_volume($_)
  364. for grep $self->volumes->[$_]->select_group_id == $group_id,
  365. 0..$#{$self->volumes};
  366. }
  367. }
  368. $self->Refresh;
  369. $self->Update;
  370. }
  371. # propagate event through callback
  372. $self->on_select->($volume_idx)
  373. if $self->on_select;
  374. if ($volume_idx != -1) {
  375. if ($e->LeftDown && $self->enable_moving) {
  376. # The mouse_to_3d gets the Z coordinate from the Z buffer at the screen coordinate $pos->x,y,
  377. # an converts the screen space coordinate to unscaled object space.
  378. my $pos3d = $self->mouse_to_3d(@$pos);
  379. # Only accept the initial position, if it is inside the volume bounding box.
  380. my $volume_bbox = $self->volumes->[$volume_idx]->transformed_bounding_box;
  381. $volume_bbox->offset(1.);
  382. if ($volume_bbox->contains_point($pos3d)) {
  383. # The dragging operation is initiated.
  384. $self->_drag_volume_idx($volume_idx);
  385. $self->_drag_start_pos($pos3d);
  386. # Remember the shift to to the object center. The object center will later be used
  387. # to limit the object placement close to the bed.
  388. $self->_drag_volume_center_offset($pos3d->vector_to($volume_bbox->center));
  389. }
  390. } elsif ($e->RightDown) {
  391. # if right clicking on volume, propagate event through callback
  392. $self->on_right_click->($e->GetPosition)
  393. if $self->on_right_click;
  394. }
  395. }
  396. }
  397. } elsif ($e->Dragging && $e->LeftIsDown && ! $self->_layer_height_edited && defined($self->_drag_volume_idx)) {
  398. # Get new position at the same Z of the initial click point.
  399. my $cur_pos = Slic3r::Linef3->new(
  400. $self->mouse_to_3d($e->GetX, $e->GetY, 0),
  401. $self->mouse_to_3d($e->GetX, $e->GetY, 1))
  402. ->intersect_plane($self->_drag_start_pos->z);
  403. # Clip the new position, so the object center remains close to the bed.
  404. {
  405. $cur_pos->translate(@{$self->_drag_volume_center_offset});
  406. my $cur_pos2 = Slic3r::Point->new(scale($cur_pos->x), scale($cur_pos->y));
  407. if (! $self->bed_polygon->contains_point($cur_pos2)) {
  408. my $ip = $self->bed_polygon->point_projection($cur_pos2);
  409. $cur_pos->set_x(unscale($ip->x));
  410. $cur_pos->set_y(unscale($ip->y));
  411. }
  412. $cur_pos->translate(@{$self->_drag_volume_center_offset->negative});
  413. }
  414. # Calculate the translation vector.
  415. my $vector = $self->_drag_start_pos->vector_to($cur_pos);
  416. # Get the volume being dragged.
  417. my $volume = $self->volumes->[$self->_drag_volume_idx];
  418. # Get all volumes belonging to the same group, if any.
  419. my @volumes = ($volume->drag_group_id == -1) ?
  420. ($volume) :
  421. grep $_->drag_group_id == $volume->drag_group_id, @{$self->volumes};
  422. # Apply new temporary volume origin and ignore Z.
  423. $_->translate($vector->x, $vector->y, 0) for @volumes;
  424. $self->_drag_start_pos($cur_pos);
  425. $self->_dragged(1);
  426. $self->Refresh;
  427. $self->Update;
  428. } elsif ($e->Dragging) {
  429. if ($self->_layer_height_edited && $object_idx_selected != -1) {
  430. $self->_variable_layer_thickness_action($e) if ($self->_layer_height_edited == 1);
  431. } elsif ($e->LeftIsDown) {
  432. # if dragging over blank area with left button, rotate
  433. if (defined $self->_drag_start_pos) {
  434. my $orig = $self->_drag_start_pos;
  435. if (TURNTABLE_MODE) {
  436. # Turntable mode is enabled by default.
  437. $self->_sphi($self->_sphi + ($pos->x - $orig->x) * TRACKBALLSIZE);
  438. $self->_stheta($self->_stheta - ($pos->y - $orig->y) * TRACKBALLSIZE); #-
  439. $self->_stheta(GIMBALL_LOCK_THETA_MAX) if $self->_stheta > GIMBALL_LOCK_THETA_MAX;
  440. $self->_stheta(0) if $self->_stheta < 0;
  441. } else {
  442. my $size = $self->GetClientSize;
  443. my @quat = trackball(
  444. $orig->x / ($size->width / 2) - 1,
  445. 1 - $orig->y / ($size->height / 2), #/
  446. $pos->x / ($size->width / 2) - 1,
  447. 1 - $pos->y / ($size->height / 2), #/
  448. );
  449. $self->_quat(mulquats($self->_quat, \@quat));
  450. }
  451. $self->on_viewport_changed->() if $self->on_viewport_changed;
  452. $self->Refresh;
  453. $self->Update;
  454. }
  455. $self->_drag_start_pos($pos);
  456. } elsif ($e->MiddleIsDown || $e->RightIsDown) {
  457. # If dragging over blank area with right button, pan.
  458. if (defined $self->_drag_start_xy) {
  459. # get point in model space at Z = 0
  460. my $cur_pos = $self->mouse_to_3d($e->GetX, $e->GetY, 0);
  461. my $orig = $self->mouse_to_3d($self->_drag_start_xy->x, $self->_drag_start_xy->y, 0);
  462. $self->_camera_target->translate(@{$orig->vector_to($cur_pos)->negative});
  463. $self->on_viewport_changed->() if $self->on_viewport_changed;
  464. $self->Refresh;
  465. $self->Update;
  466. }
  467. $self->_drag_start_xy($pos);
  468. }
  469. } elsif ($e->LeftUp || $e->MiddleUp || $e->RightUp) {
  470. if ($self->_layer_height_edited) {
  471. $self->_layer_height_edited(undef);
  472. $self->{layer_height_edit_timer}->Stop;
  473. $self->on_model_update->()
  474. if ($object_idx_selected != -1 && $self->on_model_update);
  475. } elsif ($self->on_move && defined($self->_drag_volume_idx) && $self->_dragged) {
  476. # get all volumes belonging to the same group, if any
  477. my @volume_idxs;
  478. my $group_id = $self->volumes->[$self->_drag_volume_idx]->drag_group_id;
  479. if ($group_id == -1) {
  480. @volume_idxs = ($self->_drag_volume_idx);
  481. } else {
  482. @volume_idxs = grep $self->volumes->[$_]->drag_group_id == $group_id,
  483. 0..$#{$self->volumes};
  484. }
  485. $self->on_move->(@volume_idxs);
  486. }
  487. $self->_drag_volume_idx(undef);
  488. $self->_drag_start_pos(undef);
  489. $self->_drag_start_xy(undef);
  490. $self->_dragged(undef);
  491. } elsif ($e->Moving) {
  492. $self->_mouse_pos($pos);
  493. # Only refresh if picking is enabled, in that case the objects may get highlighted if the mouse cursor
  494. # hovers over.
  495. if ($self->enable_picking) {
  496. $self->Update;
  497. $self->Refresh;
  498. }
  499. } else {
  500. $e->Skip();
  501. }
  502. }
  503. sub mouse_wheel_event {
  504. my ($self, $e) = @_;
  505. if ($e->MiddleIsDown) {
  506. # Ignore the wheel events if the middle button is pressed.
  507. return;
  508. }
  509. if ($self->layer_editing_enabled && $self->{print}) {
  510. my $object_idx_selected = $self->_first_selected_object_id_for_variable_layer_height_editing;
  511. if ($object_idx_selected != -1) {
  512. # A volume is selected. Test, whether hovering over a layer thickness bar.
  513. if ($self->_variable_layer_thickness_bar_rect_mouse_inside($e)) {
  514. # Adjust the width of the selection.
  515. $self->{layer_height_edit_band_width} = max(min($self->{layer_height_edit_band_width} * (1 + 0.1 * $e->GetWheelRotation() / $e->GetWheelDelta()), 10.), 1.5);
  516. $self->Refresh;
  517. return;
  518. }
  519. }
  520. }
  521. # Calculate the zoom delta and apply it to the current zoom factor
  522. my $zoom = $e->GetWheelRotation() / $e->GetWheelDelta();
  523. $zoom = max(min($zoom, 4), -4);
  524. $zoom /= 10;
  525. $zoom = $self->_zoom / (1-$zoom);
  526. # Don't allow to zoom too far outside the scene.
  527. my $zoom_min = $self->get_zoom_to_bounding_box_factor($self->max_bounding_box);
  528. $zoom_min *= 0.4 if defined $zoom_min;
  529. $zoom = $zoom_min if defined $zoom_min && $zoom < $zoom_min;
  530. $self->_zoom($zoom);
  531. # In order to zoom around the mouse point we need to translate
  532. # the camera target
  533. my $size = Slic3r::Pointf->new($self->GetSizeWH);
  534. my $pos = Slic3r::Pointf->new($e->GetX, $size->y - $e->GetY); #-
  535. $self->_camera_target->translate(
  536. # ($pos - $size/2) represents the vector from the viewport center
  537. # to the mouse point. By multiplying it by $zoom we get the new,
  538. # transformed, length of such vector.
  539. # Since we want that point to stay fixed, we move our camera target
  540. # in the opposite direction by the delta of the length of such vector
  541. # ($zoom - 1). We then scale everything by 1/$self->_zoom since
  542. # $self->_camera_target is expressed in terms of model units.
  543. -($pos->x - $size->x/2) * ($zoom) / $self->_zoom,
  544. -($pos->y - $size->y/2) * ($zoom) / $self->_zoom,
  545. 0,
  546. ) if 0;
  547. $self->on_viewport_changed->() if $self->on_viewport_changed;
  548. $self->Resize($self->GetSizeWH) if $self->IsShownOnScreen;
  549. $self->Refresh;
  550. }
  551. # Reset selection.
  552. sub reset_objects {
  553. my ($self) = @_;
  554. if ($self->GetContext) {
  555. $self->SetCurrent($self->GetContext);
  556. $self->volumes->release_geometry;
  557. }
  558. $self->volumes->erase;
  559. $self->_dirty(1);
  560. }
  561. # Setup camera to view all objects.
  562. sub set_viewport_from_scene {
  563. my ($self, $scene) = @_;
  564. $self->_sphi($scene->_sphi);
  565. $self->_stheta($scene->_stheta);
  566. $self->_camera_target($scene->_camera_target);
  567. $self->_zoom($scene->_zoom);
  568. $self->_quat($scene->_quat);
  569. $self->_dirty(1);
  570. }
  571. # Set the camera to a default orientation,
  572. # zoom to volumes.
  573. sub select_view {
  574. my ($self, $direction) = @_;
  575. my $dirvec;
  576. if (ref($direction)) {
  577. $dirvec = $direction;
  578. } else {
  579. if ($direction eq 'iso') {
  580. $dirvec = VIEW_DEFAULT;
  581. } elsif ($direction eq 'left') {
  582. $dirvec = VIEW_LEFT;
  583. } elsif ($direction eq 'right') {
  584. $dirvec = VIEW_RIGHT;
  585. } elsif ($direction eq 'top') {
  586. $dirvec = VIEW_TOP;
  587. } elsif ($direction eq 'bottom') {
  588. $dirvec = VIEW_BOTTOM;
  589. } elsif ($direction eq 'front') {
  590. $dirvec = VIEW_FRONT;
  591. } elsif ($direction eq 'rear') {
  592. $dirvec = VIEW_REAR;
  593. }
  594. }
  595. my $bb = $self->volumes_bounding_box;
  596. if (! $bb->empty) {
  597. $self->_sphi($dirvec->[0]);
  598. $self->_stheta($dirvec->[1]);
  599. # Avoid gimball lock.
  600. $self->_stheta(GIMBALL_LOCK_THETA_MAX) if $self->_stheta > GIMBALL_LOCK_THETA_MAX;
  601. $self->_stheta(0) if $self->_stheta < 0;
  602. # View everything.
  603. $self->zoom_to_bounding_box($bb);
  604. $self->on_viewport_changed->() if $self->on_viewport_changed;
  605. $self->Refresh;
  606. }
  607. }
  608. sub get_zoom_to_bounding_box_factor {
  609. my ($self, $bb) = @_;
  610. return undef if ($bb->empty);
  611. my $max_size = max(@{$bb->size}) * 2;
  612. return ($max_size == 0) ? undef : min($self->GetSizeWH) / $max_size;
  613. }
  614. sub zoom_to_bounding_box {
  615. my ($self, $bb) = @_;
  616. # Calculate the zoom factor needed to adjust viewport to bounding box.
  617. my $zoom = $self->get_zoom_to_bounding_box_factor($bb);
  618. if (defined $zoom) {
  619. $self->_zoom($zoom);
  620. # center view around bounding box center
  621. $self->_camera_target($bb->center);
  622. $self->on_viewport_changed->() if $self->on_viewport_changed;
  623. }
  624. }
  625. sub zoom_to_bed {
  626. my ($self) = @_;
  627. if ($self->bed_shape) {
  628. $self->zoom_to_bounding_box($self->bed_bounding_box);
  629. }
  630. }
  631. sub zoom_to_volume {
  632. my ($self, $volume_idx) = @_;
  633. my $volume = $self->volumes->[$volume_idx];
  634. my $bb = $volume->transformed_bounding_box;
  635. $self->zoom_to_bounding_box($bb);
  636. }
  637. sub zoom_to_volumes {
  638. my ($self) = @_;
  639. $self->zoom_to_bounding_box($self->volumes_bounding_box);
  640. }
  641. sub volumes_bounding_box {
  642. my ($self) = @_;
  643. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  644. $bb->merge($_->transformed_bounding_box) for @{$self->volumes};
  645. return $bb;
  646. }
  647. sub bed_bounding_box {
  648. my ($self) = @_;
  649. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  650. if ($self->bed_shape) {
  651. $bb->merge_point(Slic3r::Pointf3->new(@$_, 0)) for @{$self->bed_shape};
  652. }
  653. return $bb;
  654. }
  655. sub max_bounding_box {
  656. my ($self) = @_;
  657. my $bb = $self->bed_bounding_box;
  658. $bb->merge($self->volumes_bounding_box);
  659. return $bb;
  660. }
  661. # Used by ObjectCutDialog and ObjectPartsPanel to generate a rectangular ground plane
  662. # to support the scene objects.
  663. sub set_auto_bed_shape {
  664. my ($self, $bed_shape) = @_;
  665. # draw a default square bed around object center
  666. my $max_size = max(@{ $self->volumes_bounding_box->size });
  667. my $center = $self->volumes_bounding_box->center;
  668. $self->set_bed_shape([
  669. [ $center->x - $max_size, $center->y - $max_size ], #--
  670. [ $center->x + $max_size, $center->y - $max_size ], #--
  671. [ $center->x + $max_size, $center->y + $max_size ], #++
  672. [ $center->x - $max_size, $center->y + $max_size ], #++
  673. ]);
  674. # Set the origin for painting of the coordinate system axes.
  675. $self->origin(Slic3r::Pointf->new(@$center[X,Y]));
  676. }
  677. # Set the bed shape to a single closed 2D polygon (array of two element arrays),
  678. # triangulate the bed and store the triangles into $self->bed_triangles,
  679. # fills the $self->bed_grid_lines and sets $self->origin.
  680. # Sets $self->bed_polygon to limit the object placement.
  681. sub set_bed_shape {
  682. my ($self, $bed_shape) = @_;
  683. $self->bed_shape($bed_shape);
  684. # triangulate bed
  685. my $expolygon = Slic3r::ExPolygon->new([ map [map scale($_), @$_], @$bed_shape ]);
  686. my $bed_bb = $expolygon->bounding_box;
  687. {
  688. my @points = ();
  689. foreach my $triangle (@{ $expolygon->triangulate }) {
  690. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$triangle;
  691. }
  692. $self->bed_triangles(OpenGL::Array->new_list(GL_FLOAT, @points));
  693. }
  694. {
  695. my @polylines = ();
  696. for (my $x = $bed_bb->x_min; $x <= $bed_bb->x_max; $x += scale 10) {
  697. push @polylines, Slic3r::Polyline->new([$x,$bed_bb->y_min], [$x,$bed_bb->y_max]);
  698. }
  699. for (my $y = $bed_bb->y_min; $y <= $bed_bb->y_max; $y += scale 10) {
  700. push @polylines, Slic3r::Polyline->new([$bed_bb->x_min,$y], [$bed_bb->x_max,$y]);
  701. }
  702. # clip with a slightly grown expolygon because our lines lay on the contours and
  703. # may get erroneously clipped
  704. my @lines = map Slic3r::Line->new(@$_[0,-1]),
  705. @{intersection_pl(\@polylines, [ @{$expolygon->offset(+scaled_epsilon)} ])};
  706. # append bed contours
  707. push @lines, map @{$_->lines}, @$expolygon;
  708. my @points = ();
  709. foreach my $line (@lines) {
  710. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$line; #))
  711. }
  712. $self->bed_grid_lines(OpenGL::Array->new_list(GL_FLOAT, @points));
  713. }
  714. # Set the origin for painting of the coordinate system axes.
  715. $self->origin(Slic3r::Pointf->new(0,0));
  716. $self->bed_polygon(offset_ex([$expolygon->contour], $bed_bb->radius * 1.7, JT_ROUND, scale(0.5))->[0]->contour->clone);
  717. }
  718. sub deselect_volumes {
  719. my ($self) = @_;
  720. $_->set_selected(0) for @{$self->volumes};
  721. }
  722. sub select_volume {
  723. my ($self, $volume_idx) = @_;
  724. $self->volumes->[$volume_idx]->set_selected(1)
  725. if $volume_idx != -1;
  726. }
  727. sub SetCuttingPlane {
  728. my ($self, $z, $expolygons) = @_;
  729. $self->cutting_plane_z($z);
  730. # grow slices in order to display them better
  731. $expolygons = offset_ex([ map @$_, @$expolygons ], scale 0.1);
  732. my @verts = ();
  733. foreach my $line (map @{$_->lines}, map @$_, @$expolygons) {
  734. push @verts, (
  735. unscale($line->a->x), unscale($line->a->y), $z, #))
  736. unscale($line->b->x), unscale($line->b->y), $z, #))
  737. );
  738. }
  739. $self->cut_lines_vertices(OpenGL::Array->new_list(GL_FLOAT, @verts));
  740. }
  741. # Given an axis and angle, compute quaternion.
  742. sub axis_to_quat {
  743. my ($ax, $phi) = @_;
  744. my $lena = sqrt(reduce { $a + $b } (map { $_ * $_ } @$ax));
  745. my @q = map { $_ * (1 / $lena) } @$ax;
  746. @q = map { $_ * sin($phi / 2.0) } @q;
  747. $q[$#q + 1] = cos($phi / 2.0);
  748. return @q;
  749. }
  750. # Project a point on the virtual trackball.
  751. # If it is inside the sphere, map it to the sphere, if it outside map it
  752. # to a hyperbola.
  753. sub project_to_sphere {
  754. my ($r, $x, $y) = @_;
  755. my $d = sqrt($x * $x + $y * $y);
  756. if ($d < $r * 0.70710678118654752440) { # Inside sphere
  757. return sqrt($r * $r - $d * $d);
  758. } else { # On hyperbola
  759. my $t = $r / 1.41421356237309504880;
  760. return $t * $t / $d;
  761. }
  762. }
  763. sub cross {
  764. my ($v1, $v2) = @_;
  765. return (@$v1[1] * @$v2[2] - @$v1[2] * @$v2[1],
  766. @$v1[2] * @$v2[0] - @$v1[0] * @$v2[2],
  767. @$v1[0] * @$v2[1] - @$v1[1] * @$v2[0]);
  768. }
  769. # Simulate a track-ball. Project the points onto the virtual trackball,
  770. # then figure out the axis of rotation, which is the cross product of
  771. # P1 P2 and O P1 (O is the center of the ball, 0,0,0) Note: This is a
  772. # deformed trackball-- is a trackball in the center, but is deformed
  773. # into a hyperbolic sheet of rotation away from the center.
  774. # It is assumed that the arguments to this routine are in the range
  775. # (-1.0 ... 1.0).
  776. sub trackball {
  777. my ($p1x, $p1y, $p2x, $p2y) = @_;
  778. if ($p1x == $p2x && $p1y == $p2y) {
  779. # zero rotation
  780. return (0.0, 0.0, 0.0, 1.0);
  781. }
  782. # First, figure out z-coordinates for projection of P1 and P2 to
  783. # deformed sphere
  784. my @p1 = ($p1x, $p1y, project_to_sphere(TRACKBALLSIZE, $p1x, $p1y));
  785. my @p2 = ($p2x, $p2y, project_to_sphere(TRACKBALLSIZE, $p2x, $p2y));
  786. # axis of rotation (cross product of P1 and P2)
  787. my @a = cross(\@p2, \@p1);
  788. # Figure out how much to rotate around that axis.
  789. my @d = map { $_ * $_ } (map { $p1[$_] - $p2[$_] } 0 .. $#p1);
  790. my $t = sqrt(reduce { $a + $b } @d) / (2.0 * TRACKBALLSIZE);
  791. # Avoid problems with out-of-control values...
  792. $t = 1.0 if ($t > 1.0);
  793. $t = -1.0 if ($t < -1.0);
  794. my $phi = 2.0 * asin($t);
  795. return axis_to_quat(\@a, $phi);
  796. }
  797. # Build a rotation matrix, given a quaternion rotation.
  798. sub quat_to_rotmatrix {
  799. my ($q) = @_;
  800. my @m = ();
  801. $m[0] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[2] * @$q[2]);
  802. $m[1] = 2.0 * (@$q[0] * @$q[1] - @$q[2] * @$q[3]);
  803. $m[2] = 2.0 * (@$q[2] * @$q[0] + @$q[1] * @$q[3]);
  804. $m[3] = 0.0;
  805. $m[4] = 2.0 * (@$q[0] * @$q[1] + @$q[2] * @$q[3]);
  806. $m[5] = 1.0 - 2.0 * (@$q[2] * @$q[2] + @$q[0] * @$q[0]);
  807. $m[6] = 2.0 * (@$q[1] * @$q[2] - @$q[0] * @$q[3]);
  808. $m[7] = 0.0;
  809. $m[8] = 2.0 * (@$q[2] * @$q[0] - @$q[1] * @$q[3]);
  810. $m[9] = 2.0 * (@$q[1] * @$q[2] + @$q[0] * @$q[3]);
  811. $m[10] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[0] * @$q[0]);
  812. $m[11] = 0.0;
  813. $m[12] = 0.0;
  814. $m[13] = 0.0;
  815. $m[14] = 0.0;
  816. $m[15] = 1.0;
  817. return @m;
  818. }
  819. sub mulquats {
  820. my ($q1, $rq) = @_;
  821. return (@$q1[3] * @$rq[0] + @$q1[0] * @$rq[3] + @$q1[1] * @$rq[2] - @$q1[2] * @$rq[1],
  822. @$q1[3] * @$rq[1] + @$q1[1] * @$rq[3] + @$q1[2] * @$rq[0] - @$q1[0] * @$rq[2],
  823. @$q1[3] * @$rq[2] + @$q1[2] * @$rq[3] + @$q1[0] * @$rq[1] - @$q1[1] * @$rq[0],
  824. @$q1[3] * @$rq[3] - @$q1[0] * @$rq[0] - @$q1[1] * @$rq[1] - @$q1[2] * @$rq[2])
  825. }
  826. # Convert the screen space coordinate to an object space coordinate.
  827. # If the Z screen space coordinate is not provided, a depth buffer value is substituted.
  828. sub mouse_to_3d {
  829. my ($self, $x, $y, $z) = @_;
  830. my @viewport = glGetIntegerv_p(GL_VIEWPORT); # 4 items
  831. my @mview = glGetDoublev_p(GL_MODELVIEW_MATRIX); # 16 items
  832. my @proj = glGetDoublev_p(GL_PROJECTION_MATRIX); # 16 items
  833. $y = $viewport[3] - $y;
  834. $z //= glReadPixels_p($x, $y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT);
  835. my @projected = gluUnProject_p($x, $y, $z, @mview, @proj, @viewport);
  836. return Slic3r::Pointf3->new(@projected);
  837. }
  838. sub GetContext {
  839. my ($self) = @_;
  840. return $self->{context} ||= Wx::GLContext->new($self);
  841. }
  842. sub SetCurrent {
  843. my ($self, $context) = @_;
  844. return $self->SUPER::SetCurrent($context);
  845. }
  846. sub UseVBOs {
  847. my ($self) = @_;
  848. if (! defined ($self->{use_VBOs})) {
  849. # This is a special path for wxWidgets on GTK, where an OpenGL context is initialized
  850. # first when an OpenGL widget is shown for the first time. How ugly.
  851. return 0 if (! $self->init && $^O eq 'linux');
  852. # Don't use VBOs if anything fails.
  853. $self->{use_VBOs} = 0;
  854. if ($self->GetContext) {
  855. $self->SetCurrent($self->GetContext);
  856. Slic3r::GUI::_3DScene::_glew_init;
  857. my @gl_version = split(/\./, glGetString(GL_VERSION));
  858. $self->{use_VBOs} = int($gl_version[0]) >= 2;
  859. # print "UseVBOs $self OpenGL major: $gl_version[0], minor: $gl_version[1]. Use VBOs: ", $self->{use_VBOs}, "\n";
  860. }
  861. }
  862. return $self->{use_VBOs};
  863. }
  864. sub Resize {
  865. my ($self, $x, $y) = @_;
  866. return unless $self->GetContext;
  867. $self->_dirty(0);
  868. $self->SetCurrent($self->GetContext);
  869. glViewport(0, 0, $x, $y);
  870. $x /= $self->_zoom;
  871. $y /= $self->_zoom;
  872. glMatrixMode(GL_PROJECTION);
  873. glLoadIdentity();
  874. if ($self->_camera_type eq 'ortho') {
  875. #FIXME setting the size of the box 10x larger than necessary
  876. # is only a workaround for an incorrectly set camera.
  877. # This workaround harms Z-buffer accuracy!
  878. # my $depth = 1.05 * $self->max_bounding_box->radius();
  879. my $depth = 10.0 * $self->max_bounding_box->radius();
  880. glOrtho(
  881. -$x/2, $x/2, -$y/2, $y/2,
  882. -$depth, $depth,
  883. );
  884. } else {
  885. die "Invalid camera type: ", $self->_camera_type, "\n" if ($self->_camera_type ne 'perspective');
  886. my $bbox_r = $self->max_bounding_box->radius();
  887. my $fov = PI * 45. / 180.;
  888. my $fov_tan = tan(0.5 * $fov);
  889. my $cam_distance = 0.5 * $bbox_r / $fov_tan;
  890. $self->_camera_distance($cam_distance);
  891. my $nr = $cam_distance - $bbox_r * 1.1;
  892. my $fr = $cam_distance + $bbox_r * 1.1;
  893. $nr = 1 if ($nr < 1);
  894. $fr = $nr + 1 if ($fr < $nr + 1);
  895. my $h2 = $fov_tan * $nr;
  896. my $w2 = $h2 * $x / $y;
  897. glFrustum(-$w2, $w2, -$h2, $h2, $nr, $fr);
  898. }
  899. glMatrixMode(GL_MODELVIEW);
  900. }
  901. sub InitGL {
  902. my $self = shift;
  903. return if $self->init;
  904. return unless $self->GetContext;
  905. $self->init(1);
  906. # This is a special path for wxWidgets on GTK, where an OpenGL context is initialized
  907. # first when an OpenGL widget is shown for the first time. How ugly.
  908. # In that case the volumes are wainting to be moved to Vertex Buffer Objects
  909. # after the OpenGL context is being initialized.
  910. $self->volumes->finalize_geometry(1)
  911. if ($^O eq 'linux' && $self->UseVBOs);
  912. glClearColor(0, 0, 0, 1);
  913. glColor3f(1, 0, 0);
  914. glEnable(GL_DEPTH_TEST);
  915. glClearDepth(1.0);
  916. glDepthFunc(GL_LEQUAL);
  917. glEnable(GL_CULL_FACE);
  918. glEnable(GL_BLEND);
  919. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  920. # Set antialiasing/multisampling
  921. glDisable(GL_LINE_SMOOTH);
  922. glDisable(GL_POLYGON_SMOOTH);
  923. # See "GL_MULTISAMPLE and GL_ARRAY_BUFFER_ARB messages on failed launch"
  924. # https://github.com/alexrj/Slic3r/issues/4085
  925. eval {
  926. # Disable the multi sampling by default, so the picking by color will work correctly.
  927. glDisable(GL_MULTISAMPLE);
  928. };
  929. # Disable multi sampling if the eval failed.
  930. $self->{can_multisample} = 0 if $@;
  931. # ambient lighting
  932. glLightModelfv_p(GL_LIGHT_MODEL_AMBIENT, 0.3, 0.3, 0.3, 1);
  933. glEnable(GL_LIGHTING);
  934. glEnable(GL_LIGHT0);
  935. glEnable(GL_LIGHT1);
  936. # light from camera
  937. glLightfv_p(GL_LIGHT1, GL_POSITION, 1, 0, 1, 0);
  938. glLightfv_p(GL_LIGHT1, GL_SPECULAR, 0.3, 0.3, 0.3, 1);
  939. glLightfv_p(GL_LIGHT1, GL_DIFFUSE, 0.2, 0.2, 0.2, 1);
  940. # Enables Smooth Color Shading; try GL_FLAT for (lack of) fun.
  941. glShadeModel(GL_SMOOTH);
  942. # glMaterialfv_p(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, 0.5, 0.3, 0.3, 1);
  943. # glMaterialfv_p(GL_FRONT_AND_BACK, GL_SPECULAR, 1, 1, 1, 1);
  944. # glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50);
  945. # glMaterialfv_p(GL_FRONT_AND_BACK, GL_EMISSION, 0.1, 0, 0, 0.9);
  946. # A handy trick -- have surface material mirror the color.
  947. glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
  948. glEnable(GL_COLOR_MATERIAL);
  949. glEnable(GL_MULTISAMPLE) if ($self->{can_multisample});
  950. if ($self->UseVBOs) {
  951. my $shader = new Slic3r::GUI::_3DScene::GLShader;
  952. if (! $shader->load($self->_fragment_shader_Gouraud, $self->_vertex_shader_Gouraud)) {
  953. # if (! $shader->load($self->_fragment_shader_Phong, $self->_vertex_shader_Phong)) {
  954. print "Compilaton of path shader failed: \n" . $shader->last_error . "\n";
  955. $shader = undef;
  956. } else {
  957. $self->{plain_shader} = $shader;
  958. }
  959. }
  960. }
  961. sub DestroyGL {
  962. my $self = shift;
  963. if ($self->GetContext) {
  964. $self->SetCurrent($self->GetContext);
  965. if ($self->{plain_shader}) {
  966. $self->{plain_shader}->release;
  967. delete $self->{plain_shader};
  968. }
  969. if ($self->{layer_height_edit_shader}) {
  970. $self->{layer_height_edit_shader}->release;
  971. delete $self->{layer_height_edit_shader};
  972. }
  973. $self->volumes->release_geometry;
  974. }
  975. }
  976. sub Render {
  977. my ($self, $dc) = @_;
  978. # prevent calling SetCurrent() when window is not shown yet
  979. return unless $self->IsShownOnScreen;
  980. return unless my $context = $self->GetContext;
  981. $self->SetCurrent($context);
  982. $self->InitGL;
  983. glClearColor(1, 1, 1, 1);
  984. glClearDepth(1);
  985. glDepthFunc(GL_LESS);
  986. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  987. glMatrixMode(GL_MODELVIEW);
  988. glLoadIdentity();
  989. {
  990. # Shift the perspective camera.
  991. my $camera_pos = Slic3r::Pointf3->new(0,0,-$self->_camera_distance);
  992. glTranslatef(@$camera_pos);
  993. }
  994. if (TURNTABLE_MODE) {
  995. # Turntable mode is enabled by default.
  996. glRotatef(-$self->_stheta, 1, 0, 0); # pitch
  997. glRotatef($self->_sphi, 0, 0, 1); # yaw
  998. } else {
  999. my @rotmat = quat_to_rotmatrix($self->quat);
  1000. glMultMatrixd_p(@rotmat[0..15]);
  1001. }
  1002. glTranslatef(@{ $self->_camera_target->negative });
  1003. # light from above
  1004. glLightfv_p(GL_LIGHT0, GL_POSITION, -0.5, -0.5, 1, 0);
  1005. glLightfv_p(GL_LIGHT0, GL_SPECULAR, 0.2, 0.2, 0.2, 1);
  1006. glLightfv_p(GL_LIGHT0, GL_DIFFUSE, 0.5, 0.5, 0.5, 1);
  1007. # Head light
  1008. glLightfv_p(GL_LIGHT1, GL_POSITION, 1, 0, 1, 0);
  1009. if ($self->enable_picking) {
  1010. # Render the object for picking.
  1011. # FIXME This cannot possibly work in a multi-sampled context as the color gets mangled by the anti-aliasing.
  1012. # Better to use software ray-casting on a bounding-box hierarchy.
  1013. glPushAttrib(GL_ENABLE_BIT);
  1014. glDisable(GL_MULTISAMPLE) if ($self->{can_multisample});
  1015. glDisable(GL_LIGHTING);
  1016. glDisable(GL_BLEND);
  1017. $self->draw_volumes(1);
  1018. glFlush();
  1019. glFinish();
  1020. if (my $pos = $self->_mouse_pos) {
  1021. my $col = [ glReadPixels_p($pos->x, $self->GetSize->GetHeight - $pos->y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE) ];
  1022. my $volume_idx = $col->[0] + $col->[1]*256 + $col->[2]*256*256;
  1023. $self->_hover_volume_idx(undef);
  1024. $_->set_hover(0) for @{$self->volumes};
  1025. if ($volume_idx <= $#{$self->volumes}) {
  1026. $self->_hover_volume_idx($volume_idx);
  1027. $self->volumes->[$volume_idx]->set_hover(1);
  1028. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  1029. if ($group_id != -1) {
  1030. $_->set_hover(1) for grep { $_->select_group_id == $group_id } @{$self->volumes};
  1031. }
  1032. $self->on_hover->($volume_idx) if $self->on_hover;
  1033. }
  1034. }
  1035. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1036. glFlush();
  1037. glFinish();
  1038. glPopAttrib();
  1039. }
  1040. # draw fixed background
  1041. if ($self->background) {
  1042. glDisable(GL_LIGHTING);
  1043. glPushMatrix();
  1044. glLoadIdentity();
  1045. glMatrixMode(GL_PROJECTION);
  1046. glPushMatrix();
  1047. glLoadIdentity();
  1048. # Draws a bluish bottom to top gradient over the complete screen.
  1049. glDisable(GL_DEPTH_TEST);
  1050. glBegin(GL_QUADS);
  1051. glColor3f(0.0,0.0,0.0);
  1052. glVertex3f(-1.0,-1.0, 1.0);
  1053. glVertex3f( 1.0,-1.0, 1.0);
  1054. glColor3f(10/255,98/255,144/255);
  1055. glVertex3f( 1.0, 1.0, 1.0);
  1056. glVertex3f(-1.0, 1.0, 1.0);
  1057. glEnd();
  1058. glPopMatrix();
  1059. glEnable(GL_DEPTH_TEST);
  1060. glMatrixMode(GL_MODELVIEW);
  1061. glPopMatrix();
  1062. glEnable(GL_LIGHTING);
  1063. }
  1064. # draw ground and axes
  1065. glDisable(GL_LIGHTING);
  1066. # draw ground
  1067. my $ground_z = GROUND_Z;
  1068. if ($self->bed_triangles) {
  1069. glDisable(GL_DEPTH_TEST);
  1070. glEnable(GL_BLEND);
  1071. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1072. glEnableClientState(GL_VERTEX_ARRAY);
  1073. glColor4f(0.8, 0.6, 0.5, 0.4);
  1074. glNormal3d(0,0,1);
  1075. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_triangles->ptr());
  1076. glDrawArrays(GL_TRIANGLES, 0, $self->bed_triangles->elements / 3);
  1077. glDisableClientState(GL_VERTEX_ARRAY);
  1078. # we need depth test for grid, otherwise it would disappear when looking
  1079. # the object from below
  1080. glEnable(GL_DEPTH_TEST);
  1081. # draw grid
  1082. glLineWidth(3);
  1083. glColor4f(0.2, 0.2, 0.2, 0.4);
  1084. glEnableClientState(GL_VERTEX_ARRAY);
  1085. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_grid_lines->ptr());
  1086. glDrawArrays(GL_LINES, 0, $self->bed_grid_lines->elements / 3);
  1087. glDisableClientState(GL_VERTEX_ARRAY);
  1088. glDisable(GL_BLEND);
  1089. }
  1090. my $volumes_bb = $self->volumes_bounding_box;
  1091. {
  1092. # draw axes
  1093. # disable depth testing so that axes are not covered by ground
  1094. glDisable(GL_DEPTH_TEST);
  1095. my $origin = $self->origin;
  1096. my $axis_len = max(
  1097. 0.3 * max(@{ $self->bed_bounding_box->size }),
  1098. 2 * max(@{ $volumes_bb->size }),
  1099. );
  1100. glLineWidth(2);
  1101. glBegin(GL_LINES);
  1102. # draw line for x axis
  1103. glColor3f(1, 0, 0);
  1104. glVertex3f(@$origin, $ground_z);
  1105. glVertex3f($origin->x + $axis_len, $origin->y, $ground_z); #,,
  1106. # draw line for y axis
  1107. glColor3f(0, 1, 0);
  1108. glVertex3f(@$origin, $ground_z);
  1109. glVertex3f($origin->x, $origin->y + $axis_len, $ground_z); #++
  1110. glEnd();
  1111. # draw line for Z axis
  1112. # (re-enable depth test so that axis is correctly shown when objects are behind it)
  1113. glEnable(GL_DEPTH_TEST);
  1114. glBegin(GL_LINES);
  1115. glColor3f(0, 0, 1);
  1116. glVertex3f(@$origin, $ground_z);
  1117. glVertex3f(@$origin, $ground_z+$axis_len);
  1118. glEnd();
  1119. }
  1120. glEnable(GL_LIGHTING);
  1121. # draw objects
  1122. if (! $self->use_plain_shader) {
  1123. $self->draw_volumes;
  1124. } elsif ($self->UseVBOs) {
  1125. $self->{plain_shader}->enable if $self->{plain_shader};
  1126. $self->volumes->render_VBOs;
  1127. $self->{plain_shader}->disable;
  1128. } else {
  1129. $self->volumes->render_legacy;
  1130. }
  1131. # draw cutting plane
  1132. if (defined $self->cutting_plane_z) {
  1133. my $plane_z = $self->cutting_plane_z;
  1134. my $bb = $volumes_bb;
  1135. glDisable(GL_CULL_FACE);
  1136. glDisable(GL_LIGHTING);
  1137. glEnable(GL_BLEND);
  1138. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1139. glBegin(GL_QUADS);
  1140. glColor4f(0.8, 0.8, 0.8, 0.5);
  1141. glVertex3f($bb->x_min-20, $bb->y_min-20, $plane_z);
  1142. glVertex3f($bb->x_max+20, $bb->y_min-20, $plane_z);
  1143. glVertex3f($bb->x_max+20, $bb->y_max+20, $plane_z);
  1144. glVertex3f($bb->x_min-20, $bb->y_max+20, $plane_z);
  1145. glEnd();
  1146. glEnable(GL_CULL_FACE);
  1147. glDisable(GL_BLEND);
  1148. }
  1149. $self->draw_active_object_annotations;
  1150. $self->SwapBuffers();
  1151. # Calling glFinish has a performance penalty, but it seems to fix some OpenGL driver hang-up with extremely large scenes.
  1152. # glFinish();
  1153. }
  1154. sub draw_volumes {
  1155. # $fakecolor is a boolean indicating, that the objects shall be rendered in a color coding the object index for picking.
  1156. my ($self, $fakecolor) = @_;
  1157. glEnable(GL_BLEND);
  1158. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1159. glEnableClientState(GL_VERTEX_ARRAY);
  1160. glEnableClientState(GL_NORMAL_ARRAY);
  1161. my $z_cursor_relative = $self->_variable_layer_thickness_bar_mouse_cursor_z_relative;
  1162. foreach my $volume_idx (0..$#{$self->volumes}) {
  1163. my $volume = $self->volumes->[$volume_idx];
  1164. my $shader_active = 0;
  1165. my $object_id = int($volume->select_group_id / 1000000);
  1166. if ($self->layer_editing_enabled && ! $fakecolor && $volume->selected && $self->{layer_height_edit_shader} &&
  1167. $volume->has_layer_height_texture && $object_id < $self->{print}->object_count) {
  1168. # Update the height texture if the ModelObject::layer_height_texture is invalid.
  1169. $volume->generate_layer_height_texture($self->{print}->get_object($object_id), 0);
  1170. $self->{layer_height_edit_shader}->enable;
  1171. $self->{layer_height_edit_shader}->set_uniform('z_to_texture_row', $volume->layer_height_texture_z_to_row_id);
  1172. $self->{layer_height_edit_shader}->set_uniform('z_texture_row_to_normalized', 1. / $volume->layer_height_texture_height);
  1173. $self->{layer_height_edit_shader}->set_uniform('z_cursor', $volume->bounding_box->z_max * $z_cursor_relative);
  1174. $self->{layer_height_edit_shader}->set_uniform('z_cursor_band_width', $self->{layer_height_edit_band_width});
  1175. glBindTexture(GL_TEXTURE_2D, $self->{layer_preview_z_texture_id});
  1176. # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LEVEL, 0);
  1177. # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
  1178. glTexImage2D_c(GL_TEXTURE_2D, 0, GL_RGBA8, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1179. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1180. glTexImage2D_c(GL_TEXTURE_2D, 1, GL_RGBA8, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1181. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1182. # glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  1183. # glPixelStorei(GL_UNPACK_ROW_LENGTH, $self->{layer_preview_z_texture_width});
  1184. glTexSubImage2D_c(GL_TEXTURE_2D, 0, 0, 0, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1185. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level0);
  1186. glTexSubImage2D_c(GL_TEXTURE_2D, 1, 0, 0, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1187. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level1);
  1188. $shader_active = 1;
  1189. } elsif ($fakecolor) {
  1190. # Object picking mode. Render the object with a color encoding the object index.
  1191. my $r = ($volume_idx & 0x000000FF) >> 0;
  1192. my $g = ($volume_idx & 0x0000FF00) >> 8;
  1193. my $b = ($volume_idx & 0x00FF0000) >> 16;
  1194. glColor4f($r/255.0, $g/255.0, $b/255.0, 1);
  1195. } elsif ($volume->selected) {
  1196. glColor4f(@{ &SELECTED_COLOR });
  1197. } elsif ($volume->hover) {
  1198. glColor4f(@{ &HOVER_COLOR });
  1199. } else {
  1200. glColor4f(@{ $volume->color });
  1201. }
  1202. $volume->render;
  1203. if ($shader_active) {
  1204. glBindTexture(GL_TEXTURE_2D, 0);
  1205. $self->{layer_height_edit_shader}->disable;
  1206. }
  1207. }
  1208. glDisableClientState(GL_NORMAL_ARRAY);
  1209. glDisable(GL_BLEND);
  1210. if (defined $self->cutting_plane_z) {
  1211. glLineWidth(2);
  1212. glColor3f(0, 0, 0);
  1213. glVertexPointer_c(3, GL_FLOAT, 0, $self->cut_lines_vertices->ptr());
  1214. glDrawArrays(GL_LINES, 0, $self->cut_lines_vertices->elements / 3);
  1215. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  1216. }
  1217. glDisableClientState(GL_VERTEX_ARRAY);
  1218. }
  1219. sub _load_image_set_texture {
  1220. my ($self, $file_name) = @_;
  1221. # Load a PNG with an alpha channel.
  1222. my $img = Wx::Image->new;
  1223. $img->LoadFile(Slic3r::var($file_name), wxBITMAP_TYPE_PNG);
  1224. # Get RGB & alpha raw data from wxImage, interleave them into a Perl array.
  1225. my @rgb = unpack 'C*', $img->GetData();
  1226. my @alpha = $img->HasAlpha ? unpack 'C*', $img->GetAlpha() : (255) x (int(@rgb) / 3);
  1227. my $n_pixels = int(@alpha);
  1228. my @data = (0)x($n_pixels * 4);
  1229. for (my $i = 0; $i < $n_pixels; $i += 1) {
  1230. $data[$i*4 ] = $rgb[$i*3];
  1231. $data[$i*4+1] = $rgb[$i*3+1];
  1232. $data[$i*4+2] = $rgb[$i*3+2];
  1233. $data[$i*4+3] = $alpha[$i];
  1234. }
  1235. # Initialize a raw bitmap data.
  1236. my $params = {
  1237. loaded => 1,
  1238. valid => $n_pixels > 0,
  1239. width => $img->GetWidth,
  1240. height => $img->GetHeight,
  1241. data => OpenGL::Array->new_list(GL_UNSIGNED_BYTE, @data),
  1242. texture_id => glGenTextures_p(1)
  1243. };
  1244. # Create and initialize a texture with the raw data.
  1245. glBindTexture(GL_TEXTURE_2D, $params->{texture_id});
  1246. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1247. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1248. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
  1249. glTexImage2D_c(GL_TEXTURE_2D, 0, GL_RGBA8, $params->{width}, $params->{height}, 0, GL_RGBA, GL_UNSIGNED_BYTE, $params->{data}->ptr);
  1250. glBindTexture(GL_TEXTURE_2D, 0);
  1251. return $params;
  1252. }
  1253. sub _variable_layer_thickness_load_overlay_image {
  1254. my ($self) = @_;
  1255. $self->{layer_preview_annotation} = $self->_load_image_set_texture('variable_layer_height_tooltip.png')
  1256. if (! $self->{layer_preview_annotation}->{loaded});
  1257. return $self->{layer_preview_annotation}->{valid};
  1258. }
  1259. sub _variable_layer_thickness_load_reset_image {
  1260. my ($self) = @_;
  1261. $self->{layer_preview_reset_image} = $self->_load_image_set_texture('variable_layer_height_reset.png')
  1262. if (! $self->{layer_preview_reset_image}->{loaded});
  1263. return $self->{layer_preview_reset_image}->{valid};
  1264. }
  1265. # Paint the tooltip.
  1266. sub _render_image {
  1267. my ($self, $image, $l, $r, $b, $t) = @_;
  1268. glColor4f(1.,1.,1.,1.);
  1269. glDisable(GL_LIGHTING);
  1270. glEnable(GL_BLEND);
  1271. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1272. glEnable(GL_TEXTURE_2D);
  1273. glBindTexture(GL_TEXTURE_2D, $image->{texture_id});
  1274. glBegin(GL_QUADS);
  1275. glTexCoord2d(0.,1.); glVertex3f($l, $b, 0);
  1276. glTexCoord2d(1.,1.); glVertex3f($r, $b, 0);
  1277. glTexCoord2d(1.,0.); glVertex3f($r, $t, 0);
  1278. glTexCoord2d(0.,0.); glVertex3f($l, $t, 0);
  1279. glEnd();
  1280. glBindTexture(GL_TEXTURE_2D, 0);
  1281. glDisable(GL_TEXTURE_2D);
  1282. glDisable(GL_BLEND);
  1283. glEnable(GL_LIGHTING);
  1284. }
  1285. sub draw_active_object_annotations {
  1286. # $fakecolor is a boolean indicating, that the objects shall be rendered in a color coding the object index for picking.
  1287. my ($self) = @_;
  1288. return if (! $self->{layer_height_edit_shader} || ! $self->layer_editing_enabled);
  1289. # Find the selected volume, over which the layer editing is active.
  1290. my $volume;
  1291. foreach my $volume_idx (0..$#{$self->volumes}) {
  1292. my $v = $self->volumes->[$volume_idx];
  1293. if ($v->selected && $v->has_layer_height_texture) {
  1294. $volume = $v;
  1295. last;
  1296. }
  1297. }
  1298. return if (! $volume);
  1299. # If the active object was not allocated at the Print, go away. This should only be a momentary case between an object addition / deletion
  1300. # and an update by Platter::async_apply_config.
  1301. my $object_idx = int($volume->select_group_id / 1000000);
  1302. return if $object_idx >= $self->{print}->object_count;
  1303. # The viewport and camera are set to complete view and glOrtho(-$x/2, $x/2, -$y/2, $y/2, -$depth, $depth),
  1304. # where x, y is the window size divided by $self->_zoom.
  1305. my ($bar_left, $bar_bottom, $bar_right, $bar_top) = $self->_variable_layer_thickness_bar_rect_viewport;
  1306. my ($reset_left, $reset_bottom, $reset_right, $reset_top) = $self->_variable_layer_thickness_reset_rect_viewport;
  1307. my $z_cursor_relative = $self->_variable_layer_thickness_bar_mouse_cursor_z_relative;
  1308. $self->{layer_height_edit_shader}->enable;
  1309. $self->{layer_height_edit_shader}->set_uniform('z_to_texture_row', $volume->layer_height_texture_z_to_row_id);
  1310. $self->{layer_height_edit_shader}->set_uniform('z_texture_row_to_normalized', 1. / $volume->layer_height_texture_height);
  1311. $self->{layer_height_edit_shader}->set_uniform('z_cursor', $volume->bounding_box->z_max * $z_cursor_relative);
  1312. $self->{layer_height_edit_shader}->set_uniform('z_cursor_band_width', $self->{layer_height_edit_band_width});
  1313. glBindTexture(GL_TEXTURE_2D, $self->{layer_preview_z_texture_id});
  1314. glTexImage2D_c(GL_TEXTURE_2D, 0, GL_RGBA8, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1315. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1316. glTexImage2D_c(GL_TEXTURE_2D, 1, GL_RGBA8, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1317. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1318. glTexSubImage2D_c(GL_TEXTURE_2D, 0, 0, 0, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1319. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level0);
  1320. glTexSubImage2D_c(GL_TEXTURE_2D, 1, 0, 0, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1321. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level1);
  1322. # Render the color bar.
  1323. glDisable(GL_DEPTH_TEST);
  1324. # The viewport and camera are set to complete view and glOrtho(-$x/2, $x/2, -$y/2, $y/2, -$depth, $depth),
  1325. # where x, y is the window size divided by $self->_zoom.
  1326. glPushMatrix();
  1327. glLoadIdentity();
  1328. # Paint the overlay.
  1329. glBegin(GL_QUADS);
  1330. glVertex3f($bar_left, $bar_bottom, 0);
  1331. glVertex3f($bar_right, $bar_bottom, 0);
  1332. glVertex3f($bar_right, $bar_top, $volume->bounding_box->z_max);
  1333. glVertex3f($bar_left, $bar_top, $volume->bounding_box->z_max);
  1334. glEnd();
  1335. glBindTexture(GL_TEXTURE_2D, 0);
  1336. $self->{layer_height_edit_shader}->disable;
  1337. # Paint the tooltip.
  1338. if ($self->_variable_layer_thickness_load_overlay_image) {
  1339. my $gap = 10/$self->_zoom;
  1340. my ($l, $r, $b, $t) = ($bar_left - $self->{layer_preview_annotation}->{width}/$self->_zoom - $gap, $bar_left - $gap, $reset_bottom + $self->{layer_preview_annotation}->{height}/$self->_zoom + $gap, $reset_bottom + $gap);
  1341. $self->_render_image($self->{layer_preview_annotation}, $l, $r, $t, $b);
  1342. }
  1343. # Paint the reset button.
  1344. if ($self->_variable_layer_thickness_load_reset_image) {
  1345. $self->_render_image($self->{layer_preview_reset_image}, $reset_left, $reset_right, $reset_bottom, $reset_top);
  1346. }
  1347. # Paint the graph.
  1348. #FIXME show some kind of legend.
  1349. my $print_object = $self->{print}->get_object($object_idx);
  1350. my $max_z = unscale($print_object->size->z);
  1351. my $profile = $print_object->model_object->layer_height_profile;
  1352. my $layer_height = $print_object->config->get('layer_height');
  1353. my $layer_height_max = 10000000000.;
  1354. {
  1355. # Get a maximum layer height value.
  1356. #FIXME This is a duplicate code of Slicing.cpp.
  1357. my $nozzle_diameters = $print_object->print->config->get('nozzle_diameter');
  1358. my $layer_heights_min = $print_object->print->config->get('min_layer_height');
  1359. my $layer_heights_max = $print_object->print->config->get('max_layer_height');
  1360. for (my $i = 0; $i < scalar(@{$nozzle_diameters}); $i += 1) {
  1361. my $lh_min = ($layer_heights_min->[$i] == 0.) ? 0.07 : max(0.01, $layer_heights_min->[$i]);
  1362. my $lh_max = ($layer_heights_max->[$i] == 0.) ? (0.75 * $nozzle_diameters->[$i]) : $layer_heights_max->[$i];
  1363. $layer_height_max = min($layer_height_max, max($lh_min, $lh_max));
  1364. }
  1365. }
  1366. # Make the vertical bar a bit wider so the layer height curve does not touch the edge of the bar region.
  1367. $layer_height_max *= 1.12;
  1368. # Baseline
  1369. glColor3f(0., 0., 0.);
  1370. glBegin(GL_LINE_STRIP);
  1371. glVertex2f($bar_left + $layer_height * ($bar_right - $bar_left) / $layer_height_max, $bar_bottom);
  1372. glVertex2f($bar_left + $layer_height * ($bar_right - $bar_left) / $layer_height_max, $bar_top);
  1373. glEnd();
  1374. # Curve
  1375. glColor3f(0., 0., 1.);
  1376. glBegin(GL_LINE_STRIP);
  1377. for (my $i = 0; $i < int(@{$profile}); $i += 2) {
  1378. my $z = $profile->[$i];
  1379. my $h = $profile->[$i+1];
  1380. glVertex3f($bar_left + $h * ($bar_right - $bar_left) / $layer_height_max, $bar_bottom + $z * ($bar_top - $bar_bottom) / $max_z, $z);
  1381. }
  1382. glEnd();
  1383. # Revert the matrices.
  1384. glPopMatrix();
  1385. glEnable(GL_DEPTH_TEST);
  1386. }
  1387. sub opengl_info
  1388. {
  1389. my ($self, %params) = @_;
  1390. my %tag = Slic3r::tags($params{format});
  1391. my $gl_version = glGetString(GL_VERSION);
  1392. my $gl_vendor = glGetString(GL_VENDOR);
  1393. my $gl_renderer = glGetString(GL_RENDERER);
  1394. my $glsl_version = glGetString(GL_SHADING_LANGUAGE_VERSION);
  1395. my $out = '';
  1396. $out .= "$tag{h2start}OpenGL installation$tag{h2end}$tag{eol}";
  1397. $out .= " $tag{bstart}Using POGL$tag{bend} v$OpenGL::BUILD_VERSION$tag{eol}";
  1398. $out .= " $tag{bstart}GL version: $tag{bend}${gl_version}$tag{eol}";
  1399. $out .= " $tag{bstart}vendor: $tag{bend}${gl_vendor}$tag{eol}";
  1400. $out .= " $tag{bstart}renderer: $tag{bend}${gl_renderer}$tag{eol}";
  1401. $out .= " $tag{bstart}GLSL version: $tag{bend}${glsl_version}$tag{eol}";
  1402. # Check for other OpenGL extensions
  1403. $out .= "$tag{h2start}Installed extensions (* implemented in the module):$tag{h2end}$tag{eol}";
  1404. my $extensions = glGetString(GL_EXTENSIONS);
  1405. my @extensions = split(' ',$extensions);
  1406. foreach my $ext (sort @extensions) {
  1407. my $stat = glpCheckExtension($ext);
  1408. $out .= sprintf("%s ${ext}$tag{eol}", $stat?' ':'*');
  1409. $out .= sprintf(" ${stat}$tag{eol}") if ($stat && $stat !~ m|^$ext |);
  1410. }
  1411. return $out;
  1412. }
  1413. sub _report_opengl_state
  1414. {
  1415. my ($self, $comment) = @_;
  1416. my $err = glGetError();
  1417. return 0 if ($err == 0);
  1418. # gluErrorString() hangs. Don't use it.
  1419. # my $errorstr = gluErrorString();
  1420. my $errorstr = '';
  1421. if ($err == 0x0500) {
  1422. $errorstr = 'GL_INVALID_ENUM';
  1423. } elsif ($err == GL_INVALID_VALUE) {
  1424. $errorstr = 'GL_INVALID_VALUE';
  1425. } elsif ($err == GL_INVALID_OPERATION) {
  1426. $errorstr = 'GL_INVALID_OPERATION';
  1427. } elsif ($err == GL_STACK_OVERFLOW) {
  1428. $errorstr = 'GL_STACK_OVERFLOW';
  1429. } elsif ($err == GL_OUT_OF_MEMORY) {
  1430. $errorstr = 'GL_OUT_OF_MEMORY';
  1431. } else {
  1432. $errorstr = 'unknown';
  1433. }
  1434. if (defined($comment)) {
  1435. printf("OpenGL error at %s, nr %d (0x%x): %s\n", $comment, $err, $err, $errorstr);
  1436. } else {
  1437. printf("OpenGL error nr %d (0x%x): %s\n", $err, $err, $errorstr);
  1438. }
  1439. }
  1440. sub _vertex_shader_Gouraud {
  1441. return <<'VERTEX';
  1442. #version 110
  1443. #define INTENSITY_CORRECTION 0.7
  1444. #define LIGHT_TOP_DIR -0.6/1.31, 0.6/1.31, 1./1.31
  1445. #define LIGHT_TOP_DIFFUSE (0.8 * INTENSITY_CORRECTION)
  1446. #define LIGHT_TOP_SPECULAR (0.5 * INTENSITY_CORRECTION)
  1447. #define LIGHT_TOP_SHININESS 50.
  1448. #define LIGHT_FRONT_DIR 1./1.43, 0.2/1.43, 1./1.43
  1449. #define LIGHT_FRONT_DIFFUSE (0.3 * INTENSITY_CORRECTION)
  1450. #define LIGHT_FRONT_SPECULAR (0.0 * INTENSITY_CORRECTION)
  1451. #define LIGHT_FRONT_SHININESS 50.
  1452. #define INTENSITY_AMBIENT 0.3
  1453. varying float intensity_specular;
  1454. varying float intensity_tainted;
  1455. void main()
  1456. {
  1457. vec3 eye, normal, lightDir, viewVector, halfVector;
  1458. float NdotL, NdotHV;
  1459. eye = vec3(0., 0., 1.);
  1460. // First transform the normal into eye space and normalize the result.
  1461. normal = normalize(gl_NormalMatrix * gl_Normal);
  1462. // Now normalize the light's direction. Note that according to the OpenGL specification, the light is stored in eye space.
  1463. // Also since we're talking about a directional light, the position field is actually direction.
  1464. lightDir = vec3(LIGHT_TOP_DIR);
  1465. halfVector = normalize(lightDir + eye);
  1466. // Compute the cos of the angle between the normal and lights direction. The light is directional so the direction is constant for every vertex.
  1467. // Since these two are normalized the cosine is the dot product. We also need to clamp the result to the [0,1] range.
  1468. NdotL = max(dot(normal, lightDir), 0.0);
  1469. intensity_tainted = INTENSITY_AMBIENT + NdotL * LIGHT_TOP_DIFFUSE;
  1470. intensity_specular = 0.;
  1471. if (NdotL > 0.0)
  1472. intensity_specular = LIGHT_TOP_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_TOP_SHININESS);
  1473. // Perform the same lighting calculation for the 2nd light source.
  1474. lightDir = vec3(LIGHT_FRONT_DIR);
  1475. // halfVector = normalize(lightDir + eye);
  1476. NdotL = max(dot(normal, lightDir), 0.0);
  1477. intensity_tainted += NdotL * LIGHT_FRONT_DIFFUSE;
  1478. // compute the specular term if NdotL is larger than zero
  1479. // if (NdotL > 0.0)
  1480. // intensity_specular += LIGHT_FRONT_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_FRONT_SHININESS);
  1481. gl_Position = ftransform();
  1482. }
  1483. VERTEX
  1484. }
  1485. sub _fragment_shader_Gouraud {
  1486. return <<'FRAGMENT';
  1487. #version 110
  1488. varying float intensity_specular;
  1489. varying float intensity_tainted;
  1490. uniform vec4 uniform_color;
  1491. void main()
  1492. {
  1493. gl_FragColor =
  1494. vec4(intensity_specular, intensity_specular, intensity_specular, 0.) + uniform_color * intensity_tainted;
  1495. gl_FragColor.a = uniform_color.a;
  1496. }
  1497. FRAGMENT
  1498. }
  1499. sub _vertex_shader_Phong {
  1500. return <<'VERTEX';
  1501. #version 110
  1502. varying vec3 normal;
  1503. varying vec3 eye;
  1504. void main(void)
  1505. {
  1506. eye = normalize(vec3(gl_ModelViewMatrix * gl_Vertex));
  1507. normal = normalize(gl_NormalMatrix * gl_Normal);
  1508. gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
  1509. }
  1510. VERTEX
  1511. }
  1512. sub _fragment_shader_Phong {
  1513. return <<'FRAGMENT';
  1514. #version 110
  1515. #define INTENSITY_CORRECTION 0.7
  1516. #define LIGHT_TOP_DIR -0.6/1.31, 0.6/1.31, 1./1.31
  1517. #define LIGHT_TOP_DIFFUSE (0.8 * INTENSITY_CORRECTION)
  1518. #define LIGHT_TOP_SPECULAR (0.5 * INTENSITY_CORRECTION)
  1519. //#define LIGHT_TOP_SHININESS 50.
  1520. #define LIGHT_TOP_SHININESS 10.
  1521. #define LIGHT_FRONT_DIR 1./1.43, 0.2/1.43, 1./1.43
  1522. #define LIGHT_FRONT_DIFFUSE (0.3 * INTENSITY_CORRECTION)
  1523. #define LIGHT_FRONT_SPECULAR (0.0 * INTENSITY_CORRECTION)
  1524. #define LIGHT_FRONT_SHININESS 50.
  1525. #define INTENSITY_AMBIENT 0.0
  1526. varying vec3 normal;
  1527. varying vec3 eye;
  1528. uniform vec4 uniform_color;
  1529. void main() {
  1530. float intensity_specular = 0.;
  1531. float intensity_tainted = 0.;
  1532. float intensity = max(dot(normal,vec3(LIGHT_TOP_DIR)), 0.0);
  1533. // if the vertex is lit compute the specular color
  1534. if (intensity > 0.0) {
  1535. intensity_tainted = LIGHT_TOP_DIFFUSE * intensity;
  1536. // compute the half vector
  1537. vec3 h = normalize(vec3(LIGHT_TOP_DIR) + eye);
  1538. // compute the specular term into spec
  1539. intensity_specular = LIGHT_TOP_SPECULAR * pow(max(dot(h, normal), 0.0), LIGHT_TOP_SHININESS);
  1540. }
  1541. intensity = max(dot(normal,vec3(LIGHT_FRONT_DIR)), 0.0);
  1542. // if the vertex is lit compute the specular color
  1543. if (intensity > 0.0) {
  1544. intensity_tainted += LIGHT_FRONT_DIFFUSE * intensity;
  1545. // compute the half vector
  1546. // vec3 h = normalize(vec3(LIGHT_FRONT_DIR) + eye);
  1547. // compute the specular term into spec
  1548. // intensity_specular += LIGHT_FRONT_SPECULAR * pow(max(dot(h,normal), 0.0), LIGHT_FRONT_SHININESS);
  1549. }
  1550. gl_FragColor = max(
  1551. vec4(intensity_specular, intensity_specular, intensity_specular, 0.) + uniform_color * intensity_tainted,
  1552. INTENSITY_AMBIENT * uniform_color);
  1553. gl_FragColor.a = uniform_color.a;
  1554. }
  1555. FRAGMENT
  1556. }
  1557. sub _vertex_shader_variable_layer_height {
  1558. return <<'VERTEX';
  1559. #version 110
  1560. #define LIGHT_TOP_DIR 0., 1., 0.
  1561. #define LIGHT_TOP_DIFFUSE 0.2
  1562. #define LIGHT_TOP_SPECULAR 0.3
  1563. #define LIGHT_TOP_SHININESS 50.
  1564. #define LIGHT_FRONT_DIR 0., 0., 1.
  1565. #define LIGHT_FRONT_DIFFUSE 0.5
  1566. #define LIGHT_FRONT_SPECULAR 0.3
  1567. #define LIGHT_FRONT_SHININESS 50.
  1568. #define INTENSITY_AMBIENT 0.1
  1569. uniform float z_to_texture_row;
  1570. varying float intensity_specular;
  1571. varying float intensity_tainted;
  1572. varying float object_z;
  1573. void main()
  1574. {
  1575. vec3 eye, normal, lightDir, viewVector, halfVector;
  1576. float NdotL, NdotHV;
  1577. // eye = gl_ModelViewMatrixInverse[3].xyz;
  1578. eye = vec3(0., 0., 1.);
  1579. // First transform the normal into eye space and normalize the result.
  1580. normal = normalize(gl_NormalMatrix * gl_Normal);
  1581. // Now normalize the light's direction. Note that according to the OpenGL specification, the light is stored in eye space.
  1582. // Also since we're talking about a directional light, the position field is actually direction.
  1583. lightDir = vec3(LIGHT_TOP_DIR);
  1584. halfVector = normalize(lightDir + eye);
  1585. // Compute the cos of the angle between the normal and lights direction. The light is directional so the direction is constant for every vertex.
  1586. // Since these two are normalized the cosine is the dot product. We also need to clamp the result to the [0,1] range.
  1587. NdotL = max(dot(normal, lightDir), 0.0);
  1588. intensity_tainted = INTENSITY_AMBIENT + NdotL * LIGHT_TOP_DIFFUSE;
  1589. intensity_specular = 0.;
  1590. // if (NdotL > 0.0)
  1591. // intensity_specular = LIGHT_TOP_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_TOP_SHININESS);
  1592. // Perform the same lighting calculation for the 2nd light source.
  1593. lightDir = vec3(LIGHT_FRONT_DIR);
  1594. halfVector = normalize(lightDir + eye);
  1595. NdotL = max(dot(normal, lightDir), 0.0);
  1596. intensity_tainted += NdotL * LIGHT_FRONT_DIFFUSE;
  1597. // compute the specular term if NdotL is larger than zero
  1598. if (NdotL > 0.0)
  1599. intensity_specular += LIGHT_FRONT_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_FRONT_SHININESS);
  1600. // Scaled to widths of the Z texture.
  1601. object_z = gl_Vertex.z / gl_Vertex.w;
  1602. gl_Position = ftransform();
  1603. }
  1604. VERTEX
  1605. }
  1606. sub _fragment_shader_variable_layer_height {
  1607. return <<'FRAGMENT';
  1608. #version 110
  1609. #define M_PI 3.1415926535897932384626433832795
  1610. // 2D texture (1D texture split by the rows) of color along the object Z axis.
  1611. uniform sampler2D z_texture;
  1612. // Scaling from the Z texture rows coordinate to the normalized texture row coordinate.
  1613. uniform float z_to_texture_row;
  1614. uniform float z_texture_row_to_normalized;
  1615. varying float intensity_specular;
  1616. varying float intensity_tainted;
  1617. varying float object_z;
  1618. uniform float z_cursor;
  1619. uniform float z_cursor_band_width;
  1620. void main()
  1621. {
  1622. float object_z_row = z_to_texture_row * object_z;
  1623. // Index of the row in the texture.
  1624. float z_texture_row = floor(object_z_row);
  1625. // Normalized coordinate from 0. to 1.
  1626. float z_texture_col = object_z_row - z_texture_row;
  1627. float z_blend = 0.25 * cos(min(M_PI, abs(M_PI * (object_z - z_cursor) * 1.8 / z_cursor_band_width))) + 0.25;
  1628. // Calculate level of detail from the object Z coordinate.
  1629. // This makes the slowly sloping surfaces to be show with high detail (with stripes),
  1630. // and the vertical surfaces to be shown with low detail (no stripes)
  1631. float z_in_cells = object_z_row * 190.;
  1632. // Gradient of Z projected on the screen.
  1633. float dx_vtc = dFdx(z_in_cells);
  1634. float dy_vtc = dFdy(z_in_cells);
  1635. float lod = clamp(0.5 * log2(max(dx_vtc*dx_vtc, dy_vtc*dy_vtc)), 0., 1.);
  1636. // Sample the Z texture. Texture coordinates are normalized to <0, 1>.
  1637. vec4 color =
  1638. (1. - lod) * texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.) +
  1639. lod * texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 10000.);
  1640. // Mix the final color.
  1641. gl_FragColor =
  1642. vec4(intensity_specular, intensity_specular, intensity_specular, 1.) +
  1643. (1. - z_blend) * intensity_tainted * color +
  1644. z_blend * vec4(1., 1., 0., 0.);
  1645. // and reset the transparency.
  1646. gl_FragColor.a = 1.;
  1647. }
  1648. FRAGMENT
  1649. }
  1650. # The 3D canvas to display objects and tool paths.
  1651. package Slic3r::GUI::3DScene;
  1652. use base qw(Slic3r::GUI::3DScene::Base);
  1653. use OpenGL qw(:glconstants :gluconstants :glufunctions);
  1654. use List::Util qw(first min max);
  1655. use Slic3r::Geometry qw(scale unscale epsilon);
  1656. use Slic3r::Print::State ':steps';
  1657. __PACKAGE__->mk_accessors(qw(
  1658. color_by
  1659. select_by
  1660. drag_by
  1661. ));
  1662. sub new {
  1663. my $class = shift;
  1664. my $self = $class->SUPER::new(@_);
  1665. $self->color_by('volume'); # object | volume
  1666. $self->select_by('object'); # object | volume | instance
  1667. $self->drag_by('instance'); # object | instance
  1668. return $self;
  1669. }
  1670. sub load_object {
  1671. my ($self, $model, $print, $obj_idx, $instance_idxs) = @_;
  1672. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1673. my $model_object;
  1674. if ($model->isa('Slic3r::Model::Object')) {
  1675. $model_object = $model;
  1676. $model = $model_object->model;
  1677. $obj_idx = 0;
  1678. } else {
  1679. $model_object = $model->get_object($obj_idx);
  1680. }
  1681. $instance_idxs ||= [0..$#{$model_object->instances}];
  1682. my $volume_indices = $self->volumes->load_object(
  1683. $model_object, $obj_idx, $instance_idxs, $self->color_by, $self->select_by, $self->drag_by,
  1684. $self->UseVBOs);
  1685. return @{$volume_indices};
  1686. }
  1687. # Create 3D thick extrusion lines for a skirt and brim.
  1688. # Adds a new Slic3r::GUI::3DScene::Volume to $self->volumes.
  1689. sub load_print_toolpaths {
  1690. my ($self, $print, $colors) = @_;
  1691. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1692. Slic3r::GUI::_3DScene::_load_print_toolpaths($print, $self->volumes, $colors, $self->UseVBOs)
  1693. if ($print->step_done(STEP_SKIRT) && $print->step_done(STEP_BRIM));
  1694. }
  1695. # Create 3D thick extrusion lines for object forming extrusions.
  1696. # Adds a new Slic3r::GUI::3DScene::Volume to $self->volumes,
  1697. # one for perimeters, one for infill and one for supports.
  1698. sub load_print_object_toolpaths {
  1699. my ($self, $object, $colors) = @_;
  1700. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1701. Slic3r::GUI::_3DScene::_load_print_object_toolpaths($object, $self->volumes, $colors, $self->UseVBOs);
  1702. }
  1703. # Create 3D thick extrusion lines for wipe tower extrusions.
  1704. sub load_wipe_tower_toolpaths {
  1705. my ($self, $print, $colors) = @_;
  1706. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1707. Slic3r::GUI::_3DScene::_load_wipe_tower_toolpaths($print, $self->volumes, $colors, $self->UseVBOs)
  1708. if ($print->step_done(STEP_WIPE_TOWER));
  1709. }
  1710. sub set_toolpaths_range {
  1711. my ($self, $min_z, $max_z) = @_;
  1712. $self->volumes->set_range($min_z, $max_z);
  1713. }
  1714. 1;