3DScene.pm 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. package Slic3r::GUI::3DScene::Base;
  2. use strict;
  3. use warnings;
  4. use Wx::Event qw(EVT_PAINT EVT_SIZE EVT_ERASE_BACKGROUND EVT_IDLE EVT_MOUSEWHEEL EVT_MOUSE_EVENTS);
  5. # must load OpenGL *before* Wx::GLCanvas
  6. use OpenGL qw(:glconstants :glfunctions :glufunctions :gluconstants);
  7. use base qw(Wx::GLCanvas Class::Accessor);
  8. use Math::Trig qw(asin);
  9. use List::Util qw(reduce min max first);
  10. use Slic3r::Geometry qw(X Y Z MIN MAX triangle_normal normalize deg2rad tan scale unscale scaled_epsilon);
  11. use Slic3r::Geometry::Clipper qw(offset_ex intersection_pl);
  12. use Wx::GLCanvas qw(:all);
  13. __PACKAGE__->mk_accessors( qw(_quat _dirty init
  14. enable_picking
  15. enable_moving
  16. on_viewport_changed
  17. on_hover
  18. on_select
  19. on_double_click
  20. on_right_click
  21. on_move
  22. volumes
  23. _sphi _stheta
  24. cutting_plane_axis
  25. cutting_plane_z
  26. cut_lines_vertices
  27. bed_shape
  28. bed_triangles
  29. bed_grid_lines
  30. background
  31. origin
  32. _mouse_pos
  33. _hover_volume_idx
  34. _drag_volume_idx
  35. _drag_start_pos
  36. _drag_start_xy
  37. _dragged
  38. _camera_target
  39. _zoom
  40. ) );
  41. use constant TRACKBALLSIZE => 0.8;
  42. use constant TURNTABLE_MODE => 1;
  43. use constant GROUND_Z => -0.02;
  44. use constant SELECTED_COLOR => [0,1,0];
  45. use constant HOVER_COLOR => [0.4,0.9,0];
  46. use constant PI => 3.1415927;
  47. # Constant to determine if Vertex Buffer objects are used to draw
  48. # bed grid and the cut plane for object separation.
  49. use constant HAS_VBO => eval { glGenBuffersARB_p(0); GL_ARRAY_BUFFER_ARB; 1 };
  50. # phi / theta angles to orient the camera.
  51. use constant VIEW_TOP => [0.0,0.0];
  52. use constant VIEW_BOTTOM => [0.0,180.0];
  53. use constant VIEW_LEFT => [90.0,90.0];
  54. use constant VIEW_RIGHT => [-90.0,90.0];
  55. use constant VIEW_FRONT => [0.0,90.0];
  56. use constant VIEW_BACK => [180.0,90.0];
  57. use constant VIEW_DIAGONAL => [45.0,45.0];
  58. use constant GIMBAL_LOCK_THETA_MAX => 170;
  59. # make OpenGL::Array thread-safe
  60. {
  61. no warnings 'redefine';
  62. *OpenGL::Array::CLONE_SKIP = sub { 1 };
  63. }
  64. sub new {
  65. my ($class, $parent) = @_;
  66. # We can only enable multi sample anti aliasing wih wxWidgets 3.0.3 and with a hacked Wx::GLCanvas,
  67. # which exports some new WX_GL_XXX constants, namely WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES.
  68. my $can_multisample =
  69. Wx::wxVERSION >= 3.000003 &&
  70. defined Wx::GLCanvas->can('WX_GL_SAMPLE_BUFFERS') &&
  71. defined Wx::GLCanvas->can('WX_GL_SAMPLES');
  72. my $attrib = [WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 24];
  73. if ($can_multisample) {
  74. # Request a window with multi sampled anti aliasing. This is a new feature in Wx 3.0.3 (backported from 3.1.0).
  75. # Use eval to avoid compilation, if the subs WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES are missing.
  76. eval 'push(@$attrib, (WX_GL_SAMPLE_BUFFERS, 1, WX_GL_SAMPLES, 4));';
  77. }
  78. # wxWidgets expect the attrib list to be ended by zero.
  79. push(@$attrib, 0);
  80. # we request a depth buffer explicitely because it looks like it's not created by
  81. # default on Linux, causing transparency issues
  82. my $self = $class->SUPER::new($parent, -1, Wx::wxDefaultPosition, Wx::wxDefaultSize, 0, "", $attrib);
  83. if (Wx::wxVERSION >= 3.000003) {
  84. # Wx 3.0.3 contains an ugly hack to support some advanced OpenGL attributes through the attribute list.
  85. # The attribute list is transferred between the wxGLCanvas and wxGLContext constructors using a single static array s_wglContextAttribs.
  86. # Immediatelly force creation of the OpenGL context to consume the static variable s_wglContextAttribs.
  87. $self->GetContext();
  88. }
  89. $self->{can_multisample} = $can_multisample;
  90. $self->background(1);
  91. $self->_quat((0, 0, 0, 1));
  92. $self->_stheta(45);
  93. $self->_sphi(45);
  94. $self->_zoom(1);
  95. # 3D point in model space
  96. $self->_camera_target(Slic3r::Pointf3->new(0,0,0));
  97. $self->reset_objects;
  98. EVT_PAINT($self, sub {
  99. my $dc = Wx::PaintDC->new($self);
  100. $self->Render($dc);
  101. });
  102. EVT_SIZE($self, sub { $self->_dirty(1) });
  103. EVT_IDLE($self, sub {
  104. return unless $self->_dirty;
  105. return if !$self->IsShownOnScreen;
  106. $self->Resize( $self->GetSizeWH );
  107. $self->Refresh;
  108. });
  109. EVT_MOUSEWHEEL($self, sub {
  110. my ($self, $e) = @_;
  111. # Calculate the zoom delta and apply it to the current zoom factor
  112. my $zoom = $e->GetWheelRotation() / $e->GetWheelDelta();
  113. if ($Slic3r::GUI::Settings->{_}{invert_zoom}) {
  114. $zoom *= -1;
  115. }
  116. $zoom = max(min($zoom, 4), -4);
  117. $zoom /= 10;
  118. $self->_zoom($self->_zoom / (1-$zoom));
  119. # In order to zoom around the mouse point we need to translate
  120. # the camera target
  121. my $size = Slic3r::Pointf->new($self->GetSizeWH);
  122. my $pos = Slic3r::Pointf->new($e->GetX, $size->y - $e->GetY); #-
  123. $self->_camera_target->translate(
  124. # ($pos - $size/2) represents the vector from the viewport center
  125. # to the mouse point. By multiplying it by $zoom we get the new,
  126. # transformed, length of such vector.
  127. # Since we want that point to stay fixed, we move our camera target
  128. # in the opposite direction by the delta of the length of such vector
  129. # ($zoom - 1). We then scale everything by 1/$self->_zoom since
  130. # $self->_camera_target is expressed in terms of model units.
  131. -($pos->x - $size->x/2) * ($zoom) / $self->_zoom,
  132. -($pos->y - $size->y/2) * ($zoom) / $self->_zoom,
  133. 0,
  134. ) if 0;
  135. $self->on_viewport_changed->() if $self->on_viewport_changed;
  136. $self->_dirty(1);
  137. $self->Refresh;
  138. });
  139. EVT_MOUSE_EVENTS($self, \&mouse_event);
  140. return $self;
  141. }
  142. sub mouse_event {
  143. my ($self, $e) = @_;
  144. my $pos = Slic3r::Pointf->new($e->GetPositionXY);
  145. if ($e->Entering && &Wx::wxMSW) {
  146. # wxMSW needs focus in order to catch mouse wheel events
  147. $self->SetFocus;
  148. } elsif ($e->LeftDClick) {
  149. $self->on_double_click->()
  150. if $self->on_double_click;
  151. } elsif ($e->MiddleDClick) {
  152. if (@{$self->volumes}) {
  153. $self->zoom_to_volumes;
  154. } else {
  155. $self->zoom_to_bed;
  156. }
  157. $self->_dirty(1);
  158. $self->Refresh;
  159. } elsif (($e->LeftDown || $e->RightDown) && not $e->ShiftDown) {
  160. # If user pressed left or right button we first check whether this happened
  161. # on a volume or not.
  162. my $volume_idx = $self->_hover_volume_idx // -1;
  163. # select volume in this 3D canvas
  164. if ($self->enable_picking) {
  165. $self->deselect_volumes;
  166. $self->select_volume($volume_idx);
  167. if ($volume_idx != -1) {
  168. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  169. my @volumes;
  170. if ($group_id != -1) {
  171. $self->select_volume($_)
  172. for grep $self->volumes->[$_]->select_group_id == $group_id,
  173. 0..$#{$self->volumes};
  174. }
  175. }
  176. $self->Refresh;
  177. }
  178. # propagate event through callback
  179. $self->on_select->($volume_idx)
  180. if $self->on_select;
  181. if ($volume_idx != -1) {
  182. if ($e->LeftDown && $self->enable_moving) {
  183. $self->_drag_volume_idx($volume_idx);
  184. $self->_drag_start_pos($self->mouse_to_3d(@$pos));
  185. } elsif ($e->RightDown) {
  186. # if right clicking on volume, propagate event through callback
  187. $self->on_right_click->($e->GetPosition)
  188. if $self->on_right_click;
  189. }
  190. }
  191. } elsif ($e->Dragging && $e->LeftIsDown && defined($self->_drag_volume_idx)) {
  192. # get new position at the same Z of the initial click point
  193. my $mouse_ray = $self->mouse_ray($e->GetX, $e->GetY);
  194. my $cur_pos = $mouse_ray->intersect_plane($self->_drag_start_pos->z);
  195. # calculate the translation vector
  196. my $vector = $self->_drag_start_pos->vector_to($cur_pos);
  197. # get volume being dragged
  198. my $volume = $self->volumes->[$self->_drag_volume_idx];
  199. # get all volumes belonging to the same group, if any
  200. my @volumes;
  201. if ($volume->drag_group_id == -1) {
  202. @volumes = ($volume);
  203. } else {
  204. @volumes = grep $_->drag_group_id == $volume->drag_group_id, @{$self->volumes};
  205. }
  206. # apply new temporary volume origin and ignore Z
  207. $_->origin->translate($vector->x, $vector->y, 0) for @volumes; #,,
  208. $self->_drag_start_pos($cur_pos);
  209. $self->_dragged(1);
  210. $self->Refresh;
  211. } elsif ($e->Dragging) {
  212. if ($e->AltDown) {
  213. # Move the camera center on the Z axis based on mouse Y axis movement
  214. if (defined $self->_drag_start_pos) {
  215. my $orig = $self->_drag_start_pos;
  216. $self->_camera_target->translate(0, 0, $pos->y - $orig->y);
  217. $self->on_viewport_changed->() if $self->on_viewport_changed;
  218. $self->Refresh;
  219. }
  220. $self->_drag_start_pos($pos);
  221. } elsif ($e->LeftIsDown) {
  222. # if dragging over blank area with left button, rotate
  223. if (defined $self->_drag_start_pos) {
  224. my $orig = $self->_drag_start_pos;
  225. if (TURNTABLE_MODE) {
  226. $self->_sphi($self->_sphi + ($pos->x - $orig->x) * TRACKBALLSIZE);
  227. $self->_stheta($self->_stheta - ($pos->y - $orig->y) * TRACKBALLSIZE); #-
  228. $self->_stheta(GIMBAL_LOCK_THETA_MAX) if $self->_stheta > GIMBAL_LOCK_THETA_MAX;
  229. $self->_stheta(0) if $self->_stheta < 0;
  230. } else {
  231. my $size = $self->GetClientSize;
  232. my @quat = trackball(
  233. $orig->x / ($size->width / 2) - 1,
  234. 1 - $orig->y / ($size->height / 2), #/
  235. $pos->x / ($size->width / 2) - 1,
  236. 1 - $pos->y / ($size->height / 2), #/
  237. );
  238. $self->_quat(mulquats($self->_quat, \@quat));
  239. }
  240. $self->on_viewport_changed->() if $self->on_viewport_changed;
  241. $self->Refresh;
  242. }
  243. $self->_drag_start_pos($pos);
  244. } elsif ($e->MiddleIsDown || $e->RightIsDown) {
  245. # if dragging over blank area with right button, translate
  246. if (defined $self->_drag_start_xy) {
  247. # get point in model space at Z = 0
  248. my $cur_pos = $self->mouse_ray($e->GetX, $e->GetY)->intersect_plane(0);
  249. my $orig = $self->mouse_ray(@{$self->_drag_start_xy})->intersect_plane(0);
  250. $self->_camera_target->translate(
  251. @{$orig->vector_to($cur_pos)->negative},
  252. );
  253. $self->on_viewport_changed->() if $self->on_viewport_changed;
  254. $self->Refresh;
  255. }
  256. $self->_drag_start_xy($pos);
  257. }
  258. } elsif ($e->LeftUp || $e->MiddleUp || $e->RightUp) {
  259. if ($self->on_move && defined($self->_drag_volume_idx) && $self->_dragged) {
  260. # get all volumes belonging to the same group, if any
  261. my @volume_idxs;
  262. my $group_id = $self->volumes->[$self->_drag_volume_idx]->drag_group_id;
  263. if ($group_id == -1) {
  264. @volume_idxs = ($self->_drag_volume_idx);
  265. } else {
  266. @volume_idxs = grep $self->volumes->[$_]->drag_group_id == $group_id,
  267. 0..$#{$self->volumes};
  268. }
  269. $self->on_move->(@volume_idxs);
  270. }
  271. $self->_drag_volume_idx(undef);
  272. $self->_drag_start_pos(undef);
  273. $self->_drag_start_xy(undef);
  274. $self->_dragged(undef);
  275. } elsif ($e->Moving) {
  276. $self->_mouse_pos($pos);
  277. $self->Refresh if $self->enable_picking;
  278. } else {
  279. $e->Skip();
  280. }
  281. }
  282. sub reset_objects {
  283. my ($self) = @_;
  284. $self->volumes([]);
  285. $self->_dirty(1);
  286. }
  287. sub set_viewport_from_scene {
  288. my ($self, $scene) = @_;
  289. $self->_sphi($scene->_sphi);
  290. $self->_stheta($scene->_stheta);
  291. $self->_camera_target($scene->_camera_target);
  292. $self->_zoom($scene->_zoom);
  293. $self->_quat($scene->_quat);
  294. $self->_dirty(1);
  295. }
  296. sub zoom{
  297. my ($self, $direction) = @_;
  298. if( $direction eq 'in'){
  299. $self->_zoom($self->_zoom / (1-0.3));
  300. }
  301. elsif($direction eq 'out'){
  302. $self->_zoom($self->_zoom / (1+0.3));
  303. }
  304. $self->on_viewport_changed->() if $self->on_viewport_changed;
  305. $self->_dirty(1);
  306. $self->Refresh;
  307. }
  308. # Set the camera to a default orientation,
  309. # zoom to volumes.
  310. sub select_view {
  311. my ($self, $direction) = @_;
  312. my $dirvec;
  313. if (ref($direction)) {
  314. $dirvec = $direction;
  315. } else {
  316. if ($direction eq 'top') {
  317. $dirvec = VIEW_TOP;
  318. } elsif ($direction eq 'bottom') {
  319. $dirvec = VIEW_BOTTOM;
  320. } elsif ($direction eq 'left') {
  321. $dirvec = VIEW_LEFT;
  322. } elsif ($direction eq 'right') {
  323. $dirvec = VIEW_RIGHT;
  324. } elsif ($direction eq 'front') {
  325. $dirvec = VIEW_FRONT;
  326. } elsif ($direction eq 'back') {
  327. $dirvec = VIEW_BACK;
  328. } elsif ($direction eq 'diagonal') {
  329. $dirvec = VIEW_DIAGONAL;
  330. }
  331. }
  332. $self->_sphi($dirvec->[0]);
  333. $self->_stheta($dirvec->[1]);
  334. # Avoid gimbal lock.
  335. $self->_stheta(GIMBAL_LOCK_THETA_MAX) if $self->_stheta > GIMBAL_LOCK_THETA_MAX;
  336. $self->_stheta(0) if $self->_stheta < 0;
  337. # View everything.
  338. $self->volumes_bounding_box->defined
  339. ? $self->zoom_to_volumes
  340. : $self->zoom_to_bed;
  341. $self->on_viewport_changed->() if $self->on_viewport_changed;
  342. $self->_dirty(1);
  343. $self->Refresh;
  344. }
  345. sub zoom_to_bounding_box {
  346. my ($self, $bb) = @_;
  347. # calculate the zoom factor needed to adjust viewport to
  348. # bounding box
  349. my $max_size = max(@{$bb->size}) * 1.05;
  350. my $min_viewport_size = min($self->GetSizeWH);
  351. if ($max_size != 0) {
  352. # only re-zoom if we have a valid bounding box, avoid a divide by 0 error.
  353. $self->_zoom($min_viewport_size / $max_size);
  354. # center view around bounding box center
  355. $self->_camera_target($bb->center);
  356. $self->on_viewport_changed->() if $self->on_viewport_changed;
  357. }
  358. }
  359. sub zoom_to_bed {
  360. my ($self) = @_;
  361. if ($self->bed_shape) {
  362. $self->zoom_to_bounding_box($self->bed_bounding_box);
  363. }
  364. }
  365. sub zoom_to_volume {
  366. my ($self, $volume_idx) = @_;
  367. my $volume = $self->volumes->[$volume_idx];
  368. my $bb = $volume->transformed_bounding_box;
  369. $self->zoom_to_bounding_box($bb);
  370. }
  371. sub zoom_to_volumes {
  372. my ($self) = @_;
  373. $self->zoom_to_bounding_box($self->volumes_bounding_box);
  374. }
  375. sub volumes_bounding_box {
  376. my ($self) = @_;
  377. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  378. $bb->merge($_->transformed_bounding_box) for @{$self->volumes};
  379. return $bb;
  380. }
  381. sub bed_bounding_box {
  382. my ($self) = @_;
  383. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  384. if ($self->bed_shape) {
  385. $bb->merge_point(Slic3r::Pointf3->new(@$_, 0)) for @{$self->bed_shape};
  386. }
  387. return $bb;
  388. }
  389. sub max_bounding_box {
  390. my ($self) = @_;
  391. my $bb = $self->bed_bounding_box;
  392. $bb->merge($self->volumes_bounding_box);
  393. return $bb;
  394. }
  395. sub set_auto_bed_shape {
  396. my ($self, $bed_shape) = @_;
  397. # draw a default square bed around object center
  398. my $max_size = max(@{ $self->volumes_bounding_box->size });
  399. my $center = $self->volumes_bounding_box->center;
  400. $self->set_bed_shape([
  401. [ $center->x - $max_size, $center->y - $max_size ], #--
  402. [ $center->x + $max_size, $center->y - $max_size ], #--
  403. [ $center->x + $max_size, $center->y + $max_size ], #++
  404. [ $center->x - $max_size, $center->y + $max_size ], #++
  405. ]);
  406. $self->origin(Slic3r::Pointf->new(@$center[X,Y]));
  407. }
  408. sub set_bed_shape {
  409. my ($self, $bed_shape) = @_;
  410. $self->bed_shape($bed_shape);
  411. # triangulate bed
  412. my $expolygon = Slic3r::ExPolygon->new([ map [map scale($_), @$_], @$bed_shape ]);
  413. my $bed_bb = $expolygon->bounding_box;
  414. {
  415. my @points = ();
  416. foreach my $triangle (@{ $expolygon->triangulate }) {
  417. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$triangle; #))
  418. }
  419. $self->bed_triangles(OpenGL::Array->new_list(GL_FLOAT, @points));
  420. }
  421. {
  422. my @polylines = ();
  423. for (my $x = $bed_bb->x_min; $x <= $bed_bb->x_max; $x += scale 10) {
  424. push @polylines, Slic3r::Polyline->new([$x,$bed_bb->y_min], [$x,$bed_bb->y_max]);
  425. }
  426. for (my $y = $bed_bb->y_min; $y <= $bed_bb->y_max; $y += scale 10) {
  427. push @polylines, Slic3r::Polyline->new([$bed_bb->x_min,$y], [$bed_bb->x_max,$y]);
  428. }
  429. # clip with a slightly grown expolygon because our lines lay on the contours and
  430. # may get erroneously clipped
  431. my @lines = map Slic3r::Line->new(@$_[0,-1]),
  432. @{intersection_pl(\@polylines, [ @{$expolygon->offset(+scaled_epsilon)} ])};
  433. # append bed contours
  434. push @lines, map @{$_->lines}, @$expolygon;
  435. my @points = ();
  436. foreach my $line (@lines) {
  437. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$line; #))
  438. }
  439. $self->bed_grid_lines(OpenGL::Array->new_list(GL_FLOAT, @points));
  440. }
  441. $self->origin(Slic3r::Pointf->new(0,0));
  442. }
  443. sub deselect_volumes {
  444. my ($self) = @_;
  445. $_->selected(0) for @{$self->volumes};
  446. }
  447. sub select_volume {
  448. my ($self, $volume_idx) = @_;
  449. $self->volumes->[$volume_idx]->selected(1)
  450. if $volume_idx != -1;
  451. }
  452. sub SetCuttingPlane {
  453. my ($self, $axis, $z, $expolygons) = @_;
  454. $self->cutting_plane_axis($axis);
  455. $self->cutting_plane_z($z);
  456. # grow slices in order to display them better
  457. $expolygons = offset_ex([ map @$_, @$expolygons ], scale 0.1);
  458. my $bb = $self->volumes_bounding_box;
  459. my @verts = ();
  460. foreach my $line (map @{$_->lines}, map @$_, @$expolygons) {
  461. if ($axis == X) {
  462. push @verts, (
  463. $bb->x_min + $z, unscale($line->a->x), unscale($line->a->y), #))
  464. $bb->x_min + $z, unscale($line->b->x), unscale($line->b->y), #))
  465. );
  466. } elsif ($axis == Y) {
  467. push @verts, (
  468. unscale($line->a->y), $bb->y_min + $z, unscale($line->a->x), #))
  469. unscale($line->b->y), $bb->y_min + $z, unscale($line->b->x), #))
  470. );
  471. } else {
  472. push @verts, (
  473. unscale($line->a->x), unscale($line->a->y), $z, #))
  474. unscale($line->b->x), unscale($line->b->y), $z, #))
  475. );
  476. }
  477. }
  478. $self->cut_lines_vertices(OpenGL::Array->new_list(GL_FLOAT, @verts));
  479. }
  480. # Given an axis and angle, compute quaternion.
  481. sub axis_to_quat {
  482. my ($ax, $phi) = @_;
  483. my $lena = sqrt(reduce { $a + $b } (map { $_ * $_ } @$ax));
  484. my @q = map { $_ * (1 / $lena) } @$ax;
  485. @q = map { $_ * sin($phi / 2.0) } @q;
  486. $q[$#q + 1] = cos($phi / 2.0);
  487. return @q;
  488. }
  489. # Project a point on the virtual trackball.
  490. # If it is inside the sphere, map it to the sphere, if it outside map it
  491. # to a hyperbola.
  492. sub project_to_sphere {
  493. my ($r, $x, $y) = @_;
  494. my $d = sqrt($x * $x + $y * $y);
  495. if ($d < $r * 0.70710678118654752440) { # Inside sphere
  496. return sqrt($r * $r - $d * $d);
  497. } else { # On hyperbola
  498. my $t = $r / 1.41421356237309504880;
  499. return $t * $t / $d;
  500. }
  501. }
  502. sub cross {
  503. my ($v1, $v2) = @_;
  504. return (@$v1[1] * @$v2[2] - @$v1[2] * @$v2[1],
  505. @$v1[2] * @$v2[0] - @$v1[0] * @$v2[2],
  506. @$v1[0] * @$v2[1] - @$v1[1] * @$v2[0]);
  507. }
  508. # Simulate a track-ball. Project the points onto the virtual trackball,
  509. # then figure out the axis of rotation, which is the cross product of
  510. # P1 P2 and O P1 (O is the center of the ball, 0,0,0) Note: This is a
  511. # deformed trackball-- is a trackball in the center, but is deformed
  512. # into a hyperbolic sheet of rotation away from the center.
  513. # It is assumed that the arguments to this routine are in the range
  514. # (-1.0 ... 1.0).
  515. sub trackball {
  516. my ($p1x, $p1y, $p2x, $p2y) = @_;
  517. if ($p1x == $p2x && $p1y == $p2y) {
  518. # zero rotation
  519. return (0.0, 0.0, 0.0, 1.0);
  520. }
  521. # First, figure out z-coordinates for projection of P1 and P2 to
  522. # deformed sphere
  523. my @p1 = ($p1x, $p1y, project_to_sphere(TRACKBALLSIZE, $p1x, $p1y));
  524. my @p2 = ($p2x, $p2y, project_to_sphere(TRACKBALLSIZE, $p2x, $p2y));
  525. # axis of rotation (cross product of P1 and P2)
  526. my @a = cross(\@p2, \@p1);
  527. # Figure out how much to rotate around that axis.
  528. my @d = map { $_ * $_ } (map { $p1[$_] - $p2[$_] } 0 .. $#p1);
  529. my $t = sqrt(reduce { $a + $b } @d) / (2.0 * TRACKBALLSIZE);
  530. # Avoid problems with out-of-control values...
  531. $t = 1.0 if ($t > 1.0);
  532. $t = -1.0 if ($t < -1.0);
  533. my $phi = 2.0 * asin($t);
  534. return axis_to_quat(\@a, $phi);
  535. }
  536. # Build a rotation matrix, given a quaternion rotation.
  537. sub quat_to_rotmatrix {
  538. my ($q) = @_;
  539. my @m = ();
  540. $m[0] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[2] * @$q[2]);
  541. $m[1] = 2.0 * (@$q[0] * @$q[1] - @$q[2] * @$q[3]);
  542. $m[2] = 2.0 * (@$q[2] * @$q[0] + @$q[1] * @$q[3]);
  543. $m[3] = 0.0;
  544. $m[4] = 2.0 * (@$q[0] * @$q[1] + @$q[2] * @$q[3]);
  545. $m[5] = 1.0 - 2.0 * (@$q[2] * @$q[2] + @$q[0] * @$q[0]);
  546. $m[6] = 2.0 * (@$q[1] * @$q[2] - @$q[0] * @$q[3]);
  547. $m[7] = 0.0;
  548. $m[8] = 2.0 * (@$q[2] * @$q[0] - @$q[1] * @$q[3]);
  549. $m[9] = 2.0 * (@$q[1] * @$q[2] + @$q[0] * @$q[3]);
  550. $m[10] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[0] * @$q[0]);
  551. $m[11] = 0.0;
  552. $m[12] = 0.0;
  553. $m[13] = 0.0;
  554. $m[14] = 0.0;
  555. $m[15] = 1.0;
  556. return @m;
  557. }
  558. sub mulquats {
  559. my ($q1, $rq) = @_;
  560. return (@$q1[3] * @$rq[0] + @$q1[0] * @$rq[3] + @$q1[1] * @$rq[2] - @$q1[2] * @$rq[1],
  561. @$q1[3] * @$rq[1] + @$q1[1] * @$rq[3] + @$q1[2] * @$rq[0] - @$q1[0] * @$rq[2],
  562. @$q1[3] * @$rq[2] + @$q1[2] * @$rq[3] + @$q1[0] * @$rq[1] - @$q1[1] * @$rq[0],
  563. @$q1[3] * @$rq[3] - @$q1[0] * @$rq[0] - @$q1[1] * @$rq[1] - @$q1[2] * @$rq[2])
  564. }
  565. sub mouse_to_3d {
  566. my ($self, $x, $y, $z) = @_;
  567. my @viewport = glGetIntegerv_p(GL_VIEWPORT); # 4 items
  568. my @mview = glGetDoublev_p(GL_MODELVIEW_MATRIX); # 16 items
  569. my @proj = glGetDoublev_p(GL_PROJECTION_MATRIX); # 16 items
  570. $y = $viewport[3] - $y;
  571. $z //= glReadPixels_p($x, $y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT);
  572. my @projected = gluUnProject_p($x, $y, $z, @mview, @proj, @viewport);
  573. return Slic3r::Pointf3->new(@projected);
  574. }
  575. sub mouse_ray {
  576. my ($self, $x, $y) = @_;
  577. return Slic3r::Linef3->new(
  578. $self->mouse_to_3d($x, $y, 0),
  579. $self->mouse_to_3d($x, $y, 1),
  580. );
  581. }
  582. sub GetContext {
  583. my ($self) = @_;
  584. if (Wx::wxVERSION >= 2.009) {
  585. return $self->{context} ||= Wx::GLContext->new($self);
  586. } else {
  587. return $self->SUPER::GetContext;
  588. }
  589. }
  590. sub SetCurrent {
  591. my ($self, $context) = @_;
  592. if (Wx::wxVERSION >= 2.009) {
  593. return $self->SUPER::SetCurrent($context);
  594. } else {
  595. return $self->SUPER::SetCurrent;
  596. }
  597. }
  598. sub Resize {
  599. my ($self, $x, $y) = @_;
  600. return unless $self->GetContext;
  601. $self->_dirty(0);
  602. $self->SetCurrent($self->GetContext);
  603. glViewport(0, 0, $x, $y);
  604. $x /= $self->_zoom;
  605. $y /= $self->_zoom;
  606. glMatrixMode(GL_PROJECTION);
  607. glLoadIdentity();
  608. my $depth = 10 * max(@{ $self->max_bounding_box->size });
  609. glOrtho(
  610. -$x/2, $x/2, -$y/2, $y/2,
  611. -$depth, 2*$depth,
  612. );
  613. glMatrixMode(GL_MODELVIEW);
  614. }
  615. sub InitGL {
  616. my $self = shift;
  617. return if $self->init;
  618. return unless $self->GetContext;
  619. $self->init(1);
  620. glClearColor(0, 0, 0, 1);
  621. glColor3f(1, 0, 0);
  622. glEnable(GL_DEPTH_TEST);
  623. glClearDepth(1.0);
  624. glDepthFunc(GL_LEQUAL);
  625. glEnable(GL_CULL_FACE);
  626. glEnable(GL_BLEND);
  627. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  628. # Set antialiasing/multisampling
  629. glDisable(GL_LINE_SMOOTH);
  630. glDisable(GL_POLYGON_SMOOTH);
  631. glEnable(GL_MULTISAMPLE) if ($self->{can_multisample});
  632. # ambient lighting
  633. glLightModelfv_p(GL_LIGHT_MODEL_AMBIENT, 0.3, 0.3, 0.3, 1);
  634. glEnable(GL_LIGHTING);
  635. glEnable(GL_LIGHT0);
  636. glEnable(GL_LIGHT1);
  637. # light from camera
  638. glLightfv_p(GL_LIGHT1, GL_POSITION, 1, 0, 1, 0);
  639. glLightfv_p(GL_LIGHT1, GL_SPECULAR, 0.3, 0.3, 0.3, 1);
  640. glLightfv_p(GL_LIGHT1, GL_DIFFUSE, 0.2, 0.2, 0.2, 1);
  641. # Enables Smooth Color Shading; try GL_FLAT for (lack of) fun.
  642. glShadeModel(GL_SMOOTH);
  643. glMaterialfv_p(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, 0.3, 0.3, 0.3, 1);
  644. glMaterialfv_p(GL_FRONT_AND_BACK, GL_SPECULAR, 1, 1, 1, 1);
  645. glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50);
  646. glMaterialfv_p(GL_FRONT_AND_BACK, GL_EMISSION, 0.1, 0.1, 0.1, 0.9);
  647. # A handy trick -- have surface material mirror the color.
  648. glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
  649. glEnable(GL_COLOR_MATERIAL);
  650. glEnable(GL_MULTISAMPLE) if ($self->{can_multisample});
  651. }
  652. sub Render {
  653. my ($self, $dc) = @_;
  654. # prevent calling SetCurrent() when window is not shown yet
  655. return unless $self->IsShownOnScreen;
  656. return unless my $context = $self->GetContext;
  657. $self->SetCurrent($context);
  658. $self->InitGL;
  659. glClearColor(1, 1, 1, 1);
  660. glClearDepth(1);
  661. glDepthFunc(GL_LESS);
  662. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  663. glMatrixMode(GL_MODELVIEW);
  664. glLoadIdentity();
  665. if (TURNTABLE_MODE) {
  666. glRotatef(-$self->_stheta, 1, 0, 0); # pitch
  667. glRotatef($self->_sphi, 0, 0, 1); # yaw
  668. } else {
  669. my @rotmat = quat_to_rotmatrix($self->quat);
  670. glMultMatrixd_p(@rotmat[0..15]);
  671. }
  672. glTranslatef(@{ $self->_camera_target->negative });
  673. # light from above
  674. glLightfv_p(GL_LIGHT0, GL_POSITION, -0.5, -0.5, 1, 0);
  675. glLightfv_p(GL_LIGHT0, GL_SPECULAR, 0.2, 0.2, 0.2, 1);
  676. glLightfv_p(GL_LIGHT0, GL_DIFFUSE, 0.5, 0.5, 0.5, 1);
  677. if ($self->enable_picking) {
  678. glDisable(GL_MULTISAMPLE) if ($self->{can_multisample});
  679. glDisable(GL_LIGHTING);
  680. $self->draw_volumes(1);
  681. glFlush();
  682. glFinish();
  683. if (my $pos = $self->_mouse_pos) {
  684. my $col = [ glReadPixels_p($pos->x, $self->GetSize->GetHeight - $pos->y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE) ];
  685. my $volume_idx = $col->[0] + $col->[1]*256 + $col->[2]*256*256;
  686. $self->_hover_volume_idx(undef);
  687. $_->hover(0) for @{$self->volumes};
  688. if ($volume_idx <= $#{$self->volumes}) {
  689. $self->_hover_volume_idx($volume_idx);
  690. $self->volumes->[$volume_idx]->hover(1);
  691. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  692. if ($group_id != -1) {
  693. $_->hover(1) for grep { $_->select_group_id == $group_id } @{$self->volumes};
  694. }
  695. $self->on_hover->($volume_idx) if $self->on_hover;
  696. }
  697. }
  698. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  699. glFlush();
  700. glFinish();
  701. glEnable(GL_LIGHTING);
  702. }
  703. # draw fixed background
  704. if ($self->background) {
  705. glDisable(GL_LIGHTING);
  706. glPushMatrix();
  707. glLoadIdentity();
  708. glMatrixMode(GL_PROJECTION);
  709. glPushMatrix();
  710. glLoadIdentity();
  711. glBegin(GL_QUADS);
  712. glColor3f(0.0,0.0,0.0);
  713. glVertex2f(-1.0,-1.0);
  714. glVertex2f(1,-1.0);
  715. glColor3f(10/255,98/255,144/255);
  716. glVertex2f(1, 1);
  717. glVertex2f(-1.0, 1);
  718. glEnd();
  719. glPopMatrix();
  720. glMatrixMode(GL_MODELVIEW);
  721. glPopMatrix();
  722. glEnable(GL_LIGHTING);
  723. }
  724. # draw ground and axes
  725. glDisable(GL_LIGHTING);
  726. # draw ground
  727. my $ground_z = GROUND_Z;
  728. if ($self->bed_triangles) {
  729. glDisable(GL_DEPTH_TEST);
  730. glEnable(GL_BLEND);
  731. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  732. glEnableClientState(GL_VERTEX_ARRAY);
  733. my $triangle_vertex;
  734. if (HAS_VBO) {
  735. ($triangle_vertex) =
  736. glGenBuffersARB_p(1);
  737. $self->bed_triangles->bind($triangle_vertex);
  738. glBufferDataARB_p(GL_ARRAY_BUFFER_ARB, $self->bed_triangles, GL_STATIC_DRAW_ARB);
  739. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  740. } else {
  741. # fall back on old behavior
  742. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_triangles->ptr());
  743. }
  744. glColor4f(0.8, 0.6, 0.5, 0.4);
  745. glNormal3d(0,0,1);
  746. glDrawArrays(GL_TRIANGLES, 0, $self->bed_triangles->elements / 3);
  747. glDisableClientState(GL_VERTEX_ARRAY);
  748. # we need depth test for grid, otherwise it would disappear when looking
  749. # the object from below
  750. glEnable(GL_DEPTH_TEST);
  751. # draw grid
  752. glLineWidth(3);
  753. glEnableClientState(GL_VERTEX_ARRAY);
  754. my $grid_vertex;
  755. if (HAS_VBO) {
  756. ($grid_vertex) =
  757. glGenBuffersARB_p(1);
  758. $self->bed_grid_lines->bind($grid_vertex);
  759. glBufferDataARB_p(GL_ARRAY_BUFFER_ARB, $self->bed_grid_lines, GL_STATIC_DRAW_ARB);
  760. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  761. } else {
  762. # fall back on old behavior
  763. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_grid_lines->ptr());
  764. }
  765. glColor4f(0.2, 0.2, 0.2, 0.4);
  766. glNormal3d(0,0,1);
  767. glDrawArrays(GL_LINES, 0, $self->bed_grid_lines->elements / 3);
  768. glDisableClientState(GL_VERTEX_ARRAY);
  769. glDisable(GL_BLEND);
  770. if (HAS_VBO) {
  771. # Turn off buffer objects to let the rest of the draw code work.
  772. glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
  773. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
  774. glDeleteBuffersARB_p($grid_vertex);
  775. glDeleteBuffersARB_p($triangle_vertex);
  776. }
  777. }
  778. my $volumes_bb = $self->volumes_bounding_box;
  779. {
  780. # draw axes
  781. # disable depth testing so that axes are not covered by ground
  782. glDisable(GL_DEPTH_TEST);
  783. my $origin = $self->origin;
  784. my $axis_len = max(
  785. max(@{ $self->bed_bounding_box->size }),
  786. 1.2 * max(@{ $volumes_bb->size }),
  787. );
  788. glLineWidth(2);
  789. glBegin(GL_LINES);
  790. # draw line for x axis
  791. glColor3f(1, 0, 0);
  792. glVertex3f(@$origin, $ground_z);
  793. glVertex3f($origin->x + $axis_len, $origin->y, $ground_z); #,,
  794. # draw line for y axis
  795. glColor3f(0, 1, 0);
  796. glVertex3f(@$origin, $ground_z);
  797. glVertex3f($origin->x, $origin->y + $axis_len, $ground_z); #++
  798. glEnd();
  799. # draw line for Z axis
  800. # (re-enable depth test so that axis is correctly shown when objects are behind it)
  801. glEnable(GL_DEPTH_TEST);
  802. glBegin(GL_LINES);
  803. glColor3f(0, 0, 1);
  804. glVertex3f(@$origin, $ground_z);
  805. glVertex3f(@$origin, $ground_z+$axis_len);
  806. glEnd();
  807. }
  808. glEnable(GL_LIGHTING);
  809. # draw objects
  810. $self->draw_volumes;
  811. # draw cutting plane
  812. if (defined $self->cutting_plane_z) {
  813. my $plane_z = $self->cutting_plane_z;
  814. my $bb = $volumes_bb;
  815. glDisable(GL_CULL_FACE);
  816. glDisable(GL_LIGHTING);
  817. glEnable(GL_BLEND);
  818. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  819. glBegin(GL_QUADS);
  820. glColor4f(0.8, 0.8, 0.8, 0.5);
  821. if ($self->cutting_plane_axis == X) {
  822. glVertex3f($bb->x_min+$plane_z, $bb->y_min-20, $bb->z_min-20);
  823. glVertex3f($bb->x_min+$plane_z, $bb->y_max+20, $bb->z_min-20);
  824. glVertex3f($bb->x_min+$plane_z, $bb->y_max+20, $bb->z_max+20);
  825. glVertex3f($bb->x_min+$plane_z, $bb->y_min-20, $bb->z_max+20);
  826. } elsif ($self->cutting_plane_axis == Y) {
  827. glVertex3f($bb->x_min-20, $bb->y_min+$plane_z, $bb->z_min-20);
  828. glVertex3f($bb->x_max+20, $bb->y_min+$plane_z, $bb->z_min-20);
  829. glVertex3f($bb->x_max+20, $bb->y_min+$plane_z, $bb->z_max+20);
  830. glVertex3f($bb->x_min-20, $bb->y_min+$plane_z, $bb->z_max+20);
  831. } elsif ($self->cutting_plane_axis == Z) {
  832. glVertex3f($bb->x_min-20, $bb->y_min-20, $bb->z_min+$plane_z);
  833. glVertex3f($bb->x_max+20, $bb->y_min-20, $bb->z_min+$plane_z);
  834. glVertex3f($bb->x_max+20, $bb->y_max+20, $bb->z_min+$plane_z);
  835. glVertex3f($bb->x_min-20, $bb->y_max+20, $bb->z_min+$plane_z);
  836. }
  837. glEnd();
  838. glEnable(GL_CULL_FACE);
  839. glDisable(GL_BLEND);
  840. }
  841. if (defined $self->_drag_start_pos || defined $self->_drag_start_xy) {
  842. $self->draw_center_of_rotation($self->_camera_target->x, $self->_camera_target->y, $self->_camera_target->z);
  843. }
  844. glFlush();
  845. $self->SwapBuffers();
  846. # Calling glFinish has a performance penalty, but it seems to fix some OpenGL driver hang-up with extremely large scenes.
  847. glFinish();
  848. }
  849. sub draw_axes {
  850. my ($self, $x, $y, $z, $length, $width, $allways_visible) = @_;
  851. if ($allways_visible) {
  852. glDisable(GL_DEPTH_TEST);
  853. } else {
  854. glEnable(GL_DEPTH_TEST);
  855. }
  856. glLineWidth($width);
  857. glBegin(GL_LINES);
  858. # draw line for x axis
  859. glColor3f(1, 0, 0);
  860. glVertex3f($x, $y, $z);
  861. glVertex3f($x + $length, $y, $z);
  862. # draw line for y axis
  863. glColor3f(0, 1, 0);
  864. glVertex3f($x, $y, $z);
  865. glVertex3f($x, $y + $length, $z);
  866. # draw line for Z axis
  867. glColor3f(0, 0, 1);
  868. glVertex3f($x, $y, $z);
  869. glVertex3f($x, $y, $z + $length);
  870. glEnd();
  871. }
  872. sub draw_center_of_rotation {
  873. my ($self, $x, $y, $z) = @_;
  874. $self->draw_axes($x, $y, $z, 10, 1, 1);
  875. $self->draw_axes($x, $y, $z, 10, 4, 0);
  876. }
  877. sub draw_volumes {
  878. my ($self, $fakecolor) = @_;
  879. glEnable(GL_BLEND);
  880. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  881. glEnableClientState(GL_VERTEX_ARRAY);
  882. glEnableClientState(GL_NORMAL_ARRAY);
  883. foreach my $volume_idx (0..$#{$self->volumes}) {
  884. my $volume = $self->volumes->[$volume_idx];
  885. glPushMatrix();
  886. glTranslatef(@{$volume->origin});
  887. if ($fakecolor) {
  888. my $r = ($volume_idx & 0x000000FF) >> 0;
  889. my $g = ($volume_idx & 0x0000FF00) >> 8;
  890. my $b = ($volume_idx & 0x00FF0000) >> 16;
  891. glColor4f($r/255.0, $g/255.0, $b/255.0, 1);
  892. } elsif ($volume->selected) {
  893. glColor4f(@{ &SELECTED_COLOR }, $volume->color->[3]);
  894. } elsif ($volume->hover) {
  895. glColor4f(@{ &HOVER_COLOR }, $volume->color->[3]);
  896. } else {
  897. glColor4f(@{ $volume->color });
  898. }
  899. my @sorted_z = ();
  900. my ($min_z, $max_z);
  901. if ($volume->range && $volume->offsets) {
  902. @sorted_z = sort { $a <=> $b } keys %{$volume->offsets};
  903. ($min_z, $max_z) = @{$volume->range};
  904. $min_z = first { $_ >= $min_z } @sorted_z;
  905. $max_z = first { $_ > $max_z } @sorted_z;
  906. }
  907. glCullFace(GL_BACK);
  908. if ($volume->qverts) {
  909. my ($min_offset, $max_offset);
  910. if (defined $min_z) {
  911. $min_offset = $volume->offsets->{$min_z}->[0];
  912. }
  913. if (defined $max_z) {
  914. $max_offset = $volume->offsets->{$max_z}->[0];
  915. }
  916. $min_offset //= 0;
  917. $max_offset //= $volume->qverts->size;
  918. glVertexPointer_c(3, GL_FLOAT, 0, $volume->qverts->verts_ptr);
  919. glNormalPointer_c(GL_FLOAT, 0, $volume->qverts->norms_ptr);
  920. glDrawArrays(GL_QUADS, $min_offset / 3, ($max_offset-$min_offset) / 3);
  921. }
  922. if ($volume->tverts) {
  923. my ($min_offset, $max_offset);
  924. if (defined $min_z) {
  925. $min_offset = $volume->offsets->{$min_z}->[1];
  926. }
  927. if (defined $max_z) {
  928. $max_offset = $volume->offsets->{$max_z}->[1];
  929. }
  930. $min_offset //= 0;
  931. $max_offset //= $volume->tverts->size;
  932. glVertexPointer_c(3, GL_FLOAT, 0, $volume->tverts->verts_ptr);
  933. glNormalPointer_c(GL_FLOAT, 0, $volume->tverts->norms_ptr);
  934. glDrawArrays(GL_TRIANGLES, $min_offset / 3, ($max_offset-$min_offset) / 3);
  935. }
  936. glPopMatrix();
  937. }
  938. glDisableClientState(GL_NORMAL_ARRAY);
  939. glDisable(GL_BLEND);
  940. my $cut_vertex;
  941. if (defined $self->cutting_plane_z) {
  942. if (HAS_VBO) {
  943. # Use Vertex Buffer Object for cutting plane (previous method crashes on modern POGL).
  944. ($cut_vertex) = glGenBuffersARB_p(1);
  945. $self->cut_lines_vertices->bind($cut_vertex);
  946. glBufferDataARB_p(GL_ARRAY_BUFFER_ARB, $self->cut_lines_vertices, GL_STATIC_DRAW_ARB);
  947. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  948. } else {
  949. # Use legacy method.
  950. glVertexPointer_c(3, GL_FLOAT, 0, $self->cut_lines_vertices->ptr());
  951. }
  952. glLineWidth(2);
  953. glColor3f(0, 0, 0);
  954. glDrawArrays(GL_LINES, 0, $self->cut_lines_vertices->elements / 3);
  955. if (HAS_VBO) {
  956. # Turn off buffer objects to let the rest of the draw code work.
  957. glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
  958. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
  959. glDeleteBuffersARB_p($cut_vertex);
  960. }
  961. }
  962. glDisableClientState(GL_VERTEX_ARRAY);
  963. }
  964. package Slic3r::GUI::3DScene::Volume;
  965. use Moo;
  966. has 'bounding_box' => (is => 'ro', required => 1);
  967. has 'origin' => (is => 'rw', default => sub { Slic3r::Pointf3->new(0,0,0) });
  968. has 'color' => (is => 'ro', required => 1);
  969. has 'select_group_id' => (is => 'rw', default => sub { -1 });
  970. has 'drag_group_id' => (is => 'rw', default => sub { -1 });
  971. has 'selected' => (is => 'rw', default => sub { 0 });
  972. has 'hover' => (is => 'rw', default => sub { 0 });
  973. has 'range' => (is => 'rw');
  974. # geometric data
  975. has 'qverts' => (is => 'rw'); # GLVertexArray object
  976. has 'tverts' => (is => 'rw'); # GLVertexArray object
  977. has 'mesh' => (is => 'rw'); # only required for cut contours
  978. has 'offsets' => (is => 'rw'); # [ z => [ qverts_idx, tverts_idx ] ]
  979. sub transformed_bounding_box {
  980. my ($self) = @_;
  981. my $bb = $self->bounding_box;
  982. $bb->translate(@{$self->origin});
  983. return $bb;
  984. }
  985. package Slic3r::GUI::3DScene;
  986. use base qw(Slic3r::GUI::3DScene::Base);
  987. use OpenGL qw(:glconstants :gluconstants :glufunctions);
  988. use List::Util qw(first min max);
  989. use Slic3r::Geometry qw(scale unscale epsilon);
  990. use Slic3r::Print::State ':steps';
  991. __PACKAGE__->mk_accessors(qw(
  992. colors
  993. color_by
  994. color_toolpaths_by
  995. select_by
  996. drag_by
  997. volumes_by_object
  998. _objects_by_volumes
  999. ));
  1000. sub default_colors { [1,0.95,0.2,1], [1,0.45,0.45,1], [0.5,1,0.5,1], [0.5,0.5,1,1] }
  1001. sub new {
  1002. my $class = shift;
  1003. my $self = $class->SUPER::new(@_);
  1004. $self->colors([ $self->default_colors ]);
  1005. $self->color_by('volume'); # object | volume
  1006. $self->color_toolpaths_by('role'); # role | extruder
  1007. $self->select_by('object'); # object | volume | instance
  1008. $self->drag_by('instance'); # object | instance
  1009. $self->volumes_by_object({}); # obj_idx => [ volume_idx, volume_idx ... ]
  1010. $self->_objects_by_volumes({}); # volume_idx => [ obj_idx, instance_idx ]
  1011. return $self;
  1012. }
  1013. sub load_object {
  1014. my ($self, $model, $obj_idx, $instance_idxs) = @_;
  1015. my $model_object;
  1016. if ($model->isa('Slic3r::Model::Object')) {
  1017. $model_object = $model;
  1018. $model = $model_object->model;
  1019. $obj_idx = 0;
  1020. } else {
  1021. $model_object = $model->get_object($obj_idx);
  1022. }
  1023. $instance_idxs ||= [0..$#{$model_object->instances}];
  1024. my @volumes_idx = ();
  1025. foreach my $volume_idx (0..$#{$model_object->volumes}) {
  1026. my $volume = $model_object->volumes->[$volume_idx];
  1027. foreach my $instance_idx (@$instance_idxs) {
  1028. my $instance = $model_object->instances->[$instance_idx];
  1029. my $mesh = $volume->mesh->clone;
  1030. $instance->transform_mesh($mesh);
  1031. my $color_idx;
  1032. if ($self->color_by eq 'volume') {
  1033. $color_idx = $volume_idx;
  1034. } elsif ($self->color_by eq 'object') {
  1035. $color_idx = $obj_idx;
  1036. }
  1037. my $color = [ @{$self->colors->[ $color_idx % scalar(@{$self->colors}) ]} ];
  1038. $color->[3] = $volume->modifier ? 0.5 : 1;
  1039. push @{$self->volumes}, my $v = Slic3r::GUI::3DScene::Volume->new(
  1040. bounding_box => $mesh->bounding_box,
  1041. color => $color,
  1042. );
  1043. if ($self->select_by eq 'object') {
  1044. $v->select_group_id($obj_idx*1000000);
  1045. } elsif ($self->select_by eq 'volume') {
  1046. $v->select_group_id($obj_idx*1000000 + $volume_idx*1000);
  1047. } elsif ($self->select_by eq 'instance') {
  1048. $v->select_group_id($obj_idx*1000000 + $volume_idx*1000 + $instance_idx);
  1049. }
  1050. if ($self->drag_by eq 'object') {
  1051. $v->drag_group_id($obj_idx*1000);
  1052. } elsif ($self->drag_by eq 'instance') {
  1053. $v->drag_group_id($obj_idx*1000 + $instance_idx);
  1054. }
  1055. push @volumes_idx, my $scene_volume_idx = $#{$self->volumes};
  1056. $self->_objects_by_volumes->{$scene_volume_idx} = [ $obj_idx, $volume_idx, $instance_idx ];
  1057. my $verts = Slic3r::GUI::_3DScene::GLVertexArray->new;
  1058. $verts->load_mesh($mesh);
  1059. $v->tverts($verts);
  1060. }
  1061. }
  1062. $self->volumes_by_object->{$obj_idx} = [@volumes_idx];
  1063. return @volumes_idx;
  1064. }
  1065. sub load_print_object_slices {
  1066. my ($self, $object) = @_;
  1067. my @verts = ();
  1068. my @norms = ();
  1069. my @quad_verts = ();
  1070. my @quad_norms = ();
  1071. foreach my $layer (@{$object->layers}) {
  1072. my $gap = 0;
  1073. my $top_z = $layer->print_z;
  1074. my $bottom_z = $layer->print_z - $layer->height + $gap;
  1075. foreach my $copy (@{ $object->_shifted_copies }) {
  1076. {
  1077. my @expolygons = map $_->clone, @{$layer->slices};
  1078. $_->translate(@$copy) for @expolygons;
  1079. $self->_expolygons_to_verts(\@expolygons, $layer->print_z, \@verts, \@norms);
  1080. }
  1081. foreach my $slice (@{$layer->slices}) {
  1082. foreach my $polygon (@$slice) {
  1083. foreach my $line (@{$polygon->lines}) {
  1084. $line->translate(@$copy);
  1085. push @quad_norms, (0,0,-1), (0,0,-1);
  1086. push @quad_verts, (map unscale($_), @{$line->a}), $bottom_z;
  1087. push @quad_verts, (map unscale($_), @{$line->b}), $bottom_z;
  1088. push @quad_norms, (0,0,1), (0,0,1);
  1089. push @quad_verts, (map unscale($_), @{$line->b}), $top_z;
  1090. push @quad_verts, (map unscale($_), @{$line->a}), $top_z;
  1091. # We'll use this for the middle normal when using 4 quads:
  1092. #my $xy_normal = $line->normal;
  1093. #$_xynormal->scale(1/$line->length);
  1094. }
  1095. }
  1096. }
  1097. }
  1098. }
  1099. my $obb = $object->bounding_box;
  1100. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  1101. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$obb->min_point}, 0));
  1102. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$obb->max_point}, $object->size->z));
  1103. push @{$self->volumes}, my $v = Slic3r::GUI::3DScene::Volume->new(
  1104. bounding_box => $bb,
  1105. color => $self->colors->[0],
  1106. verts => OpenGL::Array->new_list(GL_FLOAT, @verts),
  1107. norms => OpenGL::Array->new_list(GL_FLOAT, @norms),
  1108. quad_verts => OpenGL::Array->new_list(GL_FLOAT, @quad_verts),
  1109. quad_norms => OpenGL::Array->new_list(GL_FLOAT, @quad_norms),
  1110. );
  1111. }
  1112. sub load_print_toolpaths {
  1113. my ($self, $print) = @_;
  1114. return if !$print->step_done(STEP_SKIRT);
  1115. return if !$print->step_done(STEP_BRIM);
  1116. return if !$print->has_skirt
  1117. && $print->config->brim_width == 0
  1118. && $print->config->interior_brim_width == 0
  1119. && $print->config->brim_connections_width == 0;
  1120. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  1121. {
  1122. my $pbb = $print->bounding_box;
  1123. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$pbb->min_point}));
  1124. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$pbb->max_point}));
  1125. }
  1126. my $color_by_extruder = $self->color_toolpaths_by eq 'extruder';
  1127. if (!$print->brim->empty) {
  1128. my $color = $color_by_extruder
  1129. ? $self->colors->[ ($print->brim_extruder-1) % @{$self->colors} ]
  1130. : $self->colors->[2];
  1131. push @{$self->volumes}, my $volume = Slic3r::GUI::3DScene::Volume->new(
  1132. bounding_box => $bb,
  1133. color => $color,
  1134. qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1135. tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1136. offsets => {}, # print_z => [ qverts, tverts ]
  1137. );
  1138. my $top_z = $print->get_object(0)->get_layer(0)->print_z;
  1139. $volume->offsets->{$top_z} = [0, 0];
  1140. $self->_extrusionentity_to_verts($print->brim, $top_z, Slic3r::Point->new(0,0),
  1141. $volume->qverts, $volume->tverts);
  1142. }
  1143. if (!$print->skirt->empty) {
  1144. # TODO: it's a bit difficult to predict skirt extruders with the current skirt logic.
  1145. # We need to rewrite it anyway.
  1146. my $color = +($self->default_colors)[0];
  1147. push @{$self->volumes}, my $volume = Slic3r::GUI::3DScene::Volume->new(
  1148. bounding_box => $bb,
  1149. color => $color,
  1150. qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1151. tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1152. offsets => {}, # print_z => [ qverts, tverts ]
  1153. );
  1154. my $skirt_height = 0; # number of layers
  1155. if ($print->has_infinite_skirt) {
  1156. $skirt_height = $print->total_layer_count;
  1157. } else {
  1158. $skirt_height = min($print->config->skirt_height, $print->total_layer_count);
  1159. }
  1160. $skirt_height ||= 1 if $print->config->brim_width > 0 || $print->config->interior_brim_width;
  1161. # get first $skirt_height layers (maybe this should be moved to a PrintObject method?)
  1162. my $object0 = $print->get_object(0);
  1163. my @layers = ();
  1164. push @layers, map $object0->get_layer($_-1), 1..min($skirt_height, $object0->layer_count);
  1165. push @layers, map $object0->get_support_layer($_-1), 1..min($skirt_height, $object0->support_layer_count);
  1166. @layers = sort { $a->print_z <=> $b->print_z } @layers;
  1167. @layers = @layers[0..($skirt_height-1)];
  1168. foreach my $i (0..($skirt_height-1)) {
  1169. my $top_z = $layers[$i]->print_z;
  1170. $volume->offsets->{$top_z} = [$volume->qverts->size, $volume->tverts->size];
  1171. $self->_extrusionentity_to_verts($print->skirt, $top_z, Slic3r::Point->new(0,0),
  1172. $volume->qverts, $volume->tverts);
  1173. }
  1174. }
  1175. }
  1176. sub load_print_object_toolpaths {
  1177. my ($self, $object) = @_;
  1178. # order layers by print_z
  1179. my @layers = sort { $a->print_z <=> $b->print_z }
  1180. @{$object->layers}, @{$object->support_layers};
  1181. # Bounding box of the object and its copies.
  1182. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  1183. {
  1184. my $obb = $object->bounding_box;
  1185. foreach my $copy (@{ $object->_shifted_copies }) {
  1186. my $cbb = $obb->clone;
  1187. $cbb->translate(@$copy);
  1188. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$cbb->min_point}, 0));
  1189. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$cbb->max_point}, $object->size->z));
  1190. }
  1191. }
  1192. my %volumes = (); # color => Volume
  1193. # Maximum size of an allocation block: 32MB / sizeof(float)
  1194. my $alloc_size_max = 32 * 1048576 / 4;
  1195. my $add = sub {
  1196. my ($coll, $top_z, $copy, $color) = @_;
  1197. my $volume = $volumes{$color};
  1198. if (!$volume) {
  1199. push @{$self->volumes}, $volumes{$color} = $volume = Slic3r::GUI::3DScene::Volume->new(
  1200. bounding_box => $bb,
  1201. color => $color,
  1202. qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1203. tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1204. offsets => {}, # print_z => [ qverts, tverts ]
  1205. );
  1206. }
  1207. $volume->offsets->{$top_z} //= [ $volume->qverts->size, $volume->tverts->size ];
  1208. $self->_extrusionentity_to_verts($coll, $top_z, $copy, $volume->qverts, $volume->tverts);
  1209. };
  1210. my $color_by_extruder = $self->color_toolpaths_by eq 'extruder';
  1211. foreach my $layer (@layers) {
  1212. my $top_z = $layer->print_z;
  1213. foreach my $copy (@{ $object->_shifted_copies }) {
  1214. foreach my $layerm (@{$layer->regions}) {
  1215. if ($object->step_done(STEP_PERIMETERS)) {
  1216. my $color = $color_by_extruder
  1217. ? $self->colors->[ ($layerm->region->config->perimeter_extruder-1) % @{$self->colors} ]
  1218. : $self->colors->[0];
  1219. $add->($layerm->perimeters, $top_z, $copy, $color);
  1220. }
  1221. if ($object->step_done(STEP_INFILL)) {
  1222. my $color = $color_by_extruder
  1223. ? $self->colors->[ ($layerm->region->config->infill_extruder-1) % @{$self->colors} ]
  1224. : $self->colors->[1];
  1225. if ($color_by_extruder && $layerm->region->config->infill_extruder != $layerm->region->config->solid_infill_extruder) {
  1226. # divide solid and non-solid infill
  1227. my $solid = Slic3r::ExtrusionPath::Collection->new;
  1228. my $non_solid = Slic3r::ExtrusionPath::Collection->new;
  1229. foreach my $fill (@{$layerm->fills}) {
  1230. if ($fill->[0]->is_solid_infill) {
  1231. $solid->append($fill);
  1232. } else {
  1233. $non_solid->append($fill);
  1234. }
  1235. }
  1236. $add->($non_solid, $top_z, $copy, $color);
  1237. $color = $self->colors->[ ($layerm->region->config->solid_infill_extruder-1) % @{$self->colors} ];
  1238. $add->($solid, $top_z, $copy, $color);
  1239. } else {
  1240. $add->($layerm->fills, $top_z, $copy, $color);
  1241. }
  1242. }
  1243. }
  1244. if ($layer->isa('Slic3r::Layer::Support') && $object->step_done(STEP_SUPPORTMATERIAL)) {
  1245. {
  1246. my $color = $color_by_extruder
  1247. ? $self->colors->[ ($layer->object->config->support_material_extruder-1) % @{$self->colors} ]
  1248. : $self->colors->[2];
  1249. $add->($layer->support_fills, $top_z, $copy, $color);
  1250. }
  1251. {
  1252. my $color = ($color_by_extruder)
  1253. ? $self->colors->[ ($layer->object->config->support_material_interface_extruder-1) % @{$self->colors} ]
  1254. : $self->colors->[2];
  1255. $add->($layer->support_interface_fills, $top_z, $copy, $color);
  1256. }
  1257. }
  1258. }
  1259. foreach my $color (keys %volumes) {
  1260. my $volume = $volumes{$color};
  1261. if ($volume->qverts->size() > $alloc_size_max || $volume->tverts->size() > $alloc_size_max) {
  1262. # stop appending to this volume; create a new one next time
  1263. delete $volumes{$color};
  1264. }
  1265. }
  1266. }
  1267. }
  1268. sub set_toolpaths_range {
  1269. my ($self, $min_z, $max_z) = @_;
  1270. foreach my $volume (@{$self->volumes}) {
  1271. $volume->range([ $min_z, $max_z ]);
  1272. }
  1273. }
  1274. sub _expolygons_to_verts {
  1275. my ($self, $expolygons, $z, $verts, $norms) = @_;
  1276. my $tess = gluNewTess();
  1277. gluTessCallback($tess, GLU_TESS_BEGIN, 'DEFAULT');
  1278. gluTessCallback($tess, GLU_TESS_END, 'DEFAULT');
  1279. gluTessCallback($tess, GLU_TESS_VERTEX, sub {
  1280. my ($x, $y, $z) = @_;
  1281. push @$verts, $x, $y, $z;
  1282. push @$norms, (0,0,1), (0,0,1), (0,0,1);
  1283. });
  1284. gluTessCallback($tess, GLU_TESS_COMBINE, 'DEFAULT');
  1285. gluTessCallback($tess, GLU_TESS_ERROR, 'DEFAULT');
  1286. gluTessCallback($tess, GLU_TESS_EDGE_FLAG, 'DEFAULT');
  1287. foreach my $expolygon (@$expolygons) {
  1288. gluTessBeginPolygon($tess);
  1289. foreach my $polygon (@$expolygon) {
  1290. gluTessBeginContour($tess);
  1291. gluTessVertex_p($tess, (map unscale($_), @$_), $z) for @$polygon;
  1292. gluTessEndContour($tess);
  1293. }
  1294. gluTessEndPolygon($tess);
  1295. }
  1296. gluDeleteTess($tess);
  1297. }
  1298. # Fill in the $qverts and $tverts with quads and triangles
  1299. # for the extrusion $entity.
  1300. sub _extrusionentity_to_verts {
  1301. my ($self, $entity, $top_z, $copy, $qverts, $tverts) = @_;
  1302. my ($lines, $widths, $heights, $closed);
  1303. if ($entity->isa('Slic3r::ExtrusionPath::Collection')) {
  1304. $self->_extrusionentity_to_verts($_, $top_z, $copy, $qverts, $tverts)
  1305. for @$entity;
  1306. return;
  1307. } elsif ($entity->isa('Slic3r::ExtrusionPath')) {
  1308. my $polyline = $entity->polyline->clone;
  1309. $polyline->remove_duplicate_points;
  1310. $polyline->translate(@$copy);
  1311. $lines = $polyline->lines;
  1312. $widths = [ map $entity->width, 0..$#$lines ];
  1313. $heights = [ map $entity->height, 0..$#$lines ];
  1314. $closed = 0;
  1315. } else {
  1316. $lines = [];
  1317. $widths = [];
  1318. $heights = [];
  1319. $closed = 1;
  1320. foreach my $path (@$entity) {
  1321. my $polyline = $path->polyline->clone;
  1322. $polyline->remove_duplicate_points;
  1323. $polyline->translate(@$copy);
  1324. my $path_lines = $polyline->lines;
  1325. push @$lines, @$path_lines;
  1326. push @$widths, map $path->width, 0..$#$path_lines;
  1327. push @$heights, map $path->height, 0..$#$path_lines;
  1328. }
  1329. }
  1330. # Calling the C++ implementation Slic3r::_3DScene::_extrusionentity_to_verts_do()
  1331. # This adds new vertices to the $qverts and $tverts.
  1332. Slic3r::GUI::_3DScene::_extrusionentity_to_verts_do($lines, $widths, $heights,
  1333. $closed,
  1334. # Top height of the extrusion.
  1335. $top_z,
  1336. # $copy is not used here.
  1337. $copy,
  1338. # GLVertexArray object: C++ class maintaining an std::vector<float> for coords and normals.
  1339. $qverts,
  1340. $tverts);
  1341. }
  1342. sub object_idx {
  1343. my ($self, $volume_idx) = @_;
  1344. return $self->_objects_by_volumes->{$volume_idx}[0];
  1345. }
  1346. sub volume_idx {
  1347. my ($self, $volume_idx) = @_;
  1348. return $self->_objects_by_volumes->{$volume_idx}[1];
  1349. }
  1350. sub instance_idx {
  1351. my ($self, $volume_idx) = @_;
  1352. return $self->_objects_by_volumes->{$volume_idx}[2];
  1353. }
  1354. 1;