diff --git a/docs/HLSD/gcode-preview-dragging.md b/docs/HLSD/gcode-preview-dragging.md new file mode 100644 index 0000000000..b3ee633f36 --- /dev/null +++ b/docs/HLSD/gcode-preview-dragging.md @@ -0,0 +1,147 @@ +# G-code preview while dragging + +The sliced preview draws every toolpath segment of the plate as an instanced box. On a large +plate that is tens of millions of segments, and the frame is GPU-bound: the cost is the number of +instances drawn, not anything the CPU does per frame. Dragging the camera over such a plate cannot +keep up. The `preview_reduced_detail_mode` preference (*Graphics > G-code Preview*, off by +default) lets the preview draw less while the user drags and put the full toolpaths back when they +let go. + +| Preference | Values | Effect | +|---|---|---| +| `preview_reduced_detail_mode` | `off`, `solid`, `shell` | what is drawn while dragging | + +libvgcode (`src/libvgcode`) builds and binds the reduced toolpath set, `GCodeViewer` maps the +preference onto it and draws the solid model, and `GLCanvas3D` decides when the user is dragging. +The OpenGL ES path keeps a single set and ignores the preference. + +## Two sets, one walk + +`ViewerImpl::update_enabled_entities()` walks the visible vertex range once and fills two segment +index buffers side by side: the **full** set and the **reduced** set (segments and options). +Building them together is what makes switching free: starting or ending a drag is a buffer +binding, never a rebuild. A change of mode does rebuild. Nothing is built while the mode +is off, and the reduced buffers are then uploaded empty so that the last set does not stay +allocated. + +Whatever the mode leaves out, the layers at the bottom and top of the visible range are kept whole: +they are the faces the range cuts open, and the top is what the user is looking at. An end layer +with no infill of its own does not close the print there: infill combination prints the sparse +infill of a few layers in one, leaving the others walls alone, and a support layer with no object +layer at its height gets a layer of its own. Each end therefore runs from the range's end layer to +the nearest layer that closes the print, at most eight layers deep +(`Layers::get_whole_end_layers()`), and the `Viewer` reports the two bands so that the solid +model's cut can sit at their edges. A layer closes the print when every object printed on it has +infill on it: the G-code labels its moves with their object, and `LayersClosedByInfill` in the +wrapper that feeds libvgcode tallies walls and infill per object and layer while converting the +moves (`GCodeInputData::layers_closed`). Two objects on one plate rarely combine their infill on +the same layers, and one object's sparse infill on a layer says nothing about another's, which is +why the judgement is per object. Without that list, as for a preview built from the `Print`, the +layer table judges each layer from its roles as a whole: the nearest layer with sparse infill, and +only when none is within reach, as on a print with none, the nearest layer with any infill. + +The realistic view's shadow-caster pass draws whichever set is bound, so the key of the static +shadow map includes whether the reduced set is: a map built during a drag is rebuilt on release. +In the solid model mode the shells, cut at the solid's heights, cast into the same map through +`GCodeViewer::render_solid_model_casters()`, with their cut faces: without them an open body lets +the light through, onto the bed through a band cut at both ends or onto its own far wall past the +end band's lines. The cut faces are counted and drawn as the visible pass draws them (below), which +takes a stencil the map has not got, so they go into a depth and stencil target of the viewer's, +the map's size, and are copied into the map by the `depth_copy` shader where nearer than what it +holds. The solid samples the map back under the light +the canvas passed on, so a body shades the plate, its neighbours and the end-band toolpaths as the +toolpaths it stands in for would, and takes their shadows in turn. +With the mode off the reduced flag is never raised, and a drag changes nothing in the preview. + +### Modes + +- `EndLayersOnly` (`solid` in the preference) keeps only the end bands, the supports and the + travels. + `GCodeViewer` then draws the sliced objects and the prime tower as opaque solids, see below. +- `ShellOnly` (`shell`) keeps every role but the sparse infill, internal solid infill, internal + bridge infill and gap fill, which lie under the skins or between the walls. Walls, top and + bottom surfaces, bridges, supports and the prime tower are drawn whole, so from outside the + print looks as it does at rest. The roles come from + the slicer, so the classification is exact wherever the slicer's is; what it cannot express is + the inside of the prime tower and of a support, which share one role with their outside and are + kept whole. A profile with no top or bottom shell layers, or no walls, leaves the infill on the + surface, so `GCodeViewer` turns the hiding off for such a print when it loads it, from the + print's default region settings; per-object overrides are not consulted. + +## The solid model + +The preview already loads the sliced objects as shells for its translucent ghost. +`GCodeViewer::render_solid_model()` draws those shells opaque with the +`gouraud` shader, whose z range cuts them to the visible layer range: from the top of the bottom +band to the bottom of the top band, since those layers are drawn as toolpaths and a face of the +model in either plane would flicker against them. The translucent ghost is +drawn first, as in every other mode, so the part above the cut stays visible while dragging. The +cut itself is capped, one cap of one body at a time: a pass counts, per pixel and with the depth +test off, the body's back faces less its front faces into the stencil buffer, with the body cut +at that cap alone and whole at its other end, which is zero where the ray misses the body or +crosses it whole and one where it leaves through the opening, that is, where the cap plane lies +inside the body; a quad in that cut plane, in the cap's colour darkened, is drawn where it is not +zero. The count runs with depth clamping on, since the light's frustum ends at the highest +visible layer: a part above the range, cut by its near plane, would keep only its far faces and +count as open, and cast a cap-shaped shadow of itself. Counting both cuts in one pass would see an open tube: a ray through both openings as closed +and one in through a wall and out through the other opening as open, with the cap drawn in the +air. Between the lines of a sparse layer on the cut, that quad is what shows, rather than the +first layer or the bed far below moving with the camera. The toolpath layers of the reduced set are +drawn afterwards and cap the cut with what was really printed there; the band's reach to a layer +with infill is what puts real infill lines, not a bare cap, inside the walls. The shells hold only the objects, so while this mode is on the prime tower is added from its sliced +mesh, positioned as the print placed it. It is added or removed on its own when the mode changes, +without reloading the objects, keeps its opaque color so that it never appears among the +translucent shells, and stays out of their bounding box. Supports have no mesh, so the reduced set +keeps their toolpaths whole on every layer, as the shell mode does, and the objects stand on them +as they do at rest; the travels, which the solid does not stand for either, are kept with them when +the legend shows them. `libvgcode::keep_in_reduced_set()` holds the rule for both modes. `load_shells()` drops every non-model-part volume, so a negative volume is not +cut out. + +The solid stands in for the toolpaths, so it wears their colours. In the views that colour by +filament (Summary, Filament, Tool) each body keeps the filament colour its shell was loaded with. +In every other view `GCodeViewer::update_solid_model_colors()` samples the toolpaths through +`Viewer::get_vertex_color()`: the body takes the outer wall's colour over the layers the solid +stands for, each cap the infill's in the layer it is cut under, sparse infill before solid, and +the prime tower its own role's. One vertex stands for the role, chosen by +`Viewer::find_extrusion_vertex()`: in a view that grades the toolpaths by a value, the +length-weighted median of that value over the role's extrusions in up to eight layers spread over +the interval, so that neither the acceleration ramp a wall starts on nor one layer with the fan +turned up sets the colour of the whole body; in any other view the first extrusion found. The +colours are resolved when a drag starts and when the view type or the bands change, not per frame. + +A plate whose shells are not loaded keeps drawing toolpaths, since the solid model would leave +only the end bands. So does a print whose layers do not rise in height from one to the next, as +when it is printed object by object: the cut is a single height range for the whole plate, which +the ends of the layer range then do not bound. And so does a belt printer's: its layers are planes +tilted at the belt angle, with heights in the G-code's frame, which no horizontal cut follows. + +A section view cuts the solid by its plane as it cuts the toolpaths, and the section face is one +more cap, counted on the body cut by that plane alone and drawn between the two heights. + +The solid is drawn opaque whatever the filaments' alpha: a translucent filament shows its toolpaths +inside through the walls at rest, and the solid has no inside to show. + +## Deciding that the user is dragging + +`GLCanvas3D::_update_preview_interaction()` runs at the top of every preview frame, before the +canvas decides whether to reuse its cached scene, so that the switch lands in that frame. Dragging +is `GLCanvas3D::is_user_interacting()`, the same answer the scene cache reads: the camera, the +navigator, a gizmo, the rectangle selection or either slider being held, or the camera still +turning after a click on a navigator face, which the navigator animates over the frames that +follow with no button held. A slider reports this from +ImGui's active id rather than its dirty flag, which is raised and consumed inside one frame. A +wheel step has no duration, so it holds the reduced set for a 150 ms settle time instead, and the +frame that restores the toolpaths is scheduled for when that time runs out, since the render timer +only wakes the idle loop. A drag cut short by focus or capture loss is ended explicitly, and a +button release wakes the idle loop, because on some platforms nothing else would until the next +input. + +## Reused scene frames + +`GLCanvas3D` keeps its last scene pass for frames that only rebuild the overlay (`SceneCache`). Its +key covers the canvas size, the camera and hover state, not what the toolpath sets draw, so a frame +that reuses the scene must never be one on which the set is switched. +`_update_preview_interaction()` therefore reports whether the bound set changed, and a frame on +which it did redraws the scene. The canvas neither captures nor reuses the scene while the user +drags, so no reduced frame outlives a drag, and the frame that ends a wheel's settle time is +requested as a full frame. diff --git a/resources/shaders/110/depth_copy.fs b/resources/shaders/110/depth_copy.fs new file mode 100644 index 0000000000..15be66cedf --- /dev/null +++ b/resources/shaders/110/depth_copy.fs @@ -0,0 +1,16 @@ +#version 110 + +// Copies a depth texture of the target's size into the bound depth buffer, where nearer than what +// it holds under the depth test; texels left at the far plane are skipped. + +uniform sampler2D depth_texture; +uniform vec2 map_size; + +void main() +{ + float depth = texture2D(depth_texture, gl_FragCoord.xy / map_size).r; + if (depth >= 1.0) + discard; + gl_FragDepth = depth; + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); +} diff --git a/resources/shaders/110/depth_copy.vs b/resources/shaders/110/depth_copy.vs new file mode 100644 index 0000000000..45dfcc1927 --- /dev/null +++ b/resources/shaders/110/depth_copy.vs @@ -0,0 +1,10 @@ +#version 110 + +// A quad over the whole target, given in clip space; see depth_copy.fs. + +attribute vec3 v_position; + +void main() +{ + gl_Position = vec4(v_position.xy, 0.0, 1.0); +} diff --git a/resources/shaders/140/depth_copy.fs b/resources/shaders/140/depth_copy.fs new file mode 100644 index 0000000000..680a017bf5 --- /dev/null +++ b/resources/shaders/140/depth_copy.fs @@ -0,0 +1,18 @@ +#version 140 + +// Copies a depth texture of the target's size into the bound depth buffer, where nearer than what +// it holds under the depth test; texels left at the far plane are skipped. + +uniform sampler2D depth_texture; +uniform vec2 map_size; + +out vec4 out_color; + +void main() +{ + float depth = texture(depth_texture, gl_FragCoord.xy / map_size).r; + if (depth >= 1.0) + discard; + gl_FragDepth = depth; + out_color = vec4(0.0, 0.0, 0.0, 1.0); +} diff --git a/resources/shaders/140/depth_copy.vs b/resources/shaders/140/depth_copy.vs new file mode 100644 index 0000000000..be77a63966 --- /dev/null +++ b/resources/shaders/140/depth_copy.vs @@ -0,0 +1,10 @@ +#version 140 + +// A quad over the whole target, given in clip space; see depth_copy.fs. + +in vec3 v_position; + +void main() +{ + gl_Position = vec4(v_position.xy, 0.0, 1.0); +} diff --git a/src/libslic3r/AppConfig.cpp b/src/libslic3r/AppConfig.cpp index 4d560c12ca..19142e3d97 100644 --- a/src/libslic3r/AppConfig.cpp +++ b/src/libslic3r/AppConfig.cpp @@ -224,6 +224,13 @@ void AppConfig::set_defaults() if (get("seq_top_layer_only").empty()) set("seq_top_layer_only", "1"); + // what the preview draws while the user drags it + { + const std::string mode = get("preview_reduced_detail_mode"); + if (mode != "off" && mode != "solid" && mode != "shell") + set("preview_reduced_detail_mode", "off"); + } + // ORCA: darken the layers the preview layer slider is not scrubbed to if (get("preview_dim_previous_layers").empty()) set_bool("preview_dim_previous_layers", false); diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 1a5e8965a1..6c0a770069 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -238,11 +238,15 @@ static float acceleration_time_from_distance(float initial_feedrate, float dista return (acceleration != 0.0f) ? (speed_from_distance(initial_feedrate, distance, acceleration) - initial_feedrate) / acceleration : 0.0f; } +// The id after the last "id:", so that a colon in the object's name is not read as the separator: +// "; printing object id: copy " and "; start printing object, unique label id: ". static int get_object_label_id(const std::string_view comment_1) { std::string comment(comment_1); - auto pos = comment.find(":"); - std::string num_str = comment.substr(pos + 1); + auto pos = comment.rfind("id:"); + if (pos == std::string::npos) + return -1; + std::string num_str = comment.substr(pos + 3); int id = -1; try { id = stoi(num_str); @@ -4436,7 +4440,10 @@ void GCodeProcessor::process_tags(const std::string_view comment, bool producers } // ; OBJECT_ID start - if (boost::starts_with(comment, " start printing object")) { + // Every printer labels its objects as "; printing object id: copy "; a Bambu + // printer follows it with "; start printing object, unique label id: ", whose id is the + // instance's and wins. The stop line reads " stop printing object" in both styles. + if (boost::starts_with(comment, " start printing object") || boost::starts_with(comment, " printing object")) { m_object_label_id = get_object_label_id(comment); return; } diff --git a/src/libvgcode/include/GCodeInputData.hpp b/src/libvgcode/include/GCodeInputData.hpp index e9b0983dde..a6b5685678 100644 --- a/src/libvgcode/include/GCodeInputData.hpp +++ b/src/libvgcode/include/GCodeInputData.hpp @@ -6,6 +6,7 @@ #define VGCODE_GCODEINPUTDATA_HPP #include "PathVertex.hpp" +#include #include #include "Types.hpp" @@ -31,6 +32,16 @@ struct GCodeInputData // Palette for color print colors // PaletteWithAlpha color_print_colors; + // + // Optional, one entry per layer: whether the layer's infill closes every object printed on + // it, so that the end bands of the reduced set may stop there, see + // Viewer::get_reduced_detail_whole_layers(). Bit 0: closed as seen from above, for the band + // at the top of the range; bit 1: closed as seen from below, for the band at the bottom. An + // object's top shells close it from above and its bottom shells from below. Left empty, or + // of another size than the layer count, the viewer judges each layer from the roles of the + // whole layer instead. + // + std::vector layers_closed; }; } // namespace libvgcode diff --git a/src/libvgcode/include/Types.hpp b/src/libvgcode/include/Types.hpp index ef61af9e3a..766701cab8 100644 --- a/src/libvgcode/include/Types.hpp +++ b/src/libvgcode/include/Types.hpp @@ -9,6 +9,7 @@ #define VGCODE_ENABLE_COG_AND_TOOL_MARKERS 0 #include +#include #include #include @@ -38,6 +39,15 @@ static constexpr float MAX_WIPES_RADIUS_MM = 1.0f; // Used for positions, displacements and so on. // using Vec3 = std::array; + +// A rectangle of the XY plane, by its corners; the default takes in everything. +struct XYBox +{ + std::array min{ std::numeric_limits::lowest(), std::numeric_limits::lowest() }; + std::array max{ std::numeric_limits::max(), std::numeric_limits::max() }; + + bool contains(const Vec3& p) const { return min[0] <= p[0] && p[0] <= max[0] && min[1] <= p[1] && p[1] <= max[1]; } +}; // ORCA: the per vertex data uploaded as GL_RGBA32F, see extract_pos_and_or_hwa(). using Vec4 = std::array; @@ -168,6 +178,21 @@ enum class EGCodeExtrusionRole : uint8_t static constexpr std::size_t GCODE_EXTRUSION_ROLES_COUNT = static_cast(EGCodeExtrusionRole::COUNT); +// +// What the reduced set, drawn while the user is dragging, holds in place of the full toolpaths +// +enum class EReducedDetailMode : uint8_t +{ + // nothing: no reduced set is built + Off, + // only the bottom and top layers of the visible range, and the supports, for a caller that + // draws the print itself some other way + EndLayersOnly, + // every role but the infill under the skins and the gap fill: what can be seen from outside + ShellOnly, + COUNT +}; + // // Option types // diff --git a/src/libvgcode/include/Viewer.hpp b/src/libvgcode/include/Viewer.hpp index 7343f75af7..972b3f4ca7 100644 --- a/src/libvgcode/include/Viewer.hpp +++ b/src/libvgcode/include/Viewer.hpp @@ -143,6 +143,21 @@ public: float get_dim_previous_layers_brightness() const; void set_dim_previous_layers_brightness(float value); // + // The reduced set drawn while the user drags: what the mode keeps, and always the layers at the + // bottom and top of the visible range. While a mode is set it is built alongside the full set, + // so set_reduced_detail() rebuilds nothing. Ignored on the OpenGL ES path. + // + void set_reduced_detail_mode(EReducedDetailMode mode); + // Whether the shell mode hides the infill roles; off for a profile that leaves them on the + // surface, with no top or bottom shell or no walls. + void set_reduced_detail_hide_infill(bool value); + void set_reduced_detail(bool value); + bool is_reduced_detail() const; + // The layers the reduced set draws whole at the ends of the visible layer range: every layer of + // the range up to [0], and from [1] on. Each end reaches the nearest layer with infill, so that + // a solid cut between the two shows its cap under infill, as the print shows its inside. + Interval get_reduced_detail_whole_layers() const; + // // Translucent filaments (ORCA) // Whether the filament colors keep their opacity, or are all drawn opaque. // @@ -390,6 +405,14 @@ public: // Color get_vertex_color(const PathVertex& vertex) const; // + // Return the index of the extrusion vertex of the given role that stands for the given + // layers in the current view, or get_vertices_count() if they have none. Where the view + // grades by a value, it is the length-weighted median of that value over the role's + // extrusions in up to eight layers spread over the interval; elsewhere the first one. + // Only the extrusions that end inside the box, in the XY plane, are considered. + // + size_t find_extrusion_vertex(const Interval& layers, EGCodeExtrusionRole role, const XYBox& box = XYBox()) const; + // // Return the count of detected extrusion roles // size_t get_extrusion_roles_count() const; diff --git a/src/libvgcode/src/Layers.cpp b/src/libvgcode/src/Layers.cpp index 1ef6c3236a..cb30995b72 100644 --- a/src/libvgcode/src/Layers.cpp +++ b/src/libvgcode/src/Layers.cpp @@ -22,6 +22,18 @@ static bool is_colorprint_option(const PathVertex& v) return v.type == EMoveType::PausePrint || v.type == EMoveType::CustomGCode; } +static bool is_infill(const PathVertex& v) +{ + return v.type == EMoveType::Extrude && + (v.role == EGCodeExtrusionRole::InternalInfill || + v.role == EGCodeExtrusionRole::SolidInfill || + v.role == EGCodeExtrusionRole::TopSolidInfill || + v.role == EGCodeExtrusionRole::Ironing || + v.role == EGCodeExtrusionRole::BridgeInfill || + v.role == EGCodeExtrusionRole::BottomSurface || + v.role == EGCodeExtrusionRole::InternalBridgeInfill); +} + void Layers::update(const PathVertex& vertex, uint32_t vertex_id) { if (m_items.empty() || vertex.layer_id == m_items.size()) { @@ -33,6 +45,8 @@ void Layers::update(const PathVertex& vertex, uint32_t vertex_id) item.range.set(vertex_id, vertex_id); item.times = vertex.times; item.contains_colorprint_options |= is_colorprint_option(vertex); + item.has_infill = is_infill(vertex); + item.has_sparse_infill = vertex.type == EMoveType::Extrude && vertex.role == EGCodeExtrusionRole::InternalInfill; } else { Item& item = m_items.back(); @@ -43,13 +57,58 @@ void Layers::update(const PathVertex& vertex, uint32_t vertex_id) item.times[i] += vertex.times[i]; } item.contains_colorprint_options |= is_colorprint_option(vertex); + item.has_infill |= is_infill(vertex); + item.has_sparse_infill |= vertex.type == EMoveType::Extrude && vertex.role == EGCodeExtrusionRole::InternalInfill; } } +Interval Layers::get_whole_end_layers(std::size_t max_depth) const +{ + const Interval& range = m_view_range.get(); + // the nearest layer that passes the test, from the end layer towards the other end, or the + // end layer itself when none is within reach + auto nearest = [&](Interval::value_type end, Interval::value_type limit, bool (Layers::*test)(std::size_t) const) { + const int step = (end <= limit) ? 1 : -1; + Interval::value_type layer = end; + for (std::size_t depth = 1; depth < max_depth && layer != limit; ++depth) { + if ((this->*test)(layer)) + return layer; + layer = (step > 0) ? layer + 1 : layer - 1; + } + return (this->*test)(layer) ? layer : end; + }; + auto band_edge = [&](Interval::value_type end, Interval::value_type limit) { + if (m_closed_known) { + // the top band looks down onto the layers, the bottom band up at them + bool (Layers::*closed)(std::size_t) const = (end >= limit) ? &Layers::layer_closed_from_above : &Layers::layer_closed_from_below; + return (this->*closed)(end) ? end : nearest(end, limit, closed); + } + if (layer_has_sparse_infill(end)) + return end; + const Interval::value_type sparse = nearest(end, limit, &Layers::layer_has_sparse_infill); + return (sparse != end) ? sparse : nearest(end, limit, &Layers::layer_has_infill); + }; + Interval ret = range; + ret[1] = band_edge(range[1], range[0]); + // nothing is cut under the print's first layer, so it needs no band + ret[0] = (range[0] == 0) ? 0 : band_edge(range[0], ret[1]); + return ret; +} + void Layers::reset() { m_items.clear(); m_view_range.reset(); + m_closed_known = false; +} + +void Layers::set_closed_layers(const std::vector& closed) +{ + m_closed_known = closed.size() == m_items.size(); + for (std::size_t i = 0; i < m_items.size(); ++i) { + m_items[i].closed_from_above = m_closed_known && (closed[i] & 1) != 0; + m_items[i].closed_from_below = m_closed_known && (closed[i] & 2) != 0; + } } std::vector Layers::get_times(ETimeMode mode) const diff --git a/src/libvgcode/src/Layers.hpp b/src/libvgcode/src/Layers.hpp index e55d1f04af..7226726e1f 100644 --- a/src/libvgcode/src/Layers.hpp +++ b/src/libvgcode/src/Layers.hpp @@ -44,6 +44,40 @@ public: bool layer_contains_colorprint_options(std::size_t layer_id) const { return (layer_id < m_items.size()) ? m_items[layer_id].contains_colorprint_options : false; } + // the ids of the layer's first and last vertex, which bound its vertices in any print order + Interval get_layer_vertex_range(std::size_t layer_id) const { + return (layer_id < m_items.size()) ? m_items[layer_id].range.get() : Interval{ 0, 0 }; + } + // whether the layer has an infill extrusion of any kind, sparse or solid + bool layer_has_infill(std::size_t layer_id) const { + return (layer_id < m_items.size()) ? m_items[layer_id].has_infill : false; + } + bool layer_has_sparse_infill(std::size_t layer_id) const { + return (layer_id < m_items.size()) ? m_items[layer_id].has_sparse_infill : false; + } + // Whether each layer's infill closes every object printed on it, as the caller knows it from + // the objects the moves belong to: bit 0 as seen from above, bit 1 as seen from below, see + // GCodeInputData::layers_closed. Ignored unless there is one entry per layer. + void set_closed_layers(const std::vector& closed); + bool layer_closed_from_above(std::size_t layer_id) const { + return (layer_id < m_items.size()) ? m_items[layer_id].closed_from_above : false; + } + bool layer_closed_from_below(std::size_t layer_id) const { + return (layer_id < m_items.size()) ? m_items[layer_id].closed_from_below : false; + } + // The layers at the ends of the view range that are drawn whole while the user drags: every + // layer of the range up to [0], and from [1] on. A cut right under a layer with no infill of its + // own, as infill combination leaves every layer but one in a few, or a layer of support alone, + // would cap the print where at rest its infill shows through, so each end runs to the nearest + // layer that closes the print, at most max_depth layers deep. That is the nearest layer closed + // as seen from the range's end when the caller has told which layers close every object on + // them, an object's top shells closing it from above and its bottom shells from below. Otherwise it is + // judged from the roles of the whole layer: the nearest layer with sparse infill, since + // another object's solid infill on the layer says nothing about this one's sparse infill, and + // only when no sparse infill is within reach, as on a print with none, the nearest layer with + // any infill. The two ends never cross, and a range from the print's first layer has no + // bottom band, since nothing is cut under that layer. + Interval get_whole_end_layers(std::size_t max_depth) const; std::size_t size_in_bytes_cpu() const; @@ -54,10 +88,16 @@ private: Range range; std::array times{ 0.0f, 0.0f }; bool contains_colorprint_options{ false }; + bool has_infill{ false }; + bool has_sparse_infill{ false }; + bool closed_from_above{ false }; + bool closed_from_below{ false }; }; std::vector m_items; Range m_view_range; + // whether Item::closed was set by the caller, see set_closed_layers() + bool m_closed_known{ false }; }; } // namespace libvgcode diff --git a/src/libvgcode/src/Settings.hpp b/src/libvgcode/src/Settings.hpp index 768903759f..77fc7f896e 100644 --- a/src/libvgcode/src/Settings.hpp +++ b/src/libvgcode/src/Settings.hpp @@ -29,6 +29,11 @@ struct Settings // ORCA: when disabled, the filaments are drawn opaque whatever their color's opacity bool translucent_filaments{ true }; bool spiral_vase_mode{ false }; + // what the reduced set holds and whether it is drawn. Ignored on the OpenGL ES path. + EReducedDetailMode reduced_detail_mode{ EReducedDetailMode::Off }; + // whether the shell mode may hide the infill roles: false when the profile leaves them on the surface + bool reduced_detail_hide_infill{ true }; + bool reduced_detail{ false }; // // Required update flags // diff --git a/src/libvgcode/src/Utils.cpp b/src/libvgcode/src/Utils.cpp index 46ed6a336c..d5f2d953bc 100644 --- a/src/libvgcode/src/Utils.cpp +++ b/src/libvgcode/src/Utils.cpp @@ -7,8 +7,13 @@ #include #include #include "../include/Types.hpp" +#include "../include/PathVertex.hpp" #include #include +#include +#include +#include +#include namespace libvgcode { @@ -67,5 +72,51 @@ Vec3 operator * (float f, const Vec3& v) { return { f * v[0], f * v[1], f * v[2] }; } -} // namespace libvgcode +// the roles that lie under a skin or between walls, never seen from outside the print +static bool is_hidden_in_shell(EGCodeExtrusionRole role) +{ + return role == EGCodeExtrusionRole::InternalInfill || + role == EGCodeExtrusionRole::SolidInfill || + role == EGCodeExtrusionRole::InternalBridgeInfill || + role == EGCodeExtrusionRole::GapFill; +} +static bool is_support(EGCodeExtrusionRole role) +{ + return role == EGCodeExtrusionRole::SupportMaterial || + role == EGCodeExtrusionRole::SupportMaterialInterface || + role == EGCodeExtrusionRole::SupportTransition; +} + +bool keep_in_reduced_set(EReducedDetailMode mode, bool hide_infill, const PathVertex& v, bool end_layer) +{ + if (end_layer) + return true; + switch (mode) { + // the caller draws the print itself, which stands in for neither the supports nor the travels + case EReducedDetailMode::EndLayersOnly: return v.is_travel() || (v.is_extrusion() && is_support(v.role)); + case EReducedDetailMode::ShellOnly: return v.is_option() || !v.is_extrusion() || !hide_infill || !is_hidden_in_shell(v.role); + default: return false; + } +} + +std::size_t weighted_median_index(const std::vector>& samples) +{ + std::vector order(samples.size()); + std::iota(order.begin(), order.end(), std::size_t(0)); + std::stable_sort(order.begin(), order.end(), [&samples](std::size_t a, std::size_t b) { return samples[a].first < samples[b].first; }); + double total = 0.0; + for (const std::pair& sample : samples) + total += std::max(sample.second, 0.0f); + if (total <= 0.0) + return order.empty() ? samples.size() : order[order.size() / 2]; + double sum = 0.0; + for (std::size_t id : order) { + sum += std::max(samples[id].second, 0.0f); + if (sum >= 0.5 * total) + return id; + } + return order.back(); +} + +} // namespace libvgcode diff --git a/src/libvgcode/src/Utils.hpp b/src/libvgcode/src/Utils.hpp index 4db67e426f..01568cc145 100644 --- a/src/libvgcode/src/Utils.hpp +++ b/src/libvgcode/src/Utils.hpp @@ -5,9 +5,13 @@ #ifndef VGCODE_UTILS_HPP #define VGCODE_UTILS_HPP +#include "../include/PathVertex.hpp" #include "../include/Types.hpp" #include #include +#include +#include +#include #ifdef _WIN32 #define STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + __alignof(TYPE) - 1) / __alignof(TYPE)) * __alignof(TYPE) @@ -27,6 +31,33 @@ extern bool operator != (const Vec3& v1, const Vec3& v2); extern Vec3 operator + (const Vec3& v1, const Vec3& v2); extern Vec3 operator - (const Vec3& v1, const Vec3& v2); extern Vec3 operator * (float f, const Vec3& v); +// The index of the weighted median of the samples (value, weight): in value order, the first +// sample at which the cumulative weight reaches half of the total. Samples that weigh nothing +// between them fall back to the middle one by value; no samples gives their count. +extern std::size_t weighted_median_index(const std::vector>& samples); +// Whether the reduced set the mode builds keeps the vertex, one the full set shows: all of it on the +// layers at the ends of the range, and between them what the mode keeps of the rest. +extern bool keep_in_reduced_set(EReducedDetailMode mode, bool hide_infill, const PathVertex& v, bool end_layer); +// The extrusions of the role on the layer among the vertices of the range that end inside the +// box: their ids, and a (value, length) sample of each from what the view grades by. Where the +// view grades by nothing, value_of() has no value and the first id found is returned at once. +template +std::optional collect_role_samples(const std::vector& vertices, const Interval& range, uint32_t layer_id, + EGCodeExtrusionRole role, const XYBox& box, const ValueOf& value_of, std::vector>& samples, + std::vector& ids) +{ + for (std::size_t i = range[0]; i <= range[1] && i < vertices.size(); ++i) { + const PathVertex& v = vertices[i]; + if (v.layer_id != layer_id || !v.is_extrusion() || v.role != role || !box.contains(v.position)) + continue; + const std::optional value = value_of(v); + if (!value.has_value()) + return i; + samples.emplace_back(*value, (i > 0) ? length(v.position - vertices[i - 1].position) : 0.0f); + ids.push_back(i); + } + return std::nullopt; +} } // namespace libvgcode diff --git a/src/libvgcode/src/Viewer.cpp b/src/libvgcode/src/Viewer.cpp index f61cd07c3e..ad8911adeb 100644 --- a/src/libvgcode/src/Viewer.cpp +++ b/src/libvgcode/src/Viewer.cpp @@ -149,6 +149,31 @@ void Viewer::set_translucent_filaments(bool value) m_impl->set_translucent_filaments(value); } +void Viewer::set_reduced_detail_mode(EReducedDetailMode mode) +{ + m_impl->set_reduced_detail_mode(mode); +} + +void Viewer::set_reduced_detail_hide_infill(bool value) +{ + m_impl->set_reduced_detail_hide_infill(value); +} + +void Viewer::set_reduced_detail(bool value) +{ + m_impl->set_reduced_detail(value); +} + +bool Viewer::is_reduced_detail() const +{ + return m_impl->is_reduced_detail(); +} + +Interval Viewer::get_reduced_detail_whole_layers() const +{ + return m_impl->get_reduced_detail_whole_layers(); +} + bool Viewer::is_option_visible(EOptionType type) const { return m_impl->is_option_visible(type); @@ -369,6 +394,11 @@ Color Viewer::get_vertex_color(const PathVertex& vertex) const return m_impl->get_vertex_color(vertex); } +size_t Viewer::find_extrusion_vertex(const Interval& layers, EGCodeExtrusionRole role, const XYBox& box) const +{ + return m_impl->find_extrusion_vertex(layers, role, box); +} + size_t Viewer::get_extrusion_roles_count() const { return m_impl->get_extrusion_roles_count(); diff --git a/src/libvgcode/src/ViewerImpl.cpp b/src/libvgcode/src/ViewerImpl.cpp index 7908fbed5b..5a3b272849 100644 --- a/src/libvgcode/src/ViewerImpl.cpp +++ b/src/libvgcode/src/ViewerImpl.cpp @@ -1003,9 +1003,18 @@ void ViewerImpl::reset() #else m_enabled_segments_count = 0; m_enabled_options_count = 0; + m_enabled_segments_reduced_count = 0; + m_enabled_segments_reduced_translucent_count = 0; + m_enabled_options_reduced_count = 0; + m_enabled_segments_reduced_tex_size = 0; + m_enabled_options_reduced_tex_size = 0; m_settings_used_for_ranges = std::nullopt; + delete_textures(m_enabled_options_reduced_tex_id); + delete_buffers(m_enabled_options_reduced_buf_id); + delete_textures(m_enabled_segments_reduced_tex_id); + delete_buffers(m_enabled_segments_reduced_buf_id); delete_textures(m_enabled_options_tex_id); delete_buffers(m_enabled_options_buf_id); delete_textures(m_enabled_segments_tex_id); @@ -1220,6 +1229,7 @@ void ViewerImpl::load(GCodeInputData&& gcode_data) if (!m_layers.empty()) m_layers.set_view_range(0, static_cast(m_layers.count()) - 1); + m_layers.set_closed_layers(gcode_data.layers_closed); std::sort(m_options.begin(), m_options.end()); m_options.erase(std::unique(m_options.begin(), m_options.end()), m_options.end()); @@ -1286,6 +1296,17 @@ void ViewerImpl::load(GCodeInputData&& gcode_data) glsafe(glGenTextures(1, &m_enabled_options_tex_id)); glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_enabled_options_tex_id)); + // create (but do not fill) the reduced counterparts of the two buffers above + glsafe(glGenBuffers(1, &m_enabled_segments_reduced_buf_id)); + glsafe(glBindBuffer(GL_TEXTURE_BUFFER, m_enabled_segments_reduced_buf_id)); + glsafe(glGenTextures(1, &m_enabled_segments_reduced_tex_id)); + glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_enabled_segments_reduced_tex_id)); + + glsafe(glGenBuffers(1, &m_enabled_options_reduced_buf_id)); + glsafe(glBindBuffer(GL_TEXTURE_BUFFER, m_enabled_options_reduced_buf_id)); + glsafe(glGenTextures(1, &m_enabled_options_reduced_tex_id)); + glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_enabled_options_reduced_tex_id)); + glsafe(glBindBuffer(GL_TEXTURE_BUFFER, 0)); glsafe(glBindTexture(GL_TEXTURE_BUFFER, old_bound_texture)); #endif // ENABLE_OPENGL_ES @@ -1304,6 +1325,18 @@ void ViewerImpl::update_enabled_entities() std::vector enabled_segments; std::vector enabled_options; +#ifndef ENABLE_OPENGL_ES + // the reduced set is filled by the same walk, so switching to it costs no rebuild. Whatever the + // mode leaves out, the layers at the bottom and top of the visible range are kept whole: they + // are the surfaces the range cuts open + const EReducedDetailMode reduced_mode = m_settings.reduced_detail_mode; + const bool build_reduced = reduced_mode != EReducedDetailMode::Off; + const bool hide_infill = m_settings.reduced_detail_hide_infill; + std::vector enabled_segments_reduced; + std::vector enabled_options_reduced; + const Interval& layers_range = m_layers.get_view_range(); + const Interval whole_layers = build_reduced ? get_reduced_detail_whole_layers() : Interval{ 0, 0 }; +#endif // ENABLE_OPENGL_ES Interval range = m_view_range.get_visible(); // when top layer only visualization is enabled, we need to render @@ -1351,6 +1384,15 @@ void ViewerImpl::update_enabled_entities() enabled_options.push_back(static_cast(i)); else enabled_segments.push_back(static_cast(i)); + +#ifndef ENABLE_OPENGL_ES + if (build_reduced) { + const bool end_layer = (v.layer_id >= layers_range[0] && v.layer_id <= whole_layers[0]) || + (v.layer_id >= whole_layers[1] && v.layer_id <= layers_range[1]); + if (keep_in_reduced_set(reduced_mode, hide_infill, v, end_layer)) + (v.is_option() ? enabled_options_reduced : enabled_segments_reduced).push_back(static_cast(i)); + } +#endif // ENABLE_OPENGL_ES } // ORCA: so that each pass of render() draws only its own segments, in print order @@ -1361,10 +1403,15 @@ void ViewerImpl::update_enabled_entities() m_enabled_translucent_segments_count += m_texture_data.get_enabled_translucent_segments_count(i); m_texture_data.set_enabled_options(enabled_options); #else + m_enabled_segments_reduced_translucent_count = 0; if (m_has_translucent_colors) { const auto is_opaque = [this](uint32_t id) { return m_vertices_colors[id][3] == 255; }; const auto translucent_begin = std::stable_partition(enabled_segments.begin(), enabled_segments.end(), is_opaque); m_enabled_translucent_segments_count = static_cast(std::distance(translucent_begin, enabled_segments.end())); + if (build_reduced) { + const auto reduced_translucent_begin = std::stable_partition(enabled_segments_reduced.begin(), enabled_segments_reduced.end(), is_opaque); + m_enabled_segments_reduced_translucent_count = static_cast(std::distance(reduced_translucent_begin, enabled_segments_reduced.end())); + } } m_enabled_segments_count = enabled_segments.size(); @@ -1389,6 +1436,23 @@ void ViewerImpl::update_enabled_entities() else glsafe(glBufferData(GL_TEXTURE_BUFFER, 0, nullptr, GL_STATIC_DRAW)); + m_enabled_segments_reduced_count = enabled_segments_reduced.size(); + m_enabled_options_reduced_count = enabled_options_reduced.size(); + m_enabled_segments_reduced_tex_size = enabled_segments_reduced.size() * sizeof(uint32_t); + m_enabled_options_reduced_tex_size = enabled_options_reduced.size() * sizeof(uint32_t); + + // uploaded even when nothing was built, so that the last reduced set is released as soon as + // the preference is switched off + assert(m_enabled_segments_reduced_buf_id > 0); + glsafe(glBindBuffer(GL_TEXTURE_BUFFER, m_enabled_segments_reduced_buf_id)); + glsafe(glBufferData(GL_TEXTURE_BUFFER, m_enabled_segments_reduced_tex_size, + enabled_segments_reduced.empty() ? nullptr : enabled_segments_reduced.data(), GL_STATIC_DRAW)); + + assert(m_enabled_options_reduced_buf_id > 0); + glsafe(glBindBuffer(GL_TEXTURE_BUFFER, m_enabled_options_reduced_buf_id)); + glsafe(glBufferData(GL_TEXTURE_BUFFER, m_enabled_options_reduced_tex_size, + enabled_options_reduced.empty() ? nullptr : enabled_options_reduced.data(), GL_STATIC_DRAW)); + glsafe(glBindBuffer(GL_TEXTURE_BUFFER, 0)); #endif // ENABLE_OPENGL_ES @@ -1607,6 +1671,23 @@ void ViewerImpl::set_dim_previous_layers_brightness(float value) m_settings.dim_previous_layers_brightness = value; } +// Both decide which vertices land in the reduced set, so the sets are rebuilt. +void ViewerImpl::set_reduced_detail_mode(EReducedDetailMode mode) +{ + if (m_settings.reduced_detail_mode == mode) + return; + m_settings.reduced_detail_mode = mode; + m_settings.update_enabled_entities = true; +} + +void ViewerImpl::set_reduced_detail_hide_infill(bool value) +{ + if (m_settings.reduced_detail_hide_infill == value) + return; + m_settings.reduced_detail_hide_infill = value; + m_settings.update_enabled_entities = true; +} + std::vector ViewerImpl::get_time_modes() const { std::vector ret; @@ -1731,6 +1812,51 @@ float ViewerImpl::get_estimated_time_at(size_t id) const return time; } +std::optional ViewerImpl::get_vertex_value(const PathVertex& v) const +{ + switch (m_settings.view_type) + { + case EViewType::Height: return v.height; + case EViewType::Width: return v.width; + case EViewType::Speed: return v.feedrate; + case EViewType::ActualSpeed: return v.actual_feedrate; + case EViewType::FanSpeed: return v.fan_speed; + case EViewType::Temperature: return v.temperature; + case EViewType::PressureAdvance: return v.pressure_advance; + case EViewType::Acceleration: return v.acceleration; + case EViewType::Jerk: return v.jerk; + case EViewType::VolumetricFlowRate: return v.volumetric_rate(); + case EViewType::ActualVolumetricFlowRate: return v.actual_volumetric_rate(); + case EViewType::LayerTimeLinear: + case EViewType::LayerTimeLogarithmic: return m_layers.get_layer_time(m_settings.time_mode, static_cast(v.layer_id)); + default: return std::nullopt; + } +} + +// The extrusion of the role that stands for the layers, or the vertex count. A view that grades +// by a value takes the length-weighted median of it over the role's extrusions in up to +// VERTEX_SAMPLE_LAYERS layers spread evenly over the interval, so that neither the ramp a wall +// starts on nor one odd layer sets the colour; any other view takes the first extrusion found. +// A layer's vertices lie between its first and last ids, with those of other layers among them +// in a print by object. Only the extrusions that end inside the box count, so that one object's +// walls can be told from another's on the same layers. +size_t ViewerImpl::find_extrusion_vertex(const Interval& layers, EGCodeExtrusionRole role, const XYBox& box) const +{ + std::vector> samples; + std::vector ids; + const size_t count = (layers[1] >= layers[0]) ? layers[1] - layers[0] + 1 : 0; + const size_t steps = std::min(count, VERTEX_SAMPLE_LAYERS); + const auto value_of = [this](const PathVertex& v) { return get_vertex_value(v); }; + for (size_t step = 0; step < steps; ++step) { + const size_t layer_id = layers[0] + ((steps > 1) ? step * (count - 1) / (steps - 1) : 0); + const std::optional first = collect_role_samples(m_vertices, m_layers.get_layer_vertex_range(layer_id), + static_cast(layer_id), role, box, value_of, samples, ids); + if (first.has_value()) + return *first; + } + return samples.empty() ? m_vertices.size() : ids[weighted_median_index(samples)]; +} + Color ViewerImpl::get_vertex_color(const PathVertex& v) const { if (v.type == EMoveType::Noop) @@ -1999,6 +2125,8 @@ size_t ViewerImpl::get_used_gpu_memory() const ret += m_colors_tex_size; ret += m_enabled_segments_tex_size; ret += m_enabled_options_tex_size; + ret += m_enabled_segments_reduced_tex_size; + ret += m_enabled_options_reduced_tex_size; ret += m_translucent_targets.size_in_bytes(); #endif // ENABLE_OPENGL_ES return ret; @@ -2233,7 +2361,8 @@ void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projec #ifdef ENABLE_OPENGL_ES if (m_texture_data.get_enabled_segments_count() == 0) #else - if (m_enabled_segments_count == 0) + const ActiveSet segments = active_segments(); + if (segments.count == 0) #endif // ENABLE_OPENGL_ES return; @@ -2366,10 +2495,10 @@ void ViewerImpl::render_segments(const Mat4x4& view_matrix, const Mat4x4& projec glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_colors_tex_id)); glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA8, m_colors_buf_id)); glsafe(glActiveTexture(GL_TEXTURE3)); - glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_enabled_segments_tex_id)); - glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, m_enabled_segments_buf_id)); + glsafe(glBindTexture(GL_TEXTURE_BUFFER, segments.tex_id)); + glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, segments.buf_id)); - draw(m_enabled_segments_count, m_enabled_translucent_segments_count); + draw(segments.count, segments.translucent_count); #endif // ENABLE_OPENGL_ES if (curr_cull_face) @@ -2404,7 +2533,8 @@ void ViewerImpl::render_options(const Mat4x4& view_matrix, const Mat4x4& project #ifdef ENABLE_OPENGL_ES if (m_texture_data.get_enabled_options_count() == 0) #else - if (m_enabled_options_count == 0) + const ActiveSet options = active_options(); + if (options.count == 0) #endif // ENABLE_OPENGL_ES return; @@ -2464,10 +2594,10 @@ void ViewerImpl::render_options(const Mat4x4& view_matrix, const Mat4x4& project glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_colors_tex_id)); glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA8, m_colors_buf_id)); glsafe(glActiveTexture(GL_TEXTURE3)); - glsafe(glBindTexture(GL_TEXTURE_BUFFER, m_enabled_options_tex_id)); - glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, m_enabled_options_buf_id)); + glsafe(glBindTexture(GL_TEXTURE_BUFFER, options.tex_id)); + glsafe(glTexBuffer(GL_TEXTURE_BUFFER, GL_R32UI, options.buf_id)); - m_option_template.render(m_enabled_options_count); + m_option_template.render(options.count); #endif // ENABLE_OPENGL_ES if (!curr_cull_face) @@ -2568,7 +2698,11 @@ size_t ViewerImpl::TranslucentTargets::size_in_bytes() const void ViewerImpl::render_translucent(const Mat4x4& view_matrix, const Mat4x4& projection_matrix) { apply_pending_updates(); +#ifdef ENABLE_OPENGL_ES if (m_enabled_translucent_segments_count == 0) +#else + if (active_segments().translucent_count == 0) +#endif // ENABLE_OPENGL_ES return; const Mat4x4 inv_view_matrix = inverse(view_matrix); diff --git a/src/libvgcode/src/ViewerImpl.hpp b/src/libvgcode/src/ViewerImpl.hpp index d9394d7e21..74d5d899af 100644 --- a/src/libvgcode/src/ViewerImpl.hpp +++ b/src/libvgcode/src/ViewerImpl.hpp @@ -123,6 +123,20 @@ public: void set_dim_previous_layers(bool value); float get_dim_previous_layers_brightness() const { return m_settings.dim_previous_layers_brightness; } void set_dim_previous_layers_brightness(float value); + void set_reduced_detail_mode(EReducedDetailMode mode); + void set_reduced_detail_hide_infill(bool value); + // draw from the reduced set; it is already built, so this is just a buffer binding + void set_reduced_detail(bool value) { +#ifdef ENABLE_OPENGL_ES + // no reduced set is built on OpenGL ES + value = false; +#endif // ENABLE_OPENGL_ES + m_settings.reduced_detail = value; + } + bool is_reduced_detail() const { return m_settings.reduced_detail; } + // how far the whole end bands of the reduced set reach for a layer with infill, see Layers + static constexpr std::size_t REDUCED_DETAIL_END_DEPTH = 8; + Interval get_reduced_detail_whole_layers() const { return m_layers.get_whole_end_layers(REDUCED_DETAIL_END_DEPTH); } // ORCA: whether the filament colors keep their opacity, see get_vertex_alpha() bool is_translucent_filaments() const { return m_settings.translucent_filaments; } @@ -179,6 +193,11 @@ public: float get_estimated_time() const { return m_total_time[static_cast(m_settings.time_mode)]; } float get_estimated_time_at(size_t id) const; Color get_vertex_color(const PathVertex& vertex) const; + // the value the current view grades the vertex by, where it grades by one + std::optional get_vertex_value(const PathVertex& vertex) const; + // how many layers of an interval find_extrusion_vertex() samples + static constexpr std::size_t VERTEX_SAMPLE_LAYERS = 8; + size_t find_extrusion_vertex(const Interval& layers, EGCodeExtrusionRole role, const XYBox& box) const; size_t get_extrusion_roles_count() const { return m_extrusion_roles.get_roles_count(); } std::vector get_extrusion_roles() const { return m_extrusion_roles.get_roles(); } @@ -551,6 +570,17 @@ private: unsigned int m_enabled_options_tex_id{ 0 }; size_t m_enabled_options_count{ 0 }; // + // OpenGL buffers to store the reduced set drawn while Settings::reduced_detail is set + // + unsigned int m_enabled_segments_reduced_buf_id{ 0 }; + unsigned int m_enabled_segments_reduced_tex_id{ 0 }; + size_t m_enabled_segments_reduced_count{ 0 }; + // the reduced set lists its translucent segments last as the full one does + size_t m_enabled_segments_reduced_translucent_count{ 0 }; + unsigned int m_enabled_options_reduced_buf_id{ 0 }; + unsigned int m_enabled_options_reduced_tex_id{ 0 }; + size_t m_enabled_options_reduced_count{ 0 }; + // // Caches for size of data sent to gpu, in bytes // size_t m_positions_tex_size{ 0 }; @@ -558,6 +588,29 @@ private: size_t m_colors_tex_size{ 0 }; size_t m_enabled_segments_tex_size{ 0 }; size_t m_enabled_options_tex_size{ 0 }; + size_t m_enabled_segments_reduced_tex_size{ 0 }; + size_t m_enabled_options_reduced_tex_size{ 0 }; + + // The set the next draw reads from: the reduced one while dragging, if one is built. + bool use_reduced_set() const { return m_settings.reduced_detail && m_settings.reduced_detail_mode != EReducedDetailMode::Off; } + struct ActiveSet + { + size_t count{ 0 }; + unsigned int buf_id{ 0 }; + unsigned int tex_id{ 0 }; + // of count, the last translucent_count are the translucent segments + size_t translucent_count{ 0 }; + }; + ActiveSet active_segments() const { + if (use_reduced_set()) + return { m_enabled_segments_reduced_count, m_enabled_segments_reduced_buf_id, m_enabled_segments_reduced_tex_id, m_enabled_segments_reduced_translucent_count }; + return { m_enabled_segments_count, m_enabled_segments_buf_id, m_enabled_segments_tex_id, m_enabled_translucent_segments_count }; + } + ActiveSet active_options() const { + if (use_reduced_set()) + return { m_enabled_options_reduced_count, m_enabled_options_reduced_buf_id, m_enabled_options_reduced_tex_id }; + return { m_enabled_options_count, m_enabled_options_buf_id, m_enabled_options_tex_id }; + } #endif // ENABLE_OPENGL_ES // diff --git a/src/slic3r/GUI/3DScene.hpp b/src/slic3r/GUI/3DScene.hpp index 47b451bb2c..31b44f7a41 100644 --- a/src/slic3r/GUI/3DScene.hpp +++ b/src/slic3r/GUI/3DScene.hpp @@ -397,6 +397,8 @@ public: std::vector model_per_colors; bool IsTransparent(); + const std::vector& colors() const { return m_colors; } + std::vector& colors() { return m_colors; } private: std::vector m_colors; diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index 8119a15dbe..d427d6bce0 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -39,6 +39,7 @@ #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/GLModel.hpp" #include "slic3r/GUI/GLShader.hpp" +#include "slic3r/GUI/OpenGLManager.hpp" #include "slic3r/GUI/Gizmos/GLGizmoUtils.hpp" #include "libslic3r/Point.hpp" #include @@ -59,6 +60,8 @@ #include "libslic3r/GCode/GCodeProcessor.hpp" #include "libvgcode/include/GCodeInputData.hpp" #include "libvgcode/include/ColorRange.hpp" +#include +#include #include #include "libslic3r_version.h" #include @@ -1153,6 +1156,7 @@ GCodeViewer::GCodeViewer() GCodeViewer::~GCodeViewer() { reset(); + release_caster_depth(); if (m_moves_slider) { delete m_moves_slider; m_moves_slider = nullptr; @@ -1381,6 +1385,8 @@ void GCodeViewer::load_as_gcode(const GCodeProcessorResult& gcode_result, const if (current_top_layer_only != required_top_layer_only) m_viewer.toggle_top_layer_only_view_range(); + read_reduced_detail_preferences(); + // ORCA: darken the layers the preview layer slider is not scrubbed to m_viewer.set_dim_previous_layers(get_app_config()->get_bool("preview_dim_previous_layers")); m_viewer.set_dim_previous_layers_brightness(0.01f * std::stoi(get_app_config()->get("preview_dim_previous_layers_brightness"))); @@ -1650,6 +1656,20 @@ void GCodeViewer::load_as_gcode(const GCodeProcessorResult& gcode_result, const m_belt_layer_zs.clear(); } + // The solid model is cut at the heights of the layer range's ends, which bound the range only + // if the layers never drop: printed object by object, the heights start over with each object. + // Two layers may share a height, as layers of objects with different layer heights can. + m_layers_z_rising = true; + float prev_z = 0.0f; + for (size_t i = 0; i < m_viewer.get_layers_count() && m_layers_z_rising; ++i) { + const float z = m_viewer.get_layer_z(i); + // a layer with no extrusion has no height + if (z == 0.0f) + continue; + m_layers_z_rising = z >= prev_z; + prev_z = z; + } + // #if !VGCODE_ENABLE_COG_AND_TOOL_MARKERS // const size_t vertices_count = m_viewer.get_vertices_count(); // m_cog.reset(); @@ -1742,6 +1762,10 @@ void GCodeViewer::load_as_gcode(const GCodeProcessorResult& gcode_result, const // BBS: data for rendering color arrangement recommendation m_nozzle_nums = print.config().option("nozzle_diameter")->values.size(); + // the shell drag mode hides the infill only where the profile covers it: with no top or bottom + // shell, or no walls, the infill is the surface. Per-object settings are not consulted. + const PrintRegionConfig& region = print.default_region_config(); + m_viewer.set_reduced_detail_hide_infill(region.top_shell_layers.value > 0 && region.bottom_shell_layers.value > 0 && region.wall_loops.value > 0); // Orca hack: Hide filament group for non-bbl printers if (!print.is_BBL_printer()) m_nozzle_nums = 1; std::vector filament_maps = print.get_filament_maps(); @@ -1918,6 +1942,7 @@ void GCodeViewer::reset_shell() { m_shells.volumes.clear(); m_shells.print_id = -1; + m_shells.with_wipe_tower = false; m_shell_bounding_box = BoundingBoxf3(); } @@ -2178,6 +2203,10 @@ void GCodeViewer::render_scene(int canvas_width, int canvas_height) { glsafe(::glEnable(GL_DEPTH_TEST)); render_shells(); + // while dragging in the solid model mode, the objects stand in for their toolpaths, cut to the + // visible layer range; the toolpath set then holds only the range's bottom and top layers + if (m_viewer.is_reduced_detail() && solid_model_enabled()) + render_solid_model(canvas_width, canvas_height); if (m_viewer.get_extrusion_roles_count() == 0) return; @@ -2428,6 +2457,9 @@ size_t GCodeViewer::shadow_casters_signature() const m_paths_bounding_box.max.x(), m_paths_bounding_box.max.y(), m_paths_bounding_box.max.z() }) boost::hash_combine(hash, value); boost::hash_combine(hash, m_viewer.is_top_layer_only_view_range()); + // the casters are drawn from the reduced set while dragging, with the solid model in its mode + boost::hash_combine(hash, m_viewer.is_reduced_detail()); + boost::hash_combine(hash, static_cast(m_reduced_detail_mode)); for (size_t i = 0; i < libvgcode::GCODE_EXTRUSION_ROLES_COUNT; ++i) boost::hash_combine(hash, m_viewer.is_extrusion_role_visible(libvgcode::EGCodeExtrusionRole(i))); boost::hash_combine(hash, m_viewer.is_option_visible(libvgcode::EOptionType::Travels)); @@ -2446,10 +2478,187 @@ void GCodeViewer::render_shadow_casters(const Transform3d& light_view_matrix, co libvgcode::convert(static_cast(light_view_matrix.matrix().cast())), libvgcode::convert(static_cast(light_projection_matrix.matrix().cast())), libvgcode::convert(static_cast(light_position.cast()))); + if (m_viewer.is_reduced_detail() && solid_model_enabled()) + render_solid_model_casters(light_view_matrix, light_projection_matrix); +} + +// The stencil count that tells where a body cut at one cap alone is open: with the depth test off, +// its back faces add one and its front faces take one away, so a pixel where the ray leaves the +// body through the opening ends nonzero. The caller draws the body between the two. Depth clamping +// keeps the faces past the near plane in the count: the light's frustum ends at the top visible +// layer, so without it a part above the range keeps only its far faces and counts as open. +static void begin_cap_count() +{ + glsafe(::glEnable(GL_DEPTH_CLAMP)); + glsafe(::glStencilMask(0xFF)); + glsafe(::glClear(GL_STENCIL_BUFFER_BIT)); + glsafe(::glStencilFunc(GL_ALWAYS, 0, 0xFF)); + glsafe(::glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_DECR_WRAP)); + glsafe(::glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_INCR_WRAP)); + glsafe(::glDepthMask(GL_FALSE)); + glsafe(::glDisable(GL_DEPTH_TEST)); + glsafe(::glDisable(GL_CULL_FACE)); +} + +// After the count, what is drawn next lands only where the body was open. +static void end_cap_count() +{ + glsafe(::glDisable(GL_DEPTH_CLAMP)); + glsafe(::glEnable(GL_DEPTH_TEST)); + glsafe(::glDepthMask(GL_TRUE)); + glsafe(::glStencilFunc(GL_NOTEQUAL, 0, 0xFF)); + glsafe(::glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP)); + glsafe(::glStencilMask(0x00)); +} + +// The solid casts as the toolpaths it stands in for would: the shells, cut at the same heights, +// drawn depth-only into the shadow map the canvas has bound, and the cut faces with them. Without +// its cut faces an open body lets the light through: down onto the bed through a band cut at both +// ends, or onto its own far wall, with the end band's lines throwing their shadow through the +// hollow. The cut faces are counted and drawn as render_solid_model() draws them, which takes a +// stencil the map has not got, so they go into a depth target of the viewer's first, the map's +// size, and are copied into the map from there. +void GCodeViewer::render_solid_model_casters(const Transform3d& light_view_matrix, const Transform3d& light_projection_matrix) +{ + const std::optional> z_range = solid_model_z_range(); + GLShaderProgram* shader = wxGetApp().get_shader("flat_clip"); + if (m_shells.volumes.empty() || !z_range.has_value() || shader == nullptr) + return; + + // the walls, cut by the section view as the camera sees it, so what it cuts away casts nothing + shader->start_using(); + shader->set_uniform("projection_matrix", light_projection_matrix); + shader->set_uniform("clipping_plane", m_clipping_plane); + shader->set_uniform("z_range", *z_range); + for (GLVolume* volume : m_shells.volumes.volumes) { + const Transform3d world_matrix = volume->world_matrix(); + shader->set_uniform("volume_world_matrix", world_matrix); + shader->set_uniform("view_model_matrix", light_view_matrix * world_matrix); + volume->render(); + } + shader->stop_using(); + + GLShaderProgram* copy_shader = wxGetApp().get_shader("depth_copy"); + GLint viewport[4] = { 0, 0, 0, 0 }; + glsafe(::glGetIntegerv(GL_VIEWPORT, viewport)); + // without a target of its own the body casts open + if (copy_shader == nullptr || !init_caster_depth(viewport[2], viewport[3])) + return; + std::array caps; + init_solid_model_caps(*z_range, caps); + + GLint map_fbo = 0; + glsafe(::glGetIntegerv(GL_FRAMEBUFFER_BINDING, &map_fbo)); + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, m_caster_fbo)); + glsafe(::glStencilMask(0xFF)); + glsafe(::glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)); + glsafe(::glEnable(GL_STENCIL_TEST)); + shader->start_using(); + shader->set_uniform("projection_matrix", light_projection_matrix); + for (GLVolume* volume : m_shells.volumes.volumes) { + const Transform3d world_matrix = volume->world_matrix(); + for (SolidModelCap& cap : caps) { + if (!cap.quad.is_initialized()) + continue; + begin_cap_count(); + shader->set_uniform("z_range", cap.count_z_range); + shader->set_uniform("clipping_plane", cap.count_plane); + shader->set_uniform("volume_world_matrix", world_matrix); + shader->set_uniform("view_model_matrix", light_view_matrix * world_matrix); + volume->render(); + end_cap_count(); + shader->set_uniform("z_range", cap.quad_z_range); + shader->set_uniform("clipping_plane", cap.quad_plane); + shader->set_uniform("volume_world_matrix", Transform3d::Identity()); + shader->set_uniform("view_model_matrix", light_view_matrix); + cap.quad.render(); + } + } + shader->stop_using(); + glsafe(::glStencilMask(0xFF)); + glsafe(::glDisable(GL_STENCIL_TEST)); + + // into the map, where nearer than what is there + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, static_cast(map_fbo))); + GLModel screen; + GLModel::Geometry data; + data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3 }; + data.add_vertex(Vec3f(-1.0f, -1.0f, 0.0f)); + data.add_vertex(Vec3f(1.0f, -1.0f, 0.0f)); + data.add_vertex(Vec3f(1.0f, 1.0f, 0.0f)); + data.add_vertex(Vec3f(-1.0f, 1.0f, 0.0f)); + data.add_triangle(0, 1, 2); + data.add_triangle(0, 2, 3); + screen.init_from(std::move(data)); + // bound on a unit of its own, with the volumes' own bindings left to unit 0 + glsafe(::glActiveTexture(GL_TEXTURE6)); + glsafe(::glBindTexture(GL_TEXTURE_2D, m_caster_depth)); + glsafe(::glActiveTexture(GL_TEXTURE0)); + copy_shader->start_using(); + copy_shader->set_uniform("depth_texture", 6); + copy_shader->set_uniform("map_size", std::array{ static_cast(viewport[2]), static_cast(viewport[3]) }); + screen.render(); + copy_shader->stop_using(); + glsafe(::glActiveTexture(GL_TEXTURE6)); + glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); + glsafe(::glActiveTexture(GL_TEXTURE0)); +} + +// The depth and stencil target the caster pass draws the cut faces into, the size of the shadow +// map they are copied into. +bool GCodeViewer::init_caster_depth(int width, int height) +{ + if (OpenGLManager::get_framebuffers_type() != OpenGLManager::EFramebufferType::Arb || width <= 0 || height <= 0) + return false; + if (m_caster_depth != 0 && m_caster_width == width && m_caster_height == height) + return true; + if (m_caster_depth == 0) { + glsafe(::glGenTextures(1, &m_caster_depth)); + glsafe(::glBindTexture(GL_TEXTURE_2D, m_caster_depth)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); + glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); + } + else + glsafe(::glBindTexture(GL_TEXTURE_2D, m_caster_depth)); + glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, width, height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr)); + glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); + m_caster_width = width; + m_caster_height = height; + + GLint bound_fbo = 0; + glsafe(::glGetIntegerv(GL_FRAMEBUFFER_BINDING, &bound_fbo)); + if (m_caster_fbo == 0) + glsafe(::glGenFramebuffers(1, &m_caster_fbo)); + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, m_caster_fbo)); + glsafe(::glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_caster_depth, 0)); + glsafe(::glDrawBuffer(GL_NONE)); + glsafe(::glReadBuffer(GL_NONE)); + const bool complete = ::glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + glsafe(::glBindFramebuffer(GL_FRAMEBUFFER, static_cast(bound_fbo))); + if (!complete) + release_caster_depth(); + return complete; +} + +void GCodeViewer::release_caster_depth() +{ + if (m_caster_fbo != 0) { + glsafe(::glDeleteFramebuffers(1, &m_caster_fbo)); + m_caster_fbo = 0; + } + if (m_caster_depth != 0) { + glsafe(::glDeleteTextures(1, &m_caster_depth)); + m_caster_depth = 0; + } + m_caster_width = 0; + m_caster_height = 0; } void GCodeViewer::set_shadow_map(int texture_unit, const Transform3d& light_view_projection, float intensity, float texel_size) { + m_shadow_map = { texture_unit, light_view_projection, intensity, texel_size }; m_viewer.set_shadow_map(texture_unit, libvgcode::convert(static_cast(light_view_projection.matrix().cast())), intensity, texel_size); @@ -2457,6 +2666,7 @@ void GCodeViewer::set_shadow_map(int texture_unit, const Transform3d& light_view void GCodeViewer::set_light_top_dir(const Vec3d& direction) { + m_light_top_dir = direction; m_viewer.set_light_top_dir(libvgcode::convert(static_cast(direction.cast()))); } @@ -2759,6 +2969,51 @@ void GCodeViewer::update_layers_slider_mode() // TODO m_layers_slider->SetModeAndOnlyExtruder(one_extruder_printed_model, only_extruder); } +void GCodeViewer::set_interacting(bool interacting) +{ + // With the mode off nothing changes while dragging. The solid model needs shells to stand in + // for the toolpaths and a single height to cut them at; a belt printer's layers are tilted + // planes, which no height cuts. + const bool usable = m_reduced_detail_mode != libvgcode::EReducedDetailMode::Off && + (!solid_model_enabled() || (!m_shells.volumes.empty() && m_layers_z_rising && !m_belt_view_enabled)); + // sampled afresh as each drag begins: the legend may have recoloured the toolpaths, and the + // sliders may have moved the span, since the last one + if (interacting && !m_viewer.is_reduced_detail()) + m_solid_model_colors.valid = false; + m_viewer.set_reduced_detail(interacting && usable); +} + +void GCodeViewer::read_reduced_detail_preferences() +{ + m_reduced_detail_mode = reduced_detail_mode_from_string(get_app_config()->get("preview_reduced_detail_mode")); + m_viewer.set_reduced_detail_mode(m_reduced_detail_mode); +} + +void GCodeViewer::set_reduced_detail_mode(const std::string& mode) +{ + const bool was_solid = solid_model_enabled(); + m_reduced_detail_mode = reduced_detail_mode_from_string(mode); + m_viewer.set_reduced_detail_mode(m_reduced_detail_mode); + + // Only the prime tower comes and goes with the solid model: a full reload would drop the shells + // whenever the print has moved on since they were loaded, leaving the solid model nothing to draw. + if (was_solid == solid_model_enabled() || m_shells.print_id == -1 || wxGetApp().plater() == nullptr) + return; + // the shells are loaded from the current plate's print, which is not the plater's own + const Print& print = wxGetApp().plater()->get_partplate_list().get_current_fff_print(); + if (static_cast(print.id().id) == m_shells.print_id) + update_shell_wipe_tower(print, m_gl_data_initialized); +} + +libvgcode::EReducedDetailMode GCodeViewer::reduced_detail_mode_from_string(const std::string& mode) +{ + if (mode == "solid") + return libvgcode::EReducedDetailMode::EndLayersOnly; + if (mode == "shell") + return libvgcode::EReducedDetailMode::ShellOnly; + return libvgcode::EReducedDetailMode::Off; +} + void GCodeViewer::set_layers_z_range(const std::array& layers_z_range) { m_viewer.set_layers_view_range(static_cast(layers_z_range[0]), static_cast(layers_z_range[1])); @@ -3083,7 +3338,11 @@ void GCodeViewer::export_toolpaths_to_obj(const char* filename) const void GCodeViewer::load_shells(const Print& print, bool initialized, bool force_previewing) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": initialized=%1%, force_previewing=%2%")%initialized %force_previewing; + // the shells can load before the first G-code does, so the preferences are read here as well + read_reduced_detail_preferences(); if ((print.id().id == m_shells.print_id)&&(print.get_modified_count() == m_shells.print_modify_count)) { + // the prime tower comes and goes on its own, without reloading the objects + update_shell_wipe_tower(print, initialized); //BBS: update force previewing logic if (force_previewing) m_shells.previewing = force_previewing; @@ -3192,6 +3451,7 @@ void GCodeViewer::load_shells(const Print& print, bool initialized, bool force_p m_shells.print_id = print.id().id; m_shells.print_modify_count = print.get_modified_count(); m_shells.previewing = true; + update_shell_wipe_tower(print, initialized); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": shell loaded, id change to %1%, modify_count %2%, object count %3%, glvolume count %4%") % m_shells.print_id % m_shells.print_modify_count % object_count %m_shells.volumes.volumes.size(); } @@ -3215,6 +3475,40 @@ void GCodeViewer::render_translucent_toolpaths(int canvas_width, int canvas_heig render_markers(canvas_width, canvas_height); } +// The prime tower as it was sliced, so that the solid model shows what the print shows. It keeps its +// opaque colour, so it never appears among the translucent shells, and stays out of their bounding box. +void GCodeViewer::update_shell_wipe_tower(const Print& print, bool initialized) +{ + const bool with_wipe_tower = solid_model_enabled() && print.is_step_done(psWipeTower) && print.wipe_tower_data().wipe_tower_mesh_data; + if (with_wipe_tower == m_shells.with_wipe_tower) + return; + m_shells.with_wipe_tower = with_wipe_tower; + GLVolumePtrs& volumes = m_shells.volumes.volumes; + if (!with_wipe_tower) { + volumes.erase(std::remove_if(volumes.begin(), volumes.end(), [](GLVolume* volume) { + if (!volume->is_wipe_tower) + return false; + delete volume; + return true; + }), volumes.end()); + return; + } + const PrintConfig& config = print.config(); + const int plate_idx = print.get_plate_index(); + const Vec3d plate_origin = print.get_plate_origin(); + const float x = static_cast(config.wipe_tower_x.get_at(plate_idx) + plate_origin.x()); + const float y = static_cast(config.wipe_tower_y.get_at(plate_idx) + plate_origin.y()); + const size_t first_new = volumes.size(); + m_shells.volumes.load_real_wipe_tower_preview(1000 + plate_idx, x, y, print.wipe_tower_data().wipe_tower_mesh_data->real_wipe_tower_mesh, + print.wipe_tower_data().wipe_tower_mesh_data->real_brim_mesh, true, + static_cast(config.wipe_tower_rotation_angle), false, initialized); + for (size_t i = first_new; i < volumes.size(); ++i) { + volumes[i]->zoom_to_volumes = false; + volumes[i]->force_native_color = true; + volumes[i]->set_render_color(); + } +} + void GCodeViewer::render_toolpaths() { const Camera& camera = wxGetApp().plater()->get_camera(); @@ -3422,6 +3716,288 @@ void GCodeViewer::render_shells() glsafe(::glDepthMask(GL_TRUE)); } +// The sliced objects and the prime tower drawn opaque, in their filament colours, cut to the +// visible layer range by the shader's z range. The toolpaths of the range's bottom and top layers +// are drawn afterwards and cap the cut. +// The layers at the range's ends are drawn as toolpaths, so the solid runs from the top of the +// bottom ones to the bottom of the top ones. A face of the model in either plane would otherwise +// fight the toolpaths for the same pixels and flicker while dragging. +// The layer heights are the toolpaths', which the printer's z offset is already taken out of, so +// they are in the shells' frame as they are. +// A layer with no extrusion has no height of its own; the nearest one below stands in for it. +std::optional> GCodeViewer::solid_model_z_range() const +{ + auto layer_top = [this](size_t id) { + float z = m_viewer.get_layer_z(id); + while (z == 0.0f && id > 0) + z = m_viewer.get_layer_z(--id); + return z; + }; + const libvgcode::Interval whole = m_viewer.get_reduced_detail_whole_layers(); + const float z_top = (whole[1] > 0) ? layer_top(whole[1] - 1) - 0.001f : -FLT_MAX; + const float z_bottom = layer_top(whole[0]) + 0.001f; + // the toolpaths cover the whole range + if (z_top <= z_bottom) + return std::nullopt; + return std::array{ z_bottom, z_top }; +} + +void GCodeViewer::init_solid_model_caps(const std::array& z_range, std::array& caps) const +{ + const auto [z_bottom, z_top] = z_range; + auto init_quad = [](SolidModelCap& cap, const Vec3f& center, const Vec3f& u, const Vec3f& v) { + GLModel::Geometry data; + data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3 }; + data.reserve_vertices(4); + data.reserve_indices(6); + data.add_vertex(Vec3f(center - u - v)); + data.add_vertex(Vec3f(center + u - v)); + data.add_vertex(Vec3f(center + u + v)); + data.add_vertex(Vec3f(center - u + v)); + data.add_triangle(0, 1, 2); + data.add_triangle(0, 2, 3); + cap.quad.init_from(std::move(data)); + }; + const Vec3f box_min = m_paths_bounding_box.min.cast(); + const Vec3f box_max = m_paths_bounding_box.max.cast(); + const Vec3f box_center = 0.5f * (box_min + box_max); + const float margin = 1.0f; + const Vec3f half_x(0.5f * (box_max.x() - box_min.x()) + margin, 0.0f, 0.0f); + const Vec3f half_y(0.0f, 0.5f * (box_max.y() - box_min.y()) + margin, 0.0f); + if (m_viewer.get_layers_view_range()[0] > 0) { + SolidModelCap& cap = caps[0]; + init_quad(cap, Vec3f(box_center.x(), box_center.y(), z_bottom), half_x, half_y); + cap.count_z_range = { z_bottom, FLT_MAX }; + cap.quad_plane = m_clipping_plane; + cap.color_index = 0; + } + if (z_top > -FLT_MAX) { + SolidModelCap& cap = caps[1]; + init_quad(cap, Vec3f(box_center.x(), box_center.y(), z_top), half_x, half_y); + cap.count_z_range = { -FLT_MAX, z_top }; + cap.quad_plane = m_clipping_plane; + cap.color_index = 1; + } + // the section view cuts the solid as it cuts the toolpaths; nothing else sets a plane on the shells + if (m_clipping_plane[0] != 0.0f || m_clipping_plane[1] != 0.0f || m_clipping_plane[2] != 0.0f) { + SolidModelCap& cap = caps[2]; + const Vec3f normal(m_clipping_plane[0], m_clipping_plane[1], m_clipping_plane[2]); + const Vec3f on_plane = box_center - (normal.dot(box_center) + m_clipping_plane[3]) * normal; + // the in-plane axes, turned from the unit axis the normal leans on least + const Vec3f leaning = normal.cwiseAbs(); + const Vec3f axis = (leaning.x() <= leaning.y() && leaning.x() <= leaning.z()) ? Vec3f::UnitX() : + (leaning.y() <= leaning.z()) ? Vec3f::UnitY() : Vec3f::UnitZ(); + const Vec3f u = normal.cross(axis).normalized(); + const Vec3f v = normal.cross(u); + const float reach = 0.5f * (box_max - box_min).norm() + margin; + init_quad(cap, on_plane, reach * u, reach * v); + cap.count_plane = m_clipping_plane; + cap.quad_z_range = { z_bottom, z_top }; + } +} + +void GCodeViewer::render_solid_model(int canvas_width, int canvas_height) +{ + if (m_shells.volumes.empty()) + return; + // gouraud_light has no z range, so it could not cut the model + GLShaderProgram* shader = wxGetApp().get_shader("gouraud"); + if (shader == nullptr) + return; + const std::optional> z_range = solid_model_z_range(); + if (!z_range.has_value()) + return; + const auto [z_bottom, z_top] = *z_range; + const libvgcode::Interval& layers = m_viewer.get_layers_view_range(); + const libvgcode::Interval whole = m_viewer.get_reduced_detail_whole_layers(); + + // the volumes wear the solid's colours for the frame, over their own filament colours + update_solid_model_colors(whole); + const SolidModelColors& colors = m_solid_model_colors; + // The layers the solid stands for are never the ones a slider thumb lights, so the solid + // wears what the toolpath shader gives the rest of the print: dimmed to the preference's + // brightness while the viewer dims the layers around the inspected ones, dark grey while the + // moves slider is short of the top layer's end; see libvgcode::ViewerImpl::set_layer_colors(). + const bool top_layer_only = m_viewer.is_top_layer_only_view_range(); + const bool moves_short = m_viewer.get_view_full_range()[1] != m_viewer.get_view_visible_range()[1]; + const bool inspecting = layers[0] > 0 || layers[1] + 1 < m_viewer.get_layers_count() || moves_short; + const bool dimmed = top_layer_only && inspecting && m_viewer.is_dim_previous_layers(); + const bool greyed = !dimmed && top_layer_only && moves_short; + auto shade = [dimmed, greyed, brightness = m_viewer.get_dim_previous_layers_brightness()](const ColorRGBA& color) { + if (greyed) + return ColorRGBA(64.0f / 255.0f, 64.0f / 255.0f, 64.0f / 255.0f, 1.0f); + if (dimmed) + return ColorRGBA(brightness * color.r(), brightness * color.g(), brightness * color.b(), 1.0f); + return ColorRGBA(color.r(), color.g(), color.b(), 1.0f); + }; + std::vector own_colors; + own_colors.reserve(m_shells.volumes.volumes.size()); + // the tower draws itself in its own colours and leaves the volume's at the default; one list per volume + std::vector> own_tower_colors(m_shells.volumes.volumes.size()); + for (size_t k = 0; k < m_shells.volumes.volumes.size(); ++k) { + GLVolume* volume = m_shells.volumes.volumes[k]; + own_colors.push_back(volume->color); + const std::optional& body = colors.bodies[k].body; + if (auto* tower = dynamic_cast(volume); tower != nullptr) { + own_tower_colors[k] = tower->colors(); + for (ColorRGBA& color : tower->colors()) + color = shade(body.value_or(color)); + } + volume->color = shade(body.value_or(volume->color)); + volume->set_render_color(); + } + m_shells.volumes.set_z_range(z_bottom, z_top); + // the section view cuts the solid as it cuts the toolpaths + m_shells.volumes.set_clipping_plane({ m_clipping_plane[0], m_clipping_plane[1], m_clipping_plane[2], m_clipping_plane[3] }); + + shader->start_using(); + // The realistic view's shadow map, bound by the canvas for the toolpaths, shades the solid + // too, under the same light; both are off when the map is not there. The 3D view leaves its + // own settings on the shared program, so each is set here. + shader->set_uniform("shadow_map", m_shadow_map.texture_unit); + shader->set_uniform("shadow_light_vp", m_shadow_map.light_view_projection); + shader->set_uniform("shadow_map_texel", m_shadow_map.texel_size); + shader->set_uniform("shadow_intensity", m_shadow_map.intensity); + shader->set_uniform("use_static_light", true); + shader->set_uniform("static_light_dir", m_light_top_dir); + const Camera& camera = wxGetApp().plater()->get_camera(); + shader->set_uniform("z_far", camera.get_far_z()); + shader->set_uniform("z_near", camera.get_near_z()); + m_shells.volumes.render(GLVolumeCollection::ERenderType::Opaque, false, camera.get_view_matrix(), camera.get_projection_matrix()); + shader->stop_using(); + + // The cut faces, one cap of one body at a time. A pixel looks into a body through a cut where, + // with the depth test off and the body cut at that cap alone, its back faces outnumber its + // front faces: zero where the ray misses the body or crosses it whole, one where it leaves + // through the opening, which is where the cap plane lies inside the body. Counted with two + // cuts at once the body is an open tube, and a ray through both openings would count as + // closed, one in through a wall and out through the other opening as open. There a quad in + // the cut plane, in the colour of the infill it is cut under darkened, or the body's own, + // stands in for the material, so that a sparse layer on the cut shows a solid inside between + // its lines rather than whatever lies further down. The section view's plane is one more + // cut: its cap is counted on the body cut by it alone and drawn between the heights of the + // other two, and theirs are drawn on its kept side. + GLShaderProgram* cap_shader = wxGetApp().get_shader("flat_clip"); + if (cap_shader != nullptr) { + std::array caps; + init_solid_model_caps(*z_range, caps); + glsafe(::glEnable(GL_STENCIL_TEST)); + for (size_t n = 0; n < m_shells.volumes.volumes.size(); ++n) { + GLVolume* volume = m_shells.volumes.volumes[n]; + const auto* tower = dynamic_cast(volume); + const Transform3d world_matrix = volume->world_matrix(); + for (SolidModelCap& cap : caps) { + if (!cap.quad.is_initialized()) + continue; + begin_cap_count(); + glsafe(::glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)); + // The body is drawn directly, on the uniforms the pass above left on the program: the + // collection's render would build the full preset config and sort every volume, per body. + shader->start_using(); + shader->set_uniform("z_range", cap.count_z_range); + shader->set_uniform("clipping_plane", cap.count_plane); + shader->set_uniform("volume_world_matrix", world_matrix); + shader->set_uniform("view_model_matrix", camera.get_view_matrix() * world_matrix); + volume->render(); + shader->stop_using(); + glsafe(::glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)); + end_cap_count(); + + ColorRGBA inside = volume->color; + if (tower != nullptr && !tower->colors().empty()) + inside = tower->colors().front(); + if (cap.color_index.has_value()) { + if (const std::optional& sampled = colors.bodies[n].caps[*cap.color_index]; sampled.has_value()) + inside = shade(*sampled); + } + inside = ColorRGBA(0.55f * inside.r(), 0.55f * inside.g(), 0.55f * inside.b(), 1.0f); + cap_shader->start_using(); + cap_shader->set_uniform("view_model_matrix", camera.get_view_matrix()); + cap_shader->set_uniform("projection_matrix", camera.get_projection_matrix()); + cap_shader->set_uniform("volume_world_matrix", Transform3d::Identity()); + cap_shader->set_uniform("z_range", cap.quad_z_range); + cap_shader->set_uniform("clipping_plane", cap.quad_plane); + cap.quad.set_color(inside); + cap.quad.render(); + cap_shader->stop_using(); + } + } + glsafe(::glEnable(GL_CULL_FACE)); + glsafe(::glStencilMask(0xFF)); + glsafe(::glDisable(GL_STENCIL_TEST)); + } + + m_shells.volumes.set_z_range(-FLT_MAX, FLT_MAX); + for (size_t k = 0; k < m_shells.volumes.volumes.size(); ++k) { + GLVolume* volume = m_shells.volumes.volumes[k]; + if (auto* tower = dynamic_cast(volume); tower != nullptr) + tower->colors() = own_tower_colors[k]; + volume->color = own_colors[k]; + volume->set_render_color(); + } +} + +// The solid stands in for the toolpaths, so it takes their colours in the view that colours them +// by something other than the filament: each body the outer wall's, each cap the infill's of the +// layer it is cut under, sparse if the layer has any, else solid, and the tower its own role's, +// each from the toolpaths within the body's own footprint, so that objects printed at different +// grades keep their own. The views that colour by filament leave every body its own colour. The +// bodies are sampled over the layers the solid stands for and each cap in its own layer, each +// colour that of the vertex the viewer picks to represent the role there, so a view that grades +// the toolpaths, by speed or fan, shows the solid in the grade most of that role was printed at. +// The bodies are sampled once, as the drag begins, and held while a slider drag moves the span: +// sampled again at every step, the grade would flip with the layers the sample happens to fall +// on. Each cap follows its own layer. +void GCodeViewer::update_solid_model_colors(const libvgcode::Interval& whole_layers) +{ + SolidModelColors& colors = m_solid_model_colors; + const libvgcode::EViewType view_type = m_viewer.get_view_type(); + const std::vector& volumes = m_shells.volumes.volumes; + const bool held = colors.valid && colors.view_type == view_type && colors.bodies.size() == volumes.size(); + if (held && colors.whole_layers == whole_layers) + return; + if (!held) { + colors = SolidModelColors(); + colors.valid = true; + colors.view_type = view_type; + colors.bodies.resize(volumes.size()); + } + colors.whole_layers = whole_layers; + if (view_type == libvgcode::EViewType::Summary || view_type == libvgcode::EViewType::ColorPrint || view_type == libvgcode::EViewType::Tool) + return; + + using Role = libvgcode::EGCodeExtrusionRole; + auto sample = [this](const libvgcode::Interval& layers, std::initializer_list roles, const libvgcode::XYBox& box) -> std::optional { + for (Role role : roles) { + const size_t id = m_viewer.find_extrusion_vertex(layers, role, box); + if (id < m_viewer.get_vertices_count()) + return libvgcode::convert(m_viewer.get_vertex_color(m_viewer.get_vertex_at(id))); + } + return std::nullopt; + }; + const std::initializer_list walls = { Role::ExternalPerimeter, Role::Perimeter, Role::OverhangPerimeter }; + const std::initializer_list tower_role = { Role::WipeTower }; + const std::initializer_list infill = { Role::InternalInfill, Role::SolidInfill, Role::TopSolidInfill, Role::BottomSurface, + Role::BridgeInfill, Role::InternalBridgeInfill, Role::Ironing }; + for (size_t n = 0; n < volumes.size(); ++n) { + const GLVolume* volume = volumes[n]; + const bool tower = dynamic_cast(volume) != nullptr; + // the walls' centrelines lie within the outline, pushed out by a compensation at most + const BoundingBoxf3& footprint = volume->transformed_bounding_box(); + const float margin = 1.0f; + const libvgcode::XYBox box{ { static_cast(footprint.min.x()) - margin, static_cast(footprint.min.y()) - margin }, + { static_cast(footprint.max.x()) + margin, static_cast(footprint.max.y()) + margin } }; + SolidModelColors::Body& body = colors.bodies[n]; + if (!held) + body.body = sample(whole_layers, tower ? tower_role : walls, box); + for (size_t k = 0; k < 2; ++k) { + body.caps[k] = tower ? std::nullopt : sample({ whole_layers[k], whole_layers[k] }, infill, box); + if (!body.caps[k].has_value()) + body.caps[k] = body.body; + } + } +} + //BBS void GCodeViewer::render_all_plates_stats(const std::vector& gcode_result_list, bool show /*= true*/) const { if (!show) diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index c6abdc16a1..8f75b087b6 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -27,6 +27,7 @@ #include #include +#include #include #include #include @@ -198,6 +199,8 @@ public: int print_id{-1}; int print_modify_count{-1}; bool previewing{false}; + // the prime tower was loaded with the objects, for the solid model + bool with_wipe_tower{false}; }; //BBS ConflictResultOpt m_conflict_result; @@ -325,6 +328,76 @@ private: bool m_legend_visible{ true }; bool m_legend_enabled{ true }; + // what the preview draws while the user drags, as the preference has it + libvgcode::EReducedDetailMode m_reduced_detail_mode{ libvgcode::EReducedDetailMode::Off }; + void read_reduced_detail_preferences(); + static libvgcode::EReducedDetailMode reduced_detail_mode_from_string(const std::string& mode); + // in the solid model mode, the sliced objects are drawn as solid shapes instead of toolpaths + bool solid_model_enabled() const { return m_reduced_detail_mode == libvgcode::EReducedDetailMode::EndLayersOnly; } + // whether no layer is lower than the one before, as the solid model's cut needs + bool m_layers_z_rising{ true }; + // the heights the solid model is cut at, unset where the toolpaths cover the whole range + std::optional> solid_model_z_range() const; + void render_solid_model(int canvas_width, int canvas_height); + void render_solid_model_casters(const Transform3d& light_view_matrix, const Transform3d& light_projection_matrix); + // A cut face of the solid model: a quad in the cut plane, drawn where a body cut at it alone is + // open; see render_solid_model() + struct SolidModelCap + { + GLModel quad; + // the body as the count sees it: cut at this cap alone + std::array count_z_range{ -FLT_MAX, FLT_MAX }; + std::array count_plane{ 0.0f, 0.0f, 0.0f, 1.0f }; + // the quad, cut by the other caps + std::array quad_z_range{ -FLT_MAX, FLT_MAX }; + std::array quad_plane{ 0.0f, 0.0f, 0.0f, 1.0f }; + // which of the sampled cap colours it takes, none for the body's own + std::optional color_index; + }; + // the bottom cap, then the top one, as the colours are indexed, then the section view's; a cap + // the solid is not cut at is left without a quad + void init_solid_model_caps(const std::array& z_range, std::array& caps) const; + void release_caster_depth(); + // ORCA: realistic view. The shadow map and light the canvas last passed on, which the solid + // model samples through its own shader as the toolpaths do through theirs. + struct ShadowMap + { + int texture_unit{ 0 }; + Transform3d light_view_projection{ Transform3d::Identity() }; + float intensity{ 0.0f }; + float texel_size{ 0.0f }; + }; + ShadowMap m_shadow_map; + Vec3d m_light_top_dir{ Vec3d::Zero() }; + // the cut faces from the light, counted and drawn apart from the shadow map, which has no + // stencil, then copied into it; see render_solid_model_casters() + unsigned int m_caster_fbo{ 0 }; + unsigned int m_caster_depth{ 0 }; + int m_caster_width{ 0 }; + int m_caster_height{ 0 }; + bool init_caster_depth(int width, int height); + // The solid model's colours in the current view, sampled from the toolpaths when the view + // colours them by something other than the filament; see update_solid_model_colors() + struct SolidModelColors + { + // cleared as a drag begins, see set_interacting() + bool valid{ false }; + libvgcode::EViewType view_type{ libvgcode::EViewType::COUNT }; + libvgcode::Interval whole_layers{ 0, 0 }; + // one per shell volume, from the toolpaths within its own footprint + struct Body + { + // unset where the view colours by filament, or no vertex of the role was found there + std::optional body; + // the bottom and top caps + std::array, 2> caps; + }; + std::vector bodies; + }; + SolidModelColors m_solid_model_colors; + void update_solid_model_colors(const libvgcode::Interval& whole_layers); + // the prime tower is only among the shells for the solid model, so it is added or removed when that changes + void update_shell_wipe_tower(const Print& print, bool initialized); float m_legend_height; PrintEstimatedStatistics m_print_statistics; @@ -347,7 +420,8 @@ mutable bool m_no_render_path { false }; float m_belt_angle_deg = 0.f; libvgcode::Viewer m_viewer; - // ORCA: section view, as the viewer has it. What it cuts away casts no shadow. + // ORCA: section view, as the viewer has it: kept where the dot with it is positive, a zero + // normal when off. The solid model is cut by it too, and what it cuts away casts no shadow. std::array m_clipping_plane{ 0.0f, 0.0f, 0.0f, 1.0f }; bool m_loaded_as_preview{ false }; @@ -400,7 +474,7 @@ public: // void _render_calibration_thumbnail_internal(ThumbnailData& thumbnail_data, const ThumbnailsParams& thumbnail_params, PartPlateList& partplate_list, OpenGLManager& opengl_manager); // void _render_calibration_thumbnail_framebuffer(ThumbnailData& thumbnail_data, unsigned int w, unsigned int h, const ThumbnailsParams& thumbnail_params, PartPlateList& partplate_list, OpenGLManager& opengl_manager); // void render_calibration_thumbnail(ThumbnailData& thumbnail_data, unsigned int w, unsigned int h, const ThumbnailsParams& thumbnail_params, PartPlateList& partplate_list, OpenGLManager& opengl_manager); - bool has_data() const { return !m_viewer.get_extrusion_roles().empty(); } + bool has_data() const { return m_viewer.get_extrusion_roles_count() != 0; } bool can_export_toolpaths() const; std::vector get_plater_extruder(); @@ -487,6 +561,14 @@ public: // ORCA: draw the toolpaths of translucent filament colors translucent void set_translucent_filaments(bool value) { m_viewer.set_translucent_filaments(value); } + // whether the mouse is holding either slider's handle + bool is_slider_dragging() const { return m_layers_slider->is_dragging() || m_moves_slider->is_dragging(); } + // while the user drags the camera or a slider, draw the reduced set, if the preference asks for one + void set_interacting(bool interacting); + bool is_reduced_detail() const { return m_viewer.is_reduced_detail(); } + // the preference's string value: "off", "solid" or "shell" + void set_reduced_detail_mode(const std::string& mode); + void set_layers_z_range(const std::array& layers_z_range); bool is_legend_shown() const { return m_legend_visible && m_legend_enabled; } diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 93d2b7f42b..a11667e460 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -2637,6 +2637,11 @@ void GLCanvas3D::_render_frame(bool scene_dirty, bool only_init) const bool overlay_tick = m_fps_overlay_tick; m_fps_overlay_tick = false; + // Whether the preview draws its reduced set is decided before the cached scene is consulted, + // since switching changes what the scene pass draws. + if (m_canvas_type == ECanvasType::CanvasPreview && m_render_preview && m_gcode_viewer.has_data() && _update_preview_interaction()) + scene_dirty = true; + // An overlay-only frame reuses the last scene pass. The overlay is rebuilt either way, and drawn // below once it is known whether the frame differs from the one on screen. const bool reuse_scene = !scene_dirty && _can_reuse_cached_scene(camera); @@ -3975,6 +3980,11 @@ void GLCanvas3D::bind_event_handlers() } #endif ImGui::SetWindowFocus(nullptr); + // a drag cut short never sees its button release, which would leave the reduced set drawn + if (m_canvas_type == CanvasPreview && m_mouse.dragging && m_gcode_viewer.is_reduced_detail()) + mouse_up_cleanup(); + // nor does the navigator's, whose flag holds for as long as the button is known to be down + m_navigator_dragging = false; render(); evt.Skip(); }); @@ -3988,8 +3998,15 @@ void GLCanvas3D::bind_event_handlers() for (bool& down : io.MouseDown) down = false; } - m_navigator_dragging = false; - m_mouse.down_on_toolbar = false; + // a drag cut short never sees its button release, which would leave the solid model drawn + if (m_canvas_type == CanvasPreview && m_mouse.dragging && m_gcode_viewer.is_reduced_detail()) + mouse_up_cleanup(); + if (m_navigator_dragging) { + m_navigator_dragging = false; + m_mouse.down_on_toolbar = false; + m_dirty = true; + wxWakeUpIdle(); + } render(); }); m_event_handlers_bound = true; @@ -4067,6 +4084,17 @@ void GLCanvas3D::on_idle(wxIdleEvent& evt) m_overlay_dirty |= imgui_requires_extra_frame; #endif // ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT m_dirty |= GLTexture::Compressor::has_compressed_texture_to_refresh(); + // the render timer only wakes the idle loop; the frame that puts the preview's toolpaths back + // after a wheel burst has to be asked for here, once the settle time is really up + if (m_preview_settle_pending) { + const auto now = std::chrono::steady_clock::now(); + if (now >= m_preview_interaction_until) { + m_preview_settle_pending = false; + m_dirty = true; + } + else // the timer fired early + schedule_extra_frame(static_cast(std::chrono::duration_cast(m_preview_interaction_until - now).count()) + 1); + } if (!m_dirty && !m_overlay_dirty) return; @@ -4567,6 +4595,11 @@ void GLCanvas3D::on_mouse_wheel(wxMouseEvent& evt) return; } + // only a wheel the panels did not take moves the camera; a wheel step is over before the next + // frame, so it holds the preview's reduced set for a settle time + if (m_canvas_type == CanvasPreview) + m_preview_interaction_until = std::chrono::steady_clock::now() + std::chrono::milliseconds(150); + #ifdef __WXMSW__ // For some reason the Idle event is not being generated after the mouse scroll event in case of scrolling with the two fingers on the touch pad, // if the event is not allowed to be passed further. @@ -6378,6 +6411,9 @@ void GLCanvas3D::mouse_up_cleanup() m_mouse.ignore_right_up = false; m_mouse.down_on_toolbar = false; m_dirty = true; + // the frame that follows a release puts the preview's toolpaths back, and on some platforms + // no idle event follows a button release until the next input + wxWakeUpIdle(); if (m_canvas->HasCapture()) m_canvas->ReleaseMouse(); @@ -6867,6 +6903,7 @@ void GLCanvas3D::_render_3d_navigator() if (!wxGetApp().show_3d_navigator()) { m_canvas_toolbar_pos[0] = 0; m_navigator_dragging = false; + m_navigator_animating = false; return; } @@ -6961,7 +6998,17 @@ void GLCanvas3D::_render_3d_navigator() request_extra_frame(); } - m_navigator_dragging = result.dragging; + // The navigator reports a drag only on a frame the mouse moved in, which would drop the flag on + // every still frame of a drag and leave it up after a release with no motion; it holds for as + // long as the button does. + m_navigator_dragging = result.dragging || (m_navigator_dragging && io.MouseDown[0]); + // A click on a face or a corner turns the camera over the frames that follow, with no button + // held, each reported as a change that is not a drag. The frame after the last of them is asked + // for, so that what the turn held back is drawn again. + const bool animating = result.changed && !result.dragging; + if (m_navigator_animating && !animating) + request_extra_frame(); + m_navigator_animating = animating; } #define ENABLE_THUMBNAIL_GENERATOR_DEBUG_OUTPUT 0 @@ -8694,13 +8741,22 @@ bool GLCanvas3D::_is_scene_cacheable() const return false; #endif - // The scene follows the cursor during a drag, under a gizmo that draws at the cursor, and while - // the cursor is on the layer height bar, where the object shader draws a band at its height. + // The scene follows the cursor while the user drags, under a gizmo that draws at the cursor, and + // while the cursor is on the layer height bar, where the object shader draws a band at its height. const GLGizmoBase* gizmo = m_gizmos.get_current(); const bool cursor_on_layers_bar = is_layers_editing_enabled() && m_layers_editing.bar_rect_contains(*this, (float)m_mouse.position.x(), (float)m_mouse.position.y()); - return !m_mouse.dragging && !m_gizmos.is_dragging() && !m_rectangle_selection.is_dragging() && - (gizmo == nullptr || !gizmo->render_follows_cursor()) && !cursor_on_layers_bar; + return !is_user_interacting() && (gizmo == nullptr || !gizmo->render_follows_cursor()) && !cursor_on_layers_bar; +} + +// Whether the user is holding something that moves the scene: the camera, the navigator, a gizmo, +// the rectangle selection or a preview slider, or the navigator is still turning the camera for them. +bool GLCanvas3D::is_user_interacting() const +{ + // the navigator's flag is cleared by the overlay, later in the frame than this is asked + const bool navigator_dragging = m_navigator_dragging && GImGui != nullptr && ImGui::GetIO().MouseDown[0]; + return m_mouse.dragging || navigator_dragging || m_navigator_animating || m_gizmos.is_dragging() || + m_rectangle_selection.is_dragging() || m_gcode_viewer.is_slider_dragging(); } bool GLCanvas3D::_is_frame_skipping_enabled() const @@ -10031,6 +10087,24 @@ void GLCanvas3D::_render_wireframe_overlay() shader->stop_using(); } +// The reduced set is drawn while the camera, the navigator or either slider is dragged. A wheel +// step has no duration, so it holds the reduced set for a settle time instead, and the frame that +// restores the full toolpaths is scheduled for when that time runs out. Returns whether what the scene +// pass draws changed, since a frame that reuses the cached scene would hide the change. +bool GLCanvas3D::_update_preview_interaction() +{ + const auto now = std::chrono::steady_clock::now(); + const bool settling = now < m_preview_interaction_until; + const bool dragging = is_user_interacting(); + const bool was_reduced = m_gcode_viewer.is_reduced_detail(); + m_gcode_viewer.set_interacting(dragging || settling); + if (settling && !dragging && m_gcode_viewer.is_reduced_detail()) { + m_preview_settle_pending = true; + schedule_extra_frame(static_cast(std::chrono::duration_cast(m_preview_interaction_until - now).count()) + 1); + } + return m_gcode_viewer.is_reduced_detail() != was_reduced; +} + //BBS: GUI refactor: add canvas size as parameters void GLCanvas3D::_render_gcode(int canvas_width, int canvas_height) { diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 8d834065cf..b4b60749ad 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -786,6 +786,12 @@ private: ECursorType m_cursor_type; GLSelectionRectangle m_rectangle_selection; bool m_navigator_dragging{ false }; + // whether a click on the navigator is still turning the camera, over the frames that follow it + bool m_navigator_animating{ false }; + // until when a wheel step keeps the preview's reduced set drawn + std::chrono::time_point m_preview_interaction_until{}; + // whether the frame that restores the toolpaths once that time is up is still owed + bool m_preview_settle_pending{ false }; //BBS:add plate related logic mutable std::vector m_hover_volume_idxs; @@ -1397,6 +1403,8 @@ public: void msw_rescale() { m_gcode_viewer.invalidate_legend(); } void request_extra_frame() { m_extra_frame_requested = true; } + // whether the user is holding the camera, the navigator, a gizmo, the rectangle selection or a preview slider + bool is_user_interacting() const; void schedule_extra_frame(int milliseconds); @@ -1580,6 +1588,9 @@ private: // Realistic view: binds, or unbinds, the shadow map the toolpaths read on texture unit 4. False without a map. bool _bind_gcode_shadow_map(bool bind) const; void _render_gcode_overlay(int canvas_width, int canvas_height); + // decides whether the preview draws its reduced set this frame and returns whether what the scene + // pass draws changed; runs before the cached scene is consulted + bool _update_preview_interaction(); //BBS: render a plane for assemble void _render_plane() const; void _render_selection(); diff --git a/src/slic3r/GUI/GLShadersManager.cpp b/src/slic3r/GUI/GLShadersManager.cpp index 0ea7faa4f5..49e22eff25 100644 --- a/src/slic3r/GUI/GLShadersManager.cpp +++ b/src/slic3r/GUI/GLShadersManager.cpp @@ -52,6 +52,9 @@ std::pair GLShadersManager::init() valid &= append_shader("flat", { prefix + "flat.vs", prefix + "flat.fs" }); // basic shader with plane clipping, used to render volumes in picking pass valid &= append_shader("flat_clip", { prefix + "flat_clip.vs", prefix + "flat_clip.fs" }); + // copies a depth texture into the bound depth buffer, used by the G-code preview's solid model + // to cast its cut faces into the shadow map + valid &= append_shader("depth_copy", { prefix + "depth_copy.vs", prefix + "depth_copy.fs" }); // basic shader for textures, used to render textures valid &= append_shader("flat_texture", { prefix + "flat_texture.vs", prefix + "flat_texture.fs" }); // used to apply post-processing antialiasing in screen space diff --git a/src/slic3r/GUI/IMSlider.cpp b/src/slic3r/GUI/IMSlider.cpp index c0c2decfac..2f7ae19e59 100644 --- a/src/slic3r/GUI/IMSlider.cpp +++ b/src/slic3r/GUI/IMSlider.cpp @@ -520,6 +520,11 @@ void IMSlider::draw_background_and_groove(const ImRect& bg_rect, const ImRect& g ImGui::RenderFrame(groove.Min, groove.Max, groove_col, false, 0.5 * groove.GetWidth()); } +bool IMSlider::is_dragging() const +{ + return GImGui != nullptr && m_imgui_id != 0 && GImGui->ActiveId == m_imgui_id && GImGui->IO.MouseDown[0]; +} + bool IMSlider::horizontal_slider(const char* str_id, int* value, int v_min, int v_max, const ImVec2& size, float scale) { ImGuiWindow* window = ImGui::GetCurrentWindow(); @@ -528,6 +533,7 @@ bool IMSlider::horizontal_slider(const char* str_id, int* value, int v_min, int ImGuiContext& context = *GImGui; const ImGuiID id = window->GetID(str_id); + m_imgui_id = id; const ImVec2 pos = window->DC.CursorPos; const ImRect draw_region(pos, pos + size); @@ -920,6 +926,7 @@ bool IMSlider::vertical_slider(const char* str_id, int* higher_value, int* lower ImGuiContext& context = *GImGui; const ImGuiID id = window->GetID(str_id); + m_imgui_id = id; const ImVec2 pos = window->DC.CursorPos; const ImRect draw_region(pos, pos + size); diff --git a/src/slic3r/GUI/IMSlider.hpp b/src/slic3r/GUI/IMSlider.hpp index 4f02167669..b03ac147a3 100644 --- a/src/slic3r/GUI/IMSlider.hpp +++ b/src/slic3r/GUI/IMSlider.hpp @@ -125,6 +125,9 @@ public: //BBS update scroll value changed bool is_dirty() { return m_dirty; } + // whether the mouse is holding this slider's handle, read from ImGui's active id rather than + // from the dirty flag, which is raised and consumed inside a single frame + bool is_dragging() const; void set_as_dirty(bool dirty = true) { m_dirty = dirty; } bool is_need_post_tick_event() { return m_is_need_post_tick_changed_event; } void reset_post_tick_event(bool val = false) { @@ -189,6 +192,8 @@ private: int m_higher_value; int m_one_layer_value; // ORCA bool m_dirty = false; + // the ImGui id of the slider widget, as of its last render + unsigned int m_imgui_id = 0; bool m_render_as_disabled{ false }; diff --git a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp index f91fc0ed23..35abe01c6f 100644 --- a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp +++ b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include "libslic3r/Point.hpp" @@ -235,6 +236,65 @@ static bool starts_path(const Slic3r::GCodeProcessorResult::MoveVertex& prev, || prev.mm3_per_mm != curr.mm3_per_mm || prev.acceleration != curr.acceleration || prev.jerk != curr.jerk; } +void LayersClosedByInfill::add(uint32_t layer_id, int object_id, EGCodeExtrusionRole role, EMoveType type) +{ + if (type != EMoveType::Extrude) + return; + uint8_t bit = 0; + switch (role) { + case EGCodeExtrusionRole::Perimeter: + case EGCodeExtrusionRole::ExternalPerimeter: + case EGCodeExtrusionRole::OverhangPerimeter: + bit = 1; break; + case EGCodeExtrusionRole::InternalInfill: { + bit = 2; + auto [it, inserted] = m_sparse_span.emplace(object_id, std::make_pair(layer_id, layer_id)); + if (!inserted) { + it->second.first = std::min(it->second.first, layer_id); + it->second.second = std::max(it->second.second, layer_id); + } + break; + } + case EGCodeExtrusionRole::SolidInfill: + case EGCodeExtrusionRole::TopSolidInfill: + case EGCodeExtrusionRole::Ironing: + case EGCodeExtrusionRole::BridgeInfill: + case EGCodeExtrusionRole::BottomSurface: + case EGCodeExtrusionRole::InternalBridgeInfill: + bit = 4; break; + default: + return; + } + if (layer_id >= m_layers.size()) + m_layers.resize(static_cast(layer_id) + 1); + m_layers[layer_id][object_id] |= bit; + m_labelled |= object_id >= 0; +} + +std::vector LayersClosedByInfill::finish(size_t layers_count) const +{ + if (!m_labelled) + return {}; + std::vector ret(layers_count, 0); + for (size_t i = 0; i < std::min(layers_count, m_layers.size()); ++i) { + // closed when something is printed and every object printed is closed + bool from_above = !m_layers[i].empty(); + bool from_below = from_above; + for (const auto& [object_id, bits] : m_layers[i]) { + if ((bits & 2) != 0) + continue; + const bool solid = (bits & 4) != 0; + const auto span = m_sparse_span.find(object_id); + const bool sparse_above = span != m_sparse_span.end() && span->second.second > i; + const bool sparse_below = span != m_sparse_span.end() && span->second.first < i; + from_above &= solid && !sparse_above; + from_below &= solid && !sparse_below; + } + ret[i] = static_cast((from_above ? 1 : 0) | (from_below ? 2 : 0)); + } + return ret; +} + GCodeInputData convert(const Slic3r::GCodeProcessorResult& result, const std::vector& str_tool_colors, const std::vector& str_color_print_colors, const Viewer& viewer, const Slic3r::Transform3d* belt_xform) @@ -271,22 +331,25 @@ GCodeInputData convert(const Slic3r::GCodeProcessorResult& result, const std::ve // the ids consecutively over the moves that exist. uint32_t src_layer_id = std::numeric_limits::max(); uint32_t layer_id = 0; + LayersClosedByInfill closed_layers; for (size_t i = 1; i < moves.size(); ++i) { const Slic3r::GCodeProcessorResult::MoveVertex& curr = moves[i]; const Slic3r::GCodeProcessorResult::MoveVertex& prev = moves[i - 1]; const EMoveType curr_type = convert(curr.type); + const EGCodeExtrusionRole curr_role = convert(curr.extrusion_role); if (curr.layer_id != src_layer_id) { if (src_layer_id != std::numeric_limits::max()) ++ layer_id; src_layer_id = curr.layer_id; } + closed_layers.add(layer_id, curr.object_label_id, curr_role, curr_type); if (starts_path(prev, curr, i == 1)) { // to allow libvgcode to properly detect the start/end of a path we need to add a 'phantom' vertex // equal to the current one with the exception of the position, which should match the previous move position, // and the times, which are set to zero #if VGCODE_ENABLE_COG_AND_TOOL_MARKERS const libvgcode::PathVertex vertex = { xform_pos(prev.position), curr.height, curr.width, curr.feedrate, prev.actual_feedrate, - curr.mm3_per_mm, curr.fan_speed, curr.temperature, 0.0f, convert(curr.extrusion_role), curr_type, + curr.mm3_per_mm, curr.fan_speed, curr.temperature, 0.0f, curr_role, curr_type, static_cast(curr.gcode_id), layer_id, static_cast(curr.extruder_id), static_cast(curr.cp_color_id), { 0.0f, 0.0f }, /* ORCA: Add Pressure Advance visualization support */ 0.0f, curr.pressure_advance, @@ -294,7 +357,7 @@ GCodeInputData convert(const Slic3r::GCodeProcessorResult& result, const std::ve /* ORCA: Add Jerk visualization support */ curr.jerk }; #else const libvgcode::PathVertex vertex = { xform_pos(prev.position), curr.height, curr.width, curr.feedrate, prev.actual_feedrate, - curr.mm3_per_mm, curr.fan_speed, curr.temperature, convert(curr.extrusion_role), curr_type, + curr.mm3_per_mm, curr.fan_speed, curr.temperature, curr_role, curr_type, static_cast(curr.gcode_id), layer_id, static_cast(curr.extruder_id), static_cast(curr.cp_color_id), { 0.0f, 0.0f }, /* ORCA: Add Pressure Advance visualization support */ 0.0f, curr.pressure_advance, @@ -308,14 +371,14 @@ GCodeInputData convert(const Slic3r::GCodeProcessorResult& result, const std::ve const libvgcode::PathVertex vertex = { xform_pos(curr.position), curr.height, curr.width, curr.feedrate, curr.actual_feedrate, curr.mm3_per_mm, curr.fan_speed, curr.temperature, result.filament_densities[curr.extruder_id] * curr.mm3_per_mm * (curr.position - prev.position).norm(), - convert(curr.extrusion_role), curr_type, static_cast(curr.gcode_id), layer_id, + curr_role, curr_type, static_cast(curr.gcode_id), layer_id, static_cast(curr.extruder_id), static_cast(curr.cp_color_id), curr.time, /* ORCA: Add Pressure Advance visualization support */ 0.0f, curr.pressure_advance, /* ORCA: Add Acceleration visualization support */ curr.acceleration, /* ORCA: Add Jerk visualization support */ curr.jerk }; #else const libvgcode::PathVertex vertex = { xform_pos(curr.position), curr.height, curr.width, curr.feedrate, curr.actual_feedrate, - curr.mm3_per_mm, curr.fan_speed, curr.temperature, convert(curr.extrusion_role), curr_type, + curr.mm3_per_mm, curr.fan_speed, curr.temperature, curr_role, curr_type, static_cast(curr.gcode_id), layer_id, static_cast(curr.extruder_id), static_cast(curr.cp_color_id), curr.time, /* ORCA: Add Pressure Advance visualization support */ 0.0f, curr.pressure_advance, @@ -334,6 +397,7 @@ GCodeInputData convert(const Slic3r::GCodeProcessorResult& result, const std::ve // model bounding box. Nothing extra to do here. ret.spiral_vase_mode = result.spiral_vase_mode; + ret.layers_closed = closed_layers.finish(moves.size() > 1 ? static_cast(layer_id) + 1 : 0); return ret; } diff --git a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp index b354abd81e..bf0ec4732b 100644 --- a/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp +++ b/src/slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp @@ -13,6 +13,9 @@ #include #include #include +#include +#include +#include #include "../../src/libvgcode/include/Types.hpp" #include "libslic3r/Color.hpp" @@ -71,6 +74,32 @@ extern ETimeMode convert(const Slic3r::PrintEstimatedStatistics::ETimeMode& mode // mapping from libvgcode::ETimeMode to Slic3r::PrintEstimatedStatistics::ETimeMode extern Slic3r::PrintEstimatedStatistics::ETimeMode convert(const ETimeMode& mode); +// Which layers' infill closes every object printed on them, for GCodeInputData::layers_closed. +// Sparse infill closes an object on a layer. Solid infill closes it only where the object has no +// sparse infill left in the direction the band looks from: its top shells close it as seen from +// above, its bottom shells as seen from below, and an object with no sparse infill anywhere is +// closed by any infill. In between, infill combination leaves a layer with walls and the solid +// infill under its skins alone, and its middle open. A layer of support alone closes nothing. The +// objects are the ones the G-code labels its moves with; moves of no object count as one object +// of their own. +class LayersClosedByInfill +{ +public: + void add(uint32_t layer_id, int object_id, EGCodeExtrusionRole role, EMoveType type); + // One entry per layer, bit 0 closed from above and bit 1 closed from below, 0 for a layer + // nothing was added for. Empty when no move belonged to an object (objects not labelled in + // the G-code): the viewer then judges the layers by their roles as a whole, which tells more + // than one tally of the plate. + std::vector finish(size_t layers_count) const; + +private: + // per layer, per object: bit 0 for walls, bit 1 for sparse infill, bit 2 for other infill + std::vector> m_layers; + // per object, the first and last layer with sparse infill + std::map> m_sparse_span; + bool m_labelled{ false }; +}; + // mapping from Slic3r::GCodeProcessorResult to libvgcode::GCodeInputData extern GCodeInputData convert(const Slic3r::GCodeProcessorResult& result, const std::vector& str_tool_colors, const std::vector& str_color_print_colors, const Viewer& viewer, diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index a66f09c368..16a6b390b2 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -425,7 +425,7 @@ wxBoxSizer* PreferencesDialog::create_item_combobox(wxString title, wxString too return sizer; } -wxBoxSizer *PreferencesDialog::create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::vector config_name_index, const wxString wiki_url) +wxBoxSizer *PreferencesDialog::create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::vector config_name_index, std::function onchange, const wxString wiki_url) { assert(vlist.size() == config_name_index.size()); unsigned int current_index = 0; @@ -441,8 +441,9 @@ wxBoxSizer *PreferencesDialog::create_item_combobox(wxString title, wxString too auto [sizer, combobox] = create_item_combobox_base(title, tooltip, param, vlist, current_index); //// save config - combobox->GetDropDown().Bind(wxEVT_COMBOBOX, [this, param, config_name_index](wxCommandEvent& e) { + combobox->GetDropDown().Bind(wxEVT_COMBOBOX, [this, param, config_name_index, onchange](wxCommandEvent& e) { app_config->set(param, config_name_index[e.GetSelection()]); + if (onchange != nullptr) onchange(config_name_index[e.GetSelection()]); e.Skip(); }); @@ -2040,6 +2041,33 @@ void PreferencesDialog::create_items() "preview_default_view_type", PreviewViewTypeLabels, PreviewViewTypeValues); g_sizer->Add(item_preview_view_type); + auto item_reduced_detail_mode = create_item_combobox( + _L("Simplify preview while dragging"), + _L("What the sliced preview draws while you drag the camera or a preview slider, or zoom with the mouse wheel, so that large prints stay responsive. " + "The full toolpaths are restored as soon as you let go.\n" + "Off: the full toolpaths.\n" + "Solid model: the sliced objects and the prime tower as solid shapes in the colors of the current view, cut to the visible layer range, " + "with its bottom and top layers and the supports drawn as toolpaths. Negative volumes are not cut out. " + "A print made object by object, or one on a belt printer, keeps its full toolpaths.\n" + "Shell only: every layer without its sparse infill, internal solid infill, internal bridges and gap fill, which lie under the walls and skins. " + "Walls, top and bottom surfaces, bridges, supports and the prime tower are drawn whole, so the print looks the same from outside.\n" + "The bottom and top layers of the visible range are always drawn whole; a layer with no infill of its own, as with infill combination, takes the layers down to the nearest one with infill along."), + "preview_reduced_detail_mode", + {_L("Off"), _L("Solid model"), _L("Shell only")}, + {"off", "solid", "shell"}, + // apply the new mode immediately to the currently loaded preview + [](std::string value) { + if (Plater* plater = wxGetApp().plater()) { + if (GLCanvas3D* canvas = plater->get_preview_canvas3D()) { + canvas->get_gcode_viewer().set_reduced_detail_mode(value); + canvas->set_as_dirty(); + canvas->request_extra_frame(); + } + } + } + ); + g_sizer->Add(item_reduced_detail_mode); + auto item_dim_previous_layers = create_item_checkbox( _L("Dim lower layers"), _L("When scrubbing the layer slider in the sliced preview, render the layers below the current one darkened so that only the layer being viewed is shown at full brightness."), diff --git a/src/slic3r/GUI/Preferences.hpp b/src/slic3r/GUI/Preferences.hpp index 440b8d0e0c..21f9da8a87 100644 --- a/src/slic3r/GUI/Preferences.hpp +++ b/src/slic3r/GUI/Preferences.hpp @@ -102,7 +102,7 @@ public: wxBoxSizer *create_item_title(wxString title); wxBoxSizer *create_item_label(wxString label, const wxString tooltip = "", const wxString wiki_url = ""); wxBoxSizer *create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::function onchange = {}, const wxString wiki_url = ""); - wxBoxSizer *create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::vector config_name_index, const wxString wiki_url = ""); + wxBoxSizer *create_item_combobox(wxString title, wxString tooltip, std::string param, std::vector vlist, std::vector config_name_index, std::function onchange = {}, const wxString wiki_url = ""); wxBoxSizer *create_item_region_combobox(wxString title, wxString tooltip); wxBoxSizer *create_item_language_combobox(wxString title, wxString tooltip); wxBoxSizer *create_item_loglevel_combobox(wxString title, wxString tooltip, std::vector vlist); diff --git a/tests/fff_print/test_gcode_processor.cpp b/tests/fff_print/test_gcode_processor.cpp index 82b2e760a3..b803121d6e 100644 --- a/tests/fff_print/test_gcode_processor.cpp +++ b/tests/fff_print/test_gcode_processor.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -166,3 +167,48 @@ TEST_CASE("Non-belt start G-code moves keep the first-layer Z in the processor", CHECK_THAT(result.moves[first_extrude].position.z(), WithinAbs(50., 1e-3)); CHECK_THAT(result.moves[first_extrude - 1].position.z(), WithinAbs(0.3, 1e-3)); } + +TEST_CASE("Object labels of every style give the moves their object id", "[GCodeProcessor]") +{ + // the label styles do not depend on the printer kind, and the static flag is whatever the + // test before left it + struct BBLPrinterGuard { + bool prev = GCodeProcessor::s_IsBBLPrinter; + BBLPrinterGuard() { GCodeProcessor::s_IsBBLPrinter = false; } + ~BBLPrinterGuard() { GCodeProcessor::s_IsBBLPrinter = prev; } + } bbl_guard; + + const std::string gcode = + "G90\nG21\nM83\n" + ";TYPE:Custom\n" + "G1 Z0.2 F12000\n" + ";TYPE:Outer wall\n" + "G1 X1 Y0 E0.05 F1800\n" + "; printing object part: v2.stl id:3 copy 0\n" + "G1 X2 Y0 E0.05\n" + "; stop printing object part: v2.stl id:3 copy 0\n" + "G1 X3 Y0 E0.05\n" + "; printing object other.stl id:4 copy 1\n" + "; start printing object, unique label id: 12\n" + "G1 X4 Y0 E0.05\n" + "; stop printing object, unique label id: 12\n" + "G1 X5 Y0 E0.05\n"; + + GCodeProcessor processor; + FullPrintConfig config; + config.initial_layer_print_height.value = 0.2; + processor.apply_config(config); + processor.process_buffer(gcode); + const GCodeProcessorResult &result = processor.get_result(); + + std::vector ids; + for (const GCodeProcessorResult::MoveVertex &move : result.moves) + if (move.type == EMoveType::Extrude) + ids.push_back(move.object_label_id); + REQUIRE(ids.size() == 5); + CHECK(ids[0] == -1); + CHECK(ids[1] == 3); + CHECK(ids[2] == -1); + CHECK(ids[3] == 12); + CHECK(ids[4] == -1); +} diff --git a/tests/libslic3r/test_appconfig.cpp b/tests/libslic3r/test_appconfig.cpp index 6f0ee69da7..17c1bc268c 100644 --- a/tests/libslic3r/test_appconfig.cpp +++ b/tests/libslic3r/test_appconfig.cpp @@ -13,6 +13,8 @@ #include #include +#include + using namespace Slic3r; TEST_CASE("Full collision-volume previews are opt-in and retain the user's preference", "[AppConfig][ExclusionVolume]") @@ -343,3 +345,27 @@ TEST_CASE("A backup without the checksum line is not restored", "[AppConfig][Reg CHECK(config.get("k").empty()); } #endif + +TEST_CASE("AppConfig keeps only the preview drag modes it knows", "[AppConfig]") { + AppConfig config; + const std::string key = "preview_reduced_detail_mode"; + + SECTION("a missing value becomes off") { + config.set_defaults(); + REQUIRE(config.get(key) == "off"); + } + + SECTION("a known mode is kept") { + const std::string mode = GENERATE("off", "solid", "shell"); + config.set(key, mode); + config.set_defaults(); + REQUIRE(config.get(key) == mode); + } + + SECTION("an unknown mode falls back to off") { + const std::string mode = GENERATE("layers", "outer_walls", ""); + config.set(key, mode); + config.set_defaults(); + REQUIRE(config.get(key) == "off"); + } +} diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 09cfeca2b8..ef279428cf 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -16,6 +16,10 @@ add_executable(${_TEST_NAME}_tests test_filament_color_picker.cpp test_ams_materials_setting.cpp test_gcode_preview_colors.cpp + # The reduced toolpath set's end bands, from libvgcode's layer table. + test_libvgcode_layers.cpp + # The vertex that stands for a role when the solid model takes the toolpaths' colours. + test_libvgcode_sampling.cpp test_device_progress.cpp test_device_manager_integration.cpp test_web_media_controller.cpp diff --git a/tests/slic3rutils/test_libvgcode_layers.cpp b/tests/slic3rutils/test_libvgcode_layers.cpp new file mode 100644 index 0000000000..b78a002c41 --- /dev/null +++ b/tests/slic3rutils/test_libvgcode_layers.cpp @@ -0,0 +1,287 @@ +// The end bands of the reduced toolpath set, decided by libvgcode's layer table from the roles +// each layer was printed with. +#include + +#include +#include +#include + +#include "libvgcode/include/PathVertex.hpp" +#include "libvgcode/include/Types.hpp" +#include "libvgcode/src/Layers.hpp" +#include "libvgcode/src/Utils.hpp" +#include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp" + +using libvgcode::EGCodeExtrusionRole; +using libvgcode::EMoveType; +using libvgcode::Interval; +using libvgcode::Layers; +using libvgcode::PathVertex; + +namespace { + +// One extrusion of each given role per layer, layers 0 to count - 1, 0.2 mm apart. +Layers layers_with(std::size_t count, const std::vector>& roles_per_layer) +{ + Layers layers; + uint32_t id = 0; + for (std::size_t layer = 0; layer < count; ++layer) { + const std::vector& roles = roles_per_layer[layer % roles_per_layer.size()]; + PathVertex v; + v.type = EMoveType::Travel; + v.layer_id = static_cast(layer); + v.position = { 0.0f, 0.0f, 0.2f * static_cast(layer + 1) }; + layers.update(v, id++); + for (EGCodeExtrusionRole role : roles) { + v.type = EMoveType::Extrude; + v.role = role; + layers.update(v, id++); + } + } + return layers; +} + +const std::vector walls_and_infill = { EGCodeExtrusionRole::ExternalPerimeter, EGCodeExtrusionRole::Perimeter, EGCodeExtrusionRole::InternalInfill }; +const std::vector walls_only = { EGCodeExtrusionRole::ExternalPerimeter, EGCodeExtrusionRole::Perimeter }; +const std::vector support_only = { EGCodeExtrusionRole::SupportMaterial }; + +} // namespace + +TEST_CASE("A range whose end layers have infill keeps just those two layers whole", "[Libvgcode]") +{ + Layers layers = layers_with(10, { walls_and_infill }); + layers.set_view_range(2, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 2, 7 }); +} + +TEST_CASE("A top layer with walls alone takes the layers down to the nearest infill along", "[Libvgcode]") +{ + // infill combination over three layers: the infill lands on layers 0, 3, 6 and 9 + Layers layers = layers_with(10, { walls_and_infill, walls_only, walls_only }); + layers.set_view_range(0, 8); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 6 }); + layers.set_view_range(0, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 6 }); + layers.set_view_range(0, 9); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 9 }); +} + +TEST_CASE("A bottom layer with walls alone takes the layers up to the nearest infill along", "[Libvgcode]") +{ + Layers layers = layers_with(10, { walls_and_infill, walls_only, walls_only }); + layers.set_view_range(4, 9); + CHECK(layers.get_whole_end_layers(8) == Interval{ 6, 9 }); +} + +TEST_CASE("A range from the first layer has no bottom band", "[Libvgcode]") +{ + // the bottom shells: no sparse infill on layers 0 to 2 + Layers layers = layers_with(10, { walls_only, walls_only, walls_only, walls_and_infill }); + layers.set_view_range(0, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 7 }); + layers.set_view_range(1, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 3, 7 }); +} + +TEST_CASE("A layer of support alone at the top of the range is drawn with the object layer below it", "[Libvgcode]") +{ + Layers layers = layers_with(6, { walls_and_infill, support_only }); + layers.set_view_range(0, 5); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 4 }); +} + +TEST_CASE("A layer with only solid infill ends the band on a print with no sparse infill in reach", "[Libvgcode]") +{ + Layers layers = layers_with(6, { { EGCodeExtrusionRole::ExternalPerimeter, EGCodeExtrusionRole::TopSolidInfill }, walls_only }); + layers.set_view_range(0, 5); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 4 }); +} + +TEST_CASE("Another object's solid infill on the layer does not end the band while sparse infill is in reach", "[Libvgcode]") +{ + // infill combined over two layers, and a second object topping out on the odd layers + const std::vector walls_and_top = { EGCodeExtrusionRole::ExternalPerimeter, EGCodeExtrusionRole::TopSolidInfill }; + Layers layers = layers_with(8, { walls_and_infill, walls_only, walls_and_infill, walls_and_top }); + layers.set_view_range(0, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 6 }); + layers.set_view_range(3, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 4, 6 }); +} + +TEST_CASE("An end band reaches at most the given depth and otherwise stays on the end layer", "[Libvgcode]") +{ + // infill on layers 0, 10 and 20: from the top layer 29, layer 20 is the tenth layer down + Layers layers = layers_with(30, { walls_and_infill, walls_only, walls_only, walls_only, walls_only, + walls_only, walls_only, walls_only, walls_only, walls_only }); + layers.set_view_range(0, 29); + CHECK(layers.get_whole_end_layers(10) == Interval{ 0, 20 }); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 29 }); +} + +TEST_CASE("A print with no infill keeps just the end layers whole", "[Libvgcode]") +{ + Layers layers = layers_with(30, { walls_only }); + layers.set_view_range(0, 29); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 29 }); +} + +TEST_CASE("The two end bands never cross", "[Libvgcode]") +{ + // infill on layers 0, 4 and 8: the top band of the range 4..7 reaches layer 4, the bottom layer + Layers layers = layers_with(10, { walls_and_infill, walls_only, walls_only, walls_only }); + layers.set_view_range(4, 7); + const Interval whole = layers.get_whole_end_layers(8); + CHECK(whole[0] == 4); + CHECK(whole[1] == 4); +} + +TEST_CASE("Layers the caller marks as closed decide the bands over the layer's own roles", "[Libvgcode]") +{ + // sparse infill on every layer, but the caller knows layers 5 and 6 leave an object open + Layers layers = layers_with(8, { walls_and_infill }); + layers.set_closed_layers({ 3, 3, 3, 3, 3, 0, 0, 3 }); + layers.set_view_range(0, 6); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 4 }); + layers.set_view_range(0, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 7 }); +} + +TEST_CASE("The top band reads the closure from above and the bottom band the one from below", "[Libvgcode]") +{ + // an object's bottom shells on layers 1 and 2, its top shells on 7 and 8 + Layers layers = layers_with(10, { walls_and_infill }); + layers.set_closed_layers({ 3, 2, 2, 3, 3, 3, 3, 1, 1, 3 }); + layers.set_view_range(1, 8); + CHECK(layers.get_whole_end_layers(8) == Interval{ 1, 8 }); + layers.set_view_range(2, 7); + CHECK(layers.get_whole_end_layers(8) == Interval{ 2, 7 }); +} + +TEST_CASE("A closed-layer list of the wrong size is ignored", "[Libvgcode]") +{ + Layers layers = layers_with(8, { walls_and_infill }); + layers.set_closed_layers({ 0, 0, 0 }); + layers.set_view_range(0, 6); + CHECK(layers.get_whole_end_layers(8) == Interval{ 0, 6 }); +} + +TEST_CASE("A layer is closed when every object printed on it has infill", "[Libvgcode]") +{ + using libvgcode::LayersClosedByInfill; + LayersClosedByInfill closed; + const int a = 1, b = 2, none = -1; + // layer 0: both objects print walls and sparse infill + closed.add(0, a, EGCodeExtrusionRole::ExternalPerimeter, EMoveType::Extrude); + closed.add(0, a, EGCodeExtrusionRole::InternalInfill, EMoveType::Extrude); + closed.add(0, b, EGCodeExtrusionRole::Perimeter, EMoveType::Extrude); + closed.add(0, b, EGCodeExtrusionRole::InternalInfill, EMoveType::Extrude); + // layer 1: a's infill was combined into another layer, b has its sparse infill + closed.add(1, a, EGCodeExtrusionRole::ExternalPerimeter, EMoveType::Extrude); + closed.add(1, b, EGCodeExtrusionRole::Perimeter, EMoveType::Extrude); + closed.add(1, b, EGCodeExtrusionRole::InternalInfill, EMoveType::Extrude); + // layer 2: b tops out with solid infill, a has walls and the solid infill under its skin, + // its sparse middle combined into layer 3 + closed.add(2, a, EGCodeExtrusionRole::ExternalPerimeter, EMoveType::Extrude); + closed.add(2, a, EGCodeExtrusionRole::SolidInfill, EMoveType::Extrude); + closed.add(2, b, EGCodeExtrusionRole::Perimeter, EMoveType::Extrude); + closed.add(2, b, EGCodeExtrusionRole::TopSolidInfill, EMoveType::Extrude); + // layer 3: only a, with its sparse infill; a travel changes nothing + closed.add(3, a, EGCodeExtrusionRole::ExternalPerimeter, EMoveType::Extrude); + closed.add(3, a, EGCodeExtrusionRole::InternalInfill, EMoveType::Extrude); + closed.add(3, b, EGCodeExtrusionRole::InternalInfill, EMoveType::Travel); + // layer 4: support alone + closed.add(4, a, EGCodeExtrusionRole::SupportMaterial, EMoveType::Extrude); + // layer 5: moves of no object, walls and infill + closed.add(5, none, EGCodeExtrusionRole::Perimeter, EMoveType::Extrude); + closed.add(5, none, EGCodeExtrusionRole::SolidInfill, EMoveType::Extrude); + // layer 6: nothing at all + const std::vector result = closed.finish(7); + REQUIRE(result.size() == 7); + CHECK(result[0] == 3); + CHECK(result[1] == 0); + // b's top shell closes b from above, but a's sparse middle lies both above and below + CHECK(result[2] == 0); + CHECK(result[3] == 3); + CHECK(result[4] == 0); + CHECK(result[5] == 3); + CHECK(result[6] == 0); +} + +TEST_CASE("An object's top shells close it from above and its bottom shells from below", "[Libvgcode]") +{ + using libvgcode::LayersClosedByInfill; + LayersClosedByInfill closed; + // bottom shells on layers 0 and 1, sparse infill on 2 to 4, top shells on 5 and 6 + for (uint32_t layer = 0; layer < 7; ++layer) { + closed.add(layer, 7, EGCodeExtrusionRole::ExternalPerimeter, EMoveType::Extrude); + closed.add(layer, 7, (layer >= 2 && layer <= 4) ? EGCodeExtrusionRole::InternalInfill : EGCodeExtrusionRole::SolidInfill, EMoveType::Extrude); + } + const std::vector result = closed.finish(7); + REQUIRE(result.size() == 7); + CHECK(result[0] == 2); + CHECK(result[1] == 2); + CHECK(result[2] == 3); + CHECK(result[3] == 3); + CHECK(result[4] == 3); + CHECK(result[5] == 1); + CHECK(result[6] == 1); +} + +TEST_CASE("An object with no sparse infill anywhere is closed by its solid infill", "[Libvgcode]") +{ + using libvgcode::LayersClosedByInfill; + LayersClosedByInfill closed; + closed.add(0, 7, EGCodeExtrusionRole::ExternalPerimeter, EMoveType::Extrude); + closed.add(0, 7, EGCodeExtrusionRole::SolidInfill, EMoveType::Extrude); + closed.add(1, 7, EGCodeExtrusionRole::ExternalPerimeter, EMoveType::Extrude); + closed.add(1, 7, EGCodeExtrusionRole::SolidInfill, EMoveType::Extrude); + const std::vector result = closed.finish(2); + REQUIRE(result.size() == 2); + CHECK(result[0] == 3); + CHECK(result[1] == 3); +} + +TEST_CASE("A tally with no labelled object yields no closed-layer list", "[Libvgcode]") +{ + using libvgcode::LayersClosedByInfill; + LayersClosedByInfill closed; + closed.add(0, -1, EGCodeExtrusionRole::Perimeter, EMoveType::Extrude); + closed.add(0, -1, EGCodeExtrusionRole::InternalInfill, EMoveType::Extrude); + closed.add(1, -1, EGCodeExtrusionRole::Perimeter, EMoveType::Extrude); + CHECK(closed.finish(2).empty()); +} + +namespace { + +PathVertex move_of(EMoveType type, EGCodeExtrusionRole role = EGCodeExtrusionRole::None) +{ + PathVertex v; + v.type = type; + v.role = role; + return v; +} + +} // namespace + +TEST_CASE("Between the end layers the solid model keeps the supports and the travels alone", "[Libvgcode]") +{ + using libvgcode::EReducedDetailMode; + using libvgcode::keep_in_reduced_set; + const EReducedDetailMode solid = EReducedDetailMode::EndLayersOnly; + CHECK(keep_in_reduced_set(solid, false, move_of(EMoveType::Travel), false)); + CHECK(keep_in_reduced_set(solid, false, move_of(EMoveType::Extrude, EGCodeExtrusionRole::SupportMaterial), false)); + CHECK_FALSE(keep_in_reduced_set(solid, false, move_of(EMoveType::Extrude, EGCodeExtrusionRole::ExternalPerimeter), false)); + CHECK_FALSE(keep_in_reduced_set(solid, false, move_of(EMoveType::Retract), false)); + CHECK(keep_in_reduced_set(solid, false, move_of(EMoveType::Extrude, EGCodeExtrusionRole::ExternalPerimeter), true)); +} + +TEST_CASE("Between the end layers the shell view drops only the infill under the skins", "[Libvgcode]") +{ + using libvgcode::EReducedDetailMode; + using libvgcode::keep_in_reduced_set; + const EReducedDetailMode shell = EReducedDetailMode::ShellOnly; + CHECK(keep_in_reduced_set(shell, true, move_of(EMoveType::Travel), false)); + CHECK(keep_in_reduced_set(shell, true, move_of(EMoveType::Extrude, EGCodeExtrusionRole::ExternalPerimeter), false)); + CHECK_FALSE(keep_in_reduced_set(shell, true, move_of(EMoveType::Extrude, EGCodeExtrusionRole::InternalInfill), false)); + CHECK(keep_in_reduced_set(shell, false, move_of(EMoveType::Extrude, EGCodeExtrusionRole::InternalInfill), false)); +} diff --git a/tests/slic3rutils/test_libvgcode_sampling.cpp b/tests/slic3rutils/test_libvgcode_sampling.cpp new file mode 100644 index 0000000000..0e8c750ab5 --- /dev/null +++ b/tests/slic3rutils/test_libvgcode_sampling.cpp @@ -0,0 +1,104 @@ +// The vertex that stands for a role when the solid model takes the toolpaths' colours: the +// length-weighted median of what the view grades by. +#include + +#include +#include +#include +#include +#include + +#include "libvgcode/include/PathVertex.hpp" +#include "libvgcode/include/Types.hpp" +#include "libvgcode/src/Utils.hpp" + +using libvgcode::collect_role_samples; +using libvgcode::EGCodeExtrusionRole; +using libvgcode::EMoveType; +using libvgcode::Interval; +using libvgcode::PathVertex; +using libvgcode::weighted_median_index; +using libvgcode::XYBox; + +namespace { + +// An outer wall extrusion of the layer ending at x, y, printed at the given speed. +PathVertex wall_at(float x, float y, float speed) +{ + PathVertex v; + v.type = EMoveType::Extrude; + v.role = EGCodeExtrusionRole::ExternalPerimeter; + v.layer_id = 0; + v.position = { x, y, 0.2f }; + v.feedrate = speed; + return v; +} + +const auto speed_of = [](const PathVertex& v) { return std::optional(v.feedrate); }; + +} // namespace + +TEST_CASE("Samples of equal weight give the one in the middle by value", "[Libvgcode]") +{ + const std::vector> samples = { { 30.0f, 1.0f }, { 10.0f, 1.0f }, { 20.0f, 1.0f } }; + CHECK(weighted_median_index(samples) == 2); +} + +TEST_CASE("A short ramp at the start does not outweigh the long run that follows", "[Libvgcode]") +{ + // an outer wall: a few short segments accelerating, then most of its length at full speed + const std::vector> samples = { { 5.0f, 0.1f }, { 20.0f, 0.1f }, { 60.0f, 0.1f }, { 100.0f, 5.0f }, { 100.0f, 4.0f }, { 40.0f, 0.2f } }; + CHECK(samples[weighted_median_index(samples)].first == 100.0f); +} + +TEST_CASE("Weight on the low side pulls the median down", "[Libvgcode]") +{ + const std::vector> samples = { { 100.0f, 1.0f }, { 20.0f, 3.0f }, { 50.0f, 1.0f } }; + CHECK(weighted_median_index(samples) == 1); +} + +TEST_CASE("Samples with no weight between them fall back to the middle one by value", "[Libvgcode]") +{ + const std::vector> samples = { { 3.0f, 0.0f }, { 1.0f, 0.0f }, { 2.0f, 0.0f } }; + CHECK(weighted_median_index(samples) == 2); +} + +TEST_CASE("No samples give the sample count", "[Libvgcode]") +{ + CHECK(weighted_median_index({}) == 0); +} + +TEST_CASE("Only the extrusions that end inside the box are sampled", "[Libvgcode]") +{ + // two objects on one layer: a slow one around the origin, a fast one a hundred millimetres along + const std::vector vertices = { wall_at(0.0f, 0.0f, 20.0f), wall_at(10.0f, 0.0f, 20.0f), wall_at(10.0f, 10.0f, 20.0f), + wall_at(100.0f, 0.0f, 200.0f), wall_at(110.0f, 0.0f, 200.0f), wall_at(110.0f, 10.0f, 200.0f) }; + const Interval range = { 0, vertices.size() - 1 }; + std::vector> samples; + std::vector ids; + + const XYBox fast_one{ { 99.0f, -1.0f }, { 111.0f, 11.0f } }; + CHECK(!collect_role_samples(vertices, range, 0, EGCodeExtrusionRole::ExternalPerimeter, fast_one, speed_of, samples, ids).has_value()); + CHECK(ids == std::vector{ 3, 4, 5 }); + REQUIRE(samples.size() == 3); + CHECK(samples[0].first == 200.0f); + // the length of the segment that ends at the vertex, from the one before it + CHECK(samples[1].second == 10.0f); + + samples.clear(); + ids.clear(); + CHECK(!collect_role_samples(vertices, range, 0, EGCodeExtrusionRole::ExternalPerimeter, XYBox(), speed_of, samples, ids).has_value()); + CHECK(ids.size() == 6); +} + +TEST_CASE("A view that grades by nothing takes the first extrusion in the box", "[Libvgcode]") +{ + const std::vector vertices = { wall_at(0.0f, 0.0f, 20.0f), wall_at(100.0f, 0.0f, 200.0f), wall_at(110.0f, 0.0f, 200.0f) }; + const Interval range = { 0, vertices.size() - 1 }; + std::vector> samples; + std::vector ids; + const auto no_value = [](const PathVertex&) { return std::optional(); }; + const XYBox fast_one{ { 99.0f, -1.0f }, { 111.0f, 11.0f } }; + CHECK(collect_role_samples(vertices, range, 0, EGCodeExtrusionRole::ExternalPerimeter, fast_one, no_value, samples, ids) == 1); + CHECK(samples.empty()); +}