Compare commits

..
Author SHA1 Message Date
SoftFever 693d6cbf6e Merge branch 'main' into image-gizmo 2026-10-13 19:51:55 +08:00
ExPikaPaka f546551b3f Use a model's own UV channel for texture displacement, and keep its colours through a bake (#16394) 2026-10-13 19:51:07 +08:00
Kris Austin ab42ddeef2 ci: replace deploy-nightly action with a local composite action (#16419)
WebFreak001/deploy-nightly still targets Node.js 20, so every main build
logged a deprecation warning per deploy step. The action has had no
release since 2024 and its Node 24 PR is unmerged.

The local action in .github/actions/deploy-nightly uploads the new file
under a temporary name and renames it once the upload finishes, so a
failed upload keeps the existing nightly asset. It also fails on a missing
file before deleting anything, retries transient API errors, times out
stalled transfers, handles concurrent runs, and finds the release by its
nightly-builds tag. The macOS validator DMG deploy now runs only when that
DMG was built.
2026-10-13 06:19:07 -05:00
ExPikaPakaandSoftFever 39c77325ce Carry existing colour across a bake instead of reindexing it (#16392)
* Carry existing colour across a bake instead of reindexing it

Baking, painting colour, then baking again left colour debris on surfaces
nothing had painted and destroyed what the earlier bake had laid down.

TextureDisplacementBakeJob::finalize() deserialized the volume's pre-bake
mmu_segmentation_facets into a TriangleSelector built on the post-bake mesh,
on the assumption that the bake is topology-preserving. That holds for the
classic path, which moves vertices and leaves the topology alone, but not for
the one-run pipeline, which rebuilds the mesh. TriangleSelector::deserialize()
only checks that the stored triangle ids are in range, and a bake almost
always grows the triangle count, so every stale id passed that check and
landed on an unrelated face.

Measured on a 26 mm slab baked twice at 0.19 mm with a 750 k budget: 7580
triangles ended up carrying paint neither bake produced, as far as 31 mm from
any colour that was actually laid down, while the first pass's colour was lost
where the second bake left the surface alone.

TriangleSelector::remap_painting() already transfers paint between meshes by
position, and ModelVolume::restore_painting() uses it for the same reason, so
the bake job now uses it too. It runs in process(), on the worker thread: it
builds an AABB tree over both meshes and took around a second on the case
above, which would have frozen the UI in finalize(). The bake's own colour is
still applied last, so it wins where it painted and the rest is kept, which is
what makes successive bakes accumulate rather than overwrite. If the volume is
painted while the bake is running, a timestamp check falls back to the live
mask so that stroke is not dropped.

The out_triangle comment in TextureColorRequest claimed the bake is
topology-preserving, which is what justified the original indexing; it now
says which mesh the colours belong to.

The regression test bakes twice, checks both results are closed, and checks
the first bake's colour survives the second at the positions where it was
laid down and nowhere else.

* Carry the paint across with transfer_facet_paint

The branch used TriangleSelector::remap_painting(), which pairs a source
paint triangle with a target triangle overlapping it to within
TriangleCursor::tolerance. That is right after a remesh, which leaves the
surface where it was, and wrong after a bake, which has moved it by the
relief depth - most of the paint finds no partner. transfer_facet_paint()
asks the other question: every triangle of the new mesh takes the state
painted at its foot point on the old one, which is exactly where it came
from however deep the relief.

It also does all four paint channels rather than colour alone, and it runs
where the volume is read, so the snapshot and the timestamp that guarded
against the user painting while the bake ran are no longer needed: the
annotation is read at commit time and is by definition current.

The function and its call site are byte for byte what the model-UV branch
carries, so the two merge in any order and in either order produce one
mechanism rather than two fighting over mmu_segmentation_facets. The
regression test is unchanged except for the call it makes.

---------

Co-authored-by: SoftFever <103989404+SoftFever@users.noreply.github.com>
2026-10-13 19:05:05 +08:00
ExPikaPaka af29e4d553 Image adjustment panel for texture displacement layers (#16391) 2026-10-13 18:45:21 +08:00
SoftFever df392508b7 Fix texture projection UV orientation (#16393)
# Description
An image laid onto a model came out upside down under the box
(tri-planar) projection, and on three of a cube's six faces it was also
mirrored left to right.

The sampler treats `v = 0` as the height map's top pixel row, but every
projection built `v` from world +Z, so `v` grew upward. The mirroring is
a separate defect: both faces sharing a world plane got the same `u`.

Note: re-baking an existing project now places its texture upright, so
it will look different from before. Geometry already baked into a 3mf is
unaffected.

# Images
<img width="2420" height="1655" alt="image"
src="https://github.com/user-attachments/assets/dcf7f62f-0f51-4966-97e4-d0386eb454c2"
/>



# Tests
6 tests added in `tests/libslic3r/test_texture_displacement.cpp`,
covering all six cube faces and every mapping mode, plus a full bake of
a known asymmetric image.


<!--
> A guide for users on how to download the artifacts from this PR.
-->

[How to Download Pull Requests Artifacts for
Testing](https://www.orcaslicer.com/wiki/how_to_download_pr_artifacts)
2026-10-13 18:24:00 +08:00
SoftFever 11493a2236 Merge branch 'main' into fix-texture-uv-orientation 2026-10-13 18:16:02 +08:00
SoftFever df4c8cd531 Free G-code result and preview memory on reset (#16065)
GCodeProcessorResult declares a copy assignment, which suppresses the
implicit
move assignment, so `*result = std::move(processor.extract_result())`
binds to
the copy and duplicates the whole moves array: 96 bytes per move,
measured at
147.7 MiB in one allocation for a 597k facet model at 0.08 mm, with the
source
staying alive until the export returns.

Add the move assignment. It assigns exactly the same 39 members in the
same
order as the copy, including the ones the copy deliberately leaves
alone, so a
target that carries its own filament maps and nozzle type keeps them. A
move
constructor is intentionally not added: the type holds a std::mutex, so
it is
neither copy nor move constructible today and a partial one would leave
ten
members uninitialised.

reset() now releases the two print sized vectors rather than clearing
them. Its
callers are the paths that discard a result, so the memory went back
only at the
next slice.

ViewerImpl::reset() does the same for the two vectors sized by the
print, which
is what keeps a discarded preview resident, and counts m_vertices_colors
in the
reported CPU memory, where it was missing.
2026-10-13 18:06:46 +08:00
SoftFever bf5a378479 Free G-code result buffers with clear_and_shrink 2026-10-13 18:05:51 +08:00
SoftFever f33a9bf999 Merge branch 'main' into perf/gcode-result-move 2026-10-13 16:37:00 +08:00
ExPikaPaka 053019261f Merge remote-tracking branch 'origin/image-gizmo' into image-gizmo
# Conflicts:
#	src/slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp
2026-10-13 08:47:58 +02:00
ExPikaPaka b0d586837b Merge upstream main into image-gizmo
Three conflicts, all in the texture displacement gizmo, all resolved by
keeping both sides:

- Two independent additions landed next to apply_standard_mode_presets():
  upstream's store_panel_state() and this branch's image-mode declarations.

- m_color_tex_source: upstream changed it from a raw const void* to a
  weak_ptr to the image bytes, so a freed and reallocated image can no longer
  pass for the old one. That is the better key and it is kept; the colour
  correction key this branch added sits beside it, and the cache test now
  checks the image, the smoothing and the correction.
2026-10-13 08:43:14 +02:00
ExPikaPaka 8ac8a75056 Include the headers GLGizmoImage.cpp uses directly
Adds the includes misc-include-cleaner named: libslic3r/Point.hpp for
Vec2d, Vec3f and Transform3d, GLGizmoTextureDisplacement.hpp for the
base class, IconManager.hpp for the icon lookup, and cmath, cstddef
and cstdlib for round, size_t and abs.
2026-10-12 15:31:21 +02:00
ExPikaPaka 60248cadd3 Move the Image tool's declarations off the line main now uses
store_panel_state() landed in the same place, from the .3mf persistence
branch. Same declarations, a few lines down, after bake_standard().
2026-10-12 15:14:22 +02:00
ExPikaPaka c07a082050 Add the pipette icon on a line of its own
Three other open texture-displacement branches add an icon to this list too.
Reflowing the lines they also touch is what turns four one-word additions
into four conflicts; a new line four lines away from the next one merges in
any order. Order in the list is irrelevant - the map keys by file name.
2026-10-12 14:03:43 +02:00
ExPikaPaka 1abd6649c7 Put the UV orientation tests beside the projection tests
They were appended at the end of test_texture_displacement.cpp, where every
other open texture-displacement branch also appends, so the four of them
cannot be merged in any order without a conflict in a file none of them
really disagree about. Same tests, moved next to the patch-frame test they
belong with.
2026-10-12 13:58:28 +02:00
ExPikaPaka c92721cabf fix: Negative belongs with the colour corrections, not under Background
It sat below the Background section purely because of source order, which
read as if it were part of it. Reset moves out of both sections and becomes
Reset all, since it clears the corrections and the background key alike and
a reset living inside one of them would look like it only reached that far.
2026-10-12 13:30:31 +02:00
ExPikaPaka 47a4e7447f feat: a real dropper that reads the model, foldable sections, a scrolling panel
- The dropper has its own pipette icon instead of borrowing the placement
  handle's, drawn in the house style: 16 px canvas, 0.4 stroke in #949494,
  teal on the tip, which is the part that carries the meaning.

- It picks off the model as well as off the preview. A click on the 3D view
  while it is armed reads the picture's own colour at that point, through
  the same projection the bake uses, not the pixel on screen: the screen
  pixel carries the lighting and the filament the colour was already
  quantized to, so keying on it would remove the wrong thing. The patch
  frame comes from extract_painted_patch() plus
  texture_displacement_patch_frame(), so a cylindrical or spherical layer
  reads at the same place the bake will.

- Placement, Color and Background fold away, with the triangle-and-text the
  displacement panel's "More settings" link uses rather than ImGui's own
  filled bar, which is louder than anything else in this window. Folded,
  Background still says whether it is removing anything. Open by default and
  remembered for the session only: this is panel state, not something a
  project should carry.

- The body scrolls and the footer is pinned under it, the shape the
  displacement panel already uses. With the panel this tall, Apply and Close
  were the first things to go off the bottom of a short canvas.
2026-10-12 13:21:41 +02:00
ExPikaPaka 4286cb30ba feat: a colour count instead of Two colours, and a pickable background
Two colours was the N=2 case of a more useful control, so it is replaced by
a Colors slider: 0 for off, then 2 to 12. The picture is reduced to that many
colours before the filaments are matched to it, so it prints in at most that
many.

Reduced by k-means in RGB rather than by posterizing the range, because the
useful question is which colours the picture is actually made of. A tartan
asks for its own handful of greens and reds; an even split of the range would
hand it eight shades of mud. The clustering runs over a coarse 16-per-channel
histogram, 4096 weighted points instead of a million pixels, which is what
makes it cheap enough to sit on a slider, and it is seeded the k-means++ way
so a picture with one dominant colour does not get every centre inside it.

This is not the displacement tool's "Mixed colors", which caps how many mixed
filament slots a bake may create. Nothing like it existed.

Background removal can now be told which colour to remove. The four corners
stay the default, because a background that does not reach all four of them
is not a background and that makes the common case one click, but the panel
shows the colour as a swatch that is also a picker, and a dropper beside it
takes the colour from the preview. The dropper reads the decoded image rather
than the screen: the preview is scaled, and it already has the corrections
applied, so a screen read would key the corrected colour against itself.
"Corners" puts it back.

Measured on Tartan, a cube face, four filaments:

  run                    out tris  coloured  filaments  filament shares
  image, no correction      22534     14544          4  1:91% 3:8% 4:1%
  image, 2 colors           18232     10268          2  1:66% 3:34%
  image, 3 colors           24458     16459          3  1:78% 3:18% 4:5%
  image, 5 colors           23972     15978          4  1:90% 3:9% 4:1%

Asking for 2 gives 2 and asking for 3 gives 3. Asking for 5 gives 4, which is
the contract working the right way round: only four filaments are loaded, and
"at most" is the guarantee. No run moves the surface.
2026-10-12 13:01:06 +02:00
ExPikaPaka 3ee9c02acf feat: sharpen, two colours, and remove background in the Image tool
Three more corrections, chosen because the output is a handful of flat
filament colours rather than a continuous image: what helps is whatever
decides which filament an area lands in and where the boundary between two
of them falls.

- Sharpen. An unsharp mask over the colour, reusing the sliding-window blur
  the Smoothing slider already uses, run per channel. Worth more here than
  in a photo editor: a soft edge between two colours quantizes into a ragged
  band of both, and sharpening first makes it land in one place.

- Two colours. Thresholds on luma so a logo or line art prints in exactly
  two filaments instead of speckling across several, with the split point on
  a slider.

- Remove background. The one that is not an RGB transform. DecodedHeightTexture
  gains an alpha plane, filled from the source PNG's fourth channel when it
  has one, and the key additionally clears whatever colour the picture's four
  corners share. A transparent texel is not black: sample_layer_color()'s
  covered() now reports it the same way it reports being outside an untiled
  placement, so the triangle keeps the object's own colour and the bake needs
  no new concept. The preview follows: upload_color_texture() box-filters
  coverage into the alpha channel it used to fill with 255, and the shader
  leaves the surface alone where it is below half.

The corners rather than an eyedropper: a background that does not reach all
four of them is not a background, and a picker would be a second interaction
for the case this exists to make one click. The median of the four is taken
so one stray corner cannot decide it.

Measured on Tartan, a cube face, four filaments:

  run                    out tris  coloured  max offset mm  filament shares
  image, no correction      22534     14544       0.000005  1:91% 3:8% 4:1%
  image, sharpen 1.0        24780     16783       0.000004  1:84% 3:12% 4:3%
  image, two colors         14798      6837       0.000005  2:22% 4:78%
  image, bg removed         14120      2620       0.000005  1:29% 3:16% 4:55%

Background removal cuts the painted area from 14544 triangles to 2620, which
is the whole point of it; the threshold collapses to two filaments; sharpen
shifts the shares and adds boundary triangles. None of them moves the
surface. The probe's default scene is now Tartan rather than Colour Bricks,
which has too little luma range for the threshold to show anything.
2026-10-12 12:37:57 +02:00
ExPikaPaka 533aaaed28 feat: add Hue to the Image tool's colour correction
Turns every colour of the picture around the colour wheel without changing
how light it is. This matters more here than in a photo editor: the filament
set is fixed and arbitrary, so hue is what lets the picture meet the palette
rather than the other way round. With orange loaded but no red, a small turn
puts the reds onto the orange instead of onto whatever happens to be nearest.

Implemented as Rodrigues' rotation of the colour about the grey axis, then
the Rec. 709 luma is restored exactly: the rotation preserves R+G+B, not the
weighted luma, and without the correction turning the wheel would also change
which areas read as light and dark.

Measured, same scene and harness as the other corrections:

  run                      out tris   coloured  max offset mm  filament shares
  image, no correction        12066       4052       0.000005  1:71% 2:25% 3:4%
  image, hue +60               8208        268       0.000005  2:100%
  image, hue -120              8208        268       0.000005  3:100%

The reddish brick moves onto a different filament in each direction and the
surface does not move.
2026-10-12 12:22:30 +02:00
ExPikaPaka 4dc87e876e feat: show a drop zone while a file is dragged over the view
Dropping a picture already worked, but a drag had no feedback at all: the
only way to find out whether letting go would do anything was to let go.

While a drag is over the 3D view and the Image tool is open, the canvas now
dims and shows a dashed teal border with "Drop a picture to put it on the
model" in the middle. It goes away on leave and on drop.

Three things worth knowing about how it is wired:

- wxWidgets cannot hand us the file names before the drop on GTK, so the
  zone says nothing about what is actually being dragged. It is worded as an
  invitation rather than a promise, and anything that is not a picture still
  falls through to the model loader exactly as before.

- A drag is not a mouse move as far as the canvas is concerned, so nothing
  would repaint and the zone would appear only once something else happened
  to trigger a frame. set_file_drag_over() marks the canvas dirty and asks
  for an extra frame.

- OnEnter and OnLeave are declared virtual without override, matching the
  class's existing OnDropFiles. Marking only the new ones trips
  -Winconsistent-missing-override on that pre-existing line, which is an
  error here.

The zone is drawn on the foreground draw list from inside the panel's ImGui
frame, so it covers the panel as well as the view.
2026-10-12 12:05:22 +02:00
ExPikaPaka 8bb2a1eec5 feat: match the icon weight, drop a picture onto the view, handle on by default
- The toolbar icon's stroke is 0.4 at its 16 px canvas, which renders at
  1.00 px on the 40 px sprite. Measured rather than judged: every icon on the
  gizmo bar was rasterized at 10x and the median thin run length taken, and
  1.00 px is what thirteen of the seventeen use. The previous 0.75 came out
  at 1.90, the heaviest on the bar.

- Dropping a picture on the 3D view loads it, when the Image tool is the one
  open. It is imported into the user's library on the way, as the panel's
  Import tile does, so it is there next time. With the tool closed a dropped
  PNG goes on doing whatever it did before. This mirrors the SVG drop that
  already fed the text tool, and sits next to it.

- The placement handle comes up by itself the first moment there is something
  to anchor it to, so a picture can be nudged straight after the click that
  placed it. Armed once, so turning it off stays off.

Two things had to change for that last one to be usable rather than annoying:

- A click that misses the handle now falls through to placing the picture.
  on_mouse() used to return false there and swallow it, which is right for
  the displacement tool, where the user turned the mode on deliberately, and
  wrong here, where it is on from the start and would have disabled the
  tool's one gesture.

- update_model_object() re-anchors the handle after a stroke that moved the
  paint. Previously the anchor was only refreshed on a layer switch or
  reorder, so clicking a different face left the handle behind on the old
  one.
2026-10-12 11:48:33 +02:00
ExPikaPaka 518f961640 feat: empty start, user images only, untiled preview, dockable Image panel
Five fixes to the Image tool, from using it:

- The layer now starts with no picture on it, so the panel opens on its empty
  frame with a plus in it. It used to seed the first shipped colour texture,
  which put somebody else's picture on screen before the user had chosen one.
  The frame is the only state the panel has until a picture is loaded, and
  clicking it is what creates the layer.

- Its picker offers only the user's own images. The shipped library is
  grayscale height maps, which is what the displacement tool wants and the
  opposite of what an image bake can use: it prints colour, and a height map
  has none. The Built-in section is left out rather than shown full of things
  that would all warn when picked, and the import hints now talk about
  pictures instead of height maps.

- The preview stopped tiling a layer that is not tiled. The shader had no
  tile_enabled uniform and wrapped the image unconditionally, so an untiled
  picture previewed as a repeating pattern the bake would never produce.
  in_tile() now draws the same line DecodedHeightTexture::sample() does, and
  gates the colour and all three relief paths on it. Both the 140 and the 110
  variant; glslangValidator passes on each.

- The panel docks against the right edge of the canvas, where the
  displacement panel is, with the same undock toggle in its title row, so the
  two tools do not put their controls in different corners.

- The toolbar icon's frame is square and its stroke thinner. At 16 px scaled
  to the toolbar a 1 px stroke came out at 2.5 px, heavier than every
  neighbour; 0.75 px matches them.
2026-10-12 11:31:33 +02:00
ExPikaPaka 680a597567 feat: show the picture whole in the Image panel, add tile, move and detail
Five changes to the Image tool, all in its own window bar the presets:

- The picture is shown whole, the full width of the window, instead of a row
  sized thumbnail beside a file name: it is the thing being placed, so that
  was the wrong size for it. The box shows the corrected colour texture, so
  moving a correction slider is visible in the panel as well as on the model;
  a grayscale picture has no colour texture and falls back to the height
  thumbnail. The file name stays underneath as a caption.

- Before anything is loaded the same box is an empty frame with a plus in it,
  in the same place and the same size, rather than a button of its own.
  Clicking either state opens the library, which is also where Import lives.

- Tile, off by default. A photo or a logo goes on once, so a new layer the
  Image tool creates starts with a single copy and Size sets how big that
  copy is. It is a default and not a pin, so the checkbox can turn it on.

- Move, the on-canvas placement handle the displacement tool has: drag the
  handle on the surface to slide the picture, or one of its arrows to slide
  it along one axis.

- Detail, the bake resolution, with the budget pinned to a million triangles.
  Each triangle prints in one filament, so this is how sharp an edge between
  two colours can come out, and it is the only thing left that decides it.
  The auto budget is 750 k, chosen for relief where triangles buy shape;
  here they buy the whole output, so it is worth spending more. The slider is
  seeded with the resolution Auto would have picked for the model, and warns
  when what it asks for no longer fits the budget.

Also fixes a short circuit in the panel: apply_standard_mode_presets(mv) ||
apply_image_mode_presets(mv) skipped the image presets on any frame the
standard ones changed something.

Measured with the texture-bake harness on the tool's shipped configuration
(tiling off, million-triangle budget, the seeded resolution), one cube face,
four filaments:

  run                      out tris   coloured  max offset mm  filament shares
  relief, depth 0.4 mm        41040      33902       0.216000  1:91% 2:6% 3:3%
  image, no correction        12066       4052       0.000005  1:71% 2:25% 3:4%
  image, brightness +0.5       8208        268       0.000005  4:100%
  image, contrast +0.8        11980       3910       0.000005  1:78% 2:20% 3:1%
  image, saturation 0          8208        268       0.000005  3:100%
  image, gamma 2.2            13176       5175       0.000004  1:67% 4:33%
  image, negative              8208        268       0.000005  4:100%

Fewer coloured triangles than the previous run of the same scene because
tiling is now off: one copy covers part of the face rather than repeating
across it. The surface still does not move and every correction still changes
which filaments the picture prints in.
2026-10-12 11:12:57 +02:00
ExPikaPaka e003b61e17 feat: make the Image gizmo a minimal load, click, correct, apply tool
The first cut was the displacement panel with depth hidden, which left the
brushes, the eight layer slots, the UV editor, seams, tiling and the
mesh-preparation sections in a tool that needs none of them, and offered no
way to correct the picture at all. This replaces that panel and adds the
corrections.

The flow is now: load a picture, click the model to put it there, adjust it,
press Apply.

- The Image tool gets its own window, render_image_input_window(), defined in
  GLGizmoImage.cpp. on_render_input_window() dispatches to it on the first
  line, so the displacement panel goes back to exactly what it was rather
  than being threaded with tests for which tool is drawing.

- A click places the picture: the tool pins SMART_FILL with a pointer cursor,
  so one click floods the surface it lands on out to the first fold sharper
  than the Spread angle. No brush, no erase toggle.

- Projection keeps Flat, Around, Ball and From view. Unwrap is left out and a
  layer arriving on it falls back to Flat: seams, islands and the UV pane are
  an editor's worth of interface for a tool that wants a click and a slider.

- The preview is pinned to the fast one. With no relief to build it is both
  instant and exactly the final colour, since the shader's colour path does
  not depend on depth_mm.

- The window shows only what this case needs: the picture, Spread, the four
  projections, Size, Rotation, the corrections, Apply and Close.

Colour correction is new in libslic3r. TextureDisplacementLayer gains
brightness, contrast, saturation, gamma and color_invert, all defaulting to
the identity, and apply_color_adjustments() applies them to an image's RGB
only, never to the height: a brightness slider has no business moving
geometry. It runs at the single point every bake and preview job reads a
layer's colour from, prepare_sampleable_layers(), and at the two caches that
would otherwise miss a change the image_data pointer does not show: the fast
preview's GPU texture and the mix ranking.

Measured with the texture-bake harness, one cube face painted with a colour
image, four filaments:

  run                      out tris   coloured  max offset mm  filament shares
  relief, depth 0.4 mm        41040      33902       0.216000  1:91% 2:6% 3:3%
  image, no correction        24226      17090       0.000007  1:71% 2:25% 3:4%
  image, brightness +0.5       8204       1068       0.000004  4:100%
  image, contrast +0.8        22688      15552       0.000007  1:75% 2:24% 3:1%
  image, saturation 0          8204       1068       0.000004  3:100%
  image, gamma 2.2            24754      17618       0.000007  1:66% 4:34%
  image, negative              8204       1068       0.000004  4:100%

Max offset is the distance from every output vertex to the original surface,
not a vertex-array diff: the bake refines, so a new vertex only counts as
unmoved if it lies in the old surface. Every correction moves which filaments
the picture prints in, and none of them moves the surface.
2026-10-12 10:20:44 +02:00
ExPikaPaka a800e0c186 feat: add an Image gizmo for zero-displacement colour
A separate toolbar tool for the simple case of texture displacement: put a
colour picture on the model with no relief at all.

It is a thin wrapper, not a fork. GLGizmoImage subclasses
GLGizmoTextureDisplacement and overrides one new protected virtual,
image_mode(). Painting, the layer stack, the paint masks, the texture
library, the previews and the bake are the same code reached the same way;
a zero-depth bake refines the painted area and writes the per-triangle
filament indices exactly as a relief bake does, it just displaces by
nothing.

In the base gizmo, image_mode() does three things:

- apply_image_mode_presets() pins every layer to depth 0 and turns colour on
  wherever the image has any, alongside the existing Standard-mode presets.
- The panel leaves out Depth, Midlevel, Invert, Edge fade and Blend, and the
  Standard/Pro switch, which is what keeps the mesh-preparation sections
  hidden. Bake is disabled when no image carries colour, since that bake
  would refine the mesh and produce nothing.
- add_texture_layer() seeds a new layer from the first library texture that
  has colour, rather than the first one, because most of the shipped library
  is grayscale height maps.

The two tools share one layer stack, so opening the Image tool on a volume
whose layers carry relief flattens them. Only depth changes: the paint, the
image, the tiling, the mapping and any relief already baked into the mesh
are untouched.

The toolbar icon follows Orca's menu-icon style: 16 px, 1 px #949494 frame,
#009688 on the picture inside.

The shortcut is registered but unbound: every single letter the Plater
context can reach is already taken, and a default that shadows one of them
is worse than none. docs/HLSD/keyboard-shortcuts.md now documents that an
empty default chord is a supported choice.

Measured with a probe built against this tree in the texture-bake harness:
a depth-0 bake of a painted cube face leaves every output vertex within
7 nm of the original surface (tolerance 1 um) while colouring 17090 of
24226 output triangles across 3 filaments; the same scene at depth 0.4 mm
moves vertices up to 0.216 mm.
2026-10-12 08:29:10 +02:00
ExPikaPaka 56b559d36a Fix texture projection UV orientation
An image laid onto a model came out upside down under the ordinary box
(tri-planar) projection, and on three of a cube's six faces it was also
mirrored left to right, which reads as a 180 degree rotation.

DecodedHeightTexture::sample() defines v = 0 as the height map's first
pixel row, i.e. its top. Every projection built v from world +Z, so v
grew upward and the image landed bottom row up. The one path that was
already right is the projective "project from view" matrix, which
measures window y downward.

Both halves of the box basis were wrong:

- v is now negated on all three world planes, so the top of an image
  sits at the top of the model.
- u now carries a sign for the side of the plane the face is on, chosen
  so that u x v == -normal. Without it the two faces sharing a plane get
  one u and one of them is mirrored. The sign flips exactly where that
  plane's blend weight (the fourth power of a normal component) reaches
  zero, so the blended tri-planar sum stays continuous and the hard axis
  switch the old code removed does not come back.

The same v convention was missing from the other mapping modes:
cylindrical (which also had a left handed frame, right x up rather than
up x right, so its wrap ran mirrored), spherical, the affine branch of
view projection, and the flat chart fallback of the LSCM unwrap, which
now reuses the box basis so a cube face unwraps to the orientation
tri-planar would have given it.

The basis table is exported as box_projection_axes() and the gizmo's
adjust_tangent_basis() calls it instead of restating it, so the
placement ring and offset handle cannot drift from the bake. All four
preview shaders get the matching change, including projection_axes(),
whose tangent and bitangent have to flip with the coordinate or the
relief shading inverts.

Re-baking an existing project now places its texture upright, so it will
differ from how it looked before. Geometry already baked into a 3mf is
untouched, so nothing changes until the user re-bakes.

Verified by measuring the sampled texture row and column against world
position for every mapping mode on all six faces of a cube, and by a
full bake of a quadrant coded image, which lands each quadrant within
1e-3 mm of its expected depth.
2026-10-12 07:57:50 +02:00
ExPikaPaka bea412fddf Move the G-code processing result instead of copying it
GCodeProcessorResult declares a copy assignment, which suppresses the implicit
move assignment, so `*result = std::move(processor.extract_result())` binds to
the copy and duplicates the whole moves array: 96 bytes per move, measured at
147.7 MiB in one allocation for a 597k facet model at 0.08 mm, with the source
staying alive until the export returns.

Add the move assignment. It assigns exactly the same 39 members in the same
order as the copy, including the ones the copy deliberately leaves alone, so a
target that carries its own filament maps and nozzle type keeps them. A move
constructor is intentionally not added: the type holds a std::mutex, so it is
neither copy nor move constructible today and a partial one would leave ten
members uninitialised.

reset() now releases the two print sized vectors rather than clearing them. Its
callers are the paths that discard a result, so the memory went back only at the
next slice.

ViewerImpl::reset() does the same for the two vectors sized by the print, which
is what keeps a discarded preview resident, and counts m_vertices_colors in the
reported CPU memory, where it was missing.
2026-10-01 09:15:15 +02:00
42 changed files with 4701 additions and 399 deletions
@@ -570,11 +570,6 @@ Details [source] (`Widgets/PopupWindow.cpp`).
- On GTK the sub binds an idle handler. While both are shown and the cursor is over main but not over the
sub, it builds a `wxMouseEvent(wxEVT_MOTION)` from `wxGetMousePosition()`, calls `mainDropDown->mouseMove(ev)`
**directly** (nothing is posted), and calls `e.RequestMore()` to keep polling.
- On GTK the sub also receives the wheel events the user raises over main: GDK sends a `wl_pointer.axis` only
to the surface the pointer is over, and GTK then hands that `GDK_SCROLL` to the chain's grab widget, which is
the sub. The sub installs a `GtkWidget::event` handler that replays the event on main with
`gtk_propagate_event(main->GetConnectWidget(), event)` when the event's GDK window belongs to main
(`DropDown::messureSize`).
- **GTK wrapper sizing.** `messureSize` calls `gtk_window_resize` on `m_widget` after `SetSize`, because wxGTK's
`DoSetSize` only uses `gtk_widget_set_size_request` ("gtk_window_resize does not work for GTK_WINDOW_POPUP",
`src/gtk/popupwin.cpp:181-188`).
@@ -612,32 +607,6 @@ Details [source] (`Widgets/PopupWindow.cpp`).
```
Cite: c0ae2bda99, b9ff15054f (`DropDown::mouseMove`, `DropDown::messureSize`, `DropDown::ShouldDismissOnTopWindowDeactivate`,
`PopupWindow::ShouldDismissOnTopWindowDeactivate`).
- **Rule:** On GTK, route a chained popup's wheel event by the GDK window it names, not by the grab widget and not
by the global cursor position.
**Why:** While the sub holds the grab, `gtk_main_do_event` hands every `GDK_SCROLL` of the chain to the grab
widget (the sub) with its original, un-rebased coordinates [source] (`gtkmain.c:1789-1792`, 1923-1924), while
GDK Wayland sends the axis to the surface under the pointer only (`pointer_handle_axis` → `create_scroll_event`,
`gdkdevice-wayland.c:1929, 1527`). The sub therefore sees and consumes wheel events raised over main, so the
main list never scrolls, on X11 and Wayland alike. A hit test against `wxGetMousePosition()` cannot replace the
window test: global coordinates are unreliable on Wayland (`mouse-keyboard-focus.md`). `DropDown` connects a
`GtkWidget::event` handler on the sub's `GtkWindow` (its `m_widget`), which is emitted before wx's
`::scroll-event` handler on the same widget and suppresses it when it returns TRUE (`gtkwidget.c:7696`), then
delivers the event with `gtk_propagate_event(main->GetConnectWidget(), event)`. Returning TRUE there also stops
the parent-chain propagation.
```cpp
// Wrong: emitted on the popup's outer GtkWindow, where wx has no handlers at all
g_signal_emit_by_name(main->m_widget, "scroll-event", event, &handled);
// Right (wxGTK): replay GTK's own delivery on the widget wx listens to
gtk_propagate_event(main->GetConnectWidget(), event);
```
**Where wx listens [source].** `wxPopupWindow::Create` builds a popup from two widgets: `m_widget` is the outer
`GtkWindow` and `m_wxwindow` is a `wxPizza` child added to it. `wxWindowGTK::GetConnectWidget()` is
`m_wxwindow ? m_wxwindow : m_widget`, and `ConnectWidget()` — which binds `button_press_event`, `motion_notify_event`
and `scroll_event` — is called on that widget (`src/gtk/window.cpp` `Create`, `GetConnectWidget`). A signal emitted
on the outer `GtkWindow` therefore reaches no wx handler; only events GTK delivers to the inner widget, or to a
descendant of the grab widget, are seen by wx. `GTKGetConnectWindow()`/`GTKGetMainWindow()` are the matching
GdkWindows.
Cite: `DropDown::messureSize`, `DropDown::mouseWheelMoved`.
- **Rule:** When shrinking a dropdown to fit above the display bottom, give up if fewer than two rows would
remain.
**Why:** On Wayland the popup can land where almost no vertical space is left. Clamping to that sliver made an
+29
View File
@@ -0,0 +1,29 @@
name: 'Deploy Nightly'
description: 'Upload a file to a release, replacing the asset of the same name'
inputs:
asset_path:
description: 'Path of the file to upload'
required: true
asset_name:
description: 'Asset name on the release'
required: true
content_type:
description: 'Content type of the uploaded file'
required: false
default: 'application/octet-stream'
tag:
description: 'Tag of the release to upload to'
required: false
default: 'nightly-builds'
runs:
using: 'composite'
steps:
- name: Replace release asset
shell: bash
env:
GH_TOKEN: ${{ github.token }}
ASSET_PATH: ${{ inputs.asset_path }}
ASSET_NAME: ${{ inputs.asset_name }}
CONTENT_TYPE: ${{ inputs.content_type }}
RELEASE_TAG: ${{ inputs.tag }}
run: bash "$GITHUB_ACTION_PATH/deploy.sh"
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env bash
# Replaces one asset of a GitHub release, uploading under a temporary name
# first so a failed upload leaves the old asset in place.
#
# Environment: GH_TOKEN, ASSET_PATH, ASSET_NAME, CONTENT_TYPE, RELEASE_TAG and
# the GITHUB_* variables Actions sets.
# The $names inside the single-quoted jq programs are jq variables.
# shellcheck disable=SC2016
set -euo pipefail
repo_api="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
if [ ! -f "$ASSET_PATH" ]; then
echo "::error::$ASSET_PATH does not exist"
exit 1
fi
# The speed limit turns a stalled transfer into an error that --retry handles.
curl_opts=(-sS --retry 3 --connect-timeout 30 --speed-limit 1024 --speed-time 60
-H "Authorization: Bearer $GH_TOKEN")
# Prints the response body, or reports GitHub's error body and fails.
api() {
local out
if ! out=$(curl "${curl_opts[@]}" --fail-with-body "$@"); then
# A workflow command ends at the first newline.
echo "::error::GitHub API request failed: ${out//[$'\r\n']/ }" >&2
return 1
fi
printf '%s\n' "$out"
}
http_status() {
curl "${curl_opts[@]}" -o /dev/null -w '%{http_code}' "$@"
}
# jq prints CRLF on Windows.
jqr() {
jq -r "$@" | tr -d '\r'
}
delete_asset() {
local code
code=$(http_status -X DELETE "$repo_api/releases/assets/$1")
case $code in
# A 404 means a concurrent run already deleted the asset.
204 | 404) ;;
*)
echo "::error::Deleting release asset $1 failed with HTTP $code" >&2
return 1
;;
esac
}
list_assets() {
local page=1 json
while :; do
# Callers run this inside $(...), where bash ignores set -e.
json=$(api "$repo_api/releases/$release_id/assets?per_page=100&page=$page") || exit 1
printf '%s\n' "$json"
[ "$(jqr length <<<"$json")" -eq 100 ] || break
page=$((page + 1))
done | jq -s add
}
release=$(api "$repo_api/releases/tags/$RELEASE_TAG")
release_id=$(jqr .id <<<"$release")
upload_url=$(jqr .upload_url <<<"$release")
upload_url=${upload_url%%\{*}
# Unique per run attempt, so concurrent runs never upload to the same name.
tmp_name="$ASSET_NAME.partial-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
# Deletes leftover partials older than an hour, an age no upload in progress reaches.
stale_ids=$(list_assets | jqr --arg prefix "$ASSET_NAME.partial-" \
'.[] | select((.name | startswith($prefix)) and (.created_at | fromdateiso8601) < now - 3600) | .id')
for id in $stale_ids; do
delete_asset "$id"
done
name_query=$(jqr -n --arg name "$tmp_name" '$name | @uri')
# Uploads once, since a retry after an upload that succeeded fails on the taken name.
new_id=$(api --retry 0 -X POST -H "Content-Type: $CONTENT_TYPE" -T "$ASSET_PATH" \
"$upload_url?name=$name_query" | jqr .id)
trap 'delete_asset "$new_id" || true' EXIT
rename_body=$(jq -n --arg name "$ASSET_NAME" '{name: $name}')
# Retries on HTTP 422, which a concurrent run causes by renaming its own upload
# between this delete and this rename.
for _ in 1 2 3; do
old_ids=$(list_assets | jqr --arg name "$ASSET_NAME" '.[] | select(.name == $name) | .id')
for id in $old_ids; do
delete_asset "$id"
done
code=$(http_status -X PATCH -d "$rename_body" "$repo_api/releases/assets/$new_id")
if [ "$code" = 200 ]; then
trap - EXIT
exit 0
fi
[ "$code" = 422 ] || break
done
echo "::error::Renaming $tmp_name to $ASSET_NAME failed with HTTP $code" >&2
exit 1
+1 -5
View File
@@ -441,14 +441,10 @@ jobs:
path: '/__w/OrcaSlicer/OrcaSlicer/OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak'
- name: Deploy Flatpak to nightly release
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main'
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: /__w/OrcaSlicer/OrcaSlicer/OrcaSlicer-Linux-flatpak_${{ env.ver }}_${{ matrix.variant.arch }}.flatpak
asset_name: OrcaSlicer-Linux-flatpak_nightly_${{ matrix.variant.arch }}.flatpak
asset_content_type: application/octet-stream
max_releases: 1 # optional, if there are more releases than this matching the asset_name, the oldest ones are going to be deleted
# The asset is /app (the exes link it at runtime) plus the build tree
# slimmed to what ctest needs.
- name: Package flatpak test asset
+14 -46
View File
@@ -397,25 +397,18 @@ jobs:
- name: Deploy Mac release
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' && runner.os == 'macOS' && inputs.macos-combine-only && !vars.SELF_HOSTED
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ${{ github.workspace }}/OrcaSlicer_Mac_universal_${{ env.ver }}.dmg
asset_name: OrcaSlicer_Mac_universal_nightly.dmg
asset_content_type: application/octet-stream
max_releases: 1 # optional, if there are more releases than this matching the asset_name, the oldest ones are going to be deleted
# The DMG is only built when the validator app was.
- name: Deploy Mac OrcaSlicer_profile_validator DMG release
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' && runner.os == 'macOS' && inputs.macos-combine-only && !vars.SELF_HOSTED
uses: WebFreak001/deploy-nightly@v3.2.0
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' && runner.os == 'macOS' && inputs.macos-combine-only && !vars.SELF_HOSTED && hashFiles(format('OrcaSlicer_profile_validator_Mac_universal_{0}.dmg', env.ver)) != ''
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ${{ github.workspace }}/OrcaSlicer_profile_validator_Mac_universal_${{ env.ver }}.dmg
asset_name: OrcaSlicer_profile_validator_Mac_universal_nightly.dmg
asset_content_type: application/octet-stream
max_releases: 1
# Windows
- name: Set Windows build variables
@@ -542,36 +535,27 @@ jobs:
- name: Deploy Windows release portable
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' && runner.os == 'Windows' && !vars.SELF_HOSTED
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ${{ github.workspace }}/${{ env.BUILD_DIR }}/OrcaSlicer_Windows_${{ env.ver }}${{ env.ARCH_SUFFIX }}_portable.zip
asset_name: OrcaSlicer_Windows${{ env.ARCH_SUFFIX }}_nightly_portable.zip
asset_content_type: application/x-zip-compressed
max_releases: 1
content_type: application/x-zip-compressed
- name: Deploy Windows release installer
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' && runner.os == 'Windows' && !vars.SELF_HOSTED
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ${{ github.workspace }}/${{ env.BUILD_DIR }}/OrcaSlicer_Windows_Installer_${{ env.ver }}${{ env.ARCH_SUFFIX }}.exe
asset_name: OrcaSlicer_Windows_Installer${{ env.ARCH_SUFFIX }}_nightly.exe
asset_content_type: application/x-msdownload
max_releases: 1
content_type: application/x-msdownload
- name: Deploy Windows OrcaSlicer_profile_validator release
if: github.repository == 'OrcaSlicer/OrcaSlicer' && github.ref == 'refs/heads/main' && runner.os == 'Windows' && inputs.arch != 'arm64' && !vars.SELF_HOSTED
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ${{ github.workspace }}/build/src/Release/OrcaSlicer_profile_validator.exe
asset_name: OrcaSlicer_profile_validator_Windows_nightly.exe
asset_content_type: application/x-msdownload
max_releases: 1
content_type: application/x-msdownload
- name: Build MSIX Store package Win
if: runner.os == 'Windows' && !vars.SELF_HOSTED
@@ -700,14 +684,10 @@ jobs:
- name: Deploy Ubuntu release
if: ${{ github.repository == 'OrcaSlicer/OrcaSlicer' && ! env.ACT && github.ref == 'refs/heads/main' && runner.os == 'Linux' && !vars.SELF_HOSTED }}
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ./build/OrcaSlicer_Linux_AppImage${{ env.ubuntu-ver-str }}${{ env.arch_suffix }}_${{ env.ver }}.AppImage
asset_name: OrcaSlicer_Linux_AppImage${{ env.ubuntu-ver-str }}${{ env.arch_suffix }}_nightly.AppImage
asset_content_type: application/octet-stream
max_releases: 1 # optional, if there are more releases than this matching the asset_name, the oldest ones are going to be deleted
- name: Deploy Ubuntu release
if: ${{ github.repository == 'OrcaSlicer/OrcaSlicer' && ! env.ACT && github.ref == 'refs/heads/main' && runner.os == 'Linux' && !vars.SELF_HOSTED && inputs.arch != 'aarch64' }}
run: |
@@ -716,36 +696,24 @@ jobs:
- name: Deploy Ubuntu OrcaSlicer_profile_validator release
if: ${{ github.repository == 'OrcaSlicer/OrcaSlicer' && ! env.ACT && github.ref == 'refs/heads/main' && runner.os == 'Linux' && !vars.SELF_HOSTED && inputs.arch != 'aarch64' }}
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ./build/src/Release/OrcaSlicer_profile_validator
asset_name: OrcaSlicer_profile_validator_Linux${{ env.ubuntu-ver-str }}_nightly
asset_content_type: application/octet-stream
max_releases: 1
- name: Deploy Ubuntu generate_system_cache release
if: ${{ github.repository == 'OrcaSlicer/OrcaSlicer' && ! env.ACT && github.ref == 'refs/heads/main' && runner.os == 'Linux' && !vars.SELF_HOSTED && inputs.arch != 'aarch64' }}
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ./build/src/dev-utils/Release/generate_system_cache
asset_name: generate_system_cache_Linux${{ env.ubuntu-ver-str }}_nightly
asset_content_type: application/octet-stream
max_releases: 1
- name: Deploy orca_custom_preset_tests
if: ${{ github.repository == 'OrcaSlicer/OrcaSlicer' && ! env.ACT && github.ref == 'refs/heads/main' && runner.os == 'Linux' && !vars.SELF_HOSTED && inputs.arch != 'aarch64' }}
uses: WebFreak001/deploy-nightly@v3.2.0
uses: ./.github/actions/deploy-nightly
with:
upload_url: https://uploads.github.com/repos/OrcaSlicer/OrcaSlicer/releases/137995723/assets{?name,label}
release_id: 137995723
asset_path: ${{ github.workspace }}/resources/profiles/orca_custom_preset_tests.zip
asset_name: orca_custom_preset_tests.zip
asset_content_type: application/octet-stream
max_releases: 1
# The build has just touched everything it can use, so an object
# untouched for a week is dead, usually orphaned by a flag change.
+3 -1
View File
@@ -124,7 +124,9 @@ Control on the Global page, and from the `?` key on the page of the view that re
the dialog should list it; the row's section heading is the `section_table` entry
above it, so a new section needs an entry there too. Pick a default that does not
collide inside its contexts; the `[Shortcuts]` tests check every default against the
others.
others. A default `KeyChord{}` leaves the action unbound: it is listed in the dialog
for the user to bind and matches nothing until they do, which is the honest answer
when every key its contexts can reach is already spoken for.
2. Handle it in the dispatcher of its context: `MainFrame::handle_global_shortcut`,
`GLCanvas3D::handle_shortcut`, `ObjectList::dispatch_shortcut`, or a gizmo's
`on_tool_shortcut`. A gizmo that opens on a key sets `m_shortcut` in its constructor.
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M2.5,2.5h11v11h-11z" style="fill:none;stroke:#949494;stroke-linecap:round;stroke-linejoin:round"/><path d="M8,2.5v11M2.5,8h11" style="fill:none;stroke:#949494;stroke-dasharray:1.5,1.5"/><path d="M4.5,11.5l3.5-6l3.5,6z" style="fill:#009688"/></svg>

After

Width:  |  Height:  |  Size: 340 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><g transform="rotate(-45 8 8)"><path d="M8 14.4 6.5 11.2 9.5 11.2 Z" style="fill:#009688"/><path d="M6.5 7.3 6.5 11.2 8 14.4 9.5 11.2 9.5 7.3" style="fill:none;stroke:#949494;stroke-width:0.4;stroke-linejoin:round;stroke-linecap:round"/><rect x="5.5" y="3.8" width="5" height="3.5" rx="0.9" style="fill:none;stroke:#949494;stroke-width:0.4;stroke-linejoin:round"/></g></svg>

After

Width:  |  Height:  |  Size: 458 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="5.9" cy="6.3" r="1.25" style="fill:#009688"/><path d="M3.4 11.9 6.4 7.7 8.8 10.7 10.4 8.6 12.6 11.9 Z" style="fill:#009688"/><rect x="2.375" y="2.375" width="11.25" height="11.25" rx="1.25" style="fill:none;stroke:#949494;stroke-width:0.4;stroke-linecap:round;stroke-linejoin:round"/></svg>

After

Width:  |  Height:  |  Size: 386 B

@@ -51,6 +51,11 @@ uniform float tex_aspect;
uniform float rotation_rad;
uniform vec2 uv_offset;
uniform bool invert;
// False means the layer places a single copy rather than repeating: outside that copy there is
// simply no texture. DecodedHeightTexture::sample() has always returned 0 there, so the bake got
// this right while the preview wrapped the image and showed a tiled pattern that was never going
// to be printed.
uniform bool tile_enabled;
uniform float midlevel; // the height that means "don't move"; needed by the parallax step
uniform vec3 eye_model_pos; // camera position in the texture frame (world minus tex_anchor)
uniform vec3 tex_anchor; // the volume's origin in world space: the texture frame's origin
@@ -72,17 +77,21 @@ varying float weight;
varying float island_active;
varying vec2 vertex_uv;
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - including
// the handedness, which comes out left-handed for an axis of +Z. Copied rather than "corrected", so
// the preview wraps the texture the same way round as the bake.
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - right
// handed, so the angle taken from it grows anticlockwise about the axis, which seen from outside the
// cylinder is to the viewer's right rather than mirrored.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// The raw, millimetre-valued projection of `p` (a position in the texture frame), before the layer's
// tiling/rotation/aspect/offset - a term-for-term transcription of libslic3r's project_planar(),
// project_cylindrical() and project_spherical(). `n` is read by the planar mode only.
@@ -94,7 +103,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) { // Spherical: (longitude, latitude) * radius
vec3 rel = p - patch_center;
@@ -102,10 +111,18 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
vec3 an = abs(n); // Triplanar: drop the dominant normal axis
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
// Triplanar: drop the dominant normal axis. v is negated so the image's first pixel row (v = 0)
// sits at the top of the model instead of upside down, and u is flipped on the far side of each
// plane so the two faces sharing it are not mirror images. libslic3r's box_plane_yz() and its two
// siblings, term for term.
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
// The two surface directions projection_raw()'s u and v run along at `p`, plus how many raw units one
@@ -124,7 +141,7 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec2 xy = vec2(dot(rel, right), dot(rel, fwd));
float r = length(xy);
t = (r > 1e-6) ? (fwd * xy.x - right * xy.y) / r : right; // circumferential: u runs along it
b = up; // v is the distance along the axis
b = -up; // v is the distance *against* the axis
return;
}
if (projection_mode == 2) {
@@ -133,20 +150,20 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec3 dir = (r > 1e-8) ? rel / r : vec3(0.0, 0.0, 1.0);
float c = length(dir.xy); // cos(latitude)
t = (c > 1e-6) ? vec3(-dir.y, dir.x, 0.0) / c : vec3(1.0, 0.0, 0.0);
b = cross(dir, t); // increasing latitude, unit length
b = -cross(dir, t); // v grows away from the pole, unit length
units_per_mm = vec2(1.0 / max(c, 1e-3), 1.0);
return;
}
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z) { // planar = p.yz
t = vec3(0.0, 1.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = p.xz
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else { // planar = p.xy
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 1.0, 0.0);
vec3 an = abs(n); // the same signed basis projection_raw() uses
if (an.x >= an.y && an.x >= an.z) { // planar = (+-y, -z)
t = vec3(0.0, box_face_sign(n.x), 0.0);
b = vec3(0.0, 0.0, -1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = (+-x, -z)
t = vec3(-box_face_sign(n.y), 0.0, 0.0);
b = vec3(0.0, 0.0, -1.0);
} else { // planar = (+-x, -y)
t = vec3(box_face_sign(n.z), 0.0, 0.0);
b = vec3(0.0, -1.0, 0.0);
}
}
@@ -218,6 +235,14 @@ int nearest_palette_entry(vec3 rgb)
return best;
}
// True where this uv has texture on it: everywhere when the layer repeats, and only inside the
// single placed copy when it does not. The bake's own sampler draws the same line (see
// DecodedHeightTexture::sample), so the preview now stops at the same edge it does.
bool in_tile(vec2 uv)
{
return tile_enabled || (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0);
}
void main()
{
if (any(lessThan(clipping_planes_dots, ZERO)))
@@ -243,9 +268,9 @@ void main()
? vec2(dot(island_delta_lin.xy, vertex_uv), dot(island_delta_lin.zw, vertex_uv)) + island_delta_tr
: vertex_uv;
color_uv = uv;
have_uv = true;
have_uv = in_tile(uv);
float h = texture2D(height_tex, uv).r;
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) * (have_uv ? 1.0 : 0.0);
vec3 sigmaS = dFdx(world_pos.xyz);
vec3 sigmaT = dFdy(world_pos.xyz);
vec3 R1 = cross(sigmaT, triangle_normal);
@@ -262,10 +287,12 @@ void main()
// Parallax occlusion mapping: march the view ray through the height shell and shade at the
// first point where it drops below the displaced surface (see header).
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
// uv first: outside a single placed copy there is no shell to march through.
vec2 uv = project_uv(tex_pos, triangle_normal);
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) *
(in_tile(uv) ? 1.0 : 0.0);
vec3 view_dir = normalize(eye_model_pos - tex_pos);
float v_dot_n = dot(view_dir, triangle_normal);
vec2 uv = project_uv(tex_pos, triangle_normal);
// The shell the displaced surface lives inside, as signed heights along the normal. Taken from
// both ends of h in [0, 1] so it stays correct for an inverted layer or a raised midlevel,
@@ -302,7 +329,7 @@ void main()
}
color_uv = uv; // after the parallax march, so colour and relief stay registered
have_uv = true;
have_uv = in_tile(uv);
float hL = texture2D(height_tex, uv - vec2(height_tex_texel.x, 0.0)).r;
float hR = texture2D(height_tex, uv + vec2(height_tex_texel.x, 0.0)).r;
@@ -311,7 +338,8 @@ void main()
vec2 dh_duv = vec2((hR - hL) / (2.0 * height_tex_texel.x), (hU - hD) / (2.0 * height_tex_texel.y));
float inv_tiling = (tiling_scale > 1e-6) ? (1.0 / tiling_scale) : 1.0;
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0);
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0) *
(have_uv ? 1.0 : 0.0);
float cs = cos(rotation_rad);
float sn = sin(rotation_rad);
@@ -341,7 +369,12 @@ void main()
// Only the albedo - the specular term (intensity.y) stays white - so a coloured fragment reads as
// the same material under the same light, and the relief this preview exists to show is unaffected.
vec3 albedo = uniform_color.rgb;
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0)
albedo = palette_rgb[nearest_palette_entry(texture2D(color_tex, color_uv).rgb)];
// The fourth channel is coverage: where the picture is not there, the surface keeps its own
// colour rather than being painted the black that a transparent texel's rgb reads as.
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0) {
vec4 tex_rgba = texture2D(color_tex, color_uv);
if (tex_rgba.a >= 0.5)
albedo = palette_rgb[nearest_palette_entry(tex_rgba.rgb)];
}
gl_FragColor = vec4(vec3(intensity.y) + albedo * intensity.x, uniform_color.a);
}
@@ -36,14 +36,20 @@ varying vec4 world_pos;
varying float distortion;
varying vec2 vertex_uv;
// Right handed (up x right), like libslic3r's project_cylindrical(), so the angle taken from it grows
// anticlockwise about the axis - to the viewer's right when seen from outside the cylinder.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// Term for term libslic3r's project_planar() / project_cylindrical() / project_spherical(), in mm.
vec2 projection_raw(vec3 p, vec3 n)
{
@@ -53,7 +59,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) {
vec3 rel = p - patch_center;
@@ -61,10 +67,16 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
// v negated so the image's first pixel row sits at the top of the model, u flipped on the far side
// of each plane so the two faces sharing it are not mirror images - see libslic3r's box_plane_yz().
vec3 an = abs(n);
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
vec2 project_uv(vec3 p, vec3 n)
@@ -110,6 +110,11 @@ uniform float tex_aspect;
uniform float rotation_rad;
uniform vec2 uv_offset;
uniform bool invert;
// False means the layer places a single copy rather than repeating: outside that copy there is
// simply no texture. DecodedHeightTexture::sample() has always returned 0 there, so the bake got
// this right while the preview wrapped the image and showed a tiled pattern that was never going
// to be printed.
uniform bool tile_enabled;
uniform float midlevel; // the height that means "don't move"; needed by the parallax step
uniform vec3 eye_model_pos; // camera position in the texture frame (world minus tex_anchor)
uniform vec3 tex_anchor; // the volume's origin in world space: the texture frame's origin
@@ -138,17 +143,21 @@ in vec2 vertex_uv;
out vec4 out_color;
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - including
// the handedness, which comes out left-handed for an axis of +Z. Copied rather than "corrected", so
// the preview wraps the texture the same way round as the bake.
// The cylinder's own frame, built exactly as libslic3r's project_cylindrical() builds it - right
// handed, so the angle taken from it grows anticlockwise about the axis, which seen from outside the
// cylinder is to the viewer's right rather than mirrored.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// The raw, millimetre-valued projection of `p` (a position in the texture frame), before the layer's
// tiling/rotation/aspect/offset - a term-for-term transcription of libslic3r's project_planar(),
// project_cylindrical() and project_spherical(). `n` is read by the planar mode only.
@@ -160,7 +169,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) { // Spherical: (longitude, latitude) * radius
vec3 rel = p - patch_center;
@@ -168,10 +177,18 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
vec3 an = abs(n); // Triplanar: drop the dominant normal axis
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
// Triplanar: drop the dominant normal axis. v is negated so the image's first pixel row (v = 0)
// sits at the top of the model instead of upside down, and u is flipped on the far side of each
// plane so the two faces sharing it are not mirror images. libslic3r's box_plane_yz() and its two
// siblings, term for term.
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
// The two surface directions projection_raw()'s u and v run along at `p`, plus how many raw units one
@@ -190,7 +207,7 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec2 xy = vec2(dot(rel, right), dot(rel, fwd));
float r = length(xy);
t = (r > 1e-6) ? (fwd * xy.x - right * xy.y) / r : right; // circumferential: u runs along it
b = up; // v is the distance along the axis
b = -up; // v is the distance *against* the axis
return;
}
if (projection_mode == 2) {
@@ -199,20 +216,20 @@ void projection_axes(vec3 p, vec3 n, out vec3 t, out vec3 b, out vec2 units_per_
vec3 dir = (r > 1e-8) ? rel / r : vec3(0.0, 0.0, 1.0);
float c = length(dir.xy); // cos(latitude)
t = (c > 1e-6) ? vec3(-dir.y, dir.x, 0.0) / c : vec3(1.0, 0.0, 0.0);
b = cross(dir, t); // increasing latitude, unit length
b = -cross(dir, t); // v grows away from the pole, unit length
units_per_mm = vec2(1.0 / max(c, 1e-3), 1.0);
return;
}
vec3 an = abs(n);
if (an.x >= an.y && an.x >= an.z) { // planar = p.yz
t = vec3(0.0, 1.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = p.xz
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 0.0, 1.0);
} else { // planar = p.xy
t = vec3(1.0, 0.0, 0.0);
b = vec3(0.0, 1.0, 0.0);
vec3 an = abs(n); // the same signed basis projection_raw() uses
if (an.x >= an.y && an.x >= an.z) { // planar = (+-y, -z)
t = vec3(0.0, box_face_sign(n.x), 0.0);
b = vec3(0.0, 0.0, -1.0);
} else if (an.y >= an.x && an.y >= an.z) { // planar = (+-x, -z)
t = vec3(-box_face_sign(n.y), 0.0, 0.0);
b = vec3(0.0, 0.0, -1.0);
} else { // planar = (+-x, -y)
t = vec3(box_face_sign(n.z), 0.0, 0.0);
b = vec3(0.0, -1.0, 0.0);
}
}
@@ -284,6 +301,14 @@ int nearest_palette_entry(vec3 rgb)
return best;
}
// True where this uv has texture on it: everywhere when the layer repeats, and only inside the
// single placed copy when it does not. The bake's own sampler draws the same line (see
// DecodedHeightTexture::sample), so the preview now stops at the same edge it does.
bool in_tile(vec2 uv)
{
return tile_enabled || (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0);
}
void main()
{
if (any(lessThan(clipping_planes_dots, ZERO)))
@@ -321,9 +346,9 @@ void main()
? vec2(dot(island_delta_lin.xy, vertex_uv), dot(island_delta_lin.zw, vertex_uv)) + island_delta_tr
: vertex_uv;
color_uv = uv;
have_uv = true;
have_uv = in_tile(uv);
float h = texture(height_tex, uv).r;
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
float k = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) * (have_uv ? 1.0 : 0.0);
vec3 sigmaS = dFdx(world_pos.xyz);
vec3 sigmaT = dFdy(world_pos.xyz);
vec3 R1 = cross(sigmaT, triangle_normal);
@@ -343,10 +368,12 @@ void main()
// Parallax occlusion mapping: march the view ray through the height shell and shade at the
// first point where it drops below the displaced surface (see header).
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0);
// uv first: outside a single placed copy there is no shell to march through.
vec2 uv = project_uv(tex_pos, triangle_normal);
float amp = (invert ? -1.0 : 1.0) * depth_mm * clamp(weight, 0.0, 1.0) *
(in_tile(uv) ? 1.0 : 0.0);
vec3 view_dir = normalize(eye_model_pos - tex_pos);
float v_dot_n = dot(view_dir, triangle_normal);
vec2 uv = project_uv(tex_pos, triangle_normal);
// The shell the displaced surface lives inside, as signed heights along the normal. Taken from
// both ends of h in [0, 1] so it stays correct for an inverted layer or a raised midlevel,
@@ -383,7 +410,7 @@ void main()
}
color_uv = uv; // after the parallax march, so colour and relief stay registered
have_uv = true;
have_uv = in_tile(uv);
float hL = texture(height_tex, uv - vec2(height_tex_texel.x, 0.0)).r;
float hR = texture(height_tex, uv + vec2(height_tex_texel.x, 0.0)).r;
@@ -396,7 +423,8 @@ void main()
// uv -> mm is 1/tiling_scale for the triplanar projection, so this turns the uv-space
// gradient into a real surface slope.
float inv_tiling = (tiling_scale > 1e-6) ? (1.0 / tiling_scale) : 1.0;
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0);
float amplitude = (invert ? -1.0 : 1.0) * depth_mm * inv_tiling * clamp(weight, 0.0, 1.0) *
(have_uv ? 1.0 : 0.0);
// uv was rotated by project_uv() while t/b are the unrotated model axes, so rotate the
// gradient back into the axes' frame.
float cs = cos(rotation_rad);
@@ -429,7 +457,12 @@ void main()
// Only the albedo - the specular term (intensity.y) stays white - so a coloured fragment reads as
// the same material under the same light, and the relief this preview exists to show is unaffected.
vec3 albedo = uniform_color.rgb;
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0)
albedo = palette_rgb[nearest_palette_entry(texture(color_tex, color_uv).rgb)];
// The fourth channel is coverage: where the picture is not there, the surface keeps its own
// colour rather than being painted the black that a transparent texel's rgb reads as.
if (palette_count > 0 && has_color_tex && have_uv && weight > 0.0) {
vec4 tex_rgba = texture(color_tex, color_uv);
if (tex_rgba.a >= 0.5)
albedo = palette_rgb[nearest_palette_entry(tex_rgba.rgb)];
}
out_color = vec4(vec3(intensity.y) + albedo * intensity.x, uniform_color.a);
}
@@ -47,14 +47,20 @@ in vec2 vertex_uv;
out vec4 out_color;
// Right handed (up x right), like libslic3r's project_cylindrical(), so the angle taken from it grows
// anticlockwise about the axis - to the viewer's right when seen from outside the cylinder.
void cylinder_frame(out vec3 up, out vec3 right, out vec3 fwd)
{
up = (length(patch_axis) > 1e-8) ? normalize(patch_axis) : vec3(0.0, 0.0, 1.0);
vec3 arbitrary = (abs(up.z) < 0.9) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
right = normalize(cross(up, arbitrary));
fwd = normalize(cross(right, up));
fwd = normalize(cross(up, right));
}
// Which side of a world plane a face is on, with zero counting as the positive side. Not GLSL's own
// sign(), which returns 0 there and would collapse the coordinate onto a line.
float box_face_sign(float n) { return n >= 0.0 ? 1.0 : -1.0; }
// Term for term libslic3r's project_planar() / project_cylindrical() / project_spherical(), in mm.
vec2 projection_raw(vec3 p, vec3 n)
{
@@ -64,7 +70,7 @@ vec2 projection_raw(vec3 p, vec3 n)
vec3 rel = p - patch_center;
float x = dot(rel, right);
float y = dot(rel, fwd);
return vec2(atan(y, x) * sqrt(x * x + y * y), dot(rel, up));
return vec2(atan(y, x) * sqrt(x * x + y * y), -dot(rel, up));
}
if (projection_mode == 2) {
vec3 rel = p - patch_center;
@@ -72,10 +78,16 @@ vec2 projection_raw(vec3 p, vec3 n)
if (radius < 1e-8)
return vec2(0.0);
vec3 dir = rel / radius;
return vec2(atan(dir.y, dir.x), asin(clamp(dir.z, -1.0, 1.0))) * radius;
return vec2(atan(dir.y, dir.x), -asin(clamp(dir.z, -1.0, 1.0))) * radius;
}
// v negated so the image's first pixel row sits at the top of the model, u flipped on the far side
// of each plane so the two faces sharing it are not mirror images - see libslic3r's box_plane_yz().
vec3 an = abs(n);
return (an.x >= an.y && an.x >= an.z) ? p.yz : ((an.y >= an.x && an.y >= an.z) ? p.xz : p.xy);
if (an.x >= an.y && an.x >= an.z)
return vec2(box_face_sign(n.x) * p.y, -p.z);
if (an.y >= an.x && an.y >= an.z)
return vec2(-box_face_sign(n.y) * p.x, -p.z);
return vec2(box_face_sign(n.z) * p.x, -p.y);
}
vec2 project_uv(vec3 p, vec3 n)
+3 -2
View File
@@ -2602,12 +2602,13 @@ void GCodeProcessorResult::reset() {
//BBS: add mutex for protection of gcode result
lock();
moves.clear();
// moves and lines_ends grow with the print: free them, as no reset result reuses the capacity.
clear_and_shrink(moves);
plate_mass = {};
object_masses.clear();
body_masses.clear();
support_masses.clear();
lines_ends.clear();
clear_and_shrink(lines_ends);
printable_area = Pointfs();
//BBS: add bed exclude area
bed_exclude_area = Pointfs();
+22
View File
@@ -354,6 +354,24 @@ Model Model::read_from_file(const std::string&
ObjInfo obj_info;
ObjParser::MtlData mtl_data;
result = load_obj(input_file.c_str(), &model, obj_info, message, nullptr, &mtl_data);
// Keep the model's own UV channel on the volume, whatever the colour import then does with
// the mesh: it is what TextureProjectionMethod::ModelUV maps a texture-displacement layer
// through, so a model that arrives with a UV layout is textured on that layout instead of on
// a fresh unwrap. load_obj() fills obj_info.uvs per face of the mesh it built, in the same
// order (and only when every face named a known material, hence the size check). V is flipped
// on the way in, to the convention DecodedHeightTexture samples in - the same flip
// obj_to_textured_mesh() does for the colour importer.
if (result && !obj_info.uvs.empty() && !model.objects.empty() && !model.objects.back()->volumes.empty()) {
ModelVolume &volume = *model.objects.back()->volumes[0];
const indexed_triangle_set &its = volume.mesh().its;
if (obj_info.uvs.size() == its.indices.size()) {
volume.texture_uv.resize(its.indices.size() * 3);
for (size_t fi = 0; fi < obj_info.uvs.size(); ++fi)
for (int k = 0; k < 3; ++k)
volume.texture_uv[fi * 3 + size_t(k)] =
Vec2f(obj_info.uvs[fi][size_t(k)].x(), 1.f - obj_info.uvs[fi][size_t(k)].y());
}
}
if (result && obj_info.has_uv_png && !obj_info.uvs.empty() && !model.objects.empty()) {
// Textured OBJ: hand the mesh + materials to the texture-to-color importer
// instead of the flat per-face colour dialog.
@@ -2134,6 +2152,10 @@ void ModelVolume::reset_extra_facets()
// than left referring to a mesh that no longer matches it.
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
this->texture_displacement_facet(i).reset();
// Same reasoning for the model's own UV channel: it is indexed by triangle, so against a mesh
// this no longer matches it would map the texture by another mesh's triangle numbering. A caller
// that can carry it across - see transfer_uv_channel() - puts it back after this.
this->reset_texture_uv();
}
std::optional<TriangleSelector::SavedPainting> ModelVolume::save_painting() const
+23 -2
View File
@@ -975,6 +975,26 @@ public:
// they are not a property of any single layer.
TextureDisplacementOptions texture_displacement_options;
// The model's own texture coordinates, as the file it was imported from carried them: three per
// triangle of mesh().its, in its triangle order (corner k of triangle i at 3i+k), V already
// flipped to the sampling convention (V = 0 is the image's top row). Empty when the source had
// none, which is every STL and every 3mf - only a textured OBJ brings one in today.
//
// Per corner rather than per vertex because that is what a UV layout is: the two sides of a seam
// are the same vertex with two different coordinates, and collapsing them would smear the texture
// across every island boundary. TextureProjectionMethod::ModelUV maps through it, which is what
// lets a model that already carries a UV channel be textured on the artist's own layout instead
// of on a fresh unwrap.
//
// Indexed by triangle, so anything that *replaces* the mesh has to bring it across (or drop it):
// see transfer_uv_channel(), and reset_texture_uv() for the cases that cannot.
std::vector<Vec2f> texture_uv;
bool has_texture_uv() const { return !texture_uv.empty() && texture_uv.size() == mesh().its.indices.size() * 3; }
// Forgets the channel. For a mesh change that nothing can carry it across - a split, a boolean -
// where leaving it would map the texture by another mesh's triangle numbering.
void reset_texture_uv() { texture_uv.clear(); }
// Save painting data before reset_extra_facets() discards it.
// Used for replacing mesh without losing painting data.
// Only for model parts (not modifiers/connectors).
@@ -1240,6 +1260,7 @@ private:
texture_displacement_facets_6(other.texture_displacement_facets_6), texture_displacement_facets_7(other.texture_displacement_facets_7),
texture_displacement_layers(other.texture_displacement_layers),
texture_displacement_options(other.texture_displacement_options),
texture_uv(other.texture_uv),
cut_info(other.cut_info), text_configuration(other.text_configuration), emboss_shape(other.emboss_shape)
{
assert(this->id().valid());
@@ -1338,7 +1359,7 @@ private:
cereal::load_by_value(ar, f);
mesh_changed |= tf != f.timestamp();
}
ar(texture_displacement_layers, texture_displacement_options);
ar(texture_displacement_layers, texture_displacement_options, texture_uv);
cereal::load_by_value(ar, config);
cereal::load(ar, text_configuration);
cereal::load(ar, emboss_shape);
@@ -1362,7 +1383,7 @@ private:
cereal::save_by_value(ar, fuzzy_skin_facets);
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
cereal::save_by_value(ar, texture_displacement_facet(i));
ar(texture_displacement_layers, texture_displacement_options);
ar(texture_displacement_layers, texture_displacement_options, texture_uv);
cereal::save_by_value(ar, config);
cereal::save(ar, text_configuration);
cereal::save(ar, emboss_shape);
File diff suppressed because it is too large Load Diff
+257 -10
View File
@@ -86,6 +86,17 @@ enum class TextureProjectionMethod : int
// that is inherent to view projection and is the user's call, not a bug. The projector's two
// in-plane axes live in TextureDisplacementLayer::view_project_right/up.
ViewProjected = 4,
// The model's own texture coordinates, as the file it was imported from carried them (see
// ModelVolume::texture_uv). Nothing is unwrapped or projected: the artist's layout *is* the
// placement, so a texture authored against that layout - the model's own albedo map, say - lands
// exactly where it was painted. Automatically picked for a new layer on a volume that has a UV
// channel, since re-unwrapping a model that already carries one can only be worse than using it.
//
// The uv is already normalized, so unlike every method above it is not measured in millimetres:
// "Tile size" and the non-square aspect correction do not apply to it (the layer's rotation and
// offset still do). Falls back to Triplanar when the volume has no channel, exactly as LSCM falls
// back when a patch cannot be flattened.
ModelUV = 5,
};
// Dihedral angle (degrees) above which an edge between two painted triangles becomes a chart seam
@@ -121,6 +132,11 @@ enum class TextureBlendMode : int
Subtract = 1, // acc - value (carve this layer's relief out of the layers below)
Multiply = 2, // acc * (value / 1mm) (mask/modulate the layers below by this layer)
Divide = 3, // acc / (value / 1mm) (inverse mask; guarded against a zero/near-zero divisor)
// acc = value: this layer replaces what is under it instead of combining with it, so where it is
// painted only its own relief remains. The image editor's "Normal" mode, under the name the panel
// uses. Note the stack's *colour* already behaves this way - a higher slot's colour overwrites a
// lower one's where they overlap - so this is what makes the displacement agree with it.
Override = 4,
};
// Combines one layer's signed displacement `value` (mm) into `accumulated` (mm) per `mode`.
@@ -154,6 +170,38 @@ struct TextureIsland
// chart to its true mm area, so a freshly unwrapped patch has uniform texel density to begin with.
void average_island_scales(std::vector<TextureIsland> &islands);
// Photo-style adjustments to a layer's source image, as the gizmo's image-adjustment panel sets them.
//
// These are *not* layer parameters: nothing here is stored on TextureDisplacementLayer and nothing here is
// re-applied at bake time. The panel applies them once, to the image, and the result becomes the layer's
// image - so the adjusted pixels feed the colour and the displacement together, and a brightness change
// really does change the relief. That is the intended behaviour: one image, one source of truth, rather
// than a second set of knobs the bake would have to replay in the right order.
//
// Contrast with TextureDisplacementLayer::smoothing, which *is* a layer parameter applied on every decode:
// `blur` here is a destructive edit of the image, `smoothing` is a live low-pass over whatever the image is.
struct TextureAdjustments
{
float brightness = 0.f; // [-1, 1]; 0 unchanged, -1 black, +1 white
float contrast = 0.f; // [-1, 1]; 0 unchanged, -1 flat mid-grey, +1 hard threshold
float sharpness = 0.f; // [0, 1]; 0 unchanged. Unsharp-mask amount
float blur = 0.f; // [0, 1]; 0 unchanged. Fraction of SOURCE_BLUR_SPAN, as `smoothing` is
float hue_deg = 0.f; // [-180, 180]; 0 unchanged. No effect on a grayscale image - grey has no hue
bool identity() const
{
return brightness == 0.f && contrast == 0.f && sharpness == 0.f && blur == 0.f && hue_deg == 0.f;
}
// Exact equality, which is what is wanted: these come straight off sliders, and the question asked of
// them is "is this still the value the preview on screen was computed from", not "are these close".
bool operator==(const TextureAdjustments &o) const
{
return brightness == o.brightness && contrast == o.contrast && sharpness == o.sharpness &&
blur == o.blur && hue_deg == o.hue_deg;
}
bool operator!=(const TextureAdjustments &o) const { return !(*this == o); }
};
// One texture asset plus its projection/displacement parameters. Several layers may be painted
// onto overlapping areas of the same volume: their displacements are combined per vertex, in slot
// order, each layer folding into the total via its own TextureBlendMode (see
@@ -277,6 +325,18 @@ struct TextureDisplacementLayer
// - zero or positive: a mesh vertex, every unwrapped copy of it (how edits were stored before).
std::vector<std::pair<int, Vec2f>> lscm_uv_overrides;
// Live, unsaved image adjustments from the gizmo's image-adjustment panel, applied by
// decode_height_texture() on top of the decoded image - so while the panel is open the relief, the
// colour, the thumbnails and the bake all see the adjusted image, and moving a slider really does
// change the displacement. See TextureAdjustments.
//
// Deliberately *not* serialized, by either save()/load() here or the .3mf: it is the state of an open
// editor, not a property of the layer. The panel resets it when it closes, and "Save as copy" resolves
// it by writing a new image and pointing the layer at that - which is the only way an adjustment
// becomes permanent. A project saved mid-adjustment therefore stores the unadjusted image, which is
// the honest answer: nothing was committed.
TextureAdjustments preview_adjust;
// How this layer folds into the displacement accumulated by the layers below it. Ignored for
// the lowest-slot painted layer, which has nothing beneath it to combine with (the GUI shows
// it as the "Base" layer and hides the control).
@@ -293,6 +353,32 @@ struct TextureDisplacementLayer
// for the boundary to be drawn on.
bool color_enabled = false;
// Colour correction, applied to the image's RGB before it is matched against the filaments and
// before the preview quantizes it. Never to the height: the relief is what the grayscale says,
// and a brightness slider has no business moving geometry. The defaults below are the identity,
// so a layer that never meets the Image tool behaves exactly as it did.
float brightness = 0.f; // -1 .. 1, added last, after contrast
float contrast = 0.f; // -1 .. 1, pivoted on mid grey; -1 flattens to grey, 1 doubles the slope
float hue = 0.f; // -180 .. 180 degrees, rotated about the grey axis at constant luma
float sharpness = 0.f; // 0 .. 1 unsharp mask amount, 0 is off
// How many colours the picture is allowed to use, 0 for as many as it likes. Reduced by k-means
// in RGB before the filaments are matched, so the result uses at most this many of them: 2 for a
// logo that should be two flat colours, 4 or 5 for a poster, off for a photograph.
int color_count = 0; // 0, or 2 .. 12
// Leaves the background of a picture unprinted, so the object's own colour shows through instead
// of a slab of white behind a logo. Texels the source image marked transparent always count;
// `bg_remove` additionally keys out one colour.
bool bg_remove = false;
float bg_tolerance = 0.15f; // 0 .. 1, distance from the keyed colour that still counts as background
// The colour keyed out. Taken from the median of the picture's four corners while
// `bg_from_corners` is set, which is right for nearly every logo on a flat card; the panel's
// dropper and swatch clear it and put a colour of the user's own here.
bool bg_from_corners = true;
float bg_color[3] = { 1.f, 1.f, 1.f };
float saturation = 1.f; // 0 .. 2, 1 leaves it alone, 0 is grayscale
float gamma = 1.f; // 0.2 .. 5, 1 leaves it alone; above 1 lifts the midtones
bool color_invert = false; // negative of the colour, as opposed to `invert` which flips relief
bool empty() const { return !image_data || image_data->empty(); }
template<class Archive> void save(Archive &ar) const
@@ -302,7 +388,9 @@ struct TextureDisplacementLayer
static_cast<int>(tile_method), static_cast<int>(projection_method), lscm_seam_angle_deg, islands,
static_cast<int>(blend_mode), midlevel, island_padding_mm, lscm_seam_edges, view_project_right,
view_project_up, smoothing, edge_smoothing, edge_smoothing_amount, auto_connect_islands, island_groups,
lscm_uv_overrides, view_project_projective, view_project_matrix, color_enabled);
lscm_uv_overrides, view_project_projective, view_project_matrix, color_enabled, brightness,
contrast, saturation, gamma, color_invert, hue, sharpness, color_count, bg_remove,
bg_tolerance, bg_from_corners, bg_color[0], bg_color[1], bg_color[2]);
}
template<class Archive> void load(Archive &ar)
{
@@ -314,7 +402,8 @@ struct TextureDisplacementLayer
tile_method_int, projection_method_int, lscm_seam_angle_deg, islands, blend_mode_int, midlevel,
island_padding_mm, lscm_seam_edges, view_project_right, view_project_up, smoothing, edge_smoothing,
edge_smoothing_amount, auto_connect_islands, island_groups, lscm_uv_overrides, view_project_projective,
view_project_matrix, color_enabled);
view_project_matrix, color_enabled, brightness, contrast, saturation, gamma, color_invert, hue, sharpness,
color_count, bg_remove, bg_tolerance, bg_from_corners, bg_color[0], bg_color[1], bg_color[2]);
image_data = blob.empty() ? nullptr : std::make_shared<std::vector<unsigned char>>(blob.begin(), blob.end());
tile_method = static_cast<TextureTileMethod>(tile_method_int);
projection_method = static_cast<TextureProjectionMethod>(projection_method_int);
@@ -475,11 +564,19 @@ struct DecodedHeightTexture
// has_color() is what the whole colour feature keys off: a layer set to colour a model with a
// grayscale texture on it simply colours nothing.
std::vector<uint8_t> rgb;
// Coverage: 0 where the picture is not there at all, 255 where it is fully there. Empty when the
// source image had no alpha and nothing has keyed a background out, which is the common case and
// means "opaque everywhere". Distinct from a black texel, which is a colour.
std::vector<uint8_t> alpha;
int width = 0;
int height = 0;
bool empty() const { return width <= 0 || height <= 0 || pixels.empty(); }
bool has_color() const { return !empty() && rgb.size() == size_t(width) * size_t(height) * 3; }
bool has_alpha() const { return !empty() && alpha.size() == size_t(width) * size_t(height); }
// Coverage at a uv, bilinear, in [0, 1]. 1 everywhere when there is no alpha plane.
float sample_alpha(const Vec2f &uv, bool tile_enabled = true,
TextureTileMethod tile_method = TextureTileMethod::Repeat) const;
// Bilinearly sampled height in [0, 1] at a normalized uv coordinate. When tile_enabled is false,
// a uv outside [0, 1) samples as 0 - the texture simply is not there, rather than its border
// row/column being smeared outward forever (which is what clamping the coordinate would do, and
@@ -504,6 +601,36 @@ struct DecodedHeightTexture
bool texel_tap(const Vec2f &uv, bool tile_enabled, TextureTileMethod tile_method, TexelTap &out) const;
};
// Applies `adj` to `src` and returns the result; `src` is left alone. An empty `src`, or an identity
// `adj`, gives back a copy.
//
// Order is tonal, then spatial: brightness, contrast and hue per texel first, then blur, then sharpness.
// Sharpness last is what lets the two spatial knobs be used together - blur to kill speckle, then
// sharpness to put the real edges back - instead of the blur simply undoing the sharpen.
//
// Grayscale in, grayscale out (`rgb` stays empty): promoting a grey image to RGB would hand the layer's
// colour feature a row of identical greys to "colour" the model with, and triple the stored PNG for it.
// For a colour image the height is recomputed as the luminance of the *adjusted* colour, with
// decode_height_texture()'s own coefficients, so the relief and the colour can never drift apart.
DecodedHeightTexture apply_texture_adjustments(const DecodedHeightTexture &src, const TextureAdjustments &adj);
// Blur radius, in texels, that TextureAdjustments::blur == 1 means on a `min(width, height)`-sized image:
// the same 5%-of-the-short-side span the Smoothing slider uses, under the same 48-texel cost cap, so the
// two controls bite at the same rate and a user moving between them is not surprised.
float adjustment_blur_radius(float blur, int width, int height);
// Box-filters `src` down so neither side exceeds `max_px`, preserving aspect; never upscales, and
// returns a copy when it already fits. Colour and height are filtered the same way, and the height
// stays the height - it is not recomputed from the filtered colour, because a box filter is linear and
// luminance is linear in the channels, so the two agree already.
//
// This is what lets the adjustment panel's live preview cost depend on the size of the box it is drawn
// in rather than on the size of the image: adjusting a downscaled copy per slider frame, and the
// full-size image only once, on commit. A box filter (rather than a plain decimation) is the point -
// these textures are high-frequency by nature, and dropping texels would alias the preview into
// showing detail the adjustment is not actually producing.
DecodedHeightTexture downscale_height_texture(const DecodedHeightTexture &src, int max_px);
// Decode a layer's raw image bytes into sampleable height data, plus colour when the source has any.
// Both 8-bit grayscale PNGs (the shipped library, and anything imported before colour was kept) and
// colour PNGs are accepted; for a colour source the height is its luminance, using the same
@@ -516,6 +643,19 @@ DecodedHeightTexture decode_height_texture(const TextureDisplacementLayer &layer
// texture - cheap enough to ask every frame. Smoothing does not change it, so the raw decode is what is read.
bool height_texture_has_color(const TextureDisplacementLayer &layer);
// True when `layer`'s colour correction is anything other than the identity, so callers can skip
// both the work and the cache invalidation it would otherwise force.
bool has_color_adjustments(const TextureDisplacementLayer &layer);
// Applies that correction to an already decoded image, in place, to `rgb` only. Order is gamma,
// contrast, brightness, saturation, invert, each clamped back into range - the order a photo editor
// applies them in, and the one that keeps contrast pivoted on mid grey rather than on a brightness
// the slider has already moved.
//
// Deliberately not folded into decode_height_texture(): that result is cached per image, shared by
// every layer using the same file, and keyed on the image bytes alone.
void apply_color_adjustments(DecodedHeightTexture &tex, const TextureDisplacementLayer &layer);
// Maps a linear RGB colour in [0, 1] to an index into the caller's palette, or -1 for "no colour".
//
// Deliberately a callback rather than a function here: matching a colour to a filament is a
@@ -551,11 +691,24 @@ struct TextureColorSettings
bool empty() const { return palette.empty(); }
};
// The two world directions the box projection takes its u and v along on a face whose outward
// normal is `normal`: the plane is the one that normal is closest to, and the pair is oriented as a
// viewer standing outside the model sees it - u to their right, v *down* the image, which is the
// direction v runs in the texture (v = 0 is the image's first pixel row, see
// DecodedHeightTexture::sample()). So an image comes out the way it looks in a file manager rather
// than upside down, and it is not mirrored on the three faces facing the other way.
//
// Exposed because the GUI needs the same basis for the on-canvas "adjust texture placement" gizmo
// (its ring's zero angle and its offset handle's plane), and it must not be a second, drifting copy
// of the table.
void box_projection_axes(const Vec3f &normal, Vec3f &u_axis, Vec3f &v_axis);
// Raw dominant-axis planar projection of `position` (in mm, not yet scaled/rotated/offset by any
// layer), dropping the axis position that best aligns with `normal`. Exposed on its own (rather
// than only inline inside project_texture_displacement_uv()) so GUI code - the on-canvas
// "adjust texture placement" gizmo - can map a dragged 3D point into the exact same 2D space
// tiling_scale/rotation_deg/offset operate in, without duplicating the axis-selection logic.
// layer), dropping the axis position that best aligns with `normal`. Equivalent to projecting onto
// box_projection_axes()' pair. Exposed on its own (rather than only inline inside
// project_texture_displacement_uv()) so GUI code - the on-canvas "adjust texture placement" gizmo -
// can map a dragged 3D point into the exact same 2D space tiling_scale/rotation_deg/offset operate
// in, without duplicating the axis-selection logic.
Vec2f project_planar(const Vec3f &position, const Vec3f &normal);
// Applies a layer's tiling_scale/rotation_deg/offset to an already-projected planar coordinate
@@ -568,7 +721,13 @@ Vec2f project_planar(const Vec3f &position, const Vec3f &normal);
// squeezed into a square tile: `tiling_scale` is the tile's size along u, and the tile is
// `tiling_scale * height / width` mm along v, which keeps texels square. 1 (the default) is the
// square case and leaves the coordinate exactly as it always was.
Vec2f apply_uv_transform(const Vec2f &planar, const TextureDisplacementLayer &layer, float aspect = 1.f);
//
// `normalized_uv` says the coordinate is already a uv rather than a millimetre measurement on the
// model - which is what TextureProjectionMethod::ModelUV hands in. Then neither the tiling scale (mm
// per tile is meaningless for it) nor the aspect correction (the artist's layout already accounts for
// the image's proportions) applies, and only the rotation and offset are left.
Vec2f apply_uv_transform(const Vec2f &planar, const TextureDisplacementLayer &layer, float aspect = 1.f,
bool normalized_uv = false);
// Applies a row-major 3x4 projective matrix (see TextureDisplacementLayer::view_project_matrix) to a
// local-space point, writing the resulting texture uv. Returns false - and leaves `uv` untouched -
@@ -605,6 +764,31 @@ bool sample_layer_color(const DecodedHeightTexture &texture, const TextureDispla
const Vec3f &patch_center = Vec3f::Zero(), const Vec3f &patch_axis = Vec3f::UnitZ(),
const Vec2f *lscm_uv = nullptr);
// Carries a per-facet paint annotation - the colour paint above all - from a mesh onto the mesh a
// bake produced from it: every triangle of `dst_mesh` takes the state painted at its own foot point on
// `src_mesh`, i.e. on the nearest point of the surface it was built from. Returned as one
// EnforcerBlockerType per `dst_mesh` triangle, 0 (NONE) where that foot point carried no paint.
//
// ModelVolume::restore_painting() cannot do this. Its remap pairs a source paint triangle with a
// target triangle that *overlaps* it to within 0.01 mm, which is right for a remesh or a
// simplification - they leave the surface where it was - and useless after a bake, which moves the
// surface by the relief depth. Measured on a model displaced by a tenth of its own size, that remap
// kept a quarter of the colour and left the rest unpainted; this keeps essentially all of it, because
// a foot point is exactly as far away as the relief is deep and the lookup does not care how far that
// is.
//
// The source's *sub*-triangles are what is looked up, not its triangles, so the part of a triangle a
// brush stroke only clipped a corner off keeps its own state rather than rounding to the whole
// triangle's. No distance limit is needed or wanted: the nearest point on the source surface is where
// a baked triangle came from however far the relief carried it, and an unpainted origin reports NONE
// on its own.
//
// Returns an empty vector when `src_paint` is empty or either mesh is - the caller then has nothing to
// carry, which is not the same as "carry nothing".
std::vector<uint8_t> transfer_facet_paint(const indexed_triangle_set &src_mesh,
const TriangleSelector::TriangleSplittingData &src_paint,
const indexed_triangle_set &dst_mesh);
// Area-weighted centroid and average normal of a layer's currently painted patch, in mesh-local
// coordinates - the same measurements build_texture_displacement() uses to pick its dominant
// projection axis. Used by the GUI to anchor the on-canvas "adjust texture placement" gizmo to
@@ -718,6 +902,55 @@ std::vector<Vec2f> compute_lscm_uvs(const indexed_triangle_set &patch, const Tex
// Returns an empty vector if the patch has no triangles or the unwrap carries no source_face map.
std::vector<Vec2f> compute_lscm_corner_uvs(const indexed_triangle_set &patch, const TextureDisplacementLayer &layer);
// Three UVs per patch triangle, read out of the model's *own* UV channel - the
// TextureProjectionMethod::ModelUV counterpart of compute_lscm_corner_uvs(), and laid out the same way
// (corner k of triangle i at index 3i+k).
//
// `model_uv` is the volume's channel: three uvs per triangle of `base_mesh`, in its triangle order
// (see ModelVolume::texture_uv). `patch_source` maps each patch triangle back to the base-mesh
// triangle it was cut from - TriangleSelector::get_facets_strict()'s out_source. A patch triangle is
// always a piece of exactly one base triangle, so each of its corners is interpolated barycentrically
// inside that triangle's three uvs. That is what keeps a sub-triangle the brush split (whose corners
// are not base-mesh vertices at all) on the texture, and what keeps the two sides of a UV seam
// reading from their own island instead of from one averaged coordinate.
//
// Returns an empty vector when the channel does not match `base_mesh`, when `patch_source` does not
// match `patch`, or when either is empty - the callers treat that as "no placement" and fall back,
// exactly as they do for an unwrap that failed.
std::vector<Vec2f> compute_model_corner_uvs(const indexed_triangle_set &base_mesh,
const std::vector<Vec2f> &model_uv,
const indexed_triangle_set &patch,
const std::vector<int> &patch_source);
// One UV per patch vertex, collapsed from a per-corner array: the first corner to reach a vertex wins.
// This is the per-corner/per-vertex split compute_lscm_uvs() documents, applied to any corner array -
// displacement is per-vertex, so a vertex on a seam has to settle on one of its copies.
// Returns an empty vector if `corner` is not three per patch triangle.
std::vector<Vec2f> collapse_corner_uvs(const indexed_triangle_set &patch, const std::vector<Vec2f> &corner);
// Resamples a per-corner UV channel from `src_mesh` onto `dst_mesh`, for when something replaces a
// volume's mesh and the model's own UV channel has to come along: the colour import's painted mesh,
// the gizmo's remesh/subdivide, the default bake pipeline's rebuild. Each destination corner takes the
// uv of its closest point on the source surface, interpolated barycentrically inside the source
// triangle it lands on - the same transfer LscmLookup does per point, run over every corner.
//
// Exact wherever the two meshes describe the same surface, which is the case for every caller here
// (they subdivide, repair or displace it, they do not reshape it). A corner that lands nowhere near
// the source - farther than `max_distance` (negative: no limit) - takes (0, 0).
//
// One thing a positional transfer cannot reproduce: a *seam* vertex, where one position carries a
// different uv in each island that meets there. Position alone does not say which island a corner
// belongs to, so corners on a seam all take whichever island the nearest-triangle lookup lands on,
// and the texture can be off by up to one triangle in a band along the island borders. Doing better
// needs a triangle-to-triangle correspondence, which only some of the stages that replace a mesh
// have (a remesh has none at all).
//
// Returns an empty vector when `src_uv` is not three per source triangle, or when either mesh is empty.
std::vector<Vec2f> transfer_uv_channel(const indexed_triangle_set &src_mesh,
const std::vector<Vec2f> &src_uv,
const indexed_triangle_set &dst_mesh,
float max_distance = -1.f);
// The TextureDisplacementLayer::lscm_uv_overrides key for one unwrapped vertex (an index into PatchUnwrap::uvs).
inline int lscm_uv_override_key(int unwrapped_vertex) { return -(unwrapped_vertex + 1); }
@@ -776,6 +1009,10 @@ using TextureDisplacementFacetsData = std::array<TriangleSelector::TriangleSplit
//
// `color`, when given, also reports which filament each triangle should print in - see
// TextureColorRequest.
//
// `model_uv`, when given, is the volume's own UV channel (three uvs per base-mesh triangle, see
// ModelVolume::texture_uv) and is what a TextureProjectionMethod::ModelUV layer maps through. A layer
// set to ModelUV without it falls back to Triplanar.
struct TextureColorRequest
{
// RGB -> palette index. Supplied by the GUI, which owns both the perceptual matching and the list
@@ -850,7 +1087,9 @@ indexed_triangle_set build_texture_displacement(const indexed_triangle_set
// stage, already brought back into `base_mesh`'s frame.
BakeStageRecorder *debug = nullptr,
// When given, receives what the bake spent.
TextureBakeStats *stats = nullptr);
TextureBakeStats *stats = nullptr,
// The model's own UV channel; see above.
const std::vector<Vec2f> *model_uv = nullptr);
// `volume`'s mesh coordinates -> world millimetres: its first instance's transform times its own.
// The mesh is shared by every instance, so a multi-instance object can only be baked for one of
@@ -925,11 +1164,15 @@ ColorFieldSampler make_combined_color_sampler(const indexed_triangle_set
const std::vector<TextureDisplacementLayer> &layers,
const TextureDisplacementFacetsData &facets_data,
ColorQuantizeFn quantize,
ColorQuantizeFn quantize_pure = nullptr);
ColorQuantizeFn quantize_pure = nullptr,
// The model's own UV channel, for ModelUV layers; see
// build_texture_displacement().
const std::vector<Vec2f> *model_uv = nullptr);
HeightFieldSampler make_combined_displacement_sampler(const indexed_triangle_set &base_mesh,
const std::vector<TextureDisplacementLayer> &layers,
const TextureDisplacementFacetsData &facets_data);
const TextureDisplacementFacetsData &facets_data,
const std::vector<Vec2f> *model_uv = nullptr);
// Uniformly subdivides `mesh` (every triangle recursively split into 4 via edge midpoints, using a
// shared cache so a midpoint is computed once and reused by both triangles on either side of that
@@ -1134,6 +1377,10 @@ struct TextureDisplacementPrepareResult
{
indexed_triangle_set mesh;
TextureDisplacementFacetsData masks;
// The model's own UV channel, resampled onto `mesh` (see transfer_uv_channel()). Empty when the
// volume had none. Like the masks it is handed back rather than left to the caller to recompute,
// because only the run itself knows which stages replaced the mesh.
std::vector<Vec2f> uv;
// The remesh landed but no layer's paint survived being carried onto it. Nothing is committed:
// everything downstream is driven by that paint, so baking on would bake a flat mesh.
bool paint_lost = false;
+21
View File
@@ -25,6 +25,7 @@
#include "TextureToColor/ColorUtils.hpp"
#include "Model.hpp"
#include "TextureDisplacement.hpp"
#include "TextureToColor/TriMesh.hpp"
#include "TriangleMesh.hpp"
#include "TriangleSelector.hpp"
@@ -554,9 +555,29 @@ bool apply_painted_mesh_to_volume(
<< ", unit_scale=" << unit_scale << ")";
}
// The model's own UV channel is indexed by triangle, and this replaces the triangles, so it has
// to be resampled onto them. Kept rather than dropped because it is the layout the model was
// authored against: a texture-displacement layer set to ModelUV maps through it, and the colour
// import is exactly the path a model that carries one arrives by.
const indexed_triangle_set old_its = volume.has_texture_uv() ? volume.mesh().its : indexed_triangle_set{};
const std::vector<Vec2f> old_uv = volume.texture_uv;
volume.set_mesh(std::move(new_mesh));
volume.calculate_convex_hull();
// Resampled here and not further down, while the two meshes still share a frame: the painted mesh
// was just shifted by the same source.mesh_offset the old one was centred by, so the only thing
// between them is whatever drift the repair introduced. The re-centering below translates the mesh
// again, and a translation is exactly what a closest-point transfer cannot see through - it would
// read every uv off a point that far away. A uv is a coordinate in the texture, so it does not care
// about either shift; it just has to be read before the second one happens.
if (!old_its.indices.empty())
volume.texture_uv = transfer_uv_channel(old_its, old_uv, volume.mesh().its);
else
// No channel to carry, so make sure none is left behind either: a leftover of the right length
// would read as a valid channel against a mesh it was never measured on.
volume.reset_texture_uv();
// Re-center the replaced mesh so its bbox center sits at the origin,
// matching what center_geometry_after_creation did for the original mesh.
// CGAL repair / subdivision may shift the bbox center (drift); without
+6 -3
View File
@@ -927,15 +927,17 @@ void ViewerImpl::reset()
m_used_extruders.clear();
m_total_time = { 0.0f, 0.0f };
m_travels_time = { 0.0f, 0.0f };
m_vertices.clear();
m_vertices_colors.clear();
// swap rather than clear: these are sized by the print, and a reset means the memory
// should go back, not sit reserved until the next load
std::vector<PathVertex>().swap(m_vertices);
std::vector<float>().swap(m_vertices_colors);
for (std::vector<float>& times : m_layer_start_times)
std::vector<float>().swap(times);
std::vector<uint32_t>().swap(m_layer_first_vertex);
m_layers_in_vertex_order = false;
m_valid_lines_bitset.clear();
// BitSet::clear() only zeroes the bits, it keeps the blocks allocated; load() builds a new
// bitset anyway and it is never read while m_vertices is empty
m_valid_lines_bitset = BitSet<>();
#if VGCODE_ENABLE_COG_AND_TOOL_MARKERS
m_cog_marker.reset();
#endif // VGCODE_ENABLE_COG_AND_TOOL_MARKERS
@@ -1834,6 +1836,7 @@ size_t ViewerImpl::get_used_cpu_memory() const
ret += sizeof(m_extrusion_roles_colors);
ret += sizeof(m_options_colors);
ret += STDVEC_MEMSIZE(m_vertices, PathVertex);
ret += STDVEC_MEMSIZE(m_vertices_colors, float);
for (const std::vector<float>& times : m_layer_start_times)
ret += STDVEC_MEMSIZE(times, float);
ret += STDVEC_MEMSIZE(m_layer_first_vertex, uint32_t);
+2
View File
@@ -186,6 +186,8 @@ set(SLIC3R_GUI_SOURCES
GUI/Gizmos/GLGizmoFlatten.hpp
GUI/Gizmos/GLGizmoFuzzySkin.cpp
GUI/Gizmos/GLGizmoFuzzySkin.hpp
GUI/Gizmos/GLGizmoImage.cpp
GUI/Gizmos/GLGizmoImage.hpp
GUI/Gizmos/GLGizmoMeasure.cpp
GUI/Gizmos/GLGizmoMeasure.hpp
GUI/Gizmos/GLGizmoMeshBoolean.cpp
+891
View File
@@ -0,0 +1,891 @@
#include "GLGizmoImage.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/TextureDisplacement.hpp"
#include "libslic3r/format.hpp"
#include "slic3r/GUI/Camera.hpp"
#include "slic3r/GUI/GLCanvas3D.hpp"
#include "slic3r/GUI/GLTexture.hpp"
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/IconManager.hpp"
#include "slic3r/GUI/ImGuiWrapper.hpp"
#include "slic3r/GUI/Plater.hpp"
#include "slic3r/GUI/TextureLibrary.hpp"
#include "slic3r/GUI/Shortcuts.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoUtils.hpp"
#include "slic3r/GUI/Jobs/Worker.hpp"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <imgui.h>
#include <optional>
#include <string>
#include <vector>
#include <wx/string.h>
namespace Slic3r::GUI {
GLGizmoImage::GLGizmoImage(GLCanvas3D &parent, const std::string &icon_filename, unsigned int sprite_id)
: GLGizmoTextureDisplacement(parent, icon_filename, sprite_id)
{
}
bool GLGizmoImage::on_init()
{
if (!GLGizmoTextureDisplacement::on_init())
return false;
// Everything the base set up stays - it is the same painting machinery - except the key that
// opens it, which is this tool's own.
m_shortcut = Shortcut::GizmoImage;
return true;
}
std::string GLGizmoImage::on_get_name() const
{
return _u8L("Image");
}
wxString GLGizmoImage::handle_snapshot_action_name(bool shift_down, GLGizmoPainterBase::Button button_down) const
{
// Same paint, same masks; only the undo step's wording follows the tool the user is in.
const bool erasing = shift_down || (m_erase_mode != (button_down == GLGizmoPainterBase::Button::Right));
return erasing ? _L("Remove image from the area") : _L("Place image");
}
bool GLGizmoTextureDisplacement::pick_background_at(const Vec2d &mouse_pos)
{
ModelVolume *mv = texture_volume();
ModelObject *mo = m_c->selection_info()->model_object();
TextureDisplacementLayer *layer = mv != nullptr ? active_layer() : nullptr;
if (mv == nullptr || mo == nullptr || layer == nullptr || layer->empty())
return false;
const int idx = texture_volume_raycaster_index();
if (idx < 0)
return false;
const Selection &selection = m_parent.get_selection();
const Transform3d trafo = mo->instances[selection.get_instance_idx()]->get_transformation().get_matrix() * mv->get_matrix();
const Camera &camera = wxGetApp().plater()->get_camera();
Vec3f hit = Vec3f::Zero(), normal = Vec3f::Zero();
if (!m_c->raycaster()->raycasters()[size_t(idx)]->unproject_on_mesh(
mouse_pos, trafo, camera, hit, normal,
m_c->object_clipper()->get_clipping_plane()))
return false;
// The picture's own colour at that point, read through the projection the bake uses, rather
// than the pixel on screen: the screen pixel carries the lighting and the filament the colour
// was already quantized to, so keying on it would remove the wrong thing.
//
// Uncorrected, deliberately. The key is applied at the end of the correction chain, against
// colours the earlier passes have already moved, so it has to be stated in those terms - the
// same reason the panel's dropper reads the corrected preview.
const indexed_triangle_set &base = mv->mesh().its;
const indexed_triangle_set patch =
extract_painted_patch(base, mv->texture_displacement_facet(layer->slot).get_data());
Vec3f center = Vec3f::Zero(), axis = Vec3f::UnitZ(), average_normal = Vec3f::UnitZ();
if (!patch.indices.empty())
texture_displacement_patch_frame(patch, texture_displacement_vertex_normals(base), center, axis,
average_normal);
DecodedHeightTexture tex = decode_height_texture(*layer);
apply_color_adjustments(tex, *layer);
Vec3f rgb;
if (!sample_layer_color(tex, *layer, hit, normal, rgb, center, axis))
return false;
for (int c = 0; c < 3; ++c)
layer->bg_color[c] = std::clamp(rgb[c], 0.f, 1.f);
layer->bg_from_corners = false;
layer->bg_remove = true;
m_image_bg_picking = false;
m_preview_params_dirty = true;
m_parent.set_as_dirty();
return true;
}
void GLGizmoTextureDisplacement::set_file_drag_over(bool over)
{
if (!image_mode() || m_file_drag_over == over)
return;
m_file_drag_over = over;
// A drag is not a mouse move as far as the canvas is concerned, so nothing would repaint and the
// zone would appear only once something else happened to trigger a frame.
m_parent.set_as_dirty();
m_parent.request_extra_frame();
}
// Drawn over the whole canvas on the foreground list, from inside the panel's ImGui frame, which is
// what puts it above the 3D view and above the panel itself.
void GLGizmoTextureDisplacement::render_image_drop_hint()
{
if (!m_file_drag_over)
return;
const ImVec2 size = ImGui::GetIO().DisplaySize;
if (size.x < 1.f || size.y < 1.f)
return;
ImDrawList *dl = ImGui::GetForegroundDrawList();
const ImU32 teal = ImGui::GetColorU32(ImGuiWrapper::COL_ORCA);
// Dim the view so the zone reads as a state the canvas is in, not as decoration on top of it.
dl->AddRectFilled(ImVec2(0.f, 0.f), size, IM_COL32(0, 0, 0, 70));
const float inset = std::round(ImGui::GetFontSize() * 1.2f);
const ImVec2 a(inset, inset), b(size.x - inset, size.y - inset);
if (b.x <= a.x || b.y <= a.y)
return;
// A dashed border, drawn as runs along the four edges: ImGui 1.83 has no dashed stroke.
const float dash = std::round(ImGui::GetFontSize() * 0.75f);
const float gap = dash;
const float th = std::max(2.f, std::round(ImGui::GetFontSize() * 0.12f));
for (float x = a.x; x < b.x; x += dash + gap) {
const float x1 = std::min(x + dash, b.x);
dl->AddLine(ImVec2(x, a.y), ImVec2(x1, a.y), teal, th);
dl->AddLine(ImVec2(x, b.y), ImVec2(x1, b.y), teal, th);
}
for (float y = a.y; y < b.y; y += dash + gap) {
const float y1 = std::min(y + dash, b.y);
dl->AddLine(ImVec2(a.x, y), ImVec2(a.x, y1), teal, th);
dl->AddLine(ImVec2(b.x, y), ImVec2(b.x, y1), teal, th);
}
// What dropping here will do. Worded as an invitation rather than a promise: anything that is
// not a picture falls through to the model loader, exactly as it did before this tool existed.
const std::string text = _u8L("Drop a picture to put it on the model");
const ImVec2 ts = ImGui::CalcTextSize(text.c_str());
const float pad = std::round(ImGui::GetFontSize() * 0.8f);
const ImVec2 c((a.x + b.x) * 0.5f, (a.y + b.y) * 0.5f);
const ImVec2 r0(c.x - ts.x * 0.5f - pad, c.y - ts.y * 0.5f - pad * 0.6f);
const ImVec2 r1(c.x + ts.x * 0.5f + pad, c.y + ts.y * 0.5f + pad * 0.6f);
dl->AddRectFilled(r0, r1, ImGui::GetColorU32(ImGuiCol_WindowBg, 0.92f), ImGui::GetStyle().FrameRounding);
dl->AddRect(r0, r1, teal, ImGui::GetStyle().FrameRounding, 0, th * 0.5f);
dl->AddText(ImVec2(c.x - ts.x * 0.5f, c.y - ts.y * 0.5f), ImGui::GetColorU32(ImGuiCol_Text), text.c_str());
}
bool GLGizmoTextureDisplacement::drop_image_file(const std::string &path)
{
if (!image_mode() || texture_volume() == nullptr)
return false;
// Imported rather than just read: the same thing the panel's Import tile does, so a dropped
// picture lands in "My images" and is there the next time without hunting for the file again.
std::string error;
const std::optional<TextureLibraryEntry> entry = import_texture_to_library(path, error);
if (!entry) {
show_error(nullptr, error);
return false;
}
// The tool starts with no layer at all, so a drop before anything is loaded has to make one.
if (active_layer() == nullptr)
add_texture_layer();
TextureDisplacementLayer *layer = active_layer();
if (layer == nullptr)
return false;
set_layer_texture(*layer, *entry);
m_parent.set_as_dirty();
return true;
}
// ---------------------------------------------------------------------------------------------
// The Image tool's window.
//
// A member of GLGizmoTextureDisplacement rather than of GLGizmoImage, and defined here rather than
// in that class's own file: it needs the same private machinery the displacement panel uses (the
// layer, the texture picker, the previews, the bake), and keeping it here leaves that 1700 line
// panel untouched instead of threading it with tests for which tool is drawing.
//
// What it deliberately leaves out, all of which only means something once the surface moves or once
// there is more than one picture: brushes and the erase toggle, the layer stack, blend modes, depth,
// midlevel, edge fade, tiling mode, the unwrap projection and its UV editor, seams, the wireframe
// and the mesh-preparation sections.
// ---------------------------------------------------------------------------------------------
void GLGizmoTextureDisplacement::render_image_input_window(float x, float y, float bottom_limit)
{
ModelObject *mo = m_c->selection_info()->model_object();
if (mo == nullptr)
return;
ModelVolume *mv = texture_volume();
// The palette follows project state nobody tells this gizmo about (the filaments in the
// sidebar), so it is checked once a frame and a change re-runs the preview.
cached_palette();
if (m_palette_changed)
m_preview_params_dirty = true;
// Everything this tool fixes, re-pinned each frame so what the preview shows is what Apply will
// produce: Standard's recipe, zero depth with colour on, a click that floods the connected
// surface rather than a brush, and the fast preview, which with no relief to build is both
// instant and exactly the final colour.
// Two statements, not one `||`: short-circuiting would skip the image presets on any frame the
// standard ones changed something.
const bool std_changed = apply_standard_mode_presets(mv);
const bool image_changed = apply_image_mode_presets(mv);
if (std_changed || image_changed)
m_preview_params_dirty = true;
m_tool_type = ToolType::SMART_FILL;
m_cursor_type = TriangleSelector::CursorType::POINTER;
m_erase_mode = false;
m_auto_update = true;
if (!m_use_shaded_preview)
apply_view_mode(1);
float scale = m_parent.get_scale();
#ifdef WIN32
const int dpi = get_dpi_for_window(wxGetApp().GetTopWindow());
scale *= (float) dpi / (float) DPI_DEFAULT;
#endif // WIN32
const float approx_height = m_imgui->scaled(22.f);
y = std::min(y, bottom_limit - approx_height);
// Docked (the default) it is pinned to the right edge of the 3D canvas and cannot be moved, the
// same place and the same rule as the displacement panel, so the two tools do not put their
// controls in different corners. Undocked it becomes an ordinary floating window with a title
// bar to drag it by; the position is deliberately not seeded on undock, so it stays exactly
// where it was and the user simply gains the ability to move it.
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse;
if (!m_undocked) {
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar;
// Right-aligned (pivot 1), so the width the window auto-resized to last frame does not need
// to be known here.
float right = float(m_parent.get_canvas_size().get_width()) - m_imgui->scaled(0.5f);
GizmoImguiSetNextWIndowPos(right, y, 0.f, 0.f, ImGuiCond_Always, 1.0f, 0.0f);
}
ImGuiWrapper::push_toolbar_style(m_parent.get_scale());
GizmoImguiBegin(get_name(), flags);
ensure_panel_icons();
const float previous_body_h = m_panel_body_h;
const float previous_footer_h = m_panel_footer_h;
const ImGuiStyle &style = ImGui::GetStyle();
const bool busy = m_bake_in_progress || m_prepare_in_progress;
const float panel_w = m_imgui->scaled(16.f);
const float frame_h = ImGui::GetFrameHeight();
const float icon_sm = std::round(frame_h * 1.05f);
const float gap_s = std::round(m_imgui->scaled(0.4f));
const float label_w = m_imgui->scaled(4.6f);
const float wrap_w = m_imgui->scaled(15.f);
const ImVec4 orca = ImGuiWrapper::COL_ORCA;
const ImVec4 col_frame = ImGui::GetStyleColorVec4(ImGuiCol_Separator);
const auto hover_tip = [&](const auto &text) {
if (ImGui::IsItemHovered())
m_imgui->tooltip(text, wrap_w);
};
// Label column plus a slider filling the rest of the row, the same shape the displacement panel
// uses, so the two tools read as one family.
const auto float_row = [&](const char *id, const wxString &label, float *v, float v_min, float v_max,
const char *format, bool log) -> bool {
const float x0 = ImGui::GetCursorPosX();
ImGui::AlignTextToFramePadding();
m_imgui->text(label);
ImGui::SameLine();
ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), x0 + label_w));
ImGui::SetNextItemWidth(x0 + panel_w - ImGui::GetCursorPosX());
return ImGui::SliderFloat(id, v, v_min, v_max, format,
ImGuiSliderFlags_AlwaysClamp | (log ? ImGuiSliderFlags_Logarithmic : 0));
};
// Borderless icon button, for the dock toggle: always the grey monochrome variant.
const auto icon_button = [&](int uid, const std::string &iconfile, const wxString &label,
const wxString &tip_text) -> bool {
const auto it = m_panel_icon_map.find(iconfile);
const float pad = std::max(1.f, std::round(icon_sm * 0.14f));
bool clicked = false;
ImGui::PushID(uid);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.f);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.f, 0.f, 0.f, 0.f));
if (it != m_panel_icon_map.end() && !it->second.empty() && it->second[0]->is_valid()) {
const IconManager::Icon &ic = *it->second[0];
clicked = m_imgui->image_button((ImTextureID) (intptr_t) ic.tex_id,
ImVec2(icon_sm - 2.f * pad, icon_sm - 2.f * pad), ic.tl, ic.br, int(pad));
} else {
clicked = ImGui::Button(label.ToUTF8().data(), ImVec2(0.f, icon_sm));
}
ImGui::PopStyleColor();
ImGui::PopStyleVar();
ImGui::PopID();
hover_tip(tip_text);
return clicked;
};
// A section header that folds its contents away. ImGui's own CollapsingHeader draws a filled bar
// that is louder than anything else in this window, so this is the same triangle-and-text the
// displacement panel's "More settings" link uses, at heading weight.
const auto section = [&](const char *id, const wxString &label, bool &open) {
const float arrow = std::round(ImGui::GetFontSize() * 0.55f);
const ImVec2 ts = ImGui::CalcTextSize(label.ToUTF8().data());
const ImVec2 p = ImGui::GetCursorScreenPos();
ImGui::PushID(id);
if (ImGui::InvisibleButton("##sec", ImVec2(panel_w, ts.y + gap_s)))
open = !open;
const bool hot = ImGui::IsItemHovered();
ImDrawList *dl = ImGui::GetWindowDrawList();
const ImU32 col = ImGui::GetColorU32(hot ? ImGuiCol_Text : ImGuiCol_TextDisabled);
const float cx = p.x + 0.5f * arrow, cy = p.y + 0.5f * ts.y, hs = 0.32f * arrow;
if (open)
dl->AddTriangleFilled(ImVec2(cx - hs, cy - 0.5f * hs), ImVec2(cx + hs, cy - 0.5f * hs),
ImVec2(cx, cy + 0.5f * hs), col);
else
dl->AddTriangleFilled(ImVec2(cx - 0.5f * hs, cy - hs), ImVec2(cx - 0.5f * hs, cy + hs),
ImVec2(cx + 0.5f * hs, cy), col);
dl->AddText(ImVec2(p.x + arrow + gap_s, p.y), col, label.ToUTF8().data());
ImGui::PopID();
return open;
};
// The integer twin of float_row, for the colour count.
const auto int_row = [&](const char *id, const wxString &label, int *v, int v_min, int v_max,
const char *format) -> bool {
const float x0 = ImGui::GetCursorPosX();
ImGui::AlignTextToFramePadding();
m_imgui->text(label);
ImGui::SameLine();
ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), x0 + label_w));
ImGui::SetNextItemWidth(x0 + panel_w - ImGui::GetCursorPosX());
return ImGui::SliderInt(id, v, v_min, v_max, format, ImGuiSliderFlags_AlwaysClamp);
};
// Framed icon toggle, the displacement panel's one cut down to what this window needs.
const auto icon_toggle = [&](int uid, const std::string &iconfile, bool active, const wxString &label,
const wxString &tip_text) -> bool {
const auto it = m_panel_icon_map.find(iconfile);
const float pad = std::max(1.f, std::round(icon_sm * 0.14f));
bool clicked = false;
ImGui::PushID(uid);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.f);
ImGui::PushStyleColor(ImGuiCol_Button, active ? ImVec4(orca.x, orca.y, orca.z, 0.22f) : ImVec4(0.f, 0.f, 0.f, 0.f));
if (it != m_panel_icon_map.end() && int(it->second.size()) > (active ? 1 : 0) &&
it->second[active ? 1 : 0]->is_valid()) {
const IconManager::Icon &ic = *it->second[active ? 1 : 0];
clicked = m_imgui->image_button((ImTextureID) (intptr_t) ic.tex_id,
ImVec2(icon_sm - 2.f * pad, icon_sm - 2.f * pad), ic.tl, ic.br, int(pad));
} else {
clicked = ImGui::Button(label.ToUTF8().data(), ImVec2(0.f, icon_sm));
}
ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(),
ImGui::GetColorU32(active ? orca : col_frame), style.FrameRounding);
ImGui::PopStyleColor();
ImGui::PopStyleVar();
ImGui::PopID();
hover_tip(tip_text);
return clicked;
};
TextureDisplacementLayer *layer = mv != nullptr ? active_layer() : nullptr;
{
const float x0 = ImGui::GetCursorPosX();
ImGui::AlignTextToFramePadding();
m_imgui->push_bold_font();
m_imgui->text(wxString::FromUTF8(get_name(false)));
m_imgui->pop_bold_font();
ImGui::SameLine();
ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), x0 + panel_w - icon_sm));
if (icon_button(920, "canvas_drag.svg", m_undocked ? _L("Dock panel") : _L("Undock panel"),
_L("Detach this panel so it can be dragged anywhere over the 3D view, or dock it back "
"against the right edge.")))
m_undocked = !m_undocked;
}
ImGui::Separator();
// Everything between the title and the footer scrolls as one, so Apply and Close stay on screen
// on a short canvas instead of being the first thing pushed off the bottom. Sized from last
// frame's content and footer heights, as the displacement panel's body is.
const float bottom = m_undocked ? ImGui::GetIO().DisplaySize.y : bottom_limit;
const float max_body_h = std::max(m_imgui->scaled(8.f), bottom - ImGui::GetCursorScreenPos().y -
m_panel_footer_h - style.WindowPadding.y -
style.ItemSpacing.y);
const float body_h = m_panel_body_h > 0.f ? std::min(m_panel_body_h + 1.f, max_body_h) : max_body_h;
const float scrollbar_w = m_imgui->scaled(0.5f);
const ImVec4 grab = wxGetApp().dark_mode() ? ImVec4(1.f, 1.f, 1.f, 0.26f) : ImVec4(0.f, 0.f, 0.f, 0.26f);
ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, scrollbar_w);
ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarRounding, 0.5f * scrollbar_w);
ImGui::PushStyleColor(ImGuiCol_ScrollbarBg, ImVec4(0.f, 0.f, 0.f, 0.f));
ImGui::PushStyleColor(ImGuiCol_ScrollbarGrab, grab);
ImGui::PushStyleColor(ImGuiCol_ScrollbarGrabHovered, ImVec4(grab.x, grab.y, grab.z, 0.45f));
ImGui::PushStyleColor(ImGuiCol_ScrollbarGrabActive, ImVec4(grab.x, grab.y, grab.z, 0.65f));
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.f, 0.f, 0.f, 0.f));
ImGui::BeginChild("##image_body", ImVec2(panel_w, body_h), false);
// The picture, shown whole and the full width of the window: it is the thing being placed, so a
// row-sized thumbnail beside a file name is the wrong size for it. Clicking it opens the library,
// which is also where Import lives, and before anything is loaded the same box is an empty frame
// with a plus in it - one target, in the same place, whichever state the tool is in.
const auto open_library = [&](int slot) {
m_picker_slot = slot;
m_picker_open_request = true;
};
// A layer with no picture on it is the starting state, not a broken one: the tool creates the
// layer empty and the panel stays on the frame below until a picture has been chosen.
const bool has_picture = layer != nullptr && !layer->empty();
const bool placed = mv != nullptr && mv->is_texture_displacement_painted();
// The handle comes up by itself the first moment there is something to anchor it to, so the
// picture can be nudged straight after the click that placed it without hunting for a toggle.
// Armed once: turning it back off has to stay off, not be undone on the next frame.
if (has_picture && placed && !m_image_handle_armed) {
m_image_handle_armed = true;
if (update_adjust_anchor())
m_adjust_texture_mode = true;
}
if (!has_picture) {
const float box_h = std::round(panel_w * 0.6f);
const ImVec2 p0 = ImGui::GetCursorScreenPos();
m_imgui->disabled_begin(busy || mv == nullptr);
const bool clicked = ImGui::InvisibleButton("##load", ImVec2(panel_w, box_h));
m_imgui->disabled_end();
const bool hot = ImGui::IsItemHovered();
ImDrawList *dl = ImGui::GetWindowDrawList();
const ImU32 col = ImGui::GetColorU32(hot ? orca : col_frame);
dl->AddRect(p0, ImVec2(p0.x + panel_w, p0.y + box_h), col, style.FrameRounding);
const float cx = p0.x + 0.5f * panel_w, cy = p0.y + 0.5f * box_h;
const float arm = std::round(box_h * 0.18f), thick = std::max(1.f, std::round(box_h * 0.035f));
dl->AddLine(ImVec2(cx - arm, cy), ImVec2(cx + arm, cy), col, thick);
dl->AddLine(ImVec2(cx, cy - arm), ImVec2(cx, cy + arm), col, thick);
hover_tip(_u8L("Choose a picture to put on the model."));
if (clicked) {
if (layer == nullptr)
add_texture_layer(); // created with no picture on it, on purpose
open_library(layer != nullptr ? layer->slot : m_active_layer_slot);
}
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + panel_w);
ImGui::TextDisabled("%s", _u8L("Choose a picture, then click the model to put it there.").c_str());
ImGui::PopTextWrapPos();
} else {
// The colour texture is the corrected image at full resolution, which is exactly what should
// be previewed - move a correction slider and the box follows. A grayscale picture has no
// colour texture, so it falls back to the height thumbnail.
GLTexture *shown = get_layer_color_texture(*layer);
if (shown == nullptr)
shown = get_layer_thumbnail(*layer);
const float aspect = std::max(0.05f, layer_texture_aspect(*layer));
const float box_h = std::clamp(std::round(panel_w / aspect), std::round(panel_w * 0.35f),
std::round(panel_w * 1.1f));
const ImVec2 box_min = ImGui::GetCursorScreenPos();
bool box_hit = false;
if (shown != nullptr) {
box_hit = ImGui::ImageButton((ImTextureID) (intptr_t) shown->get_id(), ImVec2(panel_w, box_h),
ImVec2(0.f, 0.f), ImVec2(1.f, 1.f), 0);
} else {
box_hit = ImGui::Button("?##thumb", ImVec2(panel_w, box_h));
}
hover_tip(m_image_bg_picking ?
_u8L("Click the background, here or on the model.") :
_u8L("Choose a different picture. Where you placed it and how it is corrected stay as "
"they are."));
if (box_hit) {
if (!m_image_bg_picking) {
open_library(layer->slot);
} else {
// Read straight out of the decoded image rather than off the screen: the preview is
// scaled, and it already has the corrections applied, so a screen read would key the
// corrected colour against itself.
const ImVec2 rel((ImGui::GetIO().MousePos.x - box_min.x) / panel_w,
(ImGui::GetIO().MousePos.y - box_min.y) / box_h);
const DecodedHeightTexture &tex = decode_height_texture(*layer);
if (tex.has_color()) {
const int px = std::clamp(int(rel.x * float(tex.width)), 0, tex.width - 1);
const int py = std::clamp(int(rel.y * float(tex.height)), 0, tex.height - 1);
const size_t i = (size_t(py) * size_t(tex.width) + size_t(px)) * 3;
for (int c = 0; c < 3; ++c)
layer->bg_color[c] = float(tex.rgb[i + size_t(c)]) / 255.f;
layer->bg_from_corners = false;
layer->bg_remove = true;
m_preview_params_dirty = true;
}
m_image_bg_picking = false;
}
}
const std::string name = layer->name.empty() ? _u8L("Image") : layer->name;
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + panel_w);
ImGui::TextDisabled("%s", name.c_str());
ImGui::PopTextWrapPos();
if (!height_texture_has_color(*layer)) {
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + panel_w);
m_imgui->warning_text(_L("This image is grayscale, so it has no colors to print. Choose a color picture."));
ImGui::PopTextWrapPos();
}
// Placing it: one click floods the surface it lands on, out to the first fold sharper than
// the angle below. No brush, no erase toggle - on a flat side or a cube face the click alone
// is the whole gesture, and the slider is there for the cases where it is not.
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + panel_w);
ImGui::TextDisabled("%s", placed ? _u8L("Click the model to move the picture somewhere else.").c_str() :
_u8L("Click the model to put the picture there.").c_str());
ImGui::PopTextWrapPos();
float fill_angle = m_smart_fill_angle;
if (float_row("##fill_angle", _L("Spread"), &fill_angle, SmartFillAngleMin, SmartFillAngleMax, "%.0f°", false))
m_smart_fill_angle = fill_angle;
hover_tip(_u8L("How far a click spreads from the spot you hit: it keeps going while the surface stays "
"flatter than this, and stops at a sharper fold. Small values keep it to one face."));
ImGui::Separator();
if (section("place", _L("Placement"), m_image_sec_place)) {
// Projection, minus Unwrap: that one is an editor's worth of UI (seams, islands, the UV pane)
// for a tool whose whole point is a click and a few sliders.
{
struct Mapping { const char *file; wxString label; wxString tip; TextureProjectionMethod method; };
const Mapping mappings[] = {
{ "menu_obj_cube.svg", _L("Flat"),
_L("Flat - lays the picture straight onto the surface from whichever axis it faces, and blends "
"where it wraps around an edge. The right choice for a face or a flat side."),
TextureProjectionMethod::Triplanar },
{ "menu_obj_cylinder.svg", _L("Around"),
_L("Around - wraps the picture around the area, for a round part like a mug or a tube."),
TextureProjectionMethod::Cylindrical },
{ "menu_obj_sphere.svg", _L("Ball"),
_L("Ball - wraps the picture around the area in both directions, for a dome or a sphere."),
TextureProjectionMethod::Spherical },
{ "texture_displacement_map_view.svg", _L("From view"),
_L("From view - throws the picture onto the area from where you are looking now, like a slide "
"projector. Line the view up with the surface first, because faces turned away stretch."),
TextureProjectionMethod::ViewProjected },
};
const float x0 = ImGui::GetCursorPosX();
ImGui::AlignTextToFramePadding();
// Plain text, like every other label in this window: the displacement panel greys its
// headings because it has many, and here there are five rows in total.
m_imgui->text(_L_CONTEXT("Mapping", "Texture Displacement"));
ImGui::SameLine();
ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), x0 + label_w));
for (int mi = 0; mi < int(IM_ARRAYSIZE(mappings)); ++mi) {
if (mi > 0)
ImGui::SameLine(0.f, gap_s);
const bool on = layer->projection_method == mappings[mi].method;
if (icon_toggle(900 + mi, mappings[mi].file, on, mappings[mi].label, mappings[mi].tip) && !on) {
// Capture the current view the moment "From view" is chosen, so it does something
// sensible immediately rather than projecting from a stale direction.
if (mappings[mi].method == TextureProjectionMethod::ViewProjected)
capture_view_projection(*layer);
layer->projection_method = mappings[mi].method;
m_preview_params_dirty = true;
}
}
}
if (layer->projection_method == TextureProjectionMethod::ViewProjected) {
if (m_imgui->button(_u8L("Capture current view"))) {
capture_view_projection(*layer);
m_preview_params_dirty = true;
}
hover_tip(_u8L("Throws the picture on again from where you are looking now. Orbit the model, press "
"this, and it is re-laid from the new angle."));
}
m_preview_params_dirty |= float_row("##size", _L("Size"), &layer->tiling_scale, 1.f, 300.f, "%.1f mm", true);
hover_tip(_u8L("How wide the picture is on the model, in millimetres."));
m_preview_params_dirty |= float_row("##rotation", _L("Rotation"), &layer->rotation_deg, 0.f, 360.f, "%.0f°", false);
hover_tip(_u8L("Turns the picture on the surface, for lining it up with an edge of the model."));
// Sliding it into place, and whether it repeats. Both belong on one row: the handle is the
// coarse control and Tile decides what it is sliding - one copy, or a pattern.
{
const float x0 = ImGui::GetCursorPosX();
ImGui::AlignTextToFramePadding();
m_imgui->text(_L("Move"));
ImGui::SameLine();
ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), x0 + label_w));
if (icon_toggle(910, "texture_displacement_adjust.svg", m_adjust_texture_mode, _L("Move on the model"),
_L("Move on the model - drag the handle that appears on the surface to slide the "
"picture around, or one of its two arrows to slide it along just that axis."))) {
if (!m_adjust_texture_mode) {
update_model_object(); // flush any pending placement before anchoring to it
if (update_adjust_anchor())
m_adjust_texture_mode = true;
else
show_error(nullptr, _u8L("Click the model to put the picture somewhere first."));
} else {
m_adjust_texture_mode = false;
m_adjust_drag_handle = AdjustHandle::None;
}
}
ImGui::SameLine(0.f, gap_s * 2.f);
if (m_imgui->bbl_checkbox(_L("Tile"), layer->tile_enabled))
m_preview_params_dirty = true;
hover_tip(_u8L("Repeats the picture over the area instead of placing a single copy. Off by "
"default, because a photo or a logo goes on once; Size then sets how big that "
"one copy is."));
}
// The one number that decides how sharp the printed picture is. Each triangle prints in a
// single filament, so the mesh under the paint has to be finer than the detail wanted out of
// the image - and the budget above is what stops that running away.
{
TextureDisplacementOptions &opts = mv->texture_displacement_options;
float edge = opts.v2_refine_mm;
m_imgui->disabled_begin(busy);
if (float_row("##resolution", _L("Detail"), &edge, 0.02f, 2.f, "%.2f mm", true)) {
opts.v2_refine_mm = edge;
m_preview_params_dirty = true;
}
m_imgui->disabled_end();
hover_tip(_u8L("How fine the mesh is made under the picture, in millimetres. Each triangle prints "
"in one filament, so this is how sharp an edge between two colors can come out. "
"Smaller costs triangles fast: halving it needs four times as many."));
// Refining past the budget is not an error - the bake simplifies back down to it - but the
// result then carries less of the picture than this slider asks for, and without saying so
// the only sign is a print that came out softer than expected.
const size_t budget = size_t(std::max(0, opts.v2_max_triangles_k)) * 1000;
const size_t needed = estimated_refined_triangles(*mv, edge);
if (budget > 0 && needed > budget * 5 / 4) {
const auto count = [](size_t n) {
return n >= 1000000 ? Slic3r::format("%1$.1f M", double(n) / 1000000.) :
Slic3r::format("%1% k", (n + 500) / 1000);
};
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + panel_w);
m_imgui->warning_text(Slic3r::format(_u8L("Needs about %1% triangles, budget %2% - it will be "
"simplified back down and come out softer."),
count(needed), count(budget)));
ImGui::PopTextWrapPos();
}
}
} // Placement
ImGui::Separator();
if (section("color", _L("Color"), m_image_sec_color)) {
// Colour correction. Every one of these changes which filament each area lands in, which is
// why they are here rather than left to whatever the file happened to contain: a photo that
// prints as mud usually only needs contrast.
m_preview_params_dirty |= float_row("##brightness", _L("Brightness"), &layer->brightness, -1.f, 1.f, "%.2f", false);
hover_tip(_u8L("Lightens or darkens the whole picture before it is matched to your filaments."));
m_preview_params_dirty |= float_row("##contrast", _L("Contrast"), &layer->contrast, -1.f, 1.f, "%.2f", false);
hover_tip(_u8L("Pushes light and dark apart. Raise it when a photo prints as mud; lower it when "
"everything collapses into the lightest and darkest filament."));
m_preview_params_dirty |= float_row("##saturation", _L("Saturation"), &layer->saturation, 0.f, 2.f, "%.2f", false);
hover_tip(_u8L("How strong the colors are. At 0 the picture is gray, so it prints in your grays and "
"blacks; raising it pushes each area towards a purer filament."));
m_preview_params_dirty |= float_row("##hue", _L("Hue"), &layer->hue, -180.f, 180.f, "%.0f°", false);
hover_tip(_u8L("Turns every color of the picture around the color wheel, without changing how light "
"it is. Your filaments are a fixed, arbitrary set, so this is what lets the picture "
"meet them: if you have orange loaded but no red, a small turn puts the reds on it."));
m_preview_params_dirty |= float_row("##gamma", _L("Gamma"), &layer->gamma, 0.2f, 5.f, "%.2f", true);
hover_tip(_u8L("Lifts or drops the midtones without touching the brightest and darkest parts. Use it "
"when the middle of the picture is the part coming out wrong."));
m_preview_params_dirty |= float_row("##sharpen", _L("Sharpen"), &layer->sharpness, 0.f, 1.f, "%.2f", false);
hover_tip(_u8L("Crisps up the edges before the picture is matched to your filaments. Worth more here "
"than in a photo: a soft edge between two colors quantizes into a ragged band of "
"both, and sharpening first makes it land in one place."));
// How many colours the picture may use. 2 is a logo in two flat colours, 4 or 5 a poster,
// off a photograph. This is not the same as the displacement tool's "Mixed colors", which
// caps how many mixed filament slots a bake may create rather than what the picture uses.
{
int count = layer->color_count;
if (int_row("##colors", _L("Colors"), &count, 0, 12, count == 0 ? _u8L("Off").c_str() : "%d")) {
// 1 is not a picture, so the slider steps over it on the way out of Off.
layer->color_count = count == 1 ? 2 : count;
m_preview_params_dirty = true;
}
hover_tip(_u8L("Reduces the picture to this many colors before your filaments are matched to "
"it, so it prints in at most that many. The colors are the ones the picture is "
"actually made of, not an even split of the range. Off leaves it alone."));
}
if (m_imgui->bbl_checkbox(_L("Negative"), layer->color_invert))
m_preview_params_dirty = true;
hover_tip(_u8L("Prints the picture inverted, light for dark and each color for its opposite."));
} // Color
ImGui::Separator();
if (!section("bg", _L("Background"), m_image_sec_bg)) {
// Folded away, but still worth saying whether it is doing anything.
ImGui::SameLine();
ImGui::TextDisabled("%s", layer->bg_remove ? _u8L("removed").c_str() : _u8L("kept").c_str());
} else {
if (m_imgui->bbl_checkbox(_L("Remove background"), layer->bg_remove))
m_preview_params_dirty = true;
hover_tip(_u8L("Leaves the background unprinted, so the object's own color shows through instead of "
"a slab of white behind a logo. A picture that is already transparent needs none of "
"this: those parts are left out either way."));
if (layer->bg_remove) {
// Which colour is being removed, shown rather than described: the swatch is also a
// picker, and the dropper beside it takes the colour from the preview above.
const float x0 = ImGui::GetCursorPosX();
ImGui::AlignTextToFramePadding();
m_imgui->text(_L("Color"));
ImGui::SameLine();
ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), x0 + label_w));
float shown_bg[3] = { layer->bg_color[0], layer->bg_color[1], layer->bg_color[2] };
if (layer->bg_from_corners) {
// Nothing has been picked, so show what the corners actually gave: the same median
// the bake will key on, not a placeholder white.
const DecodedHeightTexture &tex = decode_height_texture(*layer);
if (tex.has_color() && tex.width > 1 && tex.height > 1) {
const size_t n = size_t(tex.width) * size_t(tex.height);
const size_t corner[4] = { 0, size_t(tex.width) - 1,
(size_t(tex.height) - 1) * size_t(tex.width), n - 1 };
for (int c = 0; c < 3; ++c) {
std::array<float, 4> v{};
for (int i = 0; i < 4; ++i)
v[size_t(i)] = float(tex.rgb[corner[i] * 3 + size_t(c)]);
std::sort(v.begin(), v.end());
shown_bg[c] = 0.5f * (v[1] + v[2]) / 255.f;
}
}
}
ImGui::SetNextItemWidth(x0 + panel_w - ImGui::GetCursorPosX() - icon_sm - gap_s);
if (ImGui::ColorEdit3("##bg_color", shown_bg,
ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel)) {
for (int c = 0; c < 3; ++c)
layer->bg_color[c] = shown_bg[c];
layer->bg_from_corners = false;
m_preview_params_dirty = true;
}
hover_tip(layer->bg_from_corners ?
_u8L("Taken from the four corners of the picture, which is right for a logo on a "
"plain card. Click to choose a color yourself instead.") :
_u8L("The color being removed. Click to change it."));
ImGui::SameLine(0.f, gap_s);
if (icon_toggle(930, "texture_displacement_pipette.svg", m_image_bg_picking, _L("Pick the color"),
_L("Pick the color - then click the background, either in the preview above or on "
"the model itself.")))
m_image_bg_picking = !m_image_bg_picking;
if (!layer->bg_from_corners) {
ImGui::SameLine(0.f, gap_s);
if (m_imgui->button(_u8L("Corners"))) {
layer->bg_from_corners = true;
m_preview_params_dirty = true;
}
hover_tip(_u8L("Back to taking the color from the picture's four corners."));
}
m_preview_params_dirty |= float_row("##bg_tol", _L("Tolerance"), &layer->bg_tolerance, 0.01f, 0.6f, "%.2f", false);
hover_tip(_u8L("How different from that color still counts as background. Raise it when a "
"shadow or a gradient is left behind; lower it when it starts eating the picture."));
}
} // Background
// Outside both sections, because it clears the colour corrections and the background key
// alike, and a reset that lives inside one of them would look like it only reached that far.
ImGui::Separator();
if (m_imgui->button(_u8L("Reset all"))) {
layer->brightness = 0.f;
layer->contrast = 0.f;
layer->saturation = 1.f;
layer->hue = 0.f;
layer->gamma = 1.f;
layer->sharpness = 0.f;
layer->color_count = 0;
layer->bg_remove = false;
layer->bg_tolerance = 0.15f;
layer->bg_from_corners = true;
layer->bg_color[0] = layer->bg_color[1] = layer->bg_color[2] = 1.f;
m_image_bg_picking = false;
layer->color_invert = false;
m_preview_params_dirty = true;
}
hover_tip(_u8L("Puts every correction and the background back to where they started, leaving the "
"picture as it was loaded. Where you placed it and how big it is are not touched."));
}
// The library popup lives in this window's scope, where its open request and the popup itself
// share one ID stack.
{
const ImVec2 win_min = ImGui::GetWindowPos();
const ImVec2 win_sz = ImGui::GetWindowSize();
render_texture_library_popup(win_min, ImVec2(win_min.x + win_sz.x, win_min.y + win_sz.y));
}
// ImGui sliders report "changed" on every frame of a drag, and a preview rebuild is real work,
// so with the mouse still down it waits for the release.
if (m_preview_params_dirty && !ImGui::IsMouseDown(ImGuiMouseButton_Left)) {
rebuild_preview();
m_preview_params_dirty = false;
}
m_panel_body_h = ImGui::GetCursorPosY() - style.ItemSpacing.y;
ImGui::EndChild();
ImGui::PopStyleColor(5);
ImGui::PopStyleVar(2);
const float footer_top = ImGui::GetCursorScreenPos().y;
ImGui::Separator();
{
const bool painted = placed;
const bool no_colors = mv != nullptr && !any_layer_colors(*mv);
// Colour is the only thing this bake produces, so with a grayscale picture there would be
// nothing to show for it - and it is not a cheap no-op: the bake still refines the painted
// area and replaces the mesh with the result.
const bool can_apply = !busy && mv != nullptr && painted && !no_colors;
const float button_h = std::round(frame_h * 1.25f);
const float button_w = std::max({ ImGui::CalcTextSize(_u8L("Apply").c_str()).x,
ImGui::CalcTextSize(_u8L("Close").c_str()).x,
ImGui::CalcTextSize(_u8L("Stop").c_str()).x,
ImGui::CalcTextSize(_u8L("Working...").c_str()).x }) +
m_imgui->scaled(0.5f);
const float row_y = ImGui::GetCursorPosY();
const float icon_h = 21.f * scale;
const float row_h = std::max(icon_h, button_h);
ImGui::SetCursorPosY(row_y + (row_h - icon_h) * .5f);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(int(m_imgui->scaled(.5f)), style.ItemSpacing.y));
GLGizmoUtils::render_wiki_guide_button(m_parent, scale,
"https://www.orcaslicer.com/wiki/print_prepare/prepare_texture_displacement");
ImGui::PopStyleVar(1);
ImGui::SameLine(panel_w - button_w * 2 - style.ItemSpacing.x);
GLGizmoUtils::push_orca_button_style();
m_imgui->push_bold_font();
m_imgui->disabled_begin(!can_apply);
ImGui::SetCursorPosY(row_y + (row_h - button_h) * .5f);
const std::string apply_label = busy ? _u8L("Working...") : _u8L("Apply");
if (ImGui::Button((apply_label + "##apply").c_str(), ImVec2(button_w, button_h)))
bake_standard();
m_imgui->disabled_end();
m_imgui->pop_bold_font();
GLGizmoUtils::pop_orca_button_style();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
m_imgui->tooltip(!has_picture ? _u8L("Choose a picture first.") :
!painted ? _u8L("Click the model to place the picture first.") :
no_colors ? _u8L("This picture is grayscale, so there is nothing to print. "
"Choose a color picture.") :
_u8L("Prints the picture where you placed it, in the nearest of your "
"loaded filaments. The surface itself is left exactly where it "
"is: this adds color, not relief."),
wrap_w);
ImGui::SameLine();
if (busy) {
if (ImGui::Button((_u8L("Stop") + "##stop").c_str(), ImVec2(button_w, button_h)))
wxGetApp().plater()->get_ui_job_worker().cancel_all();
hover_tip(_u8L("Stops it. Whatever it had already finished stays on the model, and can be undone."));
} else {
if (ImGui::Button((_u8L("Close") + "##close").c_str(), ImVec2(button_w, button_h)))
m_parent.reset_all_gizmos();
hover_tip(_u8L("Closes the tool. Your picture and where you put it stay with the model."));
}
}
m_panel_footer_h = ImGui::GetCursorScreenPos().y - footer_top;
// Both heights feed back into next frame's layout, so the window needs one more frame whenever
// either of them moved.
if (std::abs(m_panel_body_h - previous_body_h) > 0.5f || std::abs(m_panel_footer_h - previous_footer_h) > 0.5f)
m_parent.request_extra_frame();
// Last, on the foreground list, so it covers the panel as well as the view.
render_image_drop_hint();
GizmoImguiEnd();
ImGuiWrapper::pop_toolbar_style();
}
} // namespace Slic3r::GUI
+46
View File
@@ -0,0 +1,46 @@
#ifndef slic3r_GLGizmoImage_hpp_
#define slic3r_GLGizmoImage_hpp_
#include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp"
#include "slic3r/GUI/I18N.hpp"
#include <string>
#include <wx/string.h>
namespace Slic3r::GUI {
class GLCanvas3D;
// "Put this picture on the model": the texture-displacement gizmo with the relief taken out of it.
//
// There is no second engine here and no copy of one. It is GLGizmoTextureDisplacement with
// image_mode() on, which pins every layer to zero depth and colour on (see
// apply_image_mode_presets()) and leaves out the controls that only mean something once the surface
// moves. Painting, the layer stack, the texture library, the previews and the bake are the very same
// code, reached the very same way - a zero-depth bake refines the painted area and writes the
// colours exactly as a relief bake does, it just displaces by nothing.
//
// Its own toolbar button because the two are different jobs, not two settings of one: a user who
// wants a photo on a part should not have to know what a height map is, or find the one slider that
// has to be zero.
class GLGizmoImage : public GLGizmoTextureDisplacement
{
public:
GLGizmoImage(GLCanvas3D &parent, const std::string &icon_filename, unsigned int sprite_id);
protected:
bool image_mode() const override { return true; }
bool on_init() override;
std::string on_get_name() const override;
wxString handle_snapshot_action_name(bool shift_down, Button button_down) const override;
std::string get_gizmo_entering_text() const override { return _u8L("Entering Image painting"); }
std::string get_gizmo_leaving_text() const override { return _u8L("Leaving Image painting"); }
std::string get_action_snapshot_name() const override { return _u8L("Image editing"); }
};
} // namespace Slic3r::GUI
#endif // slic3r_GLGizmoImage_hpp_
File diff suppressed because it is too large Load Diff
@@ -23,6 +23,7 @@
#include "libslic3r/Point.hpp"
#include <imgui.h>
#include <map>
#include <future>
#include <memory>
#include <optional>
#include "slic3r/GUI/Gizmos/GLGizmoBase.hpp"
@@ -61,6 +62,12 @@ public:
static TextureDisplacementPrepareResult prepare_mesh(const indexed_triangle_set &base,
const TextureDisplacementFacetsData &masks,
const std::vector<TextureDisplacementLayer> &layers,
// `base`'s own UV channel, when it has one
// (ModelVolume::texture_uv). Resampled onto
// the result and reported back in it, and fed
// to the samplers so a ModelUV layer drives
// the refinement through its own layout.
const std::vector<Vec2f> &model_uv,
const TextureDisplacementPrepareParams &params,
const TextureColorSettings &color_settings,
const DisplacementProgressFn &progress,
@@ -154,6 +161,33 @@ public:
// What the cache was built from.
std::vector<ColorRGBA> m_palette_filaments;
std::vector<std::shared_ptr<std::vector<unsigned char>>> m_palette_images; // the colouring layers' images
// One layer's colour correction, as a value that can be compared and cached on. It belongs to
// every cache keyed on "what the image looks like", because a correction slider changes the
// pixels while leaving the image_data pointer alone.
struct ColorAdjustKey
{
float brightness = 0.f, contrast = 0.f, saturation = 1.f, gamma = 1.f, hue = 0.f;
float sharpness = 0.f, bg_tolerance = 0.15f;
float bg_r = 1.f, bg_g = 1.f, bg_b = 1.f;
int color_count = 0;
bool invert = false, bg_remove = false, bg_from_corners = true;
bool operator==(const ColorAdjustKey &o) const
{
return brightness == o.brightness && contrast == o.contrast && saturation == o.saturation &&
gamma == o.gamma && hue == o.hue && sharpness == o.sharpness &&
bg_tolerance == o.bg_tolerance && bg_r == o.bg_r && bg_g == o.bg_g && bg_b == o.bg_b &&
color_count == o.color_count && invert == o.invert && bg_remove == o.bg_remove &&
bg_from_corners == o.bg_from_corners;
}
bool operator!=(const ColorAdjustKey &o) const { return !(*this == o); }
static ColorAdjustKey of(const TextureDisplacementLayer &l)
{
return { l.brightness, l.contrast, l.saturation, l.gamma, l.hue,
l.sharpness, l.bg_tolerance, l.bg_color[0], l.bg_color[1], l.bg_color[2],
l.color_count, l.color_invert, l.bg_remove, l.bg_from_corners };
}
};
std::vector<ColorAdjustKey> m_palette_adjusts; // alongside m_palette_images, one per entry
std::optional<std::vector<PaletteEntry>> m_mix_ranking; // rank_mixes(), computed on demand
bool m_palette_mixing = false;
int m_palette_mix_count = 0;
@@ -224,7 +258,25 @@ public:
// rotation handles instead of painting); otherwise forwards to the normal painting handling.
bool on_mouse(const wxMouseEvent &mouse_event) override;
// Loads `path` as the Image tool's picture, importing it into the user's library on the way so
// it is there next time. For a drop onto the 3D view; see PlaterDropTarget::OnDropFiles(). False
// when this is not the Image tool, or the file could not be read.
bool drop_image_file(const std::string &path);
// Called while a file is being dragged over the 3D view, so the Image tool can show that
// dropping it there will do something. Without it the drag has no feedback at all and the only
// way to find out is to let go.
void set_file_drag_over(bool over);
protected:
// True in the Image tool (see GLGizmoImage): this same gizmo restricted to the one case where
// the surface does not move at all - a colour picture laid on the model. Everything behind the
// panel is shared and unchanged: the same layers, the same paint masks, the same bake. This flag
// only tells the panel which of the two tools it is drawing, and makes it pin the values the
// restricted case fixes (see apply_image_mode_presets()).
virtual bool image_mode() const { return false; }
bool on_init() override;
void on_render_input_window(float x, float y, float bottom_limit) override;
std::string on_get_name() const override;
// Never in the assemble view: its toolbar does not offer this gizmo, and every preview here is drawn
@@ -242,8 +294,11 @@ protected:
EnforcerBlockerType get_left_button_state_type() const override { return m_erase_mode ? EnforcerBlockerType::NONE : EnforcerBlockerType::ENFORCER; }
EnforcerBlockerType get_right_button_state_type() const override { return m_erase_mode ? EnforcerBlockerType::ENFORCER : EnforcerBlockerType::NONE; }
// Paint / Erase, from the panel. See get_left_button_state_type(). Protected because a subclass
// overriding handle_snapshot_action_name() has to read the same flag to name the undo step.
bool m_erase_mode = false;
private:
bool on_init() override;
void update_model_object() override;
void update_from_model_object(bool first_update) override;
void on_opening() override {}
@@ -283,14 +338,44 @@ private:
// Standard is active so what Preview shows is always what Bake will do. Returns true if it actually
// changed something, so the caller can invalidate the preview.
bool apply_standard_mode_presets(ModelVolume *mv);
// Copies the panel's own state (active layer, Standard/Pro) onto the volume, so the project file
// can carry it. Cheap and idempotent - called wherever either of the two changes.
void store_panel_state();
// Standard mode's Bake: remesh to an even density, refine where the texture bends, then displace.
// The order matters and is the whole reason this is one button - a height map can only move
// existing vertices, so the mesh has to be prepared first, and remeshing after painting would drop
// the paint if it were not carried across (see prepare_mesh()).
void bake_standard();
// Copies the panel's own state (active layer, Standard/Pro) onto the volume, so the project file
// can carry it. Cheap and idempotent - called wherever either of the two changes.
void store_panel_state();
// Image mode's fixed values, on top of Standard's and pinned the same way (every frame, so the
// preview cannot disagree with the bake): zero depth on every layer, and colour on wherever the
// picture has any. Those two are what turn the displacement bake into "put this picture on the
// model" without a second code path. Returns true if it actually changed something.
bool apply_image_mode_presets(ModelVolume *mv);
// The Image tool's whole window: load a picture, click the model to place it, correct it, Apply.
// Defined in GLGizmoImage.cpp, beside the class it exists for, rather than here - it is a member
// only so that it can reach the same private machinery the displacement panel uses, and keeping
// it out of this file leaves that panel's 1700 lines alone.
void render_image_input_window(float x, float y, float bottom_limit);
// Set once the Image tool has switched its placement handle on for the current picture, so that
// turning the handle back off stays off instead of being re-armed on the next frame.
bool m_image_handle_armed = false;
// Set between a drag entering the 3D view and leaving or dropping on it; drives the drop zone
// render_image_input_window() draws over the canvas.
bool m_file_drag_over = false;
void render_image_drop_hint();
// Set while the panel's background dropper is armed: the next click on the picture preview takes
// the colour under it instead of opening the library.
bool m_image_bg_picking = false;
// Takes the background colour from the point of the model under `mouse_pos`: the picture's own
// colour there, read through the same projection the bake uses, not the lit pixel on screen.
// False when the ray misses or the layer does not colour that point, leaving the dropper armed.
bool pick_background_at(const Vec2d &mouse_pos);
// Which of the Image panel's sections are unfolded. Panel state for the session, deliberately
// not saved with the project.
bool m_image_sec_place = true;
bool m_image_sec_color = true;
bool m_image_sec_bg = true;
// Queues one prepare_mesh() run on the job worker and commits its result when it lands. Every
// mesh-preparation button goes through here - Pro's Remesh, Pro's adaptive Subdivide and Standard's
@@ -423,8 +508,6 @@ private:
void set_layer_texture(TextureDisplacementLayer &layer, const TextureLibraryEntry &entry);
void import_custom_texture(TextureDisplacementLayer &layer);
// Paint / Erase, from the panel. See get_left_button_state_type().
bool m_erase_mode = false;
// Per slot: whether the layer's card shows every setting or only Depth, Tile size and Rotation.
// Panel state only, not saved with the project.
std::array<bool, TEXTURE_DISPLACEMENT_MAX_LAYERS> m_layer_expanded{};
@@ -435,6 +518,71 @@ private:
std::string m_slider_type_request;
int m_slider_type_request_frame = 0;
// ---- The image-adjustment panel ----
//
// Brightness/contrast/sharpness/blur/hue over one layer's image, shown on the image itself and
// updating as the sliders move. What it produces is not a set of layer parameters: it replaces the
// layer's *image*, so the adjusted pixels feed the colour and the displacement together and a
// brightness change moves the relief too (see TextureAdjustments).
//
// An ordinary floating window rather than a popup, and deliberately so. A popup dims the canvas
// behind it and closes on any click outside itself, which between them make it impossible to watch the
// relief change on the model - which is the whole point of adjusting the image here rather than in an
// image editor. A window leaves the 3D view live, clickable and orbitable while the panel is open.
void render_image_adjust_window(const ImVec2 &panel_min, const ImVec2 &panel_max);
// Opens the panel for `layer`, decoding its image into m_adjust_source. Sliders never re-decode
// the PNG.
void open_image_adjust(const TextureDisplacementLayer &layer);
// Reads `layer`'s stored image into the panel's source buffers and records which image it came from.
// Called when the panel opens and again whenever the layer's image is swapped under it, which is why
// it leaves the slider values alone. False when the image cannot be decoded.
bool load_image_adjust_source(const TextureDisplacementLayer &layer);
// Resolves the panel: writes the adjusted image into the user's texture library as a new file and
// points `layer` at it, which is the only way an adjustment becomes permanent. Closes the panel.
void commit_image_adjust(TextureDisplacementLayer &layer);
// Closes the panel and reverts the layer's live preview_adjust to identity, so every exit that is not
// a commit - Cancel, the window's close button, the gizmo closing - leaves the layer as it was found.
void close_image_adjust();
// Collects a finished preview and starts one for the current slider values. One at a time, so a drag
// coalesces into "whatever the sliders last said" instead of a queue of superseded frames.
void update_image_adjust_preview();
int m_adjust_slot = -1; // the layer the panel is open for; -1 when closed
TextureAdjustments m_adjust; // what the sliders currently say
// What the layer's live preview_adjust was last set from, so a slider move can be told from a frame in
// which nothing happened and only the former asks the displacement to be recomputed.
TextureAdjustments m_adjust_applied;
// The layer's image as it was when the panel opened, and a small copy of it. The sliders are applied
// to the small copy for the live preview and to the full-size one exactly once, on commit. Measured on
// a 1024x1024 with every knob engaged, a full-size pass costs 13-19 ms grayscale and 40-60 ms in
// colour (130-190 ms at 2048 in colour) - far too much to repeat per slider frame. The same pass on a
// 384 px copy is 3-4 ms / 9-12 ms, and that is all the preview box can show anyway.
DecodedHeightTexture m_adjust_source;
DecodedHeightTexture m_adjust_preview_source;
// Which image_data the two buffers above were decoded from, so the panel can notice the layer's image
// being swapped from the texture picker while it is open and re-read it. Compared, never dereferenced.
const void *m_adjust_source_image = nullptr;
// And which volume the panel was opened on. Slot numbers are per volume, so without this a change of
// selection would silently rebind the open panel to whichever layer happens to hold the same slot on
// the newly selected object - a different image, under a panel the user opened for this one.
size_t m_adjust_volume_id = 0;
// The preview image on screen, re-uploaded whenever a background pass finishes.
std::unique_ptr<GLTexture> m_adjust_preview_tex;
// The live preview runs on its own thread rather than on the UI thread or on the plater's job
// worker. Not the UI thread because even the small pass is milliseconds and this runs while a slider
// is being dragged; not the job worker because that is a single FIFO shared with Bake and the
// displacement preview (see queue_preview_job()), where a per-frame image filter would sit behind -
// and delay - multi-second mesh work.
std::future<DecodedHeightTexture> m_adjust_preview_job;
TextureAdjustments m_adjust_preview_running; // what the in-flight pass is computing
TextureAdjustments m_adjust_preview_shown; // what m_adjust_preview_tex holds
bool m_adjust_preview_valid = false;
// Drops the GPU copies of the layer's image so the next frame rebuilds them from the decode, which
// is where the live adjustment is applied. Called whenever the panel moves or reverts it.
void invalidate_adjust_textures();
// "Adjust Texture" mode: instead of painting, dragging an on-canvas handle changes the active
// layer's offset. The handle is a flat panel lying in the paint patch's own tangent plane
// (a "pan" - drag anywhere on it for free 2D movement), plus two arrows along the patch's
@@ -453,8 +601,8 @@ private:
// obvious whether the next stroke adds paint (default) or erases it (Shift). Uses ImGui's
// foreground draw list, so it must be called from inside the gizmo's ImGui frame.
void render_paint_cursor_hint();
// Mesh-local tangent-plane basis at m_adjust_anchor_normal, matching project_planar()'s
// dominant-axis convention so dragging on-canvas maps consistently onto offset.
// Mesh-local tangent-plane basis at m_adjust_anchor_normal: box_projection_axes(), so dragging
// on-canvas maps consistently onto offset whichever face the anchor is on.
void adjust_tangent_basis(Vec3f &u_axis, Vec3f &v_axis) const;
// The plane a drag is measured against: the paint patch's anchor, lifted clear of the surface.
@@ -855,18 +1003,31 @@ private:
// Merges chart `b`'s join group into chart `a`'s (materialising `groups` to `chart_count` first).
static void join_island_groups(std::vector<int> &groups, int a, int b, int chart_count);
// Final per-vertex texture uv for the projections the shader can't reconstruct itself - LSCM (an
// unwrap) and ViewProjected (a projector plane the shader doesn't know). One entry per patch/base
// vertex, already through apply_uv_transform(). Empty for Triplanar/Cylindrical/Spherical, which
// the shader projects on its own. Shared by the shaded preview and the UV-check overlay.
// unwrap), ModelUV (the model's own channel) and ViewProjected (a projector plane the shader
// doesn't know). One entry per patch/base vertex, already through apply_uv_transform(). Empty for
// Triplanar/Cylindrical/Spherical, which the shader projects on its own. Shared by the shaded
// preview and the UV-check overlay.
//
// `patch_source` maps each patch triangle back to its base-mesh triangle
// (TriangleSelector::get_facets_strict()'s out_source). Only ModelUV needs it - its channel is per
// base triangle - and without it a ModelUV layer reports no uvs and the preview falls back.
std::vector<Vec2f> compute_layer_vertex_uvs(const indexed_triangle_set &patch,
const TextureDisplacementLayer &layer) const;
const TextureDisplacementLayer &layer,
const std::vector<int> *patch_source = nullptr) const;
// The same, but three UVs per patch triangle (corner 0..2 of triangle i at 3i..3i+2). This is what
// the flat, unshared-vertex preview meshes actually want: under LSCM a seam vertex has a different
// UV in each island it borders, so collapsing to one per vertex handed a triangle at an unjoined
// seam its neighbour's placement - one visibly skewed triangle per face. Every other projection is
// single-valued per point, so there a corner's UV is just its vertex's.
std::vector<Vec2f> compute_layer_corner_uvs(const indexed_triangle_set &patch,
const TextureDisplacementLayer &layer) const;
const TextureDisplacementLayer &layer,
const std::vector<int> *patch_source = nullptr) const;
// The model's own channel over `local_patch`, already through apply_uv_transform() - three per
// patch triangle. Empty when the volume has no channel, or when `patch_source` is missing. Shared
// by the two functions above so the per-vertex and per-corner forms can never disagree.
std::vector<Vec2f> model_uv_corners(const indexed_triangle_set &local_patch,
const TextureDisplacementLayer &layer,
const std::vector<int> *patch_source) const;
// The in-shader projection for `layer` (0 Triplanar, 1 Cylindrical, 2 Spherical) plus, for the two
// wrapping ones, the patch centroid and cylinder axis they wrap around - in the texture frame the
// shaders project in. Taken from the bake's own texture_displacement_patch_frame(), so a preview
@@ -915,6 +1076,7 @@ private:
enum class UVBackground { None, Height, Checker };
UVBackground m_uv_editor_bg = UVBackground::None;
float m_uv_editor_bg_smoothing = -1.f; // smoothing the height backdrop was uploaded at
TextureAdjustments m_uv_editor_bg_adjust; // and the live image adjustment it was uploaded at
const void *m_uv_editor_bg_image = nullptr; // the layer image it was uploaded from
// Per-chart distortion heatmap colour for the UV pane (#7/#14), computed once when the unwrap is
// re-solved (relative stretch doesn't change when islands are merely moved), fed to the canvas only
@@ -972,6 +1134,7 @@ private:
std::unique_ptr<GLTexture> m_color_tex;
std::weak_ptr<const std::vector<unsigned char>> m_color_tex_source;
float m_color_tex_smoothing = -1.f;
ColorAdjustKey m_color_tex_adjust;
// Library textures the picker has shown at least once, keyed by file path (see LibraryTexture).
std::map<std::string, LibraryTexture> m_library_textures;
+13
View File
@@ -22,6 +22,7 @@
//#include "slic3r/GUI/Gizmos/GLGizmoHollow.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoSeam.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoMmuSegmentation.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoImage.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoTextureDisplacement.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoSimplify.hpp"
#include "slic3r/GUI/Gizmos/GLGizmoEmboss.hpp"
@@ -201,6 +202,11 @@ void GLGizmosManager::switch_gizmos_icon_filename()
// light/dark switch.
gizmo->set_icon_filename("toolbar_texture_displacement.svg");
break;
case(EType::Image):
// Drawn flat in Orca's menu-icon palette, which reads on either background, so one file
// serves both themes here too.
gizmo->set_icon_filename("toolbar_image.svg");
break;
case(EType::MeshBoolean):
gizmo->set_icon_filename(m_is_dark ? "toolbar_meshboolean_dark.svg" : "toolbar_meshboolean.svg");
break;
@@ -252,6 +258,8 @@ bool GLGizmosManager::init()
m_gizmos.emplace_back(new GLGizmoMmuSegmentation(m_parent, m_is_dark ? "mmu_segmentation_dark.svg" : "mmu_segmentation.svg", EType::MmSegmentation));
// One shared icon (no dedicated dark variant yet); it recolours acceptably in both themes.
m_gizmos.emplace_back(new GLGizmoTextureDisplacement(m_parent, "toolbar_texture_displacement.svg", EType::TextureDisplacement));
// The same gizmo restricted to the zero-displacement case; see GLGizmoImage.
m_gizmos.emplace_back(new GLGizmoImage(m_parent, "toolbar_image.svg", EType::Image));
m_gizmos.emplace_back(new GLGizmoEmboss(m_parent, m_is_dark ? "toolbar_text_dark.svg" : "toolbar_text.svg", EType::Emboss));
m_gizmos.emplace_back(new GLGizmoSVG(m_parent));
m_gizmos.emplace_back(new GLGizmoMeasure(m_parent, m_is_dark ? "toolbar_measure_dark.svg" : "toolbar_measure.svg", EType::Measure));
@@ -591,6 +599,8 @@ bool GLGizmosManager::gizmo_event(SLAGizmoEventType action, const Vec2d& mouse_p
return dynamic_cast<GLGizmoFuzzySkin*>(m_gizmos[FuzzySkin].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down);
else if (m_current == TextureDisplacement)
return dynamic_cast<GLGizmoTextureDisplacement*>(m_gizmos[TextureDisplacement].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down);
else if (m_current == Image)
return dynamic_cast<GLGizmoImage*>(m_gizmos[Image].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down);
else if (m_current == MeshBoolean)
return dynamic_cast<GLGizmoMeshBoolean*>(m_gizmos[MeshBoolean].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down);
else if (m_current == BrimEars)
@@ -605,6 +615,7 @@ bool GLGizmosManager::is_paint_gizmo()
m_current == EType::MmSegmentation ||
m_current == EType::FuzzySkin ||
m_current == EType::TextureDisplacement ||
m_current == EType::Image ||
m_current == EType::Seam;
}
@@ -1558,6 +1569,8 @@ std::string get_name_from_gizmo_etype(GLGizmosManager::EType type)
return "Fuzzy Skin Painting";
case GLGizmosManager::EType::TextureDisplacement:
return "Texture Displacement";
case GLGizmosManager::EType::Image:
return "Image";
default:
return "";
}
@@ -96,6 +96,7 @@ public:
FuzzySkin,
MmSegmentation,
TextureDisplacement,
Image,
Emboss,
Svg,
Measure,
@@ -8,6 +8,7 @@
#include "libslic3r/TextureDisplacement.hpp"
#include <exception>
#include <cstddef>
#include <cstdint>
#include "slic3r/GUI/Jobs/Worker.hpp"
#include <memory>
@@ -26,6 +27,7 @@
#include "slic3r/Utils/UndoRedo.hpp"
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include <array>
namespace Slic3r::GUI {
@@ -74,7 +76,8 @@ void TextureDisplacementBakeJob::process(Ctl &ctl)
}
return true;
},
color, m_input.volume_to_world, nullptr, &m_stats));
color, m_input.volume_to_world, nullptr, &m_stats,
m_input.model_uv.empty() ? nullptr : &m_input.model_uv));
// Always finish at 100: this is what closes the notification. Reported even on cancel, where
// build_texture_displacement() returns an empty mesh and finalize() commits nothing.
@@ -126,16 +129,71 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept
{ mix.a_percent(), 100 - mix.a_percent() });
});
// Whether the bake replaced the triangles or only moved the vertices it was given. The classic
// path is topology-preserving by contract, so every per-triangle annotation on the volume still
// means what it did; the default pipeline refines, cuts and simplifies, so none of them do.
// Both are checked: the flag is what the bake promised, the count is what it delivered. Only
// the triangles matter - the annotations are per facet and reference no vertex index - so a
// vertex count that changed on its own (the bake compacts unreferenced vertices away) is not a
// reason to remap anything.
const bool topology_changed = m_input.options.pipeline_v2 ||
m_result.its.indices.size() != m_input.base_mesh.indices.size();
// Carry the volume's existing paint - the model's own colours above all - across that rebuild.
// Without it a bake left the mmu_segmentation_facets bitstream pointing at a triangle set that
// no longer existed, which is what scrambled the colours of an imported coloured model even
// with colour switched off on every layer and nothing in the bake that was meant to touch them.
//
// transfer_facet_paint() rather than ModelVolume::restore_painting(): the latter's remap wants
// a target triangle overlapping the source paint to within 0.01 mm, which the baked surface is
// nowhere near - it has moved by the relief depth. Nothing to do when the topology is intact:
// triangle i is still triangle i, so the paint is already exactly right and carrying it at all
// could only lose detail.
std::array<TriangleSelector::TriangleSplittingData, 4> before;
if (topology_changed) {
before[0] = volume->supported_facets.get_data();
before[1] = volume->seam_facets.get_data();
before[2] = volume->mmu_segmentation_facets.get_data();
before[3] = volume->fuzzy_skin_facets.get_data();
}
volume->set_mesh(std::move(m_result));
volume->set_new_unique_id();
volume->calculate_convex_hull();
if (topology_changed) {
const std::array<FacetsAnnotation *, 4> target{ &volume->supported_facets, &volume->seam_facets,
&volume->mmu_segmentation_facets,
&volume->fuzzy_skin_facets };
for (size_t ch = 0; ch < target.size(); ++ch) {
const std::vector<uint8_t> state =
transfer_facet_paint(m_input.base_mesh, before[ch], volume->mesh().its);
// Nothing was painted in this channel, or there is nothing to paint it onto: either
// way the annotation must not keep describing the mesh that is gone.
if (state.empty()) {
target[ch]->reset();
continue;
}
TriangleSelector selector(volume->mesh());
bool any = false;
for (size_t i = 0; i < state.size(); ++i)
if (state[i] != 0) {
selector.set_facet(int(i), EnforcerBlockerType(state[i]));
any = true;
}
if (any)
target[ch]->set(selector);
else
target[ch]->reset();
}
}
// Colour lands in mmu_segmentation_facets, merged *over* whatever is already painted there
// rather than replacing it: a triangle the texture does not colour keeps its existing filament,
// and one the user never painted at all stays at NONE, which already means "the volume's own
// filament". That is what confines the effect to the painted area without having to invent a
// colour for everything outside it. Safe to index straight onto the new mesh - the bake is
// topology-preserving, so triangle i is still triangle i.
// colour for everything outside it. What was already painted is whatever the transfer above
// left in the annotation, so this bake's colour lands on top of it rather than instead of it.
if (!m_triangle_color.empty() && m_triangle_color.size() == volume->mesh().its.indices.size()) {
TriangleSelector selector(volume->mesh());
const TriangleSelector::TriangleSplittingData &existing = volume->mmu_segmentation_facets.get_data();
@@ -159,7 +217,6 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept
// pipeline, which rebuilds and then simplifies the mesh. A mask left behind against the old
// topology is exactly what makes the gizmo reload an empty selector over a non-empty mask and
// then erase it on the next flush - see GLGizmoTextureDisplacement::update_from_model_object().
const bool topology_changed = m_input.base_mesh.indices.size() != volume->mesh().its.indices.size();
for (int slot = 0; slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++slot) {
const auto it = std::find_if(m_input.layers.begin(), m_input.layers.end(),
[slot](const TextureDisplacementLayer &l) { return l.slot == slot; });
@@ -167,6 +224,14 @@ void TextureDisplacementBakeJob::finalize(bool canceled, std::exception_ptr &ept
volume->texture_displacement_facet(slot).reset();
}
// The model's own UV channel. Resampled onto a rebuilt mesh from the surface the bake started
// from: a displaced vertex came from its foot point on that surface, which is the position its
// uv belongs to - so no distance limit, the relief depth is exactly how far it has moved.
if (!m_input.model_uv.empty())
volume->texture_uv = topology_changed ? transfer_uv_channel(m_input.base_mesh, m_input.model_uv,
volume->mesh().its) :
m_input.model_uv;
ModelObject *object = volume->get_object();
if (object == nullptr)
return;
@@ -219,6 +284,8 @@ void queue_texture_displacement_bake(const ModelVolume &volume, const TextureCol
input.take_snapshot = take_snapshot;
input.volume_id = volume.id();
input.base_mesh = volume.mesh().its;
if (volume.has_texture_uv())
input.model_uv = volume.texture_uv;
input.layers = volume.texture_displacement_layers;
input.options = volume.texture_displacement_options;
input.volume_to_world = texture_displacement_volume_to_world(volume);
@@ -34,6 +34,9 @@ struct TextureDisplacementBakeInput
// writes the volume's mmu_segmentation_facets - the same per-triangle filament assignment the MMU
// paint gizmo writes - alongside the displaced geometry.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), empty when it has none: what a ModelUV
// layer maps through, and what the commit puts back on the baked mesh.
std::vector<Vec2f> model_uv;
// Whether this job pushes its own undo step when it commits. False when the caller has already
// taken one that is meant to cover the displacement as well - Standard mode's Bake, which remeshes
// and subdivides first and has to undo as a single action.
@@ -17,6 +17,7 @@
#include "slic3r/GUI/Jobs/Worker.hpp"
#include <memory>
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/TriangleMesh.hpp"
namespace Slic3r::GUI {
@@ -52,13 +53,14 @@ void TextureDisplacementDebugJob::process(Ctl &ctl)
indexed_triangle_set mesh = m_input.base_mesh;
TextureDisplacementFacetsData masks = m_input.facets_data;
std::vector<Vec2f> uv = m_input.model_uv;
// The default pipeline can only move vertices the mesh already has, so its recipe starts with the
// preparation - which is where "first it remeshes, then it refines" actually happens. The
// experimental pipeline refines as part of the bake and has nothing to prepare.
if (m_input.run_prepare && !m_input.options.pipeline_v2) {
const TextureDisplacementPrepareResult prepared =
GLGizmoTextureDisplacement::prepare_mesh(mesh, masks, m_input.layers, m_input.prepare_params,
GLGizmoTextureDisplacement::prepare_mesh(mesh, masks, m_input.layers, uv, m_input.prepare_params,
m_input.color,
// Preparation is roughly half the run; the bake
// takes the progress bar from there.
@@ -77,12 +79,14 @@ void TextureDisplacementDebugJob::process(Ctl &ctl)
if (!prepared.mesh.indices.empty()) {
mesh = prepared.mesh;
masks = prepared.masks;
uv = prepared.uv; // resampled onto the prepared mesh, as the prepare commit stores it
}
}
build_texture_displacement(mesh, m_input.layers, masks, m_input.options,
[&report](int pct) { return report(50 + pct / 2); },
/* color */ nullptr, m_input.volume_to_world, &recorder);
/* color */ nullptr, m_input.volume_to_world, &recorder, /* stats */ nullptr,
uv.empty() ? nullptr : &uv);
m_stages = recorder.take();
ctl.update_status(100, status); // always finish at 100: this is what closes the notification
@@ -115,6 +119,8 @@ void queue_texture_displacement_debug(const ModelVolume &volume, const TextureCo
input.check_topology = check_topology;
input.color = color;
input.volume_to_world = texture_displacement_volume_to_world(volume);
if (volume.has_texture_uv())
input.model_uv = volume.texture_uv;
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
input.facets_data[size_t(i)] = volume.texture_displacement_facet(i).get_data();
@@ -47,6 +47,9 @@ struct TextureDisplacementDebugInput
// Only the quantizer is used, and only by the refinement's colour criterion - the debug run
// produces no colour of its own.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), so the recipe captured here is the one a
// ModelUV layer actually bakes through. Empty when the volume has none.
std::vector<Vec2f> model_uv;
// The edge scan behind the open / non-manifold counts is a sort over every half-edge, which on a
// multi-million triangle stage costs more than the stage did. On by default because a stage that
@@ -46,7 +46,7 @@ void TextureDisplacementPrepareJob::process(Ctl &ctl)
// idle loop.
int last_reported = 1;
m_result = GLGizmoTextureDisplacement::prepare_mesh(m_input.base_mesh, m_input.masks, m_input.layers,
m_input.params, m_input.color,
m_input.model_uv, m_input.params, m_input.color,
[&ctl, &status, &last_reported](int percent) {
if (ctl.was_canceled())
return false;
@@ -106,6 +106,10 @@ void TextureDisplacementPrepareJob::finalize(bool canceled, std::exception_ptr &
volume->restore_painting(saved_painting);
for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i)
volume->texture_displacement_facet(i).set_data(std::move(m_result.masks[size_t(i)]));
// The model's own UV channel, resampled onto the new mesh by the run. Also put back after
// restore_painting(), which resets it along with the extra facets for the same reason: it is
// indexed by triangle and the triangles have changed.
volume->texture_uv = std::move(m_result.uv);
if (ObjectList *obj_list = wxGetApp().obj_list()) {
const ModelObjectPtrs &objs = plater->model().objects;
@@ -9,6 +9,7 @@
#include "Job.hpp"
#include "libslic3r/ObjectID.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/TextureDisplacement.hpp"
namespace Slic3r {
@@ -47,6 +48,10 @@ struct TextureDisplacementPrepareInput
// skips the colour criterion entirely. Only the *quantizer* is used here: refinement follows
// perceived colour, never the interleaving that realises a mix.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), empty when it has none. prepare_mesh()
// resamples it onto the mesh it produces, and the commit puts it back - like the masks, it is
// indexed by triangle and so cannot survive the stages on its own.
std::vector<Vec2f> model_uv;
// The undo step the commit opens. Standard mode's Bake names it after the bake, because the
// displacement job that follows commits into this same step rather than pushing its own.
std::string snapshot_name;
@@ -48,7 +48,8 @@ void TextureDisplacementPreviewJob::process(Ctl &ctl)
(!m_current_generation ||
m_current_generation->load() == m_generation);
},
color, m_input.volume_to_world);
color, m_input.volume_to_world, nullptr, nullptr,
m_input.model_uv.empty() ? nullptr : &m_input.model_uv);
}
void TextureDisplacementPreviewJob::finalize(bool canceled, std::exception_ptr &eptr)
@@ -29,6 +29,9 @@ struct TextureDisplacementPreviewInput
// Empty unless a layer is colouring, in which case the preview reports the palette entry per
// triangle alongside the mesh, so the Normal view shows the colours the bake will produce.
TextureColorSettings color;
// The volume's own UV channel (ModelVolume::texture_uv), so a ModelUV layer previews through the
// same layout it will bake through. Empty when the volume has none.
std::vector<Vec2f> model_uv;
};
// A preview result: the displaced mesh, and - when the input carried a palette - one palette entry per
+59
View File
@@ -67,6 +67,7 @@
#include "slic3r/GUI/Field.hpp"
#include "slic3r/GUI/Widgets/PopupWindow.hpp"
#include <set>
#include <wx/filename.h>
#include "slic3r/GUI/Widgets/StaticLine.hpp"
#include "slic3r/GUI/GUI_ObjectSettings.hpp"
#include "slic3r/GUI/ColorDecomposeDialog.hpp"
@@ -246,6 +247,7 @@
#include "DeviceCore/DevNozzleSystem.h" // DevNozzle, GetExtNozzles / GetRackNozzles
#include "ProjectDirtyStateManager.hpp"
#include "Gizmos/GLGizmoSimplify.hpp" // create suggestion notification
#include "Gizmos/GLGizmoImage.hpp" // Drop an image onto the Image tool
#include "Gizmos/GLGizmoSVG.hpp" // Drop SVG file
#include "Gizmos/GizmoObjectManipulation.hpp"
@@ -7110,6 +7112,9 @@ void Sidebar::can_search()
p->can_search();
}
// Defined with the other drop helpers below; forward declared because the drop target uses it.
void set_image_drag_over(Plater &plater, bool over);
class PlaterDropTarget : public wxFileDropTarget
{
public:
@@ -7119,12 +7124,53 @@ public:
virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString &filenames);
// A drag has no feedback of its own, so the Image tool is told when one is over the view and
// draws a drop zone for as long as it is. wxWidgets cannot hand us the file names before the
// drop on GTK, so this says nothing about what is being dragged: the zone invites a picture,
// and anything else still falls through to the model loader.
virtual wxDragResult OnEnter(wxCoord x, wxCoord y, wxDragResult def)
{
set_image_drag_over(m_plater, true);
return wxFileDropTarget::OnEnter(x, y, def);
}
virtual void OnLeave()
{
set_image_drag_over(m_plater, false);
wxFileDropTarget::OnLeave();
}
private:
MainFrame& m_mainframe;
Plater& m_plater;
};
namespace {
// The Image gizmo, but only while it is the open one. Null otherwise, which is what keeps a drag or
// a drop from meaning anything different with the tool closed.
GLGizmoImage *open_image_gizmo(Plater &plater)
{
GLCanvas3D *canvas = plater.canvas3D();
if (canvas == nullptr)
return nullptr;
GLGizmosManager &gizmos = canvas->get_gizmos_manager();
if (gizmos.get_current_type() != GLGizmosManager::Image)
return nullptr;
return dynamic_cast<GLGizmoImage *>(gizmos.get_gizmo(GLGizmosManager::Image));
}
// True when `file` is a picture and the Image gizmo is the one currently open, in which case it has
// taken the file. Mirrors emboss_svg() below, which does the same for an SVG and the text tool.
bool drop_image_on_gizmo(Plater &plater, const wxString &file)
{
static const std::set<wxString> image_ext = { "png", "jpg", "jpeg", "bmp" };
const wxString ext = wxFileName(file).GetExt().Lower();
if (image_ext.count(ext) == 0)
return false;
GLGizmoImage *image = open_image_gizmo(plater);
return image != nullptr && image->drop_image_file(into_u8(file));
}
bool emboss_svg(Plater& plater, const wxString &svg_file, const Vec2d& mouse_drop_position)
{
std::string svg_file_str = into_u8(svg_file);
@@ -7783,6 +7829,12 @@ const std::regex Plater::priv::pattern_zip_amf(".*[.]zip[.]amf", std::regex::ica
const std::regex Plater::priv::pattern_any_amf(".*[.](amf|amf[.]xml|zip[.]amf)", std::regex::icase);
const std::regex Plater::priv::pattern_prusa(".*bbl", std::regex::icase);
void set_image_drag_over(Plater &plater, bool over)
{
if (GLGizmoImage *image = open_image_gizmo(plater))
image->set_file_drag_over(over);
}
bool PlaterDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString &filenames)
{
#ifdef WIN32
@@ -7790,11 +7842,18 @@ bool PlaterDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString &fi
this->MSWUpdateDragImageOnLeave();
#endif // WIN32
set_image_drag_over(m_plater, false); // the drag is over, whoever ends up taking the file
m_mainframe.Raise();
m_mainframe.select_tab(TAB_ID_PREPARE);
if (wxGetApp().is_editor())
m_plater.select_view_3D("3D");
// A picture dropped while the Image tool is open is that tool's input, not a model to load. Only
// then: with the tool closed a dropped PNG goes on doing whatever it did before.
if (filenames.size() == 1 && drop_image_on_gizmo(m_plater, filenames.Last()))
return true;
// When only one .svg file is dropped on scene
if (filenames.size() == 1) {
const wxString &filename = filenames.Last();
+3
View File
@@ -114,6 +114,9 @@ constexpr std::array<ShortcutInfo, size_t(Shortcut::Count)> shortcut_table = {{
SHORTCUT(GizmoAssembly, "gizmo_assembly", L("Gizmo assemble"), PLATER, { 'Y' }),
SHORTCUT(GizmoBrimEars, "gizmo_brim_ears", L("Gizmo brim ears"), PLATER, { 'E' }),
SHORTCUT(GizmoDisplacement, "gizmo_displacement", L("Gizmo texture displacement painting"), PLATER, { 'D' }),
// Unbound by default: every single letter this context can reach is already taken, and a default
// that shadows one of them is worse than none. The shortcuts dialog lists it for binding.
SHORTCUT(GizmoImage, "gizmo_image", L("Gizmo image painting"), PLATER, KeyChord{}),
// Sliders
SHORTCUT(GoToLayer, "go_to_layer", L("Jump to layer"), PREVIEW, { 'G', SHIFT }),
+1 -1
View File
@@ -38,7 +38,7 @@ enum class Shortcut : uint8_t {
MoveSelectionLeft, MoveSelectionRight, MoveSelectionUp, MoveSelectionDown, RotateSelectionLeft, RotateSelectionRight,
// Gizmos
GizmoMove, GizmoRotate, GizmoScale, GizmoFlatten, GizmoCut, GizmoMeshBoolean, GizmoFdmSupports, GizmoSeam, GizmoFuzzySkin,
GizmoMmuSegmentation, GizmoEmboss, GizmoMeasure, GizmoAssembly, GizmoBrimEars, GizmoDisplacement,
GizmoMmuSegmentation, GizmoEmboss, GizmoMeasure, GizmoAssembly, GizmoBrimEars, GizmoDisplacement, GizmoImage,
// Sliders
GoToLayer, LayerSliderUp, LayerSliderDown, MovesSliderLeft, MovesSliderRight, MovesSliderStart, MovesSliderEnd,
// Painting tools
+77 -30
View File
@@ -27,6 +27,7 @@
#include <wx/mstream.h>
#include "libslic3r/PNGReadWrite.hpp"
#include "libslic3r/TextureDisplacement.hpp"
#include "libslic3r/Utils.hpp"
#include "libslic3r/AppConfig.hpp"
@@ -158,6 +159,28 @@ bool encode_png_bytes(const wxImage &image, std::vector<unsigned char> &out, std
: encode_gray_png_bytes(image, out, error);
}
// A wxImage over decoded pixels, so the encoders above can be reached from an in-memory image as well as
// from a file. Grayscale is expanded to the three equal channels wxImage always stores, which is what
// image_has_color() then reads as "no colour" - so a grey image still encodes as a grayscale PNG.
//
// `scratch` holds the pixel buffer: the wxImage is constructed over it without taking ownership, so it
// has to outlive every use of the returned image.
wxImage image_from_decoded(const DecodedHeightTexture &image, std::vector<unsigned char> &scratch)
{
if (image.empty())
return wxImage();
const size_t n = size_t(image.width) * size_t(image.height);
scratch.resize(n * 3);
if (image.has_color())
scratch.assign(image.rgb.begin(), image.rgb.end());
else
for (size_t i = 0; i < n; ++i)
scratch[i * 3] = scratch[i * 3 + 1] = scratch[i * 3 + 2] = image.pixels[i];
return wxImage(image.width, image.height, scratch.data(), /* static_data */ true);
}
std::vector<unsigned char> read_file_bytes(const std::string &path)
{
std::ifstream ifs(path, std::ios::binary);
@@ -186,6 +209,42 @@ bool is_supported_height_map(const std::vector<unsigned char> &bytes)
std::vector<TextureLibraryEntry> g_library;
bool g_library_scanned = false;
// Writes `bytes` into the user's own texture folder as `stem`.png, uniquified so an existing texture -
// shipped-name collision, or a second edit of the same source - is never overwritten. Returns the new
// file's library entry. Shared by import_texture_to_library() and save_texture_to_library(), which
// differ only in where their bytes came from.
std::optional<TextureLibraryEntry> write_user_texture(const std::vector<unsigned char> &bytes, const std::string &stem,
std::string &error)
{
const std::string user_dir = user_texture_dir();
if (user_dir.empty()) {
error = _u8L("Could not create the folder for imported textures.");
return std::nullopt;
}
boost::filesystem::path dest = boost::filesystem::path(user_dir) / (stem + ".png");
for (int i = 2; boost::filesystem::exists(dest); ++i)
dest = boost::filesystem::path(user_dir) / (stem + " (" + std::to_string(i) + ").png");
{
boost::nowide::ofstream ofs(dest.string(), std::ios::binary);
ofs.write(reinterpret_cast<const char *>(bytes.data()), std::streamsize(bytes.size()));
if (!ofs.good()) {
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
}
}
texture_library(true); // pick the new file up
const std::string dest_str = dest.string();
for (const TextureLibraryEntry &e : g_library)
if (e.path == dest_str)
return e;
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
}
// The user's own textures, most recently used first, kept in the app config. File names are stored rather
// than paths so the order survives a moved data directory; '/' separates them because no platform allows
// it inside a file name. Bounded so a long-lived config does not grow a line without end.
@@ -317,12 +376,6 @@ bool remove_user_texture(const std::string &path, std::string &error)
std::optional<TextureLibraryEntry> import_texture_to_library(const std::string &source_path, std::string &error)
{
const std::string user_dir = user_texture_dir();
if (user_dir.empty()) {
error = _u8L("Could not create the folder for imported textures.");
return std::nullopt;
}
wxImage image;
if (!image.LoadFile(from_u8(source_path)) || !image.IsOk()) {
error = _u8L("Could not load the selected image.");
@@ -333,30 +386,7 @@ std::optional<TextureLibraryEntry> import_texture_to_library(const std::string &
if (!encode_png_bytes(image, bytes, error))
return std::nullopt;
// Never overwrite an existing texture (the user's or, if they picked the same name twice, their
// own earlier import) - uniquify instead.
const std::string stem = boost::filesystem::path(source_path).stem().string();
boost::filesystem::path dest = boost::filesystem::path(user_dir) / (stem + ".png");
for (int i = 2; boost::filesystem::exists(dest); ++i)
dest = boost::filesystem::path(user_dir) / (stem + " (" + std::to_string(i) + ").png");
{
boost::nowide::ofstream ofs(dest.string(), std::ios::binary);
ofs.write(reinterpret_cast<const char *>(bytes.data()), std::streamsize(bytes.size()));
if (!ofs.good()) {
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
}
}
texture_library(true); // pick the new file up
const std::string dest_str = dest.string();
for (const TextureLibraryEntry &e : g_library)
if (e.path == dest_str)
return e;
error = _u8L("Failed to save the imported texture.");
return std::nullopt;
return write_user_texture(bytes, boost::filesystem::path(source_path).stem().string(), error);
}
std::shared_ptr<std::vector<unsigned char>> load_texture_image_data(const std::string &path, std::string &error)
@@ -382,4 +412,21 @@ std::shared_ptr<std::vector<unsigned char>> load_texture_image_data(const std::s
return std::make_shared<std::vector<unsigned char>>(std::move(converted));
}
std::optional<TextureLibraryEntry> save_texture_to_library(const DecodedHeightTexture &image, const std::string &stem,
std::string &error)
{
std::vector<unsigned char> scratch;
const wxImage wx = image_from_decoded(image, scratch);
if (!wx.IsOk()) {
error = _u8L("The selected image is empty.");
return std::nullopt;
}
std::vector<unsigned char> bytes;
if (!encode_png_bytes(wx, bytes, error))
return std::nullopt;
return write_user_texture(bytes, stem.empty() ? std::string("texture") : stem, error);
}
} // namespace Slic3r::GUI
+10
View File
@@ -6,6 +6,8 @@
#include <string>
#include <vector>
#include "libslic3r/TextureDisplacement.hpp"
namespace Slic3r::GUI {
// One selectable height-map texture in the texture-displacement gizmo's texture picker.
@@ -57,6 +59,14 @@ std::optional<TextureLibraryEntry> import_texture_to_library(const std::string &
// Returns nullptr with `error` set if the file cannot be read or decoded at all.
std::shared_ptr<std::vector<unsigned char>> load_texture_image_data(const std::string &path, std::string &error);
// Writes `image` into user_texture_dir() as a new PNG named after `stem` (uniquified if taken, so an
// existing texture is never overwritten) and returns its library entry. The in-memory counterpart of
// import_texture_to_library(), for an image that was edited rather than read off disk.
//
// Returns nullopt with `error` set on failure.
std::optional<TextureLibraryEntry> save_texture_to_library(const DecodedHeightTexture &image, const std::string &stem,
std::string &error);
} // namespace Slic3r::GUI
#endif // slic3r_TextureLibrary_hpp_
-30
View File
@@ -19,7 +19,6 @@
#include <wx/stattext.h>
#include <wx/gdicmn.h>
#include <wx/window.h>
#include <wx/utils.h>
#ifdef __WXGTK__
#include <gtk/gtk.h>
@@ -666,35 +665,6 @@ void DropDown::messureSize()
sub->mainDropDown->mouseMove(ev);
e.RequestMore();
});
// Orca: the submenu holds the GTK grab, so GTK gives it the wheel events of the whole
// chain. GDK names the window under the cursor, so re-emit main's events on main.
g_signal_connect(sub->m_widget, "event", G_CALLBACK(+[](GtkWidget *, GdkEvent *event, gpointer data) -> gboolean {
auto *sub = static_cast<DropDown *>(data);
DropDown *main = sub->mainDropDown;
if (event->type != GDK_SCROLL || !main || !main->IsShown() || !sub->IsShown())
return FALSE;
gpointer owner = nullptr;
if (event->any.window)
gdk_window_get_user_data(event->any.window, &owner);
GtkWidget *widget = (owner && GTK_IS_WIDGET(owner)) ? GTK_WIDGET(owner) : nullptr;
bool for_main = widget && (widget == main->m_widget || gtk_widget_is_ancestor(widget, main->m_widget));
bool for_sub = widget && (widget == sub->m_widget || gtk_widget_is_ancestor(widget, sub->m_widget));
if (!for_main && for_sub) {
// The compositor may keep the pointer focus on the submenu while the cursor is over main.
wxPoint pt((int) event->scroll.x, (int) event->scroll.y);
if (sub->GetClientRect().Contains(pt))
return FALSE;
wxPoint off = sub->GetScreenRect().GetTopLeft() - main->GetScreenRect().GetTopLeft();
event->scroll.x += off.x;
event->scroll.y += off.y;
for_main = true;
}
if (!for_main)
return FALSE;
// wx connects its mouse handlers to GetConnectWidget(), the inner widget of the popup.
gtk_propagate_event(main->GetConnectWidget(), event);
return TRUE;
}), sub);
#endif
subDropDown->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent &e) {
e.SetEventObject(this);
File diff suppressed because it is too large Load Diff