1 #include "libslic3r/libslic3r.h"
2
3 #include "3DBed.hpp"
4
5 #include "libslic3r/Polygon.hpp"
6 #include "libslic3r/ClipperUtils.hpp"
7 #include "libslic3r/BoundingBox.hpp"
8 #include "libslic3r/Geometry.hpp"
9
10 #include "GUI_App.hpp"
11 #include "libslic3r/PresetBundle.hpp"
12 #include "GLCanvas3D.hpp"
13 #include "3DScene.hpp"
14
15 #include <GL/glew.h>
16
17 #include <boost/algorithm/string/predicate.hpp>
18 #include <boost/filesystem/operations.hpp>
19 #include <boost/log/trivial.hpp>
20
21 static const float GROUND_Z = -0.02f;
22
23 namespace Slic3r {
24 namespace GUI {
25
set_from_triangles(const Polygons & triangles,float z,bool generate_tex_coords)26 bool GeometryBuffer::set_from_triangles(const Polygons& triangles, float z, bool generate_tex_coords)
27 {
28 m_vertices.clear();
29 unsigned int v_size = 3 * (unsigned int)triangles.size();
30
31 if (v_size == 0)
32 return false;
33
34 m_vertices = std::vector<Vertex>(v_size, Vertex());
35
36 float min_x = unscale<float>(triangles[0].points[0](0));
37 float min_y = unscale<float>(triangles[0].points[0](1));
38 float max_x = min_x;
39 float max_y = min_y;
40
41 unsigned int v_count = 0;
42 for (const Polygon& t : triangles) {
43 for (unsigned int i = 0; i < 3; ++i) {
44 Vertex& v = m_vertices[v_count];
45
46 const Point& p = t.points[i];
47 float x = unscale<float>(p(0));
48 float y = unscale<float>(p(1));
49
50 v.position[0] = x;
51 v.position[1] = y;
52 v.position[2] = z;
53
54 if (generate_tex_coords) {
55 v.tex_coords[0] = x;
56 v.tex_coords[1] = y;
57
58 min_x = std::min(min_x, x);
59 max_x = std::max(max_x, x);
60 min_y = std::min(min_y, y);
61 max_y = std::max(max_y, y);
62 }
63
64 ++v_count;
65 }
66 }
67
68 if (generate_tex_coords) {
69 float size_x = max_x - min_x;
70 float size_y = max_y - min_y;
71
72 if ((size_x != 0.0f) && (size_y != 0.0f)) {
73 float inv_size_x = 1.0f / size_x;
74 float inv_size_y = -1.0f / size_y;
75 for (Vertex& v : m_vertices) {
76 v.tex_coords[0] = (v.tex_coords[0] - min_x) * inv_size_x;
77 v.tex_coords[1] = (v.tex_coords[1] - min_y) * inv_size_y;
78 }
79 }
80 }
81
82 return true;
83 }
84
set_from_lines(const Lines & lines,float z)85 bool GeometryBuffer::set_from_lines(const Lines& lines, float z)
86 {
87 m_vertices.clear();
88
89 unsigned int v_size = 2 * (unsigned int)lines.size();
90 if (v_size == 0)
91 return false;
92
93 m_vertices = std::vector<Vertex>(v_size, Vertex());
94
95 unsigned int v_count = 0;
96 for (const Line& l : lines) {
97 Vertex& v1 = m_vertices[v_count];
98 v1.position[0] = unscale<float>(l.a(0));
99 v1.position[1] = unscale<float>(l.a(1));
100 v1.position[2] = z;
101 ++v_count;
102
103 Vertex& v2 = m_vertices[v_count];
104 v2.position[0] = unscale<float>(l.b(0));
105 v2.position[1] = unscale<float>(l.b(1));
106 v2.position[2] = z;
107 ++v_count;
108 }
109
110 return true;
111 }
112
get_vertices_data() const113 const float* GeometryBuffer::get_vertices_data() const
114 {
115 return (m_vertices.size() > 0) ? (const float*)m_vertices.data() : nullptr;
116 }
117
118 const float Bed3D::Axes::DefaultStemRadius = 0.5f;
119 const float Bed3D::Axes::DefaultStemLength = 25.0f;
120 const float Bed3D::Axes::DefaultTipRadius = 2.5f * Bed3D::Axes::DefaultStemRadius;
121 const float Bed3D::Axes::DefaultTipLength = 5.0f;
122
set_stem_length(float length)123 void Bed3D::Axes::set_stem_length(float length)
124 {
125 m_stem_length = length;
126 m_arrow.reset();
127 }
128
render() const129 void Bed3D::Axes::render() const
130 {
131 auto render_axis = [this](const Transform3f& transform) {
132 glsafe(::glPushMatrix());
133 glsafe(::glMultMatrixf(transform.data()));
134 m_arrow.render();
135 glsafe(::glPopMatrix());
136 };
137
138 m_arrow.init_from(stilized_arrow(16, DefaultTipRadius, DefaultTipLength, DefaultStemRadius, m_stem_length));
139
140 GLShaderProgram* shader = wxGetApp().get_shader("gouraud_light");
141 if (shader == nullptr)
142 return;
143
144 glsafe(::glEnable(GL_DEPTH_TEST));
145
146 shader->start_using();
147
148 // x axis
149 std::array<float, 4> color = { 0.75f, 0.0f, 0.0f, 1.0f };
150 shader->set_uniform("uniform_color", color);
151 render_axis(Geometry::assemble_transform(m_origin, { 0.0, 0.5 * M_PI, 0.0f }).cast<float>());
152
153 // y axis
154 color = { 0.0f, 0.75f, 0.0f, 1.0f };
155 shader->set_uniform("uniform_color", color);
156 render_axis(Geometry::assemble_transform(m_origin, { -0.5 * M_PI, 0.0, 0.0f }).cast<float>());
157
158 // z axis
159 color = { 0.0f, 0.0f, 0.75f, 1.0f };
160 shader->set_uniform("uniform_color", color);
161 render_axis(Geometry::assemble_transform(m_origin).cast<float>());
162
163 shader->stop_using();
164
165 glsafe(::glDisable(GL_DEPTH_TEST));
166 }
167
Bed3D()168 Bed3D::Bed3D()
169 : m_type(Custom)
170 , m_vbo_id(0)
171 , m_scale_factor(1.0f)
172 {
173 }
174
set_shape(const Pointfs & shape,const std::string & custom_texture,const std::string & custom_model,bool force_as_custom)175 bool Bed3D::set_shape(const Pointfs& shape, const std::string& custom_texture, const std::string& custom_model, bool force_as_custom)
176 {
177 auto check_texture = [](const std::string& texture) {
178 return !texture.empty() && (boost::algorithm::iends_with(texture, ".png") || boost::algorithm::iends_with(texture, ".svg")) && boost::filesystem::exists(texture);
179 };
180
181 auto check_model = [](const std::string& model) {
182 return !model.empty() && boost::algorithm::iends_with(model, ".stl") && boost::filesystem::exists(model);
183 };
184
185 EType type;
186 std::string model;
187 std::string texture;
188 if (force_as_custom)
189 type = Custom;
190 else {
191 auto [new_type, system_model, system_texture] = detect_type(shape);
192 type = new_type;
193 model = system_model;
194 texture = system_texture;
195 }
196
197 std::string texture_filename = custom_texture.empty() ? texture : custom_texture;
198 if (!check_texture(texture_filename))
199 texture_filename.clear();
200
201 std::string model_filename = custom_model.empty() ? model : custom_model;
202 if (!check_model(model_filename))
203 model_filename.clear();
204
205 if (m_shape == shape && m_type == type && m_texture_filename == texture_filename && m_model_filename == model_filename)
206 // No change, no need to update the UI.
207 return false;
208
209 m_shape = shape;
210 m_texture_filename = texture_filename;
211 m_model_filename = model_filename;
212 m_type = type;
213
214 calc_bounding_boxes();
215
216 ExPolygon poly;
217 for (const Vec2d& p : m_shape) {
218 poly.contour.append(Point(scale_(p(0)), scale_(p(1))));
219 }
220
221 calc_triangles(poly);
222
223 const BoundingBox& bed_bbox = poly.contour.bounding_box();
224 calc_gridlines(poly, bed_bbox);
225
226 m_polygon = offset_ex(poly.contour, (float)bed_bbox.radius() * 1.7f, jtRound, scale_(0.5))[0].contour;
227
228 reset();
229 m_texture.reset();
230 m_model.reset();
231
232 // Set the origin and size for rendering the coordinate system axes.
233 m_axes.set_origin({ 0.0, 0.0, static_cast<double>(GROUND_Z) });
234 m_axes.set_stem_length(0.1f * static_cast<float>(m_bounding_box.max_size()));
235
236 // Let the calee to update the UI.
237 return true;
238 }
239
contains(const Point & point) const240 bool Bed3D::contains(const Point& point) const
241 {
242 return m_polygon.contains(point);
243 }
244
point_projection(const Point & point) const245 Point Bed3D::point_projection(const Point& point) const
246 {
247 return m_polygon.point_projection(point);
248 }
249
render(GLCanvas3D & canvas,bool bottom,float scale_factor,bool show_axes,bool show_texture) const250 void Bed3D::render(GLCanvas3D& canvas, bool bottom, float scale_factor,
251 bool show_axes, bool show_texture) const
252 {
253 m_scale_factor = scale_factor;
254
255 if (show_axes)
256 render_axes();
257
258 glsafe(::glEnable(GL_DEPTH_TEST));
259
260 switch (m_type)
261 {
262 case System: { render_system(canvas, bottom, show_texture); break; }
263 default:
264 case Custom: { render_custom(canvas, bottom, show_texture); break; }
265 }
266
267 glsafe(::glDisable(GL_DEPTH_TEST));
268 }
269
calc_bounding_boxes() const270 void Bed3D::calc_bounding_boxes() const
271 {
272 m_bounding_box = BoundingBoxf3();
273 for (const Vec2d& p : m_shape) {
274 m_bounding_box.merge(Vec3d(p(0), p(1), 0.0));
275 }
276
277 m_extended_bounding_box = m_bounding_box;
278
279 // extend to contain axes
280 m_extended_bounding_box.merge(m_axes.get_origin() + m_axes.get_total_length() * Vec3d::Ones());
281 m_extended_bounding_box.merge(m_extended_bounding_box.min + Vec3d(-Axes::DefaultTipRadius, -Axes::DefaultTipRadius, m_extended_bounding_box.max(2)));
282
283 // extend to contain model, if any
284 BoundingBoxf3 model_bb = m_model.get_bounding_box();
285 if (model_bb.defined) {
286 model_bb.translate(m_model_offset);
287 m_extended_bounding_box.merge(model_bb);
288 }
289 }
290
calc_triangles(const ExPolygon & poly)291 void Bed3D::calc_triangles(const ExPolygon& poly)
292 {
293 Polygons triangles;
294 poly.triangulate_p2t(&triangles);
295
296 if (!m_triangles.set_from_triangles(triangles, GROUND_Z, true))
297 printf("Unable to create bed triangles\n");
298 }
299
calc_gridlines(const ExPolygon & poly,const BoundingBox & bed_bbox)300 void Bed3D::calc_gridlines(const ExPolygon& poly, const BoundingBox& bed_bbox)
301 {
302 Polylines axes_lines;
303 for (coord_t x = bed_bbox.min(0); x <= bed_bbox.max(0); x += scale_(10.0)) {
304 Polyline line;
305 line.append(Point(x, bed_bbox.min(1)));
306 line.append(Point(x, bed_bbox.max(1)));
307 axes_lines.push_back(line);
308 }
309 for (coord_t y = bed_bbox.min(1); y <= bed_bbox.max(1); y += scale_(10.0)) {
310 Polyline line;
311 line.append(Point(bed_bbox.min(0), y));
312 line.append(Point(bed_bbox.max(0), y));
313 axes_lines.push_back(line);
314 }
315
316 // clip with a slightly grown expolygon because our lines lay on the contours and may get erroneously clipped
317 Lines gridlines = to_lines(intersection_pl(axes_lines, offset(poly, (float)SCALED_EPSILON)));
318
319 // append bed contours
320 Lines contour_lines = to_lines(poly);
321 std::copy(contour_lines.begin(), contour_lines.end(), std::back_inserter(gridlines));
322
323 if (!m_gridlines.set_from_lines(gridlines, GROUND_Z))
324 printf("Unable to create bed grid lines\n");
325 }
326
327
detect_type(const Pointfs & shape) const328 std::tuple<Bed3D::EType, std::string, std::string> Bed3D::detect_type(const Pointfs& shape) const
329 {
330 auto bundle = wxGetApp().preset_bundle;
331 if (bundle != nullptr) {
332 const Preset* curr = &bundle->printers.get_selected_preset();
333 while (curr != nullptr) {
334 if (curr->config.has("bed_shape")) {
335 if (shape == dynamic_cast<const ConfigOptionPoints*>(curr->config.option("bed_shape"))->values) {
336 std::string model_filename = PresetUtils::system_printer_bed_model(*curr);
337 std::string texture_filename = PresetUtils::system_printer_bed_texture(*curr);
338 if (!model_filename.empty() && !texture_filename.empty())
339 return { System, model_filename, texture_filename };
340 }
341 }
342
343 curr = bundle->printers.get_preset_parent(*curr);
344 }
345 }
346
347 return { Custom, "", "" };
348 }
349
render_axes() const350 void Bed3D::render_axes() const
351 {
352 if (!m_shape.empty())
353 m_axes.render();
354 }
355
render_system(GLCanvas3D & canvas,bool bottom,bool show_texture) const356 void Bed3D::render_system(GLCanvas3D& canvas, bool bottom, bool show_texture) const
357 {
358 if (!bottom)
359 render_model();
360
361 if (show_texture)
362 render_texture(bottom, canvas);
363 }
364
render_texture(bool bottom,GLCanvas3D & canvas) const365 void Bed3D::render_texture(bool bottom, GLCanvas3D& canvas) const
366 {
367 if (m_texture_filename.empty()) {
368 m_texture.reset();
369 render_default(bottom);
370 return;
371 }
372
373 if ((m_texture.get_id() == 0) || (m_texture.get_source() != m_texture_filename)) {
374 m_texture.reset();
375
376 if (boost::algorithm::iends_with(m_texture_filename, ".svg")) {
377 // use higher resolution images if graphic card and opengl version allow
378 GLint max_tex_size = OpenGLManager::get_gl_info().get_max_tex_size();
379 if ((m_temp_texture.get_id() == 0) || (m_temp_texture.get_source() != m_texture_filename)) {
380 // generate a temporary lower resolution texture to show while no main texture levels have been compressed
381 if (!m_temp_texture.load_from_svg_file(m_texture_filename, false, false, false, max_tex_size / 8)) {
382 render_default(bottom);
383 return;
384 }
385 canvas.request_extra_frame();
386 }
387
388 // starts generating the main texture, compression will run asynchronously
389 if (!m_texture.load_from_svg_file(m_texture_filename, true, true, true, max_tex_size)) {
390 render_default(bottom);
391 return;
392 }
393 }
394 else if (boost::algorithm::iends_with(m_texture_filename, ".png")) {
395 // generate a temporary lower resolution texture to show while no main texture levels have been compressed
396 if ((m_temp_texture.get_id() == 0) || (m_temp_texture.get_source() != m_texture_filename)) {
397 if (!m_temp_texture.load_from_file(m_texture_filename, false, GLTexture::None, false)) {
398 render_default(bottom);
399 return;
400 }
401 canvas.request_extra_frame();
402 }
403
404 // starts generating the main texture, compression will run asynchronously
405 if (!m_texture.load_from_file(m_texture_filename, true, GLTexture::MultiThreaded, true)) {
406 render_default(bottom);
407 return;
408 }
409 }
410 else {
411 render_default(bottom);
412 return;
413 }
414 }
415 else if (m_texture.unsent_compressed_data_available()) {
416 // sends to gpu the already available compressed levels of the main texture
417 m_texture.send_compressed_data_to_gpu();
418
419 // the temporary texture is not needed anymore, reset it
420 if (m_temp_texture.get_id() != 0)
421 m_temp_texture.reset();
422
423 canvas.request_extra_frame();
424
425 }
426
427 if (m_triangles.get_vertices_count() > 0) {
428 GLShaderProgram* shader = wxGetApp().get_shader("printbed");
429 if (shader != nullptr) {
430 shader->start_using();
431 shader->set_uniform("transparent_background", bottom);
432 shader->set_uniform("svg_source", boost::algorithm::iends_with(m_texture.get_source(), ".svg"));
433
434 if (m_vbo_id == 0) {
435 glsafe(::glGenBuffers(1, &m_vbo_id));
436 glsafe(::glBindBuffer(GL_ARRAY_BUFFER, m_vbo_id));
437 glsafe(::glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)m_triangles.get_vertices_data_size(), (const GLvoid*)m_triangles.get_vertices_data(), GL_STATIC_DRAW));
438 glsafe(::glBindBuffer(GL_ARRAY_BUFFER, 0));
439 }
440
441 glsafe(::glEnable(GL_DEPTH_TEST));
442 glsafe(::glDepthMask(GL_FALSE));
443
444 glsafe(::glEnable(GL_BLEND));
445 glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
446
447 if (bottom)
448 glsafe(::glFrontFace(GL_CW));
449
450 unsigned int stride = m_triangles.get_vertex_data_size();
451
452 GLint position_id = shader->get_attrib_location("v_position");
453 GLint tex_coords_id = shader->get_attrib_location("v_tex_coords");
454
455 // show the temporary texture while no compressed data is available
456 GLuint tex_id = (GLuint)m_temp_texture.get_id();
457 if (tex_id == 0)
458 tex_id = (GLuint)m_texture.get_id();
459
460 glsafe(::glBindTexture(GL_TEXTURE_2D, tex_id));
461 glsafe(::glBindBuffer(GL_ARRAY_BUFFER, m_vbo_id));
462
463 if (position_id != -1) {
464 glsafe(::glEnableVertexAttribArray(position_id));
465 glsafe(::glVertexAttribPointer(position_id, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)(intptr_t)m_triangles.get_position_offset()));
466 }
467 if (tex_coords_id != -1) {
468 glsafe(::glEnableVertexAttribArray(tex_coords_id));
469 glsafe(::glVertexAttribPointer(tex_coords_id, 2, GL_FLOAT, GL_FALSE, stride, (GLvoid*)(intptr_t)m_triangles.get_tex_coords_offset()));
470 }
471
472 glsafe(::glDrawArrays(GL_TRIANGLES, 0, (GLsizei)m_triangles.get_vertices_count()));
473
474 if (tex_coords_id != -1)
475 glsafe(::glDisableVertexAttribArray(tex_coords_id));
476
477 if (position_id != -1)
478 glsafe(::glDisableVertexAttribArray(position_id));
479
480 glsafe(::glBindBuffer(GL_ARRAY_BUFFER, 0));
481 glsafe(::glBindTexture(GL_TEXTURE_2D, 0));
482
483 if (bottom)
484 glsafe(::glFrontFace(GL_CCW));
485
486 glsafe(::glDisable(GL_BLEND));
487 glsafe(::glDepthMask(GL_TRUE));
488
489 shader->stop_using();
490 }
491 }
492 }
493
render_model() const494 void Bed3D::render_model() const
495 {
496 if (m_model_filename.empty())
497 return;
498
499 if ((m_model.get_filename() != m_model_filename) && m_model.init_from_file(m_model_filename)) {
500 // move the model so that its origin (0.0, 0.0, 0.0) goes into the bed shape center and a bit down to avoid z-fighting with the texture quad
501 Vec3d shift = m_bounding_box.center();
502 shift(2) = -0.03;
503 m_model_offset = shift;
504
505 // update extended bounding box
506 calc_bounding_boxes();
507 }
508
509 if (!m_model.get_filename().empty()) {
510 GLShaderProgram* shader = wxGetApp().get_shader("gouraud_light");
511 if (shader != nullptr) {
512 shader->start_using();
513 shader->set_uniform("uniform_color", m_model_color);
514 ::glPushMatrix();
515 ::glTranslated(m_model_offset(0), m_model_offset(1), m_model_offset(2));
516 m_model.render();
517 ::glPopMatrix();
518 shader->stop_using();
519 }
520 }
521 }
522
render_custom(GLCanvas3D & canvas,bool bottom,bool show_texture) const523 void Bed3D::render_custom(GLCanvas3D& canvas, bool bottom, bool show_texture) const
524 {
525 if (m_texture_filename.empty() && m_model_filename.empty()) {
526 render_default(bottom);
527 return;
528 }
529
530 if (!bottom)
531 render_model();
532
533 if (show_texture)
534 render_texture(bottom, canvas);
535 }
536
render_default(bool bottom) const537 void Bed3D::render_default(bool bottom) const
538 {
539 m_texture.reset();
540
541 unsigned int triangles_vcount = m_triangles.get_vertices_count();
542 if (triangles_vcount > 0) {
543 bool has_model = !m_model.get_filename().empty();
544
545 glsafe(::glEnable(GL_DEPTH_TEST));
546 glsafe(::glEnable(GL_BLEND));
547 glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
548
549 glsafe(::glEnableClientState(GL_VERTEX_ARRAY));
550
551 if (!has_model && !bottom) {
552 // draw background
553 glsafe(::glDepthMask(GL_FALSE));
554 glsafe(::glColor4fv(m_model_color.data()));
555 glsafe(::glNormal3d(0.0f, 0.0f, 1.0f));
556 glsafe(::glVertexPointer(3, GL_FLOAT, m_triangles.get_vertex_data_size(), (GLvoid*)m_triangles.get_vertices_data()));
557 glsafe(::glDrawArrays(GL_TRIANGLES, 0, (GLsizei)triangles_vcount));
558 glsafe(::glDepthMask(GL_TRUE));
559 }
560
561 // draw grid
562 glsafe(::glLineWidth(1.5f * m_scale_factor));
563 if (has_model && !bottom)
564 glsafe(::glColor4f(0.9f, 0.9f, 0.9f, 1.0f));
565 else
566 glsafe(::glColor4f(0.9f, 0.9f, 0.9f, 0.6f));
567 glsafe(::glVertexPointer(3, GL_FLOAT, m_triangles.get_vertex_data_size(), (GLvoid*)m_gridlines.get_vertices_data()));
568 glsafe(::glDrawArrays(GL_LINES, 0, (GLsizei)m_gridlines.get_vertices_count()));
569
570 glsafe(::glDisableClientState(GL_VERTEX_ARRAY));
571
572 glsafe(::glDisable(GL_BLEND));
573 }
574 }
575
reset()576 void Bed3D::reset()
577 {
578 if (m_vbo_id > 0) {
579 glsafe(::glDeleteBuffers(1, &m_vbo_id));
580 m_vbo_id = 0;
581 }
582 }
583
584 } // GUI
585 } // Slic3r
586