3DScene.pm 79 KB

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