OrcaSlicer/src/libslic3r/TriangleMeshSlicer.cpp
SoftFever bba367cde8
Feature/merge 1.8.2 (#3193)
* FIX: user preset sync token

Change-Id: Id2aa865b778ee9ac4cfddb68ceef0374507b519b
Jira: none

* FIX: Bitmap cache not take effect

Change-Id: I972098fdbda0b4542c6c759a8f5e1f0f2a30852b
Jira: STUDIO-4991

* NEW: Open HotModel Link With GetParam-From bambustudio

JIRA: NO JIRA

Change-Id: I4ac49bac5ee0c50988c76a38b00b7ba7dc3201f5

* NEW:AmsMaterialsSetting Support for user-preset

JIRA: STUDIO-5135
Change-Id: If848047cd5dbd059d440de30989c505c361305a7

* FIX: upload custom root preset fail

Change-Id: I621c8d542dd604b07cc5df63d97d7a31558d3aba
Jira: none

* FIX: show custom filament in AMS filament list

Change-Id: I79b9f8f2f08db8c52bbed76f1ea133baff383c00
Jira: none

* FIX: dailytips window and gcodeviwer legend window size issue

reset to original logic of dailytips and legend window size

jira: new

Change-Id: Iacb016bb222ba3f87317cfbe1f2b003802d773a5

* ENH: add text translation

jira: new

Change-Id: I780cfb8a0a64d806b5e0a414b6598e3b7bdf52dc

* FIX: Delete and search object outside the plate

JIRA:
1. STUDIO-5132 Deleting object outside the plate will crash
2. STUDIO-5146 The search function cannot search for object outside the plate

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I84cb3fe990a9c2a182e7434c262466a70545280e

* FIX: [5149 5142 5141 5140 5136] create printer and filament issue

Jira: 5149 5142 5141 5140 5136
5149 process preset name can not show all
5142 improt configs combobox not update
5141 disable modify filament_vendor
5140 disable input Bambu and Generic vendor
5136 preset list window adjust

Change-Id: I111a23996146cc16cc7f533c8616d50223d34c40
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ci: update build version to 01.08.00.54

Change-Id: Ifd69c01a82f627a9c6cf4fe0d48a759563ee90e7

* FIX: print model from sdcard with p1p

Change-Id: If85383ba762022ead3dd754ae02a08817b891114
Jira: none

* FIX: dailytips text translation

jira: STUDIO-2556

Change-Id: If44e503615b09ee1692f42ba1f998918ec5bd691

* FIX: clone shortcut key conflict with quit in macos

jira: STUDIO-5166

Change-Id: I548f275bb68d3b0e6bb3cfad6fe93df09d507da3

* FIX:User preset material settings dependent on firmware

JIRA: 5167
Change-Id: I82cf26848594b01155883ad0aa2e9ee77d371fb2

* ENH:update the description of nozzle detection

Change-Id: Id27b25c69dc11fcf66fc82053af705906ae8c370

* FIX: [5159 5165 5171 5172] create printer and filament issue

Jira: 5159 5165 5171 5172
5159 create printer dialog no refresh
5165 create printer 2 step dialog no refersh
5171 change font
5172 edit filament dialog darkUI issue
input special character is prohibited
'/' in preset name translate to '-'
update printer combobox

Change-Id: I5fa27836dab7f604f1a065c65efa099c7a2f0f96
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ci: update build version to 01.08.00.55

Change-Id: If1865d561cf274719204662314de163497759e89

* FIX:fix GLmodel deconstruction causing section not to be rendered

Jira: STUDIO-5156
Change-Id: Ibb2f459920989ee54f7b827352dc8893424b4de6

* FIX: missing unlock cause device or resource busy

Change-Id: I87563312ea9c6ce4e4e471da7ce7a02b53b64762

* FIX: some translation

Change-Id: I9758cbc758030b5a3945697a50ca4898af9fcb1b

* ci: update build version to 01.08.00.56

Change-Id: Id5ee53dd2ebb0b37b6927dc58b3cca94a1f66a83

* ENH: remove PLA GLOW in A1 mini

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Id99c1bbd4248e28df9150a85eecec831f6f32856

* ci: update build version to 01.08.00.57

Change-Id: Ib4dfa60f097128b76b95bb14ca04978619021b56

* Allow line width of nozzle diameter * 2.5

As it were, 1 mm would be disallowed but 0.99 would be allowed for 0.4
nozzle.  1 mm is the sane maximum and 0.99 is unnecessary tedious to write.

* Russian translation update

Russian translation Bambu Studio_v1.8.0 Beta

* FIX: scale problem in needs_retraction

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Idfbe954b22fa6aa5769c55e46874fa6a80ecbf45
(cherry picked from commit 4e853f50b748e3af11e2d64862b6ee557fda361b)

* ENH: CLI: support load_assemble_list

JIRA: STUDIO-4848
Change-Id: Ife11533740988331ea71eac86c370e625970cb8b

* FIX: align to Y not working

This is a bug introduced in 7fbb650 when solving jira STUDIO-4695.
Now we use a more decent way to solve it.

Change-Id: I92deffcb9fe53e8a24c93fe973446ae37df07375
(cherry picked from commit bd98430dbd15eb6c9bb4b447990e0dcf8a50eef0)

* ENH: Add buried points for cut and meshboolean

JIRA: NONE

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I67ce498d0c335dd7a8582f56b880c2c8314f8541

* FIX: 5092 edit filament add scrolled window

Jira: 5092

Change-Id: I53ae996b04e4e2f1b1ddce6a858d505001b11615
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX: can not select user preset when create filament

Jira: XXXX
github: 1936
and fix add preset for printer dialog can not show selected printer

Change-Id: Id4308c6bdca17d52d4aa321db359941aa87e0e45
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ENH: template filament don't be show in filament list and sort

Jira: 5160 5179

Change-Id: I56a7e1897e1ef3c061dc66d318896413ca25b76b
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX: [5174] export configs dialog issue

filament name too long to can not show all

Jira: 5174

Change-Id: I92018c9d7f86009b78b533592d899b4b5d78c3c8
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ENH: add filament Bambu TPU 95A HF

1.As title

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I752ec43da6297a6c172679997ce68f2318a7b8fb

* ENH: modify some params with filaments

1.Modify the PEI bed temperature of PLA Basic, Matte, and Tough to 65 in
 A1 mini. Set the bed temperature for the first layer of Bambu PETG-CF
 to 65 and 70 for the other layers

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ia902bbb7f824082d5346709d781cac64296f47a8

* ENH: add more status during printing

JIRA: STUDIO-5195

Change-Id: I85b3107839c6e2fdecbc10d90a876463e284468c
Signed-off-by: Stone Li <stone.li@bambulab.com>

* FIX:cut imgui has overlapping rendering on Apple

Jira: STUDIO-5150
Change-Id: I7969e19dc189cd617026a183067dad628208955c

* FIX:not TakeSnapshot for m_start_dragging_m

Jira: STUDIO-5176

Change-Id: Ia03e3e2c2664dbdcffa19ec8d0fa97dfd95e6d35

* FIX: rendered color changes

Jira: STUDIO-4956
during the drag processin connectors editing state

Change-Id: I3027176ea9f93a9ba9d6a2052f41aaa4adef79f1

* FIX: merge the patch from Prusa

Thanks for PrusaSlicer and YuSanka
Jira:STUDIO-5175
commit 510d59687b3b19c4a0f4e6540620d0694dd1b7ac
Author: YuSanka <yusanka@gmail.com>
Date:   Thu Oct 5 14:13:14 2023 +0200
    Follow-up 1b451cdf: Fixed #11415 - Connectors disappear when slicing => only when using multiple cut planes AND excluding parts

Change-Id: I9ccd5b85f482d723d21fccf5e104c9e0a9cc4849

* FIX:Press ESC directly to exit after entering the profile rendering

rendering is not normal,Code from PrusaSlicer,thanks for PrusaSlicer and enricoturri1966
commit a078627552f54497ed0518dc7bc349d243576d19
Author: enricoturri1966 <enricoturri@seznam.cz>
Date:   Mon Jan 30 14:00:02 2023 +0100

    Follow-up of 1218103fd620b319c56fd08116f81b581c537188 - Fixed gizmo missbehavior when closing a gizmo by resetting the selection clicking on the scene

Jira: STUDIO-5164
Change-Id: I261da9dba2a5ac37f3e263c175fbccd80d8045bd

* FIX: correct the strings and move create printer dialog center

Jira: 5221 5183

Change-Id: Ida4eba63f0e962ffcc8000fcc04cf20849577217
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ENH: CLI: skip layer height limit validate when slicing for existing models

JIRA: no jira
Change-Id: I1444a28b500ca7d08ed2606eecfa5cfaf261105e

* ENH:update the translation of auto refill

jira:[for translation]

Change-Id: Iaa7b4f3d7cd88c8b4f69a3db721ebd8ca8986eea

* FIX: icon issue for copying

Jira: STUDIO-4168

Icon issue when filling bed with copies

Change-Id: I61a03ecae02b75602c236ed2810e9c9cfe5a19f9
(cherry picked from commit b5079f8a2e79f19f65803f23ef4fd83aff17c84a)

* ENH: update some filament params

1. Modify texture bed temp to 65
2. Modify max-v-speed for ABS
3. Modify some params in Generic PA
4. Modify PLA,PVA params

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I42584a6015b8526f6bbb93024316968198bd76ce

* FIX: 3770 printable checkbox incorrect display in darkUI

Jira: 3770

Change-Id: I97f67d7a0ffc41f6ee625abeecc52ee4e73cf318

* FIX:Display garbled code in AmsMaterialsSetting pop-up

Change-Id: I50531e939afa7715ae376bac47172ccf7b248114

* ENH:Modifying the Line Color of Transparent Materials

JIRA: STUDIO-4311,5088,4983
Change-Id: I9e63413dc9cd7d523f0f7f1a2e32c4537a84467a

* FIX: crash when async delete printer file

Change-Id: I92c5e812d04da263338fb0eea2fd7583cf9ecde0
Jira: STUDIO-5222

* FIX: 3733 backup time not effective

Jira: 3733

Change-Id: I50c2ce156fcbd0a17aa8a6777bce04aa6093c830
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX: enable edit and delete preset btn and fix issue

Jira: XXXX

Change-Id: I724d7236b28fcc4746698f094531948a8fbb5d93
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX:send print job,file name displays error

JIRA:3137
Change-Id: I1c113025d274a13fba1b845a58aada14058fadd4

* FIX: skip hold user preset from sync

Change-Id: I2252246e19bd80903ad82170782ea49535d30d05
Jira: STUDIO-5185

* FIX: 5115 translations

Jira: 5115

Change-Id: I21b03bdd4d28c0bb097226143177e763cf8c777f
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX: add link for ironing parameter

Change-Id: I451f5549db3ac2205aa5703a2e5edc831e946af8

* FIX: scale problem in lift type decide

1. Scale the travel threshhold

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ib594d640fe63b0919bc9318af88577513f7dbf30

* ENH: add small perimeter speed and threshold

The original param is added by Prusa. Thanks orca for adding threshold.

1. Re add small perimeter speed and threhold.

github: #2221

Change-Id: I35b269b26f085d80f0edca28650bb21fc04898d7

* FIX: modify the picture of pa manual cali

Jira: STUDIO-5102
Change-Id: Id87898959ad4461b7bd2505b159271f2aa589c36

* FIX: Filament preset is the same with the first one

Jira: STUDIO-4519

Filament preset is the same wit the first one, it should align with the
last one.

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I304d0ff0fbc1c8948d410ea552e4d42b6a4e8fd9

* FIX: scoreDailog dark mode issue

Jira: 4570

Change-Id: I8be97b306a1494f73e3bba678ecc864e7ff88ca3

* FIX: CLI: fix the slicing issue while only one object with multicolor using seq-print

JIRA: no-jira
Change-Id: Iea2d23ff8e484bf2fd58aa2f596a8e4e4292fe39

* ENH: open support wall count for normal support

1. open support wall count for normal support
  Enabling this option makes normal support stronger and gives
  better overhang quality, but also more difficult to removal.
  Jira: STUDIO-5192
2. fix a bug where tree support (hybrid style) may get overlapped
  extrusions near the walls.
3. fix a bug where raft layers can't be 1 in tree support
  Jira: STUDIO-5261

Change-Id: Iadc0c67a9b50b5b221c8e83d5aa22ed282018cf8
(cherry picked from commit c0bb0084e386cb70ed6e16edf93190e4b38f5b90)

* FIX: compiling error on linux

jira: none
Change-Id: I1a4563503b5ddf74a1979cc0cee7a15b8aced904
(cherry picked from commit de52c6ca62c9f3a6314ddf5a856c1d8534329886)

* ENH: add translation for small perimeter

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I95013649e4e0c07c0f04b89a91488814c8d228cc

* FIX: clone shortcut key issue on macos

jira: STUDIO-5166

Change-Id: I1967da1d443ed43bd750dad8e11560688d7bd533

* FIX: custom gcode window cannot paste/ navigate

jira: STUDIO-5208、STUDIO-5070

Change-Id: I4ecb9d06cf5db0ae53a4678181aae9298bac106b

* ENH: modify dailytips collapse & expand interaction

jira: STUDIO-5209、STUDIO-5210

Change-Id: Ifb0b998e5004d4b49390ba5a250eaf4743bf3471

* ENH:Add shortcut keys and lists for objects search

JIRA: STUDIO-5157 STUDIO-5158 STUDIO-5240

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: Ic7cfaaa9b4bb8a85208bafab7fe3bafdb78f0045

* FIX:Re-calculate button with White Box displayed in dark mode

JIRA: STUDIO-5098

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I07cc6c72d5dbd03b72573cd27dd5938bb0e6a29a

* NEW: display plate index when printing a task

JIRA: STUDIO-2689

display on the thumbnail of the current task

Change-Id: I5f1f46c56e9d1e9120a66d491551908dfad099d6
Signed-off-by: Stone Li <stone.li@bambulab.com>

* ENH:fixed incorrect path prefix

jira:[for file path prefix]

Change-Id: Ie9e3999f02b78272e528ceceb479e746d46a7e6c

* FIX: thumbnail is not clear in dark mode

JIRA: STUDIO-5087

Change-Id: Ie86493ed71b5554095927f061509a1f551758b61
Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>

* FIX: translation

Jira: XXXX

Change-Id: Id03f0d704aa852632a907ea628d1277400112062
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ENH: first nozzle change to 0.4 and nozzle change to mm

Jira: XXXX

Change-Id: I14defd36442dbd7008e46782b08415b6244224f1
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ENH:editing_window_width's value is small on the laptop

Jira: STUDIO-5238 STUDIO-5265
apply_selected_connectors should check_and_update_connectors_state

Change-Id: I8c2c1c920cc4d197d1908815a3e62f4962335451

* FIX: fix new_bed_shape's calculation process

Jira: STUDIO-5122
Change-Id: I5f3e6a301a297123af28692c90bef6759f425b06

* ENH:update some translations

jira:[STUDIO-5262]

Change-Id: Idb1d3586888043ac325f272bc7a2b788adb3e9e5

* FIX: edit text command resets object settings

Jira: STUDIO-4655

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: Iac25c4e40f1d0d32e6d1f40e62226cc22bc96042

* ci: update build version to 01.08.00.58

Change-Id: Iacfec02aa50c617e4c9fe566319b07b30d47dce1

* FIX: remove GetUserAgent

Change-Id: I92886e1f0dcb091109231a10da8c19d51178e13b
Jira: STUDIO-5205

* FIX: nozzle_diameter_map data structure adjustment

Change-Id: Ifb724afc0fcf974e6d331e73ecac723107a102cf

* ENH:add _A and _B for perform_with_groove

Jira: STUDIO-5267
Change-Id: Iee3310dfa1cd8e6680310f0af0eff5c817490813

* ENH:is_equal for min_z and max_z

Jira: STUDIO-5267
Change-Id: I9493883d8be9d44e26ddc9afe62b7e9eb09c5052

* ci: update build version to 01.08.00.59

Change-Id: Ie8ed29ccf5d6c94594eb2ab8b717416fbeace3bd

* FIX:Image display unclear in light mode

JIRA:5161
Change-Id: I134cc64a2af0dfff60c47d0ff09d78d9c0f86b3f

* FIX:fix bugs of non manifold edge

Jira: STUDIO-5267

Change-Id: I8ac9a2cf96da0bc07ee00b309e65611b92fd174d

* ENH:nozzle type detection

jira:[STUDIO-5246]

Change-Id: Ic41a2161a0e41d23f56af93ad8ec34cc83ada0e3

* ENH: upadte P1S start gcode

1.turn on MC board fan by default on P1S

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I5b2f7868e350942fb8b7baf7d429e22a0987184a
(cherry picked from commit e866a575b6b7d9552f7412f84272f4b48dfc3961)

* ENH: improve support style's tooltip

jira: none
Change-Id: I8ee858d7052f04ce7ea6b226a500c7d1bf8a482f
(cherry picked from commit 665f31c4fcde22bd894cbb4a5fb160635947f2a4)

* ENH: set layer range error to warning

1. If layer range exceeds maximum/minimum layer range in printer
settings,pop up a window to warn

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I0304ee790e557ecf967f355c171993d1f51b5057

* ENH: CLI: remove the warning of layer height

JIRA: no jira
Change-Id: Idaceee4f52611479fc3f4238d016d891b4dc8cd1

* FIX: the word search is not translated

Jira: STUDIO-5224

The world search in the device panel is not translated.

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: Ia3d651c2159a3aad94e10cd0a6da98848f53ee2a
(cherry picked from commit 4a46a0a4750d82d49c9523f4b668a1a00c41ed83)

* FIX: Bitmap will flash when sending printing task

Jira: STUDIO-5278

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: Ib0c8710b8d5d6b98fad043c950f054aa35bea965

* ENH:display the euler angle of rotation plane

Jira: STUDIO-5268
Change-Id: I6b7b431931d60f1a9a832908400417781798c472

* ci: update build version to 01.08.00.60

Change-Id: I1c15b5c6437554c43327cd6b537f7a5860dba5a0

* ENH:cancel EnterReturnsTrue for imgui in cut

Jira: STUDIO-5269
Change-Id: I2832e1dccaf9755448debe7b2bd56426f90dfe0d

* ci: update build version to 01.08.00.61

Change-Id: Ib03e664a20990322c788686550c491d0139d8237

* FIX: some translation problems

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: If9f2af53b4f0bfa9469e84bcba68cc182df4a473

* add: Ukrainian lang support for 1.8

* FIX: calibration selected preset is null in some case

jira: STUDIO-5258

Change-Id: Iee63593c5f833c5a43e3b1d1c9ddb82f8c69569a

* FIX: create filament issue

Jira: 5296 5297 5295 5302 5311 5276

5296 create filament: list has same printer
5297 create filament: filament combobox has blank options
5298 edit filament: delete last preset prompt users
5302 create filament: filament combox has cili preset
5311 create filament: printer name too long to can not show all
5276 edit filament: PLA Aero filament type filter issue
add prusa vendor
Revised copy

Change-Id: I5dcc615ce0951b1a9953fa12283f6090f5069045

* FIX: some translation

Change-Id: Icb8614a0af18f96d15f3b97c17e0f6f708296847

* FIX:cancel is_equal for slicing function

Jira: STUDIO-5267
Change-Id: I66d759aa2c968f8a28a6a5d8378929754f2db689

* FIX:UI stuck due to pop-up window with wrong chamber temperature

JIRA: 5304
Change-Id: I1a49a7219b7a6f5700243704c348724e7930ce1a

* FIX: allow input '+' and hide edit preset btn

Change-Id: I97aec7c3ac4cc8b9d6c535f0126aaa1926553d86

* ENH: handle printer direct close and not retry

Change-Id: I5dd55f8085cf6383a8420ab41e614ea6ae210c78
Jira: STUDIO-5305

* ci: update build version to 01.08.00.62

Change-Id: I09716bf79354b503197c751272fd3171e0abc8fd

* add: new translation to ukr for AirFlow and Prusa

* add: Texture Plate name fix

* FIX:add slice_facet_for_cut_mesh api for cut tool

and modify section_vertices_map 's traverse
Jira: STUDIO-5267
Change-Id: Ifc4b183a4e4c4fdb4f47742f14f70a1ed93fa056

Change-Id: I52bfaef8926ef967b78a6cb712a1731a1b528a24

* FIX: Make the front smaller for Czech in device panel

Jira: STUDIO-5151

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I315174b55f923da069854fb4fed8cf3937b82074

* FIX: there is no object can be jumped to in notification

jira: new

Change-Id: Ib81bf49236952ede24a2de126051572d63916e01

* FIX: add height range, modifier in Preview pane will crash

jira: STUDIO-5340

1. fix crash at add height range, modifiers in Preview from objectList
2. fix an assert hit when slicing
3. fix an assert hit when enter AssembleView
4. forbidden popup menu by right-click objectList in Preview

Change-Id: I444bc76b1a4307999b387e4f60386b2d272bd308

* FIX: Black spot in the sending printing task page

Jira: STUDIO-5307

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I3bd97c063ec5f0faf7d12047da39f60ce55cae4b

* FIX: reset_cut_by_contours should update_buffer_data

Jira: STUDIO-5376
Change-Id: I5aacb1f7b65822031d7138abd61a45b09c743531

* ENH:editing_window_width's value is small on the laptop

Jira: STUDIO-5238 STUDIO-5265
Change-Id: Ia958772bcb081817da621115f99328bb62770cd5

* ENH: bumped version to 1.8.1

Change-Id: I9d25403daa5b7b8ca415c0b364670da9e0f932b0

* FIX: create filament dialog: create btn can not show all

Jira: 5310 5331

Change-Id: I185272c90d9ff1c3d6b47abbefbf488d0d965cca

* FIX:update custom_texture when new_shape=false

Jira: STUDIO-5287
Change-Id: I3add95f9f9345c14a48cc7467513d1b3ce95f4c9

* ENH:editing_window_width's value is small on the laptop

Jira: STUDIO-5238
Change-Id: I9044129f4e0c8ca7469db05b3e547fca4754342a

* FIX:add slash_to_back_slash for saving file path

Jira: STUDIO-5287
Change-Id: I9f3c176cd0831c793958f08601c63efac98176a4

* FIX: a button color didn't response to dark mode change

jira: STUDIO-5315

Change-Id: I95489f01ccd1f77b9e95b0d0f69e5398d2e88487

* FIX: height range layers displayed in wrong position

jira: STUDIO-5341

Change-Id: I83918b4624f367efa54321f1898e1176cdb04ea9

* FIX: auto arranging issues with locked plates

1. global auto arranging may put items overlap with wipe tower if some plates are locked
jira: STUDIO-5329
2. items outside bed may overlap with plate boundary if it's rotated
jira: STUDIO-5329
3. plate-wise auto arranging uses wrong min_obj_distance if the
plate is by-layer printing but global setting is by-object printing
jira: STUDIO-5330

Change-Id: I5dba2f1317e183c9aeec1cb2bd227fbddf4316e6
(cherry picked from commit db1eac41efff5f1e8d5ac0af74c6fc7ab59fc253)

* FIX:  a mistake in upward machine

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ibdb26c3d904634f322aef0dc0c7b8867d9fb5854

* FIX:a blank pop-up appears

JIRA:XXXX
Change-Id: Ice92b55204e4897fec024a6d99412eb810bddd4a

* FIX:fixed failure in updating nozzle type

jira:[STUDIO-5248]

Change-Id: Iad37b5d5b76d37cb1723ef21d7c39b1e3fcaf8d7

* FIX:fixed issue with AI monitoring settings

jira:[STUDIO-5082]

Change-Id: I967fe3c1e9da61a55bcbfaa2a8e067dd5af18f72

* FIX:fixed issue with lan mode

jira:[STUDIO-5189]

Change-Id: I1d0a05f19dcea154cf3ef2b61ed0546d3581905e

* FIX:update text for loading or unloading filaments

jira:[STUDIO-5231]

Change-Id: Ic7729c3ec012485b3d87e3d01f11e87502c67895

* FIX: Revert "ENH: do not leave a gap for top...

Revert "ENH: do not leave a gap for top interface if the top z distance is 0"

This reverts commit 79ea32c7cbbdb7e689637980af7c36caf42284c9.

Revert reason: the supports are impossible to remove in some cases.
jira: STUDIO-5385

Change-Id: I376a6f4dfd78da6dfea68b9ac3d552cddd0b4272
(cherry picked from commit 34e38b705fde7f5d7f9a3a89c96a3627ce0c998e)

* ENH: improve normal support's quality

1. Add a base_interface_layer when using Supp.W
2. Fix a bug where base_angle and interface_angle are wong

jira: STUDIO-5386
Change-Id: I52ab32c63b3cd1e6e2ba6463b01ae26699cf13d3
(cherry picked from commit 92ddd4a10b793572a1fa009da5b9e44fcdf81de2)

* NEW:tracking stl model files

jira:[STUDIO-5372]

Change-Id: Idb1275b07441f0cd06c24588d5f7c20f81f1556c

* FIX: edit filament dialog: preset name too long to del btn nan't show

Jira: 5336 5174
and verify string normalization

Change-Id: I380c3bed2bf43d01094b68979a8b67f4187c0b93

* FIX: some translation

Jira: 5232 5300 5334

Change-Id: Ie474ca823011e81aab82a9809af3d6e42980496b

* FIX: some translation

Change-Id: Iaabe6087bed3b7d47d911cf4fb51c770804e72fb

* ENH: change default tree_support_wall_count to 0

Now normal support also uses this option, so we can't default it to 1, otherwise normal supports will be too hard to remove.

jira: none
Change-Id: Ic5700af5c17e3a7b265c8915f28b0db35c6e06e6
(cherry picked from commit 6b84a9826da108b76569e686bd9def0b23ae29fd)

* FIX:The name of the material in the error prompt is empty

JIRA:STUDIO-4907
Change-Id: I3cf44f099256a51f21a44a89c89c000f734d1f36

* ci: update build version to 01.08.01.51

Change-Id: Ib20f5a12b65472102befec0a2adf82744fc29c46

* FIX: imgui textinput cannot paste on macos

jira: STUDIO-5070、STUDIO-5365

Change-Id: Iea8f41e12744ecda0fbb95c1a8f2e014a7cdc384

* FIX: not cache printer file list on error

Change-Id: I99843aedbf14d3d1d553ccac9b0bd26403274a82
Jira: none

* FIX: thread of close BBLUserPresetExceedLimit notify

Change-Id: I9698134ba1cc91fc83eac441f900d68c4c4b556a

* ENH: Resolve non manifold edges by fixing model interfaces

Jira: STUDIO-5124
Change-Id: I7ea86be44acb80b6c4762a76208b4a031acd0b27

* FIX:nozzle type sync

jira:[STUDIO-5248]

Change-Id: I63d48628832473d8d371ed643dc8528b00382531

* FIX: array bound happen in TriangleSelector::deserialize

Jira: STUDIO-5170
Change-Id: I92b72a887845b462fad208f13607293b44d3d333

* FIX:cropping rendering without considering assembly views

Jira: STUDIO-5260
Change-Id: Ia56cf80b305ae05f25f06ec277f85b3c5430a6df

* FIX: PA for custom filament not available in BL Studio

github: 2971
Change-Id: I6ccd36a183e7367d69557300f7242f5403f4bb33

* FIX: Bitmap is way too small on Mac

Jira: STUDIO-5393

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I6b550669fa8cd5fc9bfa6ed96d64d19a949f01b2

* FIX: move shutdown wait to OnExit

Change-Id: I70d9a2bb686525ae5273aa9d63e25691da4ab65c
Jira: STUDIO-2884

* FIX: calibration manage result dialog issue on macos

jira: STUDIO-4949 STUDIO-5378

Change-Id: I00abefd45a0d274a4b68bb1ab18debe8f91d169e

* FIX: adjust bed shape dialog button UI style

fix that button text is hard to see in dark mode
jira: STUDIO-5247

Change-Id: I2cf5b3cdd2eff9b821bdf5525bec4f329fc58dd1

* FIX: 5331 rescale btn

Jira: STUDIO-5331

Change-Id: If153424b8480e64b166018e3cd98c17db557d0a8
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX: support do not generate

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ide9709d95203185538e280517f7aa6136beeda44

* FIX: remove not match printer config ota cache

Change-Id: Ib73fc2ea31fa2186061cfcb5a170bc59b9db84ca
Jira: none

* FIX:cancel the variable of "checkbox_size"  as a fixed value

Jira: STUDIO-5150
Change-Id: I30d876d141b8b35ab4a3fee4889993d87b7c1741

* ENH:add reset_cut_by_contours in on_load function

Jira:STUDIO-5269
m_connector_size_tolerance default value is 0.1f

Change-Id: I6c67fff3cb0c1190e9141ed6f68fbfa848679f35

* ENH:cancel EnterReturnsTrue for imgui in cut

Jira: STUDIO-5269
Change-Id: Ifc4b183a4e4c4fdb4f47742f14f70a1ed93fa056
Signed-off-by: zhou.xu <zhou.xu@bambulab.com>

* FIX: dailytips should not change content frequently when slicing all

jira: STUDIO-5234

Change-Id: Icb7e9c28404d9db8ebed58d937e13f89c5403b5c

* FIX: objectList clone shortcut key issue

jira: new

Change-Id: Ia75bf58a7d53f962e1af6c2fd97497270b7eea84

* ENH:handling cases without msgs

jira:[STUDIO-5401 STUDIO-5399]

Change-Id: Iae651d5a19a45b0138a6aa621326a8b4a9649824

* ENH: optimize param description

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Id0ca9224227a716b21fc0b8430722264dc319344

* ENH: add translation

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I3b1f04fee3cd6322793794ad8b8707859f6c7d26

* FIX: close edit preset paramsDialog, mac unresponsive

Jira: 5298

Change-Id: I021e00567354cfb1f2f5f1f2bf6ba1fc35b164c5

* ENH:disable AI monitoring on the p1p series

Change-Id: I514bb1fb1ced6c03dd619230a9adac3be63f2de2

* ci: update build version to 01.08.01.52

Change-Id: I9f5e30d3fc4b7ef9321c522d3c18fce98f03742f

* FIX: close edit preset paramsDialog, mac unresponsive

Change-Id: Ic816754a20b7f6a5cdb46475750eb301fec3ad3a

* FIX: organic support not work with raft only

There is no raft generated when only raft enabled but no support needed.
jira: none

Change-Id: Ic0c9269e2f98038d85c9bc54e4a85f892dc5d764

* FIX: CLI: add object config when assemble

JIRA: no jira
Change-Id: I945f820fb58f2f643170b4b0b66742f6bbbdfd29

* FIX: delete preset prompt

Jira: XXXX

Change-Id: I6511c806c56393d4f6bd72d1c506da59675d49ff

* FIX:Reorganize the assignment of variables of "m_editing_window_width"

Jira: STUDIO-5238
Change-Id: If369916f3f5c21510f5f297bfd05c1230bdda7a4

* ENH: CLI: re-compute flush_volumes_matrix when it is missed

Change-Id: Ie8f53c6bef003b1434de02ea14de5787b376484f

* FIX: some translation for delete filament

Change-Id: Ib46a8eba33f2e21016476aaab4a57a740e86b1b8

* FIX: scrolled window / del preset / edit filament issue

Jira: 5092
GitHub: 1936
edit filament: just one preset, the scroll bar obscures the preset name
edit filament: delete selected preset, click no, but preset be deleted
from UI
edit filament: serial sometimes displays incorrectly

Change-Id: Ibc91609e252179de0c05ca065099756da6631165

* ci: update build version to 01.08.01.53

Change-Id: I5563a2c0812ab9a0d7727df27e17e681066ffa08

* FIX: mistake in filament vendor

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I3af712e417379d8b98ae18feebffe465bfa1e72d

* NEW:set customized materials for the A1 P1 series

Change-Id: I9c34f62867c074bf9ebb315013e5e40526e0eac7

* ci: update build version to 01.08.01.54

Change-Id: I579dcee428417ae7e7f7a96bd315a7066d72d974

* FIX: the flow rate ratio crashes after load model

for third party printer
Jira: 5244

Change-Id: Idd829c9d99eeba9d180653ac8de4e51b9a0d6370

* FIX: The maximum value is not printed in PA line mode

Jira: 5046  4951
Change-Id: Ic81f9a75ce7f088fe950fdde283ff5c942cd6e83

* ENH:add preset check for sending files

Change-Id: Ia3313d281b5ce91e277b380498014ffdac5debd3

* ci: update build version to 01.08.01.55

Change-Id: Ia839344d01a43f7159f376d4147337575c4edbe1

* FIX: locale loading user preset

Change-Id: I88521e4b10cb802d9253eb79a6b78b3286f15a33
Jira: STUDIO-5436

* FIX: sync user preset notify crash on exit

Change-Id: I88f5dbcbd487293ea847ea6092efb61744399541
Jira: STUDIO-5413

* ci: update build version to 01.08.01.56

Change-Id: Id7a9718d5f920da50d52fd2ef220acf5d3270d3c

* GUI/Field: Fix crash in color picker init (#2220)

wxButton->GetBitmap() may return an invalid wxBitmap.
Guard against this.

* FIX: custom filament preset display in cali history issue

jira: new

Change-Id: I4145450a231adff542ab1a7428b3479f4074e06a

* FIX: meshboolean transform result issue

jira: STUDIO-5425

Change-Id: If66fe909ce4458c1b3192e4fd8a3d758fe7c7eaa

* FIX: fix combobox and delete btn in filament setting enabled

Jira: XXXX

Change-Id: I8b659bd77ceb97c8cea9d3e5e931f4ea50822721

* ci: update build version to 01.08.01.57

Change-Id: I7a6f5439863ca81275ae8b80f1b5cf0bb36c4c0f

* unix: Use canonical mime-type for 3MF files

model/3mf is the canonical mime-type, but keep the
application/vnd.ms-3mfdocument alias.

See for details:
https://gitlab.freedesktop.org/xdg/shared-mime-info/-/merge_requests/179

* FIX: fix the compiling issue under windows

github: https://github.com/bambulab/BambuStudio/issues/3028
Change-Id: Iafde9d2086c0cd31aa12e39cef7ded1e19e9d3e7

* add: K1 and K1Max Support

* fix: Optimized STL and PNG for plates K1 & K1Max

* fix: simple version of models

* FIX: Close scan_first_layer when PA line cali

Jira: XXXX
Change-Id: Ide5c0038f4028b8f1d445a6b2d09b705d7872fb8

* FIX: CLI: fix the wipe tower disappear issue

JIRA: no jira
Change-Id: I547a8468b0bea06912d5d9ceee1c8deead85e28f

* FIX: the preset is the same with the first one when switching printers

Jira: STUDIO-5433

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: Icf1979f2bcffbc9c59a072924df5073fc3eac363

* FIX: [5504] Optimization description

Jira: 5540

Change-Id: I9379f2c69b6724ec1ef5294dd3c404b0e3189486

* FIX: [5451]Directly crash when memory is low

Jira: 5451

Change-Id: I5c75994e2bd556bec7ce8de6be44888e6924ff56

* ci: update build version to 01.08.01.58

Change-Id: I12b1e3ca6b07ed13f3ad42ab2f40b825cb84a8dc

* ENH: CLI: refine some logic

1. set wipe tower position to default when duplicate object
2. add cli_safe check logic when switch printers

JIRA: no jira
Change-Id: Iebe62f8be6acd6f44743abf3b0fe92ec04c94197

* ENH: CLI: allow height shrink when printer switch

to let the error generated at validate
JIRA: no jira

Change-Id: I94db90db858659a9254dfdc0a6eed04fd40d3768

* ENH: add support for A1

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I5dfd8f3b6b872c01d8093527df1a3c37b8a0d56d

* ENH: refine description of interface not for base

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ibe11e845b90ef2caf96d5780eaaf8764755cce1d

* ENH: version: bumped to 1.8.2

Change-Id: Ic9acb5607ec94188112999afa41f2052281a08f1

* ENH: update some machine settings

1. Update A1 mini start  gcode
2. Update A1 load/unload filament time

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I84825a47f2741e95ca122382e4119d35a61bdbf6

* ENH: support for head wrap detect

1.Add "in_head_wrap_detect_zone".Detect if the model projection enters
a specified area.

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I6aed5a782d2f33f023bdc19cf06dff0957828eeb

* ENH: modify default head detect zone

1. Set default head detect to empty

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I686c4c3115041471bc016cf3b0972ed730af64d3

* ENH: change head wrap detect zone

Change to (156,156)-(180,180)

jira:[new]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I7b9dec3fbf44d31311fd7eb331e52f307f45ede1

* FIX:backup iterator location

Jira: STUDIO-5267
Change-Id: Id035c9225a858bb551aa4f09870fc4c6bb30b255

* NEW:compatible with p1p (plus)

jira:[p1p]

Change-Id: I7b30903dc0a728604c4f33c325aa79fd3bd08f68

* NEW:installed & supported p1p(plus)

jira:[pip plus]

Change-Id: I0a69f8629749e3076465b85f28aa39d5e7ae6277

* ENH: modify default head wrap detect zone

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I39ccc810a19192919a21b5608d3fa2a806c787ee

* FIX: excpetion when plate center is negative

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ia1066bd7457181711d0a59b9544d65ed502410e0

* FIX: big window's scaling causes incomplete display

Jira: STUDIO-5530
Change-Id: I1d69e60658e49e43d4b3de718f2fd6739bab73ce

* ENH: update: remove the comment which is not used when updating preset

JIRA: no jira
Change-Id: Ic930eea50a7beb78aa6dc7c53fbb5c366857e825
(cherry picked from commit e0225fc147702cf73e6eda4830a2592c7598901c)

* FIX: wrong initial layer height in profile

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I91f1779761a13f70d68ad51041b7f75ef872c138

* NEW:add N2S picture and printers

JIRA: XXXX
Change-Id: Id8eddd9fafd07c967abfb1543c1b01ad8c0e1b0c

* ENH: rearrange machine pos on printer selection page

Signed-off-by: qing.zhang <qing.zhang@bambulab.com>
Change-Id: Iccc52043c232d19384487884e4071343744976a9

* ci: update build version to 01.08.02.51

Change-Id: I1985730c4ea29528a6f9b03f56c73131a07779b0

* ENH: some translations

Jira: STUDIO-5434

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: Ie6868728edfc40bd1d20dec6a78d8e5ea7f8edf8

* ENH: do not cancel printing job when timeout

JIRA: STUDIO-5009

Change-Id: I067470173acc26d7ecd8ceb6f0e04ac7f03e3a4d
Signed-off-by: Stone Li <stone.li@bambulab.com>
(cherry picked from commit 7ab5817c7229c5179adca026ffacb97c2affd292)

* ENH: udpate A1 series gcode

1. Update A1 mini change layer gcode
2. Update A1 start gcode

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I131676a991f4727bca1ea2fa727f40f293d06139

* ENH:After cutting,fix non manifold edges needed confirmed by user

Jira: STUDIO-5217
Change-Id: I52ba0db27ebe0b7b763c49311c7aa305bc4dcd5a

* ENH: linux: refine the d-bus name

github: #3075
Change-Id: Icf997f4f9203f4d429e3b6058d6d6e5f23bf29ac
(cherry picked from commit 5c766bff445cefee488ba9d057121b04c8e1445d)

* NEW:add "bed type to follow machine preset" function

Jira: STUDIO-5535
Change-Id: I2ef99a0a783a074d9379685adde11fddfd6f8cec

* NEW:add "default_bed_type"

Jira: STUDIO-5535
Change-Id: Ice1262937923b62854b0196229d5fb99392470af

* ENH:comment out two line code

Jira: STUDIO-5535
Change-Id: I5475e4f9ec6fb7e4abdb3d950da34fadead3b606

* ENH:translate three texts

Jira: STUDIO-5535
Change-Id: I00938567f0ae30bb354042769021451364bef308

* FIX: incorrect flag in A1 mini gcode

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: If587678bf0aa06c079a9d3cbff9f2c7628c5e380

* ci: update build version to 01.08.02.52

Change-Id: I2d8310b7321fefcb742d4cdbe5e4bc9a035ec45a

* FIX: Allow vendors that are not entirely numerical

github: #3082

Change-Id: I318f4df7f65c934ab6703e0970d775b754b24276

* ENH: update A1 series first layer speed

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I597bcf86f202f681eccfda4306be5619d669ea5a

* FIX: CLI: fix the wipe tower issue while mapping to one filament

JIRA: STUDIO-5550
Change-Id: I0b8d3af09d16bdfc45cdc5951d182f7e33dc9b93

* FIX: crash when support type and style are inconsistent

jira: STUDIO-5428
Change-Id: Ib1e79c71736810099e15282c30524e55e8f60f34
(cherry picked from commit aefb7fbaf25146c03bd2eb336f58ed2eb0e83ea6)

* NEW:display beta version

JIRA: XXXX
Change-Id: I78d748e53b266c3397b1c038c3425a52c573cc88

* FIX: slice error: WipeTowerIntegration::append_tcr

when print by object with multi-color
Jira: XXXX

Change-Id: Ic9ee2f6de45abb4a118fdb4cf89dea9ca7335094

* ci: update build version to 01.08.02.53

Change-Id: I980bff783b59fc6e9d6fd12a016c2daa2840991f

* FIX: remove duplicated profiles

jira:[NEW]

Signed-off-by: XunZhangBambu <xun.zhang@bambulab.com>
Change-Id: Iaa87233ae6c327faf43a152bdb0cd6fa8c5131d7

* FIX: translation: vendor can not be number

Jira: XXXX

Change-Id: I7bd45de944e8b25b30c88ab742b35d996c933966

* ci: update build version to 01.08.02.54

Change-Id: Ib83b131c533a03d6e48e9ded5e6f9ba574819756

* ENH: update A1 extruder clearance radius

jira:[NEW]

Signed-off-by: XunZhangBambu <xun.zhang@bambulab.com>
Change-Id: I13cfb882c672083dcd1af2c1be448c5422fdbc0a

* ci: update build version to 01.08.02.55

Change-Id: I8d7016d27166b457e4cdc198b61e6aa36a72b8c1

* FIX: bed_type not follow machine preset

Jira: STUDIO-5578
when direct open project from https://makerworld.com/

Change-Id: I3281cf45e3057d766008487975b4585d2e277110

* ci: update build version to 01.08.02.56

Change-Id: I43cadeeb1a2fa150fa9396a63b9bc471da1500d5

* update strings

* autofix mesh after cut

---------

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>
Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Signed-off-by: Stone Li <stone.li@bambulab.com>
Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Signed-off-by: zhou.xu <zhou.xu@bambulab.com>
Signed-off-by: qing.zhang <qing.zhang@bambulab.com>
Signed-off-by: XunZhangBambu <xun.zhang@bambulab.com>
Co-authored-by: chunmao.guo <chunmao.guo@bambulab.com>
Co-authored-by: zorro.zhang <zorro.zhang@bambulab.com>
Co-authored-by: hu.wang <hu.wang@bambulab.com>
Co-authored-by: liz.li <liz.li@bambulab.com>
Co-authored-by: Kunlong Ma <kunlong.ma@bambulab.com>
Co-authored-by: maosheng.wei <maosheng.wei@bambulab.com>
Co-authored-by: gerrit <gerrit@bambulab.com>
Co-authored-by: tao wang <tao.wang@bambulab.com>
Co-authored-by: zhou.xu <zhou.xu@bambulab.com>
Co-authored-by: xun.zhang <xun.zhang@bambulab.com>
Co-authored-by: the Raz <rasmus@abc.se>
Co-authored-by: Andy <andylg@yandex.ru>
Co-authored-by: lane.wei <lane.wei@bambulab.com>
Co-authored-by: Arthur <arthur.tang@bambulab.com>
Co-authored-by: Stone Li <stone.li@bambulab.com>
Co-authored-by: enricoturri1966 <enricoturri@seznam.cz>
Co-authored-by: wenjie.guo <wenjie.guo@bambulab.com>
Co-authored-by: zhimin.zeng <zhimin.zeng@bambulab.com>
Co-authored-by: Dmytro Chystiakov <dlchistyakov@gmail.com>
Co-authored-by: mia <652892+mia-0@users.noreply.github.com>
Co-authored-by: Bastien Nocera <hadess@hadess.net>
Co-authored-by: qing.zhang <qing.zhang@bambulab.com>
2023-12-19 23:46:19 +08:00

2559 lines
125 KiB
C++

///|/ Copyright (c) Prusa Research 2021 - 2023 Vojtěch Bubník @bubnikv, Lukáš Matěna @lukasmatena, Pavel Mikuš @Godrak, Lukáš Hejl @hejllukas
///|/
///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher
///|/
#include "ClipperUtils.hpp"
#include "Geometry.hpp"
#include "Tesselate.hpp"
#include "TriangleMesh.hpp"
#include "TriangleMeshSlicer.hpp"
#include "Utils.hpp"
// BBS
#include "MeshBoolean.hpp"
#include <algorithm>
#include <cmath>
#include <deque>
#include <queue>
#include <mutex>
#include <utility>
#include <boost/log/trivial.hpp>
#include <tbb/parallel_for.h>
#ifndef NDEBUG
// #define EXPENSIVE_DEBUG_CHECKS
#endif // NDEBUG
#if 0
#define DEBUG
#define _DEBUG
#undef NDEBUG
#define SLIC3R_DEBUG
// #define SLIC3R_TRIANGLEMESH_DEBUG
#endif
#include <assert.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
// #define SLIC3R_DEBUG_SLICE_PROCESSING
#if defined(SLIC3R_DEBUG) || defined(SLIC3R_DEBUG_SLICE_PROCESSING)
#include "SVG.hpp"
#endif
namespace Slic3r {
const float epson = 1e-3;
bool is_equal(float lh, float rh)
{
return abs(lh - rh) <= epson;
}
bool is_equal_for_sort(float lh, float rh) {
return abs(lh - rh) <= 1e-8;
}
bool is_equal(const Vec3f &lh, const Vec3f &rh) {
return is_equal(lh[0], rh[0]) && is_equal(lh[1], rh[1]) && is_equal(lh[2], rh[2]);
}
class IntersectionReference
{
public:
IntersectionReference() = default;
IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {}
// Where is this intersection point located? On mesh vertex or mesh edge?
// Only one of the following will be set, the other will remain set to -1.
// Index of the mesh vertex.
int point_id { -1 };
// Index of the mesh edge.
int edge_id { -1 };
};
class IntersectionPoint : public Point, public IntersectionReference
{
public:
IntersectionPoint() = default;
IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {}
IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {}
// Inherits coord_t x, y
};
class IntersectionLine : public Line
{
public:
IntersectionLine() = default;
bool skip() const { return (this->flags & SKIP) != 0; }
void set_skip() { this->flags |= SKIP; }
bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); }
void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; }
void reverse() { std::swap(a, b); std::swap(a_id, b_id); std::swap(edge_a_id, edge_b_id); }
// Inherits Point a, b
// For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1.
// Vertex indices of the line end points.
int a_id { -1 };
int b_id { -1 };
// Source mesh edges of the line end points.
int edge_a_id { -1 };
int edge_b_id { -1 };
enum class FacetEdgeType {
// A general case, the cutting plane intersect a face at two different edges.
General,
// Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane.
Top,
// Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane.
Bottom,
// Two vertices are aligned with the cutting plane, the edge is shared by two triangles, where one
// triangle is below or at the cutting plane and the other is above or at the cutting plane (only one
// vertex may lie on the plane).
TopBottom,
// All three vertices of a face are aligned with the cutting plane.
Horizontal,
// Edge
Slab,
};
// feGeneral, feTop, feBottom, feHorizontal
FacetEdgeType edge_type { FacetEdgeType::General };
// Used to skip duplicate edges.
enum {
// Triangle edge added, because it has no neighbor.
EDGE0_NO_NEIGHBOR = 0x001,
EDGE1_NO_NEIGHBOR = 0x002,
EDGE2_NO_NEIGHBOR = 0x004,
// Triangle edge added, because it makes a fold with another horizontal edge.
EDGE0_FOLD = 0x010,
EDGE1_FOLD = 0x020,
EDGE2_FOLD = 0x040,
// The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds).
NO_SEED = 0x100,
SKIP = 0x200,
};
uint32_t flags { 0 };
#ifndef NDEBUG
enum class Source {
BottomPlane,
TopPlane,
Slab,
};
Source source { Source::BottomPlane };
#endif // NDEBUG
};
using IntersectionLines = std::vector<IntersectionLine>;
enum class FacetSliceType {
NoSlice = 0,
Slicing = 1,
Cutting = 2
};
// Return true, if the facet has been sliced and line_out has been filled.
static FacetSliceType slice_facet(
// Z height of the slice in XY plane. Scaled or unscaled (same as vertices[].z()).
float slice_z,
// 3 vertices of the triangle, XY scaled. Z scaled or unscaled (same as slice_z).
const stl_vertex *vertices,
const stl_triangle_vertex_indices &indices,
const Vec3i &edge_ids,
const int idx_vertex_lowest,
const bool horizontal,
IntersectionLine &line_out)
{
IntersectionPoint points[3];
size_t num_points = 0;
auto point_on_layer = size_t(-1);
// Reorder vertices so that the first one is the one with lowest Z.
// This is needed to get all intersection lines in a consistent order
// (external on the right of the line)
for (int j = 0; j < 3; ++ j) { // loop through facet edges
int edge_id;
const stl_vertex *a, *b, *c;
int a_id, b_id;
{
int k = (idx_vertex_lowest + j) % 3;
int l = (k + 1) % 3;
edge_id = edge_ids(k);
a_id = indices[k];
a = vertices + k;
b_id = indices[l];
b = vertices + l;
c = vertices + (k + 2) % 3;
}
// Is edge or face aligned with the cutting plane?
if (a->z() == slice_z && b->z() == slice_z) {
// Edge is horizontal and belongs to the current layer.
// The following rotation of the three vertices may not be efficient, but this branch happens rarely.
const stl_vertex &v0 = vertices[0];
const stl_vertex &v1 = vertices[1];
const stl_vertex &v2 = vertices[2];
// We may ignore this edge for slicing purposes, but we may still use it for object cutting.
FacetSliceType result = FacetSliceType::Slicing;
if (horizontal) {
// All three vertices are aligned with slice_z.
line_out.edge_type = IntersectionLine::FacetEdgeType::Horizontal;
result = FacetSliceType::Cutting;
double normal = (v1.x() - v0.x()) * (v2.y() - v1.y()) - (v1.y() - v0.y()) * (v2.x() - v1.x());
if (normal < 0) {
// If normal points downwards this is a bottom horizontal facet so we reverse its point order.
std::swap(a, b);
std::swap(a_id, b_id);
}
} else {
// Two vertices are aligned with the cutting plane, the third vertex is below or above the cutting plane.
// Is the third vertex below the cutting plane?
bool third_below = v0.z() < slice_z || v1.z() < slice_z || v2.z() < slice_z;
// Two vertices on the cutting plane, the third vertex is below the plane. Consider the edge to be part of the slice
// only if it is the upper edge.
// (the bottom most edge resp. vertex of a triangle is not owned by the triangle, but the top most edge resp. vertex is part of the triangle
// in respect to the cutting plane).
result = third_below ? FacetSliceType::Slicing : FacetSliceType::Cutting;
if (third_below) {
line_out.edge_type = IntersectionLine::FacetEdgeType::Top;
std::swap(a, b);
std::swap(a_id, b_id);
} else
line_out.edge_type = IntersectionLine::FacetEdgeType::Bottom;
}
line_out.a.x() = a->x();
line_out.a.y() = a->y();
line_out.b.x() = b->x();
line_out.b.y() = b->y();
line_out.a_id = a_id;
line_out.b_id = b_id;
assert(line_out.a != line_out.b);
return result;
}
if (a->z() == slice_z) {
// Only point a alings with the cutting plane.
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != a_id) {
point_on_layer = num_points;
IntersectionPoint &point = points[num_points ++];
point.x() = a->x();
point.y() = a->y();
point.point_id = a_id;
}
} else if (b->z() == slice_z) {
// Only point b alings with the cutting plane.
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != b_id) {
point_on_layer = num_points;
IntersectionPoint &point = points[num_points ++];
point.x() = b->x();
point.y() = b->y();
point.point_id = b_id;
}
} else if ((a->z() < slice_z && b->z() > slice_z) || (b->z() < slice_z && a->z() > slice_z)) {
// A general case. The face edge intersects the cutting plane. Calculate the intersection point.
assert(a_id != b_id);
// Sort the edge to give a consistent answer.
if (a_id > b_id) {
std::swap(a_id, b_id);
std::swap(a, b);
}
IntersectionPoint &point = points[num_points];
double t = (double(slice_z) - double(b->z())) / (double(a->z()) - double(b->z()));
if (t <= 0.) {
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != a_id) {
point.x() = a->x();
point.y() = a->y();
point_on_layer = num_points ++;
point.point_id = a_id;
}
} else if (t >= 1.) {
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != b_id) {
point.x() = b->x();
point.y() = b->y();
point_on_layer = num_points ++;
point.point_id = b_id;
}
} else {
point.x() = coord_t(floor(double(b->x()) + (double(a->x()) - double(b->x())) * t + 0.5));
point.y() = coord_t(floor(double(b->y()) + (double(a->y()) - double(b->y())) * t + 0.5));
point.edge_id = edge_id;
++ num_points;
}
}
}
// Facets must intersect each plane 0 or 2 times, or it may touch the plane at a single vertex only.
assert(num_points < 3);
if (num_points == 2) {
line_out.edge_type = IntersectionLine::FacetEdgeType::General;
line_out.a = static_cast<const Point&>(points[1]);
line_out.b = static_cast<const Point&>(points[0]);
line_out.a_id = points[1].point_id;
line_out.b_id = points[0].point_id;
line_out.edge_a_id = points[1].edge_id;
line_out.edge_b_id = points[0].edge_id;
// Not a zero lenght edge.
//FIXME slice_facet() may create zero length edges due to rounding of doubles into coord_t.
//assert(line_out.a != line_out.b);
// The plane cuts at least one edge in a general position.
assert(line_out.a_id == -1 || line_out.b_id == -1);
assert(line_out.edge_a_id != -1 || line_out.edge_b_id != -1);
// General slicing position, use the segment for both slicing and object cutting.
#if 0
if (line_out.a_id != -1 && line_out.b_id != -1) {
// Solving a degenerate case, where both the intersections snapped to an edge.
// Correctly classify the face as below or above based on the position of the 3rd point.
int i = indices[0];
if (i == line_out.a_id || i == line_out.b_id)
i = indices[1];
if (i == line_out.a_id || i == line_out.b_id)
i = indices[2];
assert(i != line_out.a_id && i != line_out.b_id);
line_out.edge_type = ((m_use_quaternion ?
(m_quaternion * this->v_scaled_shared[i]).z()
: this->v_scaled_shared[i].z()) < slice_z) ? IntersectionLine::FacetEdgeType::Top : IntersectionLine::FacetEdgeType::Bottom;
}
#endif
return FacetSliceType::Slicing;
}
return FacetSliceType::NoSlice;
}
// Return true, if the facet has been sliced and line_out has been filled.
static FacetSliceType slice_facet_for_cut_mesh(
// Z height of the slice in XY plane. Scaled or unscaled (same as vertices[].z()).
float slice_z,
// 3 vertices of the triangle, XY scaled. Z scaled or unscaled (same as slice_z).
const stl_vertex * vertices,
const stl_triangle_vertex_indices &indices,
const Vec3i & edge_ids,
const int idx_vertex_lowest,
const bool horizontal,
IntersectionLine & line_out)
{
IntersectionPoint points[3];
size_t num_points = 0;
auto point_on_layer = size_t(-1);
// Reorder vertices so that the first one is the one with lowest Z.
// This is needed to get all intersection lines in a consistent order
// (external on the right of the line)
for (int j = 0; j < 3; ++j) { // loop through facet edges
int edge_id;
const stl_vertex *a, *b, *c;
int a_id, b_id;
{
int k = (idx_vertex_lowest + j) % 3;
int l = (k + 1) % 3;
edge_id = edge_ids(k);
a_id = indices[k];
a = vertices + k;
b_id = indices[l];
b = vertices + l;
c = vertices + (k + 2) % 3;
}
// Is edge or face aligned with the cutting plane?
if (is_equal(a->z(), slice_z) && is_equal(b->z(), slice_z)) {
// Edge is horizontal and belongs to the current layer.
// The following rotation of the three vertices may not be efficient, but this branch happens rarely.
const stl_vertex &v0 = vertices[0];
const stl_vertex &v1 = vertices[1];
const stl_vertex &v2 = vertices[2];
// We may ignore this edge for slicing purposes, but we may still use it for object cutting.
FacetSliceType result = FacetSliceType::Slicing;
if (horizontal) {
// All three vertices are aligned with slice_z.
line_out.edge_type = IntersectionLine::FacetEdgeType::Horizontal;
result = FacetSliceType::Cutting;
double normal = (v1.x() - v0.x()) * (v2.y() - v1.y()) - (v1.y() - v0.y()) * (v2.x() - v1.x());
if (normal < 0) {
// If normal points downwards this is a bottom horizontal facet so we reverse its point order.
std::swap(a, b);
std::swap(a_id, b_id);
}
} else {
// Two vertices are aligned with the cutting plane, the third vertex is below or above the cutting plane.
// Is the third vertex below the cutting plane?
bool third_below = c->z() < slice_z;
// Two vertices on the cutting plane, the third vertex is below the plane. Consider the edge to be part of the slice
// only if it is the upper edge.
// (the bottom most edge resp. vertex of a triangle is not owned by the triangle, but the top most edge resp. vertex is part of the triangle
// in respect to the cutting plane).
result = third_below ? FacetSliceType::Slicing : FacetSliceType::Cutting;
if (third_below) {
line_out.edge_type = IntersectionLine::FacetEdgeType::Top;
std::swap(a, b);
std::swap(a_id, b_id);
} else
line_out.edge_type = IntersectionLine::FacetEdgeType::Bottom;
}
line_out.a.x() = a->x();
line_out.a.y() = a->y();
line_out.b.x() = b->x();
line_out.b.y() = b->y();
line_out.a_id = a_id;
line_out.b_id = b_id;
assert(line_out.a != line_out.b);
return result;
}
if (is_equal(a->z(), slice_z)) {
// Only point a alings with the cutting plane.
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != a_id) {
point_on_layer = num_points;
IntersectionPoint &point = points[num_points++];
point.x() = a->x();
point.y() = a->y();
point.point_id = a_id;
}
} else if (is_equal(b->z(), slice_z)) {
// Only point b alings with the cutting plane.
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != b_id) {
point_on_layer = num_points;
IntersectionPoint &point = points[num_points++];
point.x() = b->x();
point.y() = b->y();
point.point_id = b_id;
}
} else if ((a->z() < slice_z && b->z() > slice_z) || (b->z() < slice_z && a->z() > slice_z)) {
// A general case. The face edge intersects the cutting plane. Calculate the intersection point.
assert(a_id != b_id);
// Sort the edge to give a consistent answer.
if (a_id > b_id) {
std::swap(a_id, b_id);
std::swap(a, b);
}
IntersectionPoint &point = points[num_points];
double t = (double(slice_z) - double(b->z())) / (double(a->z()) - double(b->z()));
if (t <= 0.) {
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != a_id) {
point.x() = a->x();
point.y() = a->y();
point_on_layer = num_points++;
point.point_id = a_id;
}
} else if (t >= 1.) {
if (point_on_layer == size_t(-1) || points[point_on_layer].point_id != b_id) {
point.x() = b->x();
point.y() = b->y();
point_on_layer = num_points++;
point.point_id = b_id;
}
} else {
point.x() = coord_t(floor(double(b->x()) + (double(a->x()) - double(b->x())) * t + 0.5));
point.y() = coord_t(floor(double(b->y()) + (double(a->y()) - double(b->y())) * t + 0.5));
point.edge_id = edge_id;
++num_points;
}
}
}
// Facets must intersect each plane 0 or 2 times, or it may touch the plane at a single vertex only.
assert(num_points < 3);
if (num_points == 2) {
line_out.edge_type = IntersectionLine::FacetEdgeType::General;
line_out.a = static_cast<const Point &>(points[1]);
line_out.b = static_cast<const Point &>(points[0]);
line_out.a_id = points[1].point_id;
line_out.b_id = points[0].point_id;
line_out.edge_a_id = points[1].edge_id;
line_out.edge_b_id = points[0].edge_id;
// Not a zero lenght edge.
// FIXME slice_facet() may create zero length edges due to rounding of doubles into coord_t.
// assert(line_out.a != line_out.b);
// The plane cuts at least one edge in a general position.
assert(line_out.a_id == -1 || line_out.b_id == -1);
assert(line_out.edge_a_id != -1 || line_out.edge_b_id != -1);
// General slicing position, use the segment for both slicing and object cutting.
return FacetSliceType::Slicing;
}
return FacetSliceType::NoSlice;
}
template<typename TransformVertex>
void slice_facet_at_zs(
// Scaled or unscaled vertices. transform_vertex_fn may scale zs.
const std::vector<Vec3f> &mesh_vertices,
const TransformVertex &transform_vertex_fn,
const stl_triangle_vertex_indices &indices,
const Vec3i &edge_ids,
// Scaled or unscaled zs. If vertices have their zs scaled or transform_vertex_fn scales them, then zs have to be scaled as well.
const std::vector<float> &zs,
std::vector<IntersectionLines> &lines,
std::array<std::mutex, 64> &lines_mutex)
{
stl_vertex vertices[3] { transform_vertex_fn(mesh_vertices[indices(0)]), transform_vertex_fn(mesh_vertices[indices(1)]), transform_vertex_fn(mesh_vertices[indices(2)]) };
// find facet extents
const float min_z = fminf(vertices[0].z(), fminf(vertices[1].z(), vertices[2].z()));
const float max_z = fmaxf(vertices[0].z(), fmaxf(vertices[1].z(), vertices[2].z()));
// find layer extents
auto min_layer = std::lower_bound(zs.begin(), zs.end(), min_z); // first layer whose slice_z is >= min_z
auto max_layer = std::upper_bound(min_layer, zs.end(), max_z); // first layer whose slice_z is > max_z
int idx_vertex_lowest = (vertices[1].z() == min_z) ? 1 : ((vertices[2].z() == min_z) ? 2 : 0);
for (auto it = min_layer; it != max_layer; ++ it) {
IntersectionLine il;
// Ignore horizontal triangles. Any valid horizontal triangle must have a vertical triangle connected, otherwise the part has zero volume.
if (min_z != max_z && slice_facet(*it, vertices, indices, edge_ids, idx_vertex_lowest, false, il) == FacetSliceType::Slicing) {
assert(il.edge_type != IntersectionLine::FacetEdgeType::Horizontal);
size_t slice_id = it - zs.begin();
boost::lock_guard<std::mutex> l(lines_mutex[slice_id % lines_mutex.size()]);
lines[slice_id].emplace_back(il);
}
}
}
template<typename TransformVertex, typename ThrowOnCancel>
static inline std::vector<IntersectionLines> slice_make_lines(
const std::vector<stl_vertex> &vertices,
const TransformVertex &transform_vertex_fn,
const std::vector<stl_triangle_vertex_indices> &indices,
const std::vector<Vec3i> &face_edge_ids,
const std::vector<float> &zs,
const ThrowOnCancel throw_on_cancel_fn)
{
std::vector<IntersectionLines> lines(zs.size(), IntersectionLines());
std::array<std::mutex, 64> lines_mutex;
tbb::parallel_for(
tbb::blocked_range<int>(0, int(indices.size())),
[&vertices, &transform_vertex_fn, &indices, &face_edge_ids, &zs, &lines, &lines_mutex, throw_on_cancel_fn](const tbb::blocked_range<int> &range) {
for (int face_idx = range.begin(); face_idx < range.end(); ++ face_idx) {
if ((face_idx & 0x0ffff) == 0)
throw_on_cancel_fn();
slice_facet_at_zs(vertices, transform_vertex_fn, indices[face_idx], face_edge_ids[face_idx], zs, lines, lines_mutex);
}
}
);
return lines;
}
template<typename TransformVertex, typename FaceFilter>
static inline IntersectionLines slice_make_lines(
const std::vector<stl_vertex> &mesh_vertices,
const TransformVertex &transform_vertex_fn,
const std::vector<stl_triangle_vertex_indices> &mesh_faces,
const std::vector<Vec3i> &face_edge_ids,
const float plane_z,
FaceFilter face_filter)
{
IntersectionLines lines;
for (int face_idx = 0; face_idx < int(mesh_faces.size()); ++ face_idx)
if (face_filter(face_idx)) {
const Vec3i &indices = mesh_faces[face_idx];
stl_vertex vertices[3] { transform_vertex_fn(mesh_vertices[indices(0)]), transform_vertex_fn(mesh_vertices[indices(1)]), transform_vertex_fn(mesh_vertices[indices(2)]) };
// find facet extents
const float min_z = fminf(vertices[0].z(), fminf(vertices[1].z(), vertices[2].z()));
const float max_z = fmaxf(vertices[0].z(), fmaxf(vertices[1].z(), vertices[2].z()));
assert(min_z <= plane_z && max_z >= plane_z);
int idx_vertex_lowest = (vertices[1].z() == min_z) ? 1 : ((vertices[2].z() == min_z) ? 2 : 0);
IntersectionLine il;
// Ignore horizontal triangles. Any valid horizontal triangle must have a vertical triangle connected, otherwise the part has zero volume.
if (min_z != max_z && slice_facet(plane_z, vertices, indices, face_edge_ids[face_idx], idx_vertex_lowest, false, il) == FacetSliceType::Slicing) {
assert(il.edge_type != IntersectionLine::FacetEdgeType::Horizontal);
lines.emplace_back(il);
}
}
return lines;
}
// For projecting triangle sets onto slice slabs.
struct SlabLines {
// Intersection lines of a slice with a triangle set, CCW oriented.
std::vector<IntersectionLines> at_slice;
// Projections of triangle set boundary lines into layer below (for projection from the top)
// or into layer above (for projection from the bottom).
// In both cases the intersection lines are CCW oriented.
std::vector<IntersectionLines> between_slices;
};
// Orientation of the face normal in regard to a XY plane pointing upwards.
enum class FaceOrientation : char {
// Z component of the normal is positive.
Up,
// Z component of the normal is negative.
Down,
// Z component of the normal is zero.
Vertical,
// Triangle is degenerate, thus its normal is undefined. We may want to slice the degenerate triangles
// because of the connectivity information they carry.
Degenerate
};
template<bool ProjectionFromTop>
void slice_facet_with_slabs(
// Scaled or unscaled vertices. transform_vertex_fn may scale zs.
const std::vector<Vec3f> &mesh_vertices,
const std::vector<stl_triangle_vertex_indices> &mesh_triangles,
const size_t facet_idx,
const Vec3i &facet_neighbors,
const Vec3i &facet_edge_ids,
// Increase edge_ids at the top plane of the slab edges by num_edges to allow chaining
// from bottom plane of the slab to the top plane of the slab and vice versa.
const int num_edges,
const std::vector<float> &zs,
SlabLines &lines,
std::array<std::mutex, 64> &lines_mutex)
{
const stl_triangle_vertex_indices &indices = mesh_triangles[facet_idx];
stl_vertex vertices[3] { mesh_vertices[indices(0)], mesh_vertices[indices(1)], mesh_vertices[indices(2)] };
// find facet extents
const float min_z = fminf(vertices[0].z(), fminf(vertices[1].z(), vertices[2].z()));
const float max_z = fmaxf(vertices[0].z(), fmaxf(vertices[1].z(), vertices[2].z()));
const bool horizontal = min_z == max_z;
// find layer extents
auto min_layer = std::lower_bound(zs.begin(), zs.end(), min_z); // first layer whose slice_z is >= min_z
auto max_layer = std::upper_bound(min_layer, zs.end(), max_z); // first layer whose slice_z is > max_z
assert(min_layer == zs.end() ? max_layer == zs.end() : *min_layer >= min_z);
assert(max_layer == zs.end() || *max_layer > max_z);
auto emit_slab_edge = [&lines, &lines_mutex](IntersectionLine il, size_t slab_id, bool reverse) {
if (reverse)
il.reverse();
boost::lock_guard<std::mutex> l(lines_mutex[(slab_id + lines_mutex.size() / 2) % lines_mutex.size()]);
lines.between_slices[slab_id].emplace_back(il);
};
if (min_layer == max_layer || horizontal) {
// Horizontal face or a nearly horizontal face that fits between two layers or below the bottom most or above the top most layer.
assert(horizontal || zs.empty() || max_z < zs.front() || min_z > zs.back() ||
(min_layer == max_layer && min_layer != zs.end() && min_layer != zs.begin() && *(min_layer - 1) < min_z && *min_layer > max_z));
if (horizontal && min_layer != zs.end() && *min_layer == min_z) {
// Slicing a horizontal triangle with a slicing plane. The triangle has to be upwards facing for ProjectionFromTop
// and downwards facing for ! ProjectionFromTop.
assert(min_layer != max_layer);
// Slicing plane with which the triangle is coplanar.
size_t slice_id = min_layer - zs.begin();
#if 0
// Project the coplanar bottom facing triangles to their slicing plane for both top and bottom facing surfaces.
// This behavior is different from slice_mesh() / slice_mesh_ex(), which do not slice bottom facing faces exactly on slicing plane.
size_t line_id = slice_id;
#else
// Project the coplanar bottom facing triangles to the plane above the slicing plane to match the behavior of slice_mesh() / slice_mesh_ex(),
// where the slicing plane slices the top facing surfaces, but misses the bottom facing surfaces.
if (size_t line_id = ProjectionFromTop ? slice_id : slice_id + 1; ProjectionFromTop || line_id < lines.at_slice.size())
#endif
for (int iedge = 0; iedge < 3; ++ iedge)
if (facet_neighbors(iedge) == -1) {
int i = iedge;
int j = next_idx_modulo(i, 3);
assert(vertices[i].z() == zs[slice_id]);
assert(vertices[j].z() == zs[slice_id]);
IntersectionLine il {
{ to_2d(vertices[i]).cast<coord_t>(), to_2d(vertices[j]).cast<coord_t>() },
indices(i), indices(j), -1, -1,
ProjectionFromTop ? IntersectionLine::FacetEdgeType::Bottom : IntersectionLine::FacetEdgeType::Top
};
// Don't flip the FacetEdgeType::Top edge, it will be flipped when chaining.
// if (! ProjectionFromTop) il.reverse();
boost::lock_guard<std::mutex> l(lines_mutex[line_id % lines_mutex.size()]);
lines.at_slice[line_id].emplace_back(il);
}
} else {
// Triangle is completely between two slicing planes, the triangle may or may not be horizontal, which
// does not matter for the processing of such a triangle.
size_t slab_id;
if (ProjectionFromTop) {
if (max_layer == zs.begin()) {
// Not slicing the triangle and it is below the lowest layer.
return;
} else {
// Not slicing the triangle and it could be projected into a slab.
slab_id = max_layer - zs.begin();
}
} else {
// projection from bottom
if (min_layer == zs.end()) {
// Not slicing the triangle and it is above the highest layer.
return;
} else {
// Not slicing the triangle and it could be projected into a slab.
slab_id = min_layer - zs.begin();
}
}
if (ProjectionFromTop)
-- slab_id;
for (int iedge = 0; iedge < 3; ++ iedge)
if (facet_neighbors(iedge) == -1) {
int i = iedge;
int j = next_idx_modulo(i, 3);
assert(ProjectionFromTop ? vertices[i].z() >= zs[slab_id] : vertices[i].z() <= zs[slab_id]);
assert(ProjectionFromTop ? vertices[j].z() >= zs[slab_id] : vertices[j].z() <= zs[slab_id]);
emit_slab_edge(
IntersectionLine {
{ to_2d(vertices[i]).cast<coord_t>(), to_2d(vertices[j]).cast<coord_t>() },
indices(i), indices(j), -1, -1, IntersectionLine::FacetEdgeType::Slab
},
slab_id, ! ProjectionFromTop);
}
}
} else {
// The triangle is not horizontal and at least a single slicing plane intersects the triangle.
int idx_vertex_lowest = (vertices[1].z() == min_z) ? 1 : ((vertices[2].z() == min_z) ? 2 : 0);
IntersectionLine il_prev;
for (auto it = min_layer; it != max_layer; ++ it) {
IntersectionLine il;
auto type = slice_facet(*it, vertices, indices, facet_edge_ids, idx_vertex_lowest, false, il);
if (type == FacetSliceType::NoSlice) {
// One and exactly one vertex is touching the slicing plane.
} else {
if (il.edge_type == IntersectionLine::FacetEdgeType::Top || il.edge_type == IntersectionLine::FacetEdgeType::Bottom) {
// The non-horizontal triangle is being sliced at one of its edges.
// If the edge is open (it does not have a neighbor), add it.
// If the edge has a neighbor, then add it as TopBottom, and do it just once.
assert(il.a_id != -1 && il.b_id != -1);
assert(il.edge_a_id == -1 && il.edge_b_id == -1);
// Identify edge ID from the edge vertices.
int edge_id;
if (type == FacetSliceType::Cutting) {
// The edge is oriented CCW along the face perimeter.
assert(il.edge_type == IntersectionLine::FacetEdgeType::Bottom);
edge_id = il.a_id == indices(0) ? 0 : il.a_id == indices(1) ? 1 : 2;
assert(il.a_id == indices(edge_id));
assert(il.b_id == indices(next_idx_modulo(edge_id, 3)));
} else {
// The edge is oriented CW along the face perimeter.
assert(type == FacetSliceType::Slicing);
assert(il.edge_type == IntersectionLine::FacetEdgeType::Top);
edge_id = il.b_id == indices(0) ? 0 : il.b_id == indices(1) ? 1 : 2;
assert(il.b_id == indices(edge_id));
assert(il.a_id == indices(next_idx_modulo(edge_id, 3)));
}
int neighbor_idx = facet_neighbors(edge_id);
if (neighbor_idx == -1) {
// Save the open edge for sure.
type = FacetSliceType::Slicing;
} else {
#ifndef NDEBUG
const stl_triangle_vertex_indices &neighbor = mesh_triangles[neighbor_idx];
float z = *it;
int num_on_plane = (mesh_vertices[neighbor(0)].z() == z) + (mesh_vertices[neighbor(1)].z() == z) + (mesh_vertices[neighbor(2)].z() == z);
assert(num_on_plane == 2 || num_on_plane == 3);
#endif // NDEBUG
#if 0
if (mesh_vertices[neighbor(0)].z() == z && mesh_vertices[neighbor(1)].z() == z && mesh_vertices[neighbor(2)].z() == z) {
// The neighbor triangle is horizontal.
// Assign the horizontal projections to slicing planes differently from the usual triangle mesh slicing:
// Slicing plane slices top surfaces when projecting from top, it slices bottom surfaces when projecting from bottom.
// Is the corner convex or concave?
if (il.edge_type == (ProjectionFromTop ? IntersectionLine::FacetEdgeType::Top : IntersectionLine::FacetEdgeType::Bottom)) {
// Convex corner. Add this edge to both slabs, the edge is a boundary edge of both the projection patch below and
// above this slicing plane.
type = FacetSliceType::Slicing;
il.edge_type = IntersectionLine::FacetEdgeType::TopBottom;
} else {
// Concave corner. Ignore this edge, it is internal to the projection patch.
type = FacetSliceType::Cutting;
}
} else
#else
// Project the coplanar bottom facing triangles to the plane above the slicing plane to match the behavior of slice_mesh() / slice_mesh_ex(),
// where the slicing plane slices the top facing surfaces, but misses the bottom facing surfaces.
#endif
if (il.edge_type == IntersectionLine::FacetEdgeType::Top) {
// Indicate that the edge belongs to both the slab below and above the plane.
assert(type == FacetSliceType::Slicing);
il.edge_type = IntersectionLine::FacetEdgeType::TopBottom;
} else {
// Don't add this edge, as the neighbor triangle will add the same edge as FacetEdgeType::TopBottom.
assert(type == FacetSliceType::Cutting);
assert(il.edge_type == IntersectionLine::FacetEdgeType::Bottom);
}
}
}
if (type == FacetSliceType::Slicing) {
if (! ProjectionFromTop)
il.reverse();
size_t line_id = it - zs.begin();
boost::lock_guard<std::mutex> l(lines_mutex[line_id % lines_mutex.size()]);
lines.at_slice[line_id].emplace_back(il);
}
}
if (! ProjectionFromTop || it != zs.begin()) {
size_t slab_id = it - zs.begin();
if (ProjectionFromTop)
-- slab_id;
// Try to project unbound edges.
for (int iedge = 0; iedge < 3; ++ iedge)
if (facet_neighbors(iedge) == -1) {
// Unbound edge.
int edge_id = facet_edge_ids(iedge);
bool intersects_this = il.edge_a_id == edge_id || il.edge_b_id == edge_id;
bool intersects_prev = il_prev.edge_a_id == edge_id || il_prev.edge_b_id == edge_id;
int i = iedge;
int j = next_idx_modulo(i, 3);
assert((! intersects_this && ! intersects_prev) || vertices[j].z() != vertices[i].z());
bool edge_up = vertices[j].z() > vertices[i].z();
if (intersects_this && intersects_prev) {
// Intersects both, emit the segment between these intersections.
Line l(il_prev.edge_a_id == edge_id ? il_prev.a : il_prev.b,
il.edge_a_id == edge_id ? il.a : il.b);
emit_slab_edge(
IntersectionLine { l, -1, -1, edge_id, edge_id + num_edges, IntersectionLine::FacetEdgeType::Slab },
slab_id, ProjectionFromTop != edge_up);
} else if (intersects_this) {
// Intersects just the top plane, may touch the bottom plane.
assert((vertices[i].z() > *it && vertices[j].z() < *it) || (vertices[i].z() < *it && vertices[j].z() > *it));
assert(il.edge_a_id == edge_id || il.edge_b_id == edge_id);
emit_slab_edge(
IntersectionLine { {
to_2d(edge_up ? vertices[i] : vertices[j]).cast<coord_t>(),
il.edge_a_id == edge_id ? il.a : il.b
},
edge_up ? indices(i) : indices(j), -1, -1, edge_id + num_edges, IntersectionLine::FacetEdgeType::Slab
},
slab_id, ProjectionFromTop != edge_up);
} else if (intersects_prev) {
// Intersects just the bottom plane, may touch the top vertex.
assert(*it <= max_z);
#ifndef NDEBUG
{
auto it_prev = it;
-- it_prev;
assert((vertices[i].z() > *it_prev && vertices[j].z() < *it_prev) || (vertices[i].z() < *it_prev && vertices[j].z() > *it_prev));
}
#endif // NDEBUG
emit_slab_edge(
IntersectionLine { {
il_prev.edge_a_id == edge_id ? il_prev.a : il_prev.b,
to_2d(edge_up ? vertices[j] : vertices[i]).cast<coord_t>()
},
-1, edge_up ? indices(j) : indices(i), edge_id, -1, IntersectionLine::FacetEdgeType::Slab
},
slab_id, ProjectionFromTop != edge_up);
} else if (float zi = vertices[i].z(), zj = vertices[j].z(); zi < *it || zj < *it) {
// The edge does not intersect the current plane and it does not intersect the previous plane either.
// Both points have to be inside the slab.
assert(zi <= *it && zj <= *it);
#ifndef NDEBUG
if (type == FacetSliceType::Slicing || type == FacetSliceType::Cutting) {
// Such edge should already be processed in the code above, it shall be skipped here.
assert(indices(i) != il.b_id || indices(j) != il.a_id);
assert(indices(i) != il.a_id || indices(j) != il.b_id);
}
#endif // NDEBUG
// Is it inside the slab?
bool inside_slab = true;
if (it != min_layer) {
auto it_prev = it;
-- it_prev;
assert(*it_prev >= *min_layer && *it_prev < *it);
// One point may touch the plane below, the other must not.
inside_slab = zi > *it_prev || zj > *it_prev;
// Both points have to be inside the slab.
assert(! inside_slab || (zi >= *it_prev && zj >= *it_prev));
}
if (inside_slab) {
assert(ProjectionFromTop ? vertices[i].z() >= zs[slab_id] : vertices[i].z() <= zs[slab_id]);
assert(ProjectionFromTop ? vertices[j].z() >= zs[slab_id] : vertices[j].z() <= zs[slab_id]);
emit_slab_edge(
IntersectionLine {
{ to_2d(vertices[i]).cast<coord_t>(), to_2d(vertices[j]).cast<coord_t>() },
indices(i), indices(j), -1, -1, IntersectionLine::FacetEdgeType::Slab
},
slab_id, ! ProjectionFromTop);
}
}
}
}
il_prev = il;
}
if (ProjectionFromTop || max_layer != zs.end()) {
// Try to project unbound edges above the last slicing plane to the last slab.
// Last layer slicing this triangle.
auto it = max_layer - 1;
size_t slab_id = max_layer - zs.begin();
if (ProjectionFromTop)
-- slab_id;
for (int iedge = 0; iedge < 3; ++ iedge)
if (facet_neighbors(iedge) == -1) {
// Unbound edge.
int edge_id = facet_edge_ids(iedge);
int i = iedge;
int j = next_idx_modulo(i, 3);
if (il_prev.edge_a_id == edge_id || il_prev.edge_b_id == edge_id) {
// Intersects just the bottom plane, may touch the top vertex.
assert((vertices[i].z() > *it && vertices[j].z() < *it) || (vertices[i].z() < *it && vertices[j].z() > *it));
bool edge_up = vertices[j].z() > vertices[i].z();
emit_slab_edge(
IntersectionLine{ {
il_prev.edge_a_id == edge_id ? il_prev.a : il_prev.b,
to_2d(edge_up ? vertices[j] : vertices[i]).cast<coord_t>()
},
-1, edge_up ? indices(j) : indices(i), edge_id, -1, IntersectionLine::FacetEdgeType::Slab
},
slab_id, ProjectionFromTop != edge_up);
} else if (float zi = vertices[i].z(), zj = vertices[j].z(); zi > *it || zj > *it) {
// The edge does not intersect the current plane and it does not intersect the previous plane either.
// Both points have to be inside the slab.
assert(zi >= *it && zj >= *it);
assert(max_layer == zs.end() || (zi < *max_layer && zj < *max_layer));
emit_slab_edge(
IntersectionLine{
{ to_2d(vertices[i]).cast<coord_t>(), to_2d(vertices[j]).cast<coord_t>() },
indices(i), indices(j), -1, -1, IntersectionLine::FacetEdgeType::Slab
},
slab_id, ! ProjectionFromTop);
}
}
}
}
}
// used by slice_mesh_slabs() to produce on-slice lines and between-slices lines.
// Returning top / bottom SlabLines.
template<typename ThrowOnCancel>
inline std::pair<SlabLines, SlabLines> slice_slabs_make_lines(
const std::vector<stl_vertex> &vertices,
const std::vector<stl_triangle_vertex_indices> &indices,
const std::vector<Vec3i> &face_neighbors,
const std::vector<Vec3i> &face_edge_ids,
// Total number of edges. All face_edge_ids are lower than num_edges.
// num_edges will be used to distinguish between intersections with the top and bottom plane.
const int num_edges,
const std::vector<FaceOrientation> &face_orientation,
const std::vector<float> &zs,
bool top,
bool bottom,
const ThrowOnCancel throw_on_cancel_fn)
{
std::pair<SlabLines, SlabLines> out;
SlabLines &lines_top = out.first;
SlabLines &lines_bottom = out.second;
std::array<std::mutex, 64> lines_mutex_top;
std::array<std::mutex, 64> lines_mutex_bottom;
if (top) {
lines_top.at_slice.assign(zs.size(), IntersectionLines());
lines_top.between_slices.assign(zs.size(), IntersectionLines());
}
if (bottom) {
lines_bottom.at_slice.assign(zs.size(), IntersectionLines());
lines_bottom.between_slices.assign(zs.size(), IntersectionLines());
}
tbb::parallel_for(
tbb::blocked_range<int>(0, int(indices.size())),
[&vertices, &indices, &face_neighbors, &face_edge_ids, num_edges, &face_orientation, &zs, top, bottom, &lines_top, &lines_bottom, &lines_mutex_top, &lines_mutex_bottom, throw_on_cancel_fn]
(const tbb::blocked_range<int> &range) {
for (int face_idx = range.begin(); face_idx < range.end(); ++ face_idx) {
if ((face_idx & 0x0ffff) == 0)
throw_on_cancel_fn();
FaceOrientation fo = face_orientation[face_idx];
Vec3i edge_ids = face_edge_ids[face_idx];
if (top && (fo == FaceOrientation::Up || fo == FaceOrientation::Degenerate)) {
Vec3i neighbors = face_neighbors[face_idx];
// Reset neighborship of this triangle in case the other triangle is oriented backwards from this one.
for (int i = 0; i < 3; ++ i)
if (neighbors(i) != -1) {
FaceOrientation fo2 = face_orientation[neighbors(i)];
if (fo2 != FaceOrientation::Up && fo2 != FaceOrientation::Degenerate)
neighbors(i) = -1;
}
slice_facet_with_slabs<true>(vertices, indices, face_idx, neighbors, edge_ids, num_edges, zs, lines_top, lines_mutex_top);
}
// BBS: add vertical faces option
if (bottom && (fo == FaceOrientation::Down || fo == FaceOrientation::Degenerate)) {
Vec3i neighbors = face_neighbors[face_idx];
// Reset neighborship of this triangle in case the other triangle is oriented backwards from this one.
for (int i = 0; i < 3; ++ i)
if (neighbors(i) != -1) {
FaceOrientation fo2 = face_orientation[neighbors(i)];
if (fo2 != FaceOrientation::Down && fo2 != FaceOrientation::Degenerate)
neighbors(i) = -1;
}
slice_facet_with_slabs<false>(vertices, indices, face_idx, neighbors, edge_ids, num_edges, zs, lines_bottom, lines_mutex_bottom);
}
}
}
);
return out;
}
#if 0
//FIXME Should this go away? For valid meshes the function slice_facet() returns Slicing
// and sets edges of vertical triangles to produce only a single edge per pair of neighbor faces.
// So the following code makes only sense now to handle degenerate meshes with more than two faces
// sharing a single edge.
static inline void remove_tangent_edges(std::vector<IntersectionLine> &lines)
{
std::vector<IntersectionLine*> by_vertex_pair;
by_vertex_pair.reserve(lines.size());
for (IntersectionLine& line : lines)
if (line.edge_type != IntersectionLine::FacetEdgeType::General && line.a_id != -1)
// This is a face edge. Check whether there is its neighbor stored in lines.
by_vertex_pair.emplace_back(&line);
auto edges_lower_sorted = [](const IntersectionLine *l1, const IntersectionLine *l2) {
// Sort vertices of l1, l2 lexicographically
int l1a = l1->a_id;
int l1b = l1->b_id;
int l2a = l2->a_id;
int l2b = l2->b_id;
if (l1a > l1b)
std::swap(l1a, l1b);
if (l2a > l2b)
std::swap(l2a, l2b);
// Lexicographical "lower" operator on lexicographically sorted vertices should bring equal edges together when sored.
return l1a < l2a || (l1a == l2a && l1b < l2b);
};
std::sort(by_vertex_pair.begin(), by_vertex_pair.end(), edges_lower_sorted);
for (auto line = by_vertex_pair.begin(); line != by_vertex_pair.end(); ++ line) {
IntersectionLine &l1 = **line;
if (! l1.skip()) {
// Iterate as long as line and line2 edges share the same end points.
for (auto line2 = line + 1; line2 != by_vertex_pair.end() && ! edges_lower_sorted(*line, *line2); ++ line2) {
// Lines must share the end points.
assert(! edges_lower_sorted(*line, *line2));
assert(! edges_lower_sorted(*line2, *line));
IntersectionLine &l2 = **line2;
if (l2.skip())
continue;
if (l1.a_id == l2.a_id) {
assert(l1.b_id == l2.b_id);
l2.set_skip();
// If they are both oriented upwards or downwards (like a 'V'),
// then we can remove both edges from this layer since it won't
// affect the sliced shape.
// If one of them is oriented upwards and the other is oriented
// downwards, let's only keep one of them (it doesn't matter which
// one since all 'top' lines were reversed at slicing).
if (l1.edge_type == l2.edge_type) {
l1.set_skip();
break;
}
} else {
assert(l1.a_id == l2.b_id && l1.b_id == l2.a_id);
// If this edge joins two horizontal facets, remove both of them.
if (l1.edge_type == IntersectionLine::FacetEdgeType::Horizontal && l2.edge_type == IntersectionLine::FacetEdgeType::Horizontal) {
l1.set_skip();
l2.set_skip();
break;
}
}
}
}
}
}
#endif
struct OpenPolyline {
OpenPolyline() = default;
OpenPolyline(const IntersectionReference &start, const IntersectionReference &end, Points &&points) :
start(start), end(end), points(std::move(points)), consumed(false) { this->length = Slic3r::length(this->points); }
void reverse() {
std::swap(start, end);
std::reverse(points.begin(), points.end());
}
IntersectionReference start;
IntersectionReference end;
Points points;
double length;
bool consumed;
};
// called by make_loops() to connect sliced triangles into closed loops and open polylines by the triangle connectivity.
// Only connects segments crossing triangles of the same orientation.
static void chain_lines_by_triangle_connectivity(IntersectionLines &lines, Polygons &loops, std::vector<OpenPolyline> &open_polylines)
{
// Build a map of lines by edge_a_id and a_id.
std::vector<IntersectionLine*> by_edge_a_id;
std::vector<IntersectionLine*> by_a_id;
by_edge_a_id.reserve(lines.size());
by_a_id.reserve(lines.size());
for (IntersectionLine &line : lines) {
if (! line.skip()) {
if (line.edge_a_id != -1)
by_edge_a_id.emplace_back(&line);
if (line.a_id != -1)
by_a_id.emplace_back(&line);
}
}
auto by_edge_lower = [](const IntersectionLine* il1, const IntersectionLine *il2) { return il1->edge_a_id < il2->edge_a_id; };
auto by_vertex_lower = [](const IntersectionLine* il1, const IntersectionLine *il2) { return il1->a_id < il2->a_id; };
std::sort(by_edge_a_id.begin(), by_edge_a_id.end(), by_edge_lower);
std::sort(by_a_id.begin(), by_a_id.end(), by_vertex_lower);
// Chain the segments with a greedy algorithm, collect the loops and unclosed polylines.
IntersectionLines::iterator it_line_seed = lines.begin();
for (;;) {
// take first spare line and start a new loop
IntersectionLine *first_line = nullptr;
for (; it_line_seed != lines.end(); ++ it_line_seed)
if (it_line_seed->is_seed_candidate()) {
//if (! it_line_seed->skip()) {
first_line = &(*it_line_seed ++);
break;
}
if (first_line == nullptr)
break;
first_line->set_skip();
Points loop_pts;
loop_pts.emplace_back(first_line->a);
IntersectionLine *last_line = first_line;
/*
printf("first_line edge_a_id = %d, edge_b_id = %d, a_id = %d, b_id = %d, a = %d,%d, b = %d,%d\n",
first_line->edge_a_id, first_line->edge_b_id, first_line->a_id, first_line->b_id,
first_line->a.x, first_line->a.y, first_line->b.x, first_line->b.y);
*/
IntersectionLine key;
for (;;) {
// find a line starting where last one finishes
IntersectionLine* next_line = nullptr;
if (last_line->edge_b_id != -1) {
key.edge_a_id = last_line->edge_b_id;
auto it_begin = std::lower_bound(by_edge_a_id.begin(), by_edge_a_id.end(), &key, by_edge_lower);
if (it_begin != by_edge_a_id.end()) {
auto it_end = std::upper_bound(it_begin, by_edge_a_id.end(), &key, by_edge_lower);
for (auto it_line = it_begin; it_line != it_end; ++ it_line)
if (! (*it_line)->skip()) {
next_line = *it_line;
break;
}
}
}
if (next_line == nullptr && last_line->b_id != -1) {
key.a_id = last_line->b_id;
auto it_begin = std::lower_bound(by_a_id.begin(), by_a_id.end(), &key, by_vertex_lower);
if (it_begin != by_a_id.end()) {
auto it_end = std::upper_bound(it_begin, by_a_id.end(), &key, by_vertex_lower);
for (auto it_line = it_begin; it_line != it_end; ++ it_line)
if (! (*it_line)->skip()) {
next_line = *it_line;
break;
}
}
}
if (next_line == nullptr) {
// Check whether we closed this loop.
if ((first_line->edge_a_id != -1 && first_line->edge_a_id == last_line->edge_b_id) ||
(first_line->a_id != -1 && first_line->a_id == last_line->b_id)) {
// The current loop is complete. Add it to the output.
assert(first_line->a == last_line->b);
loops.emplace_back(std::move(loop_pts));
#ifdef SLIC3R_TRIANGLEMESH_DEBUG
printf(" Discovered %s polygon of %d points\n", (p.is_counter_clockwise() ? "ccw" : "cw"), (int)p.points.size());
#endif
} else {
// This is an open polyline. Add it to the list of open polylines. These open polylines will processed later.
loop_pts.emplace_back(last_line->b);
open_polylines.emplace_back(OpenPolyline(
IntersectionReference(first_line->a_id, first_line->edge_a_id),
IntersectionReference(last_line->b_id, last_line->edge_b_id), std::move(loop_pts)));
}
break;
}
/*
printf("next_line edge_a_id = %d, edge_b_id = %d, a_id = %d, b_id = %d, a = %d,%d, b = %d,%d\n",
next_line->edge_a_id, next_line->edge_b_id, next_line->a_id, next_line->b_id,
next_line->a.x, next_line->a.y, next_line->b.x, next_line->b.y);
*/
assert(last_line->b == next_line->a);
loop_pts.emplace_back(next_line->a);
last_line = next_line;
next_line->set_skip();
}
}
}
std::vector<OpenPolyline*> open_polylines_sorted(std::vector<OpenPolyline> &open_polylines, bool update_lengths)
{
std::vector<OpenPolyline*> out;
out.reserve(open_polylines.size());
for (OpenPolyline &opl : open_polylines)
if (! opl.consumed) {
if (update_lengths)
opl.length = Slic3r::length(opl.points);
out.emplace_back(&opl);
}
std::sort(out.begin(), out.end(), [](const OpenPolyline *lhs, const OpenPolyline *rhs){ return lhs->length > rhs->length; });
return out;
}
// called by make_loops() to connect remaining open polylines across shared triangle edges and vertices.
// Depending on "try_connect_reversed", it may or may not connect segments crossing triangles of opposite orientation.
static void chain_open_polylines_exact(std::vector<OpenPolyline> &open_polylines, Polygons &loops, bool try_connect_reversed)
{
// Store the end points of open_polylines into vectors sorted
struct OpenPolylineEnd {
OpenPolylineEnd(OpenPolyline *polyline, bool start) : polyline(polyline), start(start) {}
OpenPolyline *polyline;
// Is it the start or end point?
bool start;
const IntersectionReference& ipref() const { return start ? polyline->start : polyline->end; }
// Return a unique ID for the intersection point.
// Return a positive id for a point, or a negative id for an edge.
int id() const { const IntersectionReference &r = ipref(); return (r.point_id >= 0) ? r.point_id : - r.edge_id; }
bool operator==(const OpenPolylineEnd &rhs) const { return this->polyline == rhs.polyline && this->start == rhs.start; }
};
auto by_id_lower = [](const OpenPolylineEnd &ope1, const OpenPolylineEnd &ope2) { return ope1.id() < ope2.id(); };
std::vector<OpenPolylineEnd> by_id;
by_id.reserve(2 * open_polylines.size());
for (OpenPolyline &opl : open_polylines) {
if (opl.start.point_id != -1 || opl.start.edge_id != -1)
by_id.emplace_back(OpenPolylineEnd(&opl, true));
if (try_connect_reversed && (opl.end.point_id != -1 || opl.end.edge_id != -1))
by_id.emplace_back(OpenPolylineEnd(&opl, false));
}
std::sort(by_id.begin(), by_id.end(), by_id_lower);
// Find an iterator to by_id_lower for the particular end of OpenPolyline (by comparing the OpenPolyline pointer and the start attribute).
auto find_polyline_end = [&by_id, by_id_lower](const OpenPolylineEnd &end) -> std::vector<OpenPolylineEnd>::iterator {
for (auto it = std::lower_bound(by_id.begin(), by_id.end(), end, by_id_lower);
it != by_id.end() && it->id() == end.id(); ++ it)
if (*it == end)
return it;
return by_id.end();
};
// Try to connect the loops.
std::vector<OpenPolyline*> sorted_by_length = open_polylines_sorted(open_polylines, false);
for (OpenPolyline *opl : sorted_by_length) {
if (opl->consumed)
continue;
opl->consumed = true;
OpenPolylineEnd end(opl, false);
for (;;) {
// find a line starting where last one finishes
auto it_next_start = std::lower_bound(by_id.begin(), by_id.end(), end, by_id_lower);
for (; it_next_start != by_id.end() && it_next_start->id() == end.id(); ++ it_next_start)
if (! it_next_start->polyline->consumed)
goto found;
// The current loop could not be closed. Unmark the segment.
opl->consumed = false;
break;
found:
// Attach this polyline to the end of the initial polyline.
if (it_next_start->start) {
auto it = it_next_start->polyline->points.begin();
std::copy(++ it, it_next_start->polyline->points.end(), back_inserter(opl->points));
} else {
auto it = it_next_start->polyline->points.rbegin();
std::copy(++ it, it_next_start->polyline->points.rend(), back_inserter(opl->points));
}
opl->length += it_next_start->polyline->length;
// Mark the next polyline as consumed.
it_next_start->polyline->points.clear();
it_next_start->polyline->length = 0.;
it_next_start->polyline->consumed = true;
if (try_connect_reversed) {
// Running in a mode, where the polylines may be connected by mixing their orientations.
// Update the end point lookup structure after the end point of the current polyline was extended.
auto it_end = find_polyline_end(end);
auto it_next_end = find_polyline_end(OpenPolylineEnd(it_next_start->polyline, !it_next_start->start));
// Swap the end points of the current and next polyline, but keep the polyline ptr and the start flag.
std::swap(opl->end, it_next_end->start ? it_next_end->polyline->start : it_next_end->polyline->end);
// Swap the positions of OpenPolylineEnd structures in the sorted array to match their respective end point positions.
std::swap(*it_end, *it_next_end);
}
// Check whether we closed this loop.
if ((opl->start.edge_id != -1 && opl->start.edge_id == opl->end.edge_id) ||
(opl->start.point_id != -1 && opl->start.point_id == opl->end.point_id)) {
// The current loop is complete. Add it to the output.
//assert(opl->points.front().point_id == opl->points.back().point_id);
//assert(opl->points.front().edge_id == opl->points.back().edge_id);
// Remove the duplicate last point.
opl->points.pop_back();
if (opl->points.size() >= 3) {
if (try_connect_reversed && area(opl->points) < 0)
// The closed polygon is patched from pieces with messed up orientation, therefore
// the orientation of the patched up polygon is not known.
// Orient the patched up polygons CCW. This heuristic may close some holes and cavities.
std::reverse(opl->points.begin(), opl->points.end());
loops.emplace_back(std::move(opl->points));
}
opl->points.clear();
break;
}
// Continue with the current loop.
}
}
}
// called by make_loops() to connect remaining open polylines across shared triangle edges and vertices,
// possibly closing small gaps.
// Depending on "try_connect_reversed", it may or may not connect segments crossing triangles of opposite orientation.
static void chain_open_polylines_close_gaps(std::vector<OpenPolyline> &open_polylines, Polygons &loops, double max_gap, bool try_connect_reversed)
{
const coord_t max_gap_scaled = (coord_t)scale_(max_gap);
// Sort the open polylines by their length, so the new loops will be seeded from longer chains.
// Update the polyline lengths, return only not yet consumed polylines.
std::vector<OpenPolyline*> sorted_by_length = open_polylines_sorted(open_polylines, true);
// Store the end points of open_polylines into ClosestPointInRadiusLookup<OpenPolylineEnd>.
struct OpenPolylineEnd {
OpenPolylineEnd(OpenPolyline *polyline, bool start) : polyline(polyline), start(start) {}
OpenPolyline *polyline;
// Is it the start or end point?
bool start;
const Point& point() const { return start ? polyline->points.front() : polyline->points.back(); }
bool operator==(const OpenPolylineEnd &rhs) const { return this->polyline == rhs.polyline && this->start == rhs.start; }
};
struct OpenPolylineEndAccessor {
const Point* operator()(const OpenPolylineEnd &pt) const { return pt.polyline->consumed ? nullptr : &pt.point(); }
};
typedef ClosestPointInRadiusLookup<OpenPolylineEnd, OpenPolylineEndAccessor> ClosestPointLookupType;
ClosestPointLookupType closest_end_point_lookup(max_gap_scaled);
for (OpenPolyline *opl : sorted_by_length) {
closest_end_point_lookup.insert(OpenPolylineEnd(opl, true));
if (try_connect_reversed)
closest_end_point_lookup.insert(OpenPolylineEnd(opl, false));
}
// Try to connect the loops.
for (OpenPolyline *opl : sorted_by_length) {
if (opl->consumed)
continue;
OpenPolylineEnd end(opl, false);
if (try_connect_reversed)
// The end point of this polyline will be modified, thus the following entry will become invalid. Remove it.
closest_end_point_lookup.erase(end);
opl->consumed = true;
size_t n_segments_joined = 1;
for (;;) {
// Find a line starting where last one finishes, only return non-consumed open polylines (OpenPolylineEndAccessor returns null for consumed).
std::pair<const OpenPolylineEnd*, double> next_start_and_dist = closest_end_point_lookup.find(end.point());
const OpenPolylineEnd *next_start = next_start_and_dist.first;
// Check whether we closed this loop.
double current_loop_closing_distance2 = (opl->points.back() - opl->points.front()).cast<double>().squaredNorm();
bool loop_closed = current_loop_closing_distance2 < coordf_t(max_gap_scaled) * coordf_t(max_gap_scaled);
if (next_start != nullptr && loop_closed && current_loop_closing_distance2 < next_start_and_dist.second) {
// Heuristics to decide, whether to close the loop, or connect another polyline.
// One should avoid closing loops shorter than max_gap_scaled.
loop_closed = sqrt(current_loop_closing_distance2) < 0.3 * length(opl->points);
}
if (loop_closed) {
// Remove the start point of the current polyline from the lookup.
// Mark the current segment as not consumed, otherwise the closest_end_point_lookup.erase() would fail.
opl->consumed = false;
closest_end_point_lookup.erase(OpenPolylineEnd(opl, true));
if (current_loop_closing_distance2 == 0.) {
// Remove the duplicate last point.
opl->points.pop_back();
} else {
// The end points are different, keep both of them.
}
if (opl->points.size() >= 3) {
if (try_connect_reversed && n_segments_joined > 1 && area(opl->points) < 0)
// The closed polygon is patched from pieces with messed up orientation, therefore
// the orientation of the patched up polygon is not known.
// Orient the patched up polygons CCW. This heuristic may close some holes and cavities.
std::reverse(opl->points.begin(), opl->points.end());
loops.emplace_back(std::move(opl->points));
}
opl->points.clear();
opl->consumed = true;
break;
}
if (next_start == nullptr) {
// The current loop could not be closed. Unmark the segment.
opl->consumed = false;
if (try_connect_reversed)
// Re-insert the end point.
closest_end_point_lookup.insert(OpenPolylineEnd(opl, false));
break;
}
// Attach this polyline to the end of the initial polyline.
if (next_start->start) {
auto it = next_start->polyline->points.begin();
if (*it == opl->points.back())
++ it;
std::copy(it, next_start->polyline->points.end(), back_inserter(opl->points));
} else {
auto it = next_start->polyline->points.rbegin();
if (*it == opl->points.back())
++ it;
std::copy(it, next_start->polyline->points.rend(), back_inserter(opl->points));
}
++ n_segments_joined;
// Remove the end points of the consumed polyline segment from the lookup.
OpenPolyline *opl2 = next_start->polyline;
closest_end_point_lookup.erase(OpenPolylineEnd(opl2, true));
if (try_connect_reversed)
closest_end_point_lookup.erase(OpenPolylineEnd(opl2, false));
opl2->points.clear();
opl2->consumed = true;
// Continue with the current loop.
}
}
}
static Polygons make_loops(
// Lines will have their flags modified.
IntersectionLines &lines)
{
Polygons loops;
#if 0
//FIXME slice_facet() may create zero length edges due to rounding of doubles into coord_t.
//#ifdef _DEBUG
for (const Line &l : lines)
assert(l.a != l.b);
#endif /* _DEBUG */
// There should be no tangent edges, as the horizontal triangles are ignored and if two triangles touch at a cutting plane,
// only the bottom triangle is considered to be cutting the plane.
// remove_tangent_edges(lines);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
BoundingBox bbox_svg;
{
static int iRun = 0;
for (const Line &line : lines) {
bbox_svg.merge(line.a);
bbox_svg.merge(line.b);
}
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-raw_lines-%d.svg", iRun ++).c_str(), bbox_svg);
for (const Line &line : lines)
svg.draw(line);
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
std::vector<OpenPolyline> open_polylines;
chain_lines_by_triangle_connectivity(lines, loops, open_polylines);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRun = 0;
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-polylines-%d.svg", iRun ++).c_str(), bbox_svg);
svg.draw(union_ex(loops));
for (const OpenPolyline &pl : open_polylines)
svg.draw(Polyline(pl.points), "red");
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
// Now process the open polylines.
// Do it in two rounds, first try to connect in the same direction only,
// then try to connect the open polylines in reversed order as well.
chain_open_polylines_exact(open_polylines, loops, false);
chain_open_polylines_exact(open_polylines, loops, true);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRun = 0;
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-polylines2-%d.svg", iRun++).c_str(), bbox_svg);
svg.draw(union_ex(loops));
for (const OpenPolyline &pl : open_polylines) {
if (pl.points.empty())
continue;
svg.draw(Polyline(pl.points), "red");
svg.draw(pl.points.front(), "blue");
svg.draw(pl.points.back(), "blue");
}
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
// Try to close gaps.
// Do it in two rounds, first try to connect in the same direction only,
// then try to connect the open polylines in reversed order as well.
#if 0
for (double max_gap : { EPSILON, 0.001, 0.1, 1., 2. }) {
chain_open_polylines_close_gaps(open_polylines, *loops, max_gap, false);
chain_open_polylines_close_gaps(open_polylines, *loops, max_gap, true);
}
#else
const double max_gap = 2.; //mm
chain_open_polylines_close_gaps(open_polylines, loops, max_gap, false);
chain_open_polylines_close_gaps(open_polylines, loops, max_gap, true);
#endif
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRun = 0;
SVG svg(debug_out_path("TriangleMeshSlicer_make_loops-polylines-final-%d.svg", iRun++).c_str(), bbox_svg);
svg.draw(union_ex(loops));
for (const OpenPolyline &pl : open_polylines) {
if (pl.points.empty())
continue;
svg.draw(Polyline(pl.points), "red");
svg.draw(pl.points.front(), "blue");
svg.draw(pl.points.back(), "blue");
}
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
return loops;
}
template<typename ThrowOnCancel>
static std::vector<Polygons> make_loops(
// Lines will have their flags modified.
std::vector<IntersectionLines> &lines,
const MeshSlicingParams &params,
ThrowOnCancel throw_on_cancel)
{
std::vector<Polygons> layers;
layers.resize(lines.size());
tbb::parallel_for(
tbb::blocked_range<size_t>(0, lines.size()),
[&lines, &layers, &params, throw_on_cancel](const tbb::blocked_range<size_t> &range) {
for (size_t line_idx = range.begin(); line_idx < range.end(); ++ line_idx) {
if ((line_idx & 0x0ffff) == 0)
throw_on_cancel();
Polygons &polygons = layers[line_idx];
polygons = make_loops(lines[line_idx]);
auto this_mode = line_idx < params.slicing_mode_normal_below_layer ? params.mode_below : params.mode;
if (! polygons.empty()) {
if (this_mode == MeshSlicingParams::SlicingMode::Positive) {
// Reorient all loops to be CCW.
for (Polygon& p : polygons)
p.make_counter_clockwise();
}
else if (this_mode == MeshSlicingParams::SlicingMode::PositiveLargestContour) {
// Keep just the largest polygon, make it CCW.
double max_area = 0.;
Polygon* max_area_polygon = nullptr;
for (Polygon& p : polygons) {
double a = p.area();
if (std::abs(a) > std::abs(max_area)) {
max_area = a;
max_area_polygon = &p;
}
}
assert(max_area_polygon != nullptr);
if (max_area < 0.)
max_area_polygon->reverse();
Polygon p(std::move(*max_area_polygon));
polygons.clear();
polygons.emplace_back(std::move(p));
}
}
}
}
);
return layers;
}
// used by slice_mesh_slabs() to produce loops from on-slice lines and between-slices lines.
template<bool ProjectionFromTop, typename ThrowOnCancel>
static std::vector<Polygons> make_slab_loops(
// Lines will have their flags modified.
SlabLines &lines,
// To differentiate edge IDs of the top plane from the edge IDs of the bottom plane for chaining.
int num_edges,
ThrowOnCancel throw_on_cancel)
{
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
static int iRun = 0;
++ iRun;
#endif // SLIC3R_DEBUG_SLICE_PROCESSING
assert(! lines.at_slice.empty() && lines.at_slice.size() == lines.between_slices.size());
std::vector<Polygons> layers;
layers.resize(lines.at_slice.size());
tbb::parallel_for(
tbb::blocked_range<int>(0, int(lines.at_slice.size())),
[&lines, num_edges, &layers, throw_on_cancel](const tbb::blocked_range<int> &range) {
for (int line_idx = range.begin(); line_idx < range.end(); ++ line_idx) {
if ((line_idx & 0x0ffff) == 0)
throw_on_cancel();
IntersectionLines in;
size_t nlines = lines.between_slices[line_idx].size();
int slice_below = ProjectionFromTop ? line_idx : line_idx - 1;
int slice_above = ProjectionFromTop ? line_idx + 1 : line_idx;
bool has_slice_below = ProjectionFromTop || line_idx > 0;
bool has_slice_above = ! ProjectionFromTop || line_idx + 1 < int(lines.at_slice.size());
if (has_slice_below)
nlines += lines.at_slice[slice_below].size();
if (has_slice_above)
nlines += lines.at_slice[slice_above].size();
if (nlines) {
in.reserve(nlines);
if (has_slice_below) {
for (const IntersectionLine &l : lines.at_slice[slice_below])
if (l.edge_type != IntersectionLine::FacetEdgeType::Top) {
in.emplace_back(l);
#ifndef NDEBUG
in.back().source = IntersectionLine::Source::BottomPlane;
#endif // NDEBUG
}
}
{
// Edges in between slice_below and slice_above.
#ifndef NDEBUG
size_t old_size = in.size();
#endif // NDEBUG
// Edge IDs of end points on in-between lines that touch the layer above are already increased with num_edges.
append(in, lines.between_slices[line_idx]);
#ifndef NDEBUG
for (auto it = in.begin() + old_size; it != in.end(); ++ it) {
assert(it->edge_type == IntersectionLine::FacetEdgeType::Slab);
it->source = IntersectionLine::Source::Slab;
}
#endif // NDEBUG
}
if (has_slice_above) {
for (const IntersectionLine &lsrc : lines.at_slice[slice_above])
if (lsrc.edge_type != IntersectionLine::FacetEdgeType::Bottom) {
in.emplace_back(lsrc);
auto &l = in.back();
l.reverse();
// Differentiate edge IDs of the top plane from the edge IDs of the bottom plane for chaining.
if (l.edge_a_id >= 0)
l.edge_a_id += num_edges;
if (l.edge_b_id >= 0)
l.edge_b_id += num_edges;
#ifndef NDEBUG
l.source = IntersectionLine::Source::TopPlane;
#endif // NDEBUG
}
}
if (! in.empty()) {
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
BoundingBox bbox_svg;
coordf_t stroke_width = scale_(0.02);
{
for (const IntersectionLine &line : in) {
bbox_svg.merge(line.a);
bbox_svg.merge(line.b);
}
SVG svg(debug_out_path("make_slab_loops-in-%d-%d-%s.svg", iRun, line_idx, ProjectionFromTop ? "top" : "bottom").c_str(), bbox_svg);
svg.arrows = true;
for (const IntersectionLine& line : in) {
const char* color = line.source == IntersectionLine::Source::BottomPlane ? "red" : line.source == IntersectionLine::Source::TopPlane ? "blue" : "green";
svg.draw(line, color, stroke_width);
}
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
Polygons &loops = layers[line_idx];
std::vector<OpenPolyline> open_polylines;
chain_lines_by_triangle_connectivity(in, loops, open_polylines);
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
SVG svg(debug_out_path("make_slab_loops-out-%d-%d-%s.svg", iRun, line_idx, ProjectionFromTop ? "top" : "bottom").c_str(), bbox_svg);
svg.arrows = true;
for (const IntersectionLine& line : in) {
const char* color = line.source == IntersectionLine::Source::BottomPlane ? "red" : line.source == IntersectionLine::Source::TopPlane ? "blue" : "green";
svg.draw(line, color, stroke_width);
}
svg.draw(loops, "black");
svg.Close();
}
{
SVG svg(debug_out_path("make_slab_loops-open-polylines-%d-%d-%s.svg", iRun, line_idx, ProjectionFromTop ? "top" : "bottom").c_str(), bbox_svg);
svg.draw(loops, "black");
svg.arrows = true;
for (const OpenPolyline &open_polyline : open_polylines)
svg.draw(Polyline(open_polyline.points), "black", stroke_width);
svg.Close();
}
#endif /* SLIC3R_DEBUG_SLICE_PROCESSING */
assert(! loops.empty());
assert(open_polylines.empty());
if (! open_polylines.empty())
BOOST_LOG_TRIVIAL(trace) << "make_slab_loops - chaining failed. #" << open_polylines.size() << " open polylines";
}
}
}
}
);
return layers;
}
// Used to cut the mesh into two halves.
static ExPolygons make_expolygons_simple(std::vector<IntersectionLine> &lines)
{
ExPolygons slices;
Polygons holes;
for (Polygon &loop : make_loops(lines))
if (loop.area() >= 0.)
slices.emplace_back(std::move(loop));
else
holes.emplace_back(std::move(loop));
// If there are holes, then there should also be outer contours.
assert(holes.empty() || ! slices.empty());
if (! slices.empty())
{
// Assign holes to outer contours.
for (Polygon &hole : holes) {
// Find an outer contour to a hole.
int slice_idx = -1;
double current_contour_area = std::numeric_limits<double>::max();
for (ExPolygon &slice : slices)
if (slice.contour.contains(hole.points.front())) {
double area = slice.contour.area();
if (area < current_contour_area) {
slice_idx = &slice - slices.data();
current_contour_area = area;
}
}
// assert(slice_idx != -1);
if (slice_idx == -1)
// Ignore this hole.
continue;
assert(current_contour_area < std::numeric_limits<double>::max() && current_contour_area >= -hole.area());
slices[slice_idx].holes.emplace_back(std::move(hole));
}
#if 0
// If the input mesh is not valid, the holes may intersect with the external contour.
// Rather subtract them from the outer contour.
Polygons poly;
for (auto it_slice = slices->begin(); it_slice != slices->end(); ++ it_slice) {
if (it_slice->holes.empty()) {
poly.emplace_back(std::move(it_slice->contour));
} else {
Polygons contours;
contours.emplace_back(std::move(it_slice->contour));
for (auto it = it_slice->holes.begin(); it != it_slice->holes.end(); ++ it)
it->reverse();
polygons_append(poly, diff(contours, it_slice->holes));
}
}
// If the input mesh is not valid, the input contours may intersect.
*slices = union_ex(poly);
#endif
#if 0
// If the input mesh is not valid, the holes may intersect with the external contour.
// Rather subtract them from the outer contour.
ExPolygons poly;
for (auto it_slice = slices->begin(); it_slice != slices->end(); ++ it_slice) {
Polygons contours;
contours.emplace_back(std::move(it_slice->contour));
for (auto it = it_slice->holes.begin(); it != it_slice->holes.end(); ++ it)
it->reverse();
expolygons_append(poly, diff_ex(contours, it_slice->holes));
}
// If the input mesh is not valid, the input contours may intersect.
*slices = std::move(poly);
#endif
}
return slices;
}
static void make_expolygons(const Polygons &loops, const float closing_radius, const float extra_offset, ClipperLib::PolyFillType fill_type, ExPolygons* slices)
{
/*
Input loops are not suitable for evenodd nor nonzero fill types, as we might get
two consecutive concentric loops having the same winding order - and we have to
respect such order. In that case, evenodd would create wrong inversions, and nonzero
would ignore holes inside two concentric contours.
So we're ordering loops and collapse consecutive concentric loops having the same
winding order.
TODO: find a faster algorithm for this, maybe with some sort of binary search.
If we computed a "nesting tree" we could also just remove the consecutive loops
having the same winding order, and remove the extra one(s) so that we could just
supply everything to offset() instead of performing several union/diff calls.
we sort by area assuming that the outermost loops have larger area;
the previous sorting method, based on $b->contains($a->[0]), failed to nest
loops correctly in some edge cases when original model had overlapping facets
*/
/* The following lines are commented out because they can generate wrong polygons,
see for example issue #661 */
//std::vector<double> area;
//std::vector<size_t> sorted_area; // vector of indices
//for (Polygons::const_iterator loop = loops.begin(); loop != loops.end(); ++ loop) {
// area.emplace_back(loop->area());
// sorted_area.emplace_back(loop - loops.begin());
//}
//
//// outer first
//std::sort(sorted_area.begin(), sorted_area.end(),
// [&area](size_t a, size_t b) { return std::abs(area[a]) > std::abs(area[b]); });
//// we don't perform a safety offset now because it might reverse cw loops
//Polygons p_slices;
//for (std::vector<size_t>::const_iterator loop_idx = sorted_area.begin(); loop_idx != sorted_area.end(); ++ loop_idx) {
// /* we rely on the already computed area to determine the winding order
// of the loops, since the Orientation() function provided by Clipper
// would do the same, thus repeating the calculation */
// Polygons::const_iterator loop = loops.begin() + *loop_idx;
// if (area[*loop_idx] > +EPSILON)
// p_slices.emplace_back(*loop);
// else if (area[*loop_idx] < -EPSILON)
// //FIXME This is arbitrary and possibly very slow.
// // If the hole is inside a polygon, then there is no need to diff.
// // If the hole intersects a polygon boundary, then diff it, but then
// // there is no guarantee of an ordering of the loops.
// // Maybe we can test for the intersection before running the expensive diff algorithm?
// p_slices = diff(p_slices, *loop);
//}
// Perform a safety offset to merge very close facets (TODO: find test case for this)
// 0.0499 comes from https://github.com/slic3r/Slic3r/issues/959
// double safety_offset = scale_(0.0499);
// 0.0001 is set to satisfy GH #520, #1029, #1364
assert(closing_radius >= 0);
// Allowing negative extra_offset for shrinking a contour. This likely only makes sense if slicing a single region only.
//assert(extra_offset >= 0);
double offset_out;
double offset_in;
if (closing_radius >= extra_offset) {
offset_out = + scale_(closing_radius);
offset_in = - scale_(closing_radius - extra_offset);
} else {
offset_out = + scale_(extra_offset);
offset_in = 0.;
}
/* The following line is commented out because it can generate wrong polygons,
see for example issue #661 */
//ExPolygons ex_slices = closing(p_slices, safety_offset);
#ifdef SLIC3R_TRIANGLEMESH_DEBUG
size_t holes_count = 0;
for (ExPolygons::const_iterator e = ex_slices.begin(); e != ex_slices.end(); ++ e)
holes_count += e->holes.size();
printf("%zu surface(s) having %zu holes detected from %zu polylines\n",
ex_slices.size(), holes_count, loops.size());
#endif
// append to the supplied collection
expolygons_append(*slices,
offset_out > 0 && offset_in < 0 ? offset2_ex(union_ex(loops, fill_type), offset_out, offset_in) :
offset_out > 0 ? offset_ex(union_ex(loops, fill_type), offset_out) :
offset_in < 0 ? offset_ex(union_ex(loops, fill_type), offset_in) :
union_ex(loops, fill_type));
}
// Make a trafo for transforming the vertices. Scale up in XY, not in Z.
static inline Transform3f make_trafo_for_slicing(const Transform3d &trafo)
{
auto t = trafo;
static constexpr const double s = 1. / SCALING_FACTOR;
t.prescale(Vec3d(s, s, 1.));
return t.cast<float>();
}
static inline bool is_identity(const Transform3d &trafo)
{
return trafo.matrix() == Transform3d::Identity().matrix();
}
static std::vector<stl_vertex> transform_mesh_vertices_for_slicing(const indexed_triangle_set &mesh, const Transform3d &trafo)
{
// Copy and scale vertices in XY, don't scale in Z.
// Possibly apply the transformation.
static constexpr const double s = 1. / SCALING_FACTOR;
std::vector<stl_vertex> out(mesh.vertices);
if (is_identity(trafo)) {
// Identity.
for (stl_vertex &v : out) {
// Scale just XY, leave Z unscaled.
v.x() *= float(s);
v.y() *= float(s);
}
} else {
// Transform the vertices, scale up in XY, not in Y.
auto t = trafo;
t.prescale(Vec3d(s, s, 1.));
auto tf = t.cast<float>();
for (stl_vertex &v : out)
v = tf * v;
}
return out;
}
std::vector<Polygons> slice_mesh(
const indexed_triangle_set &mesh,
// Unscaled Zs
const std::vector<float> &zs,
const MeshSlicingParams &params,
std::function<void()> throw_on_cancel)
{
BOOST_LOG_TRIVIAL(debug) << "slice_mesh to polygons";
std::vector<IntersectionLines> lines;
{
//FIXME facets_edges is likely not needed and quite costly to calculate.
// Instead of edge identifiers, one shall use a sorted pair of edge vertex indices.
// However facets_edges assigns a single edge ID to two triangles only, thus when factoring facets_edges out, one will have
// to make sure that no code relies on it.
std::vector<Vec3i> face_edge_ids = its_face_edge_ids(mesh);
if (zs.size() <= 1) {
// It likely is not worthwile to copy the vertices. Apply the transformation in place.
if (is_identity(params.trafo)) {
lines = slice_make_lines(
mesh.vertices, [](const Vec3f &p) { return Vec3f(scaled<float>(p.x()), scaled<float>(p.y()), p.z()); },
mesh.indices, face_edge_ids, zs, throw_on_cancel);
} else {
// Transform the vertices, scale up in XY, not in Z.
Transform3f tf = make_trafo_for_slicing(params.trafo);
lines = slice_make_lines(mesh.vertices, [tf](const Vec3f &p) { return tf * p; }, mesh.indices, face_edge_ids, zs, throw_on_cancel);
}
} else {
// Copy and scale vertices in XY, don't scale in Z. Possibly apply the transformation.
lines = slice_make_lines(
transform_mesh_vertices_for_slicing(mesh, params.trafo),
[](const Vec3f &p) { return p; }, mesh.indices, face_edge_ids, zs, throw_on_cancel);
}
}
throw_on_cancel();
std::vector<Polygons> layers = make_loops(lines, params, throw_on_cancel);
#ifdef SLIC3R_DEBUG
{
static int iRun = 0;
for (size_t i = 0; i < z.size(); ++ i) {
Polygons &polygons = (*layers)[i];
ExPolygons expolygons = union_ex(polygons, true);
SVG::export_expolygons(debug_out_path("slice_%d_%d.svg", iRun, i).c_str(), expolygons);
{
BoundingBox bbox;
for (const IntersectionLine &l : lines[i]) {
bbox.merge(l.a);
bbox.merge(l.b);
}
SVG svg(debug_out_path("slice_loops_%d_%d.svg", iRun, i).c_str(), bbox);
svg.draw(expolygons);
for (const IntersectionLine &l : lines[i])
svg.draw(l, "red", 0);
svg.draw_outline(expolygons, "black", "blue", 0);
svg.Close();
}
#if 0
//FIXME slice_facet() may create zero length edges due to rounding of doubles into coord_t.
for (Polygon &poly : polygons) {
for (size_t i = 1; i < poly.points.size(); ++ i)
assert(poly.points[i-1] != poly.points[i]);
assert(poly.points.front() != poly.points.back());
}
#endif
}
++ iRun;
}
#endif
return layers;
}
// Specialized version for a single slicing plane only, running on a single thread.
Polygons slice_mesh(
const indexed_triangle_set &mesh,
// Unscaled Zs
const float plane_z,
const MeshSlicingParams &params)
{
std::vector<IntersectionLines> lines;
{
bool trafo_identity = is_identity(params.trafo);
Transform3f tf;
std::vector<bool> face_mask(mesh.indices.size(), false);
{
// 1) Mark vertices as below or above the slicing plane.
std::vector<char> vertex_side(mesh.vertices.size(), 0);
if (trafo_identity) {
for (size_t i = 0; i < mesh.vertices.size(); ++ i) {
float z = mesh.vertices[i].z();
char s = z < plane_z ? -1 : z == plane_z ? 0 : 1;
vertex_side[i] = s;
}
} else {
tf = make_trafo_for_slicing(params.trafo);
for (size_t i = 0; i < mesh.vertices.size(); ++ i) {
//FIXME don't need to transform x & y, just Z.
float z = (tf * mesh.vertices[i]).z();
char s = z < plane_z ? -1 : z == plane_z ? 0 : 1;
vertex_side[i] = s;
}
}
// 2) Mark faces crossing the plane.
for (size_t i = 0; i < mesh.indices.size(); ++ i) {
const Vec3i &face = mesh.indices[i];
int sides[3] = { vertex_side[face(0)], vertex_side[face(1)], vertex_side[face(2)] };
face_mask[i] = sides[0] * sides[1] <= 0 || sides[1] * sides[2] <= 0 || sides[0] * sides[2] <= 0;
}
}
// 3) Calculate face neighbors for just the faces in face_mask.
std::vector<Vec3i> face_edge_ids = its_face_edge_ids(mesh, face_mask);
// 4) Slice "face_mask" triangles, collect line segments.
// It likely is not worthwile to copy the vertices. Apply the transformation in place.
if (trafo_identity) {
lines.emplace_back(slice_make_lines(
mesh.vertices, [](const Vec3f &p) { return Vec3f(scaled<float>(p.x()), scaled<float>(p.y()), p.z()); },
mesh.indices, face_edge_ids, plane_z, [&face_mask](int face_idx) { return face_mask[face_idx]; }));
} else {
// Transform the vertices, scale up in XY, not in Z.
lines.emplace_back(slice_make_lines(mesh.vertices, [tf](const Vec3f& p) { return tf * p; }, mesh.indices, face_edge_ids, plane_z,
[&face_mask](int face_idx) { return face_mask[face_idx]; }));
}
}
// 5) Chain the line segments.
std::vector<Polygons> layers = make_loops(lines, params, [](){});
assert(layers.size() == 1);
return layers.front();
}
std::vector<ExPolygons> slice_mesh_ex(
const indexed_triangle_set &mesh,
const std::vector<float> &zs,
const MeshSlicingParamsEx &params,
std::function<void()> throw_on_cancel)
{
std::vector<Polygons> layers_p;
{
MeshSlicingParams slicing_params(params);
if (params.mode == MeshSlicingParams::SlicingMode::PositiveLargestContour)
slicing_params.mode = MeshSlicingParams::SlicingMode::Positive;
if (params.mode_below == MeshSlicingParams::SlicingMode::PositiveLargestContour)
slicing_params.mode_below = MeshSlicingParams::SlicingMode::Positive;
layers_p = slice_mesh(mesh, zs, slicing_params, throw_on_cancel);
}
// BOOST_LOG_TRIVIAL(debug) << "slice_mesh make_expolygons in parallel - start";
std::vector<ExPolygons> layers(layers_p.size(), ExPolygons{});
tbb::parallel_for(
tbb::blocked_range<size_t>(0, layers_p.size()),
[&layers_p, &params, &layers, throw_on_cancel]
(const tbb::blocked_range<size_t>& range) {
auto resolution = scaled<float>(params.resolution);
for (size_t layer_id = range.begin(); layer_id < range.end(); ++ layer_id) {
throw_on_cancel();
ExPolygons &expolygons = layers[layer_id];
const auto this_mode = layer_id < params.slicing_mode_normal_below_layer ? params.mode_below : params.mode;
Slic3r::make_expolygons(
layers_p[layer_id], params.closing_radius, params.extra_offset,
this_mode == MeshSlicingParams::SlicingMode::EvenOdd ? ClipperLib::pftEvenOdd :
this_mode == MeshSlicingParams::SlicingMode::PositiveLargestContour ? ClipperLib::pftPositive : ClipperLib::pftNonZero,
&expolygons);
//FIXME simplify
if (this_mode == MeshSlicingParams::SlicingMode::PositiveLargestContour)
keep_largest_contour_only(expolygons);
if (resolution != 0.) {
ExPolygons simplified;
simplified.reserve(expolygons.size());
for (const ExPolygon &ex : expolygons)
append(simplified, ex.simplify(resolution));
expolygons = std::move(simplified);
}
}
});
// BOOST_LOG_TRIVIAL(debug) << "slice_mesh make_expolygons in parallel - end";
return layers;
}
// Slice a triangle set with a set of Z slabs (thick layers).
// The effect is similar to producing the usual top / bottom layers from a sliced mesh by
// subtracting layer[i] from layer[i - 1] for the top surfaces resp.
// subtracting layer[i] from layer[i + 1] for the bottom surfaces,
// with the exception that the triangle set this function processes may not cover the whole top resp. bottom surface.
// top resp. bottom surfaces are calculated only if out_top resp. out_bottom is not null.
void slice_mesh_slabs(
const indexed_triangle_set &mesh,
// Unscaled Zs
const std::vector<float> &zs,
const Transform3d &trafo,
std::vector<Polygons> *out_top,
std::vector<Polygons> *out_bottom,
std::function<void()> throw_on_cancel)
{
BOOST_LOG_TRIVIAL(debug) << "slice_mesh_slabs to polygons";
#ifdef EXPENSIVE_DEBUG_CHECKS
{
// Verify that the vertices are unique.
auto v = mesh.vertices;
std::sort(v.begin(), v.end(), [](auto &l, auto &r) {
return l.x() < r.x() || (l.x() == r.x() && (l.y() < r.y() || (l.y() == r.y() && l.z() < r.z())));
});
size_t num_duplicates = v.end() - std::unique(v.begin(), v.end());
assert(num_duplicates == 0);
}
if (0)
{
// Verify that there are no T-joints.
// The T-joints could likely be already part of the source mesh.
for (const auto &tri : mesh.indices)
for (int i = 0; i < 3; ++ i) {
int j = next_idx_modulo(i, 3);
int k = next_idx_modulo(j, 3);
auto &v1 = mesh.vertices[tri(i)];
auto &v2 = mesh.vertices[tri(j)];
auto &v3 = mesh.vertices[tri(k)];
for (auto &pt : mesh.vertices)
if (&pt != &v1 && &pt != &v2) {
assert(pt != v1 && pt != v2);
assert((pt - v1).norm() > EPSILON);
assert((pt - v2).norm() > EPSILON);
auto l2 = (v2 - v1).squaredNorm();
assert(l2 > 0);
auto t = (pt - v1).dot(v2 - v1);
if (t > 0 && t < l2) {
auto d2 = (pt - v1).squaredNorm() - sqr(t) / l2;
auto d = sqrt(std::max(d2, 0.f));
if (&pt == &v3) {
if (d < EPSILON)
printf("Degenerate triangle!\n");
} else {
assert(d > EPSILON);
}
}
}
}
}
#endif // EXPENSIVE_DEBUG_CHECKS
std::vector<stl_vertex> vertices_transformed = transform_mesh_vertices_for_slicing(mesh, trafo);
const auto mirrored_sign = int64_t(trafo.matrix().block(0, 0, 3, 3).determinant() < 0 ? -1 : 1);
std::vector<FaceOrientation> face_orientation(mesh.indices.size(), FaceOrientation::Up);
for (const stl_triangle_vertex_indices &tri : mesh.indices) {
const Vec3f fa = vertices_transformed[tri(0)];
const Vec3f fb = vertices_transformed[tri(1)];
const Vec3f fc = vertices_transformed[tri(2)];
assert(fa != fb && fa != fc && fb != fc);
const Point a = to_2d(fa).cast<coord_t>();
const Point b = to_2d(fb).cast<coord_t>();
const Point c = to_2d(fc).cast<coord_t>();
const int64_t d = cross2((b - a).cast<int64_t>(), (c - b).cast<int64_t>()) * mirrored_sign;
FaceOrientation fo = FaceOrientation::Vertical;
if (d > 0)
fo = FaceOrientation::Up;
else if (d < 0)
fo = FaceOrientation::Down;
else {
// Is the triangle vertical or degenerate?
assert(d == 0);
fo = fa == fb || fa == fc || fb == fc ? FaceOrientation::Degenerate : FaceOrientation::Vertical;
}
face_orientation[&tri - mesh.indices.data()] = fo;
}
std::vector<Vec3i> face_neighbors = its_face_neighbors_par(mesh);
int num_edges;
std::vector<Vec3i> face_edge_ids = its_face_edge_ids(mesh, face_neighbors, true, &num_edges);
std::pair<SlabLines, SlabLines> lines = slice_slabs_make_lines(
vertices_transformed, mesh.indices, face_neighbors, face_edge_ids, num_edges, face_orientation, zs,
out_top != nullptr, out_bottom != nullptr, throw_on_cancel);
throw_on_cancel();
if (out_top)
*out_top = make_slab_loops<true>(lines.first, num_edges, throw_on_cancel);
if (out_bottom)
*out_bottom = make_slab_loops<false>(lines.second, num_edges, throw_on_cancel);
}
// Remove duplicates of slice_vertices, optionally triangulate the cut.
static void triangulate_slice(
indexed_triangle_set &its,
IntersectionLines &lines,
std::vector<int> &slice_vertices,
// Vertices of the original (unsliced) mesh. Newly added vertices are those on the slice.
int num_original_vertices,
// Z height of the slice.
float z,
bool triangulate,
bool normals_down,
const std::map<int, Vec3f*> &section_vertices_map)
{
sort_remove_duplicates(slice_vertices);
// 1) Create map of the slice vertices from positions to mesh indices.
// As the caller will likely add duplicate points when intersecting triangle edges, there will be duplicates.
std::vector<std::pair<Vec2f, int>> map_vertex_to_index;
map_vertex_to_index.reserve(slice_vertices.size());
for (int i : slice_vertices)
map_vertex_to_index.emplace_back(to_2d(its.vertices[i]), i);
std::sort(map_vertex_to_index.begin(), map_vertex_to_index.end(),
[](const std::pair<Vec2f, int> &l, const std::pair<Vec2f, int> &r) {
return l.first.x() < r.first.x() ||
(is_equal_for_sort(l.first.x(), r.first.x()) && (l.first.y()< r.first.y() ||
(is_equal_for_sort(l.first.y(), r.first.y()) && l.second < r.second)));
});
// 2) Discover duplicate points on the slice. Remap duplicate vertices to a vertex with a lowest index.
// Remove denegerate triangles, if they happen to be created by merging duplicate vertices.
{
std::vector<int> map_duplicate_vertex(int(its.vertices.size()) - num_original_vertices, -1);
int i = 0;
int k = 0;
for (; i < int(map_vertex_to_index.size());) {
map_vertex_to_index[k ++] = map_vertex_to_index[i];
const Vec2f &ipos = map_vertex_to_index[i].first;
const int iidx = map_vertex_to_index[i].second;
if (iidx >= num_original_vertices)
// map to itself
map_duplicate_vertex[iidx - num_original_vertices] = iidx;
int j = i;
for (++ j; j < int(map_vertex_to_index.size()) && is_equal(ipos.x(), map_vertex_to_index[j].first.x()) && is_equal(ipos.y(), map_vertex_to_index[j].first.y()); ++ j) {
const int jidx = map_vertex_to_index[j].second;
assert(jidx >= num_original_vertices);
if (jidx >= num_original_vertices)
// map to the first vertex
map_duplicate_vertex[jidx - num_original_vertices] = iidx;
}
i = j;
}
map_vertex_to_index.erase(map_vertex_to_index.begin() + k, map_vertex_to_index.end());
for (i = 0; i < int(its.indices.size());) {
stl_triangle_vertex_indices &f = its.indices[i];
// Remap the newly added face vertices.
for (k = 0; k < 3; ++ k)
if (f(k) >= num_original_vertices)
f(k) = map_duplicate_vertex[f(k) - num_original_vertices];
if (f(0) == f(1) || f(0) == f(2) || f(1) == f(2)) {
// Remove degenerate face.
f = its.indices.back();
its.indices.pop_back();
} else
// Keep the face.
++ i;
}
}
if (triangulate) {
size_t idx_vertex_new_first = its.vertices.size();
Pointf3s triangles = triangulate_expolygons_3d(make_expolygons_simple(lines), z, normals_down);
for (size_t i = 0; i < triangles.size(); ) {
stl_triangle_vertex_indices facet;
for (size_t j = 0; j < 3; ++ j) {
Vec3f v = triangles[i ++].cast<float>();
auto it = lower_bound_by_predicate(map_vertex_to_index.begin(), map_vertex_to_index.end(),
[&v](const std::pair<Vec2f, int> &l) {
return l.first.x() < v.x() || (is_equal_for_sort(l.first.x(), v.x()) && l.first.y() < v.y());
});
auto back_it = it;
int idx = -1;
bool exist = false;
for (auto iter = section_vertices_map.begin(); iter != section_vertices_map.end(); iter++) {
if (is_equal(v, *iter->second)) {
idx = iter->first;
exist = true;
break;
}
}
// go on finding
if (!exist) {
for (; it != map_vertex_to_index.end(); it++) {
if (is_equal(it->first.x(), v.x()) && is_equal(it->first.y(), v.y())) {
idx = it->second;
exist = true;
break;
}
}
}
// go on finding
if (!exist) {
it = back_it;
for (; it != map_vertex_to_index.begin(); it--) {
if (is_equal(it->first.x(), v.x()) && is_equal(it->first.y(), v.y())) {
idx = it->second;
exist = true;
break;
}
}
}
if (!exist){
// Try to find the vertex in the list of newly added vertices. Those vertices are not matched on the cut and they shall be rare.
for (size_t k = idx_vertex_new_first; k < its.vertices.size(); ++ k)
if (its.vertices[k] == v) {
idx = int(k);
break;
}
if (idx == -1) {
idx = int(its.vertices.size());
its.vertices.emplace_back(v);
}
}
facet(j) = idx;
}
if (facet(0) != facet(1) && facet(0) != facet(2) && facet(1) != facet(2))
its.indices.emplace_back(facet);
}
}
// Remove vertices, which are not referenced by any face.
its_compactify_vertices(its);
// Degenerate faces should not be created.
// its_remove_degenerate_faces(its);
}
void project_mesh(
const indexed_triangle_set &mesh,
const Transform3d &trafo,
Polygons *out_top,
Polygons *out_bottom,
std::function<void()> throw_on_cancel)
{
std::vector<Polygons> top, bottom;
std::vector<float> zs { -1e10, 1e10 };
slice_mesh_slabs(mesh, zs, trafo, out_top ? &top : nullptr, out_bottom ? &bottom : nullptr, throw_on_cancel);
if (out_top)
*out_top = std::move(top.front());
if (out_bottom)
*out_bottom = std::move(bottom.back());
}
Polygons project_mesh(
const indexed_triangle_set &mesh,
const Transform3d &trafo,
std::function<void()> throw_on_cancel)
{
std::vector<Polygons> top, bottom;
std::vector<float> zs { -1e10, 1e10 };
slice_mesh_slabs(mesh, zs, trafo, &top, &bottom, throw_on_cancel);
return union_(top.front(), bottom.back());
}
void cut_mesh(const indexed_triangle_set& mesh, float z, indexed_triangle_set* upper, indexed_triangle_set* lower, bool triangulate_caps)
{
assert(upper || lower);
if (upper == nullptr && lower == nullptr)
return;
BOOST_LOG_TRIVIAL(trace) << "cut_mesh - slicing object";
if (upper) {
upper->clear();
upper->vertices = mesh.vertices;
upper->indices.reserve(mesh.indices.size());
}
if (lower) {
lower->clear();
lower->vertices = mesh.vertices;
lower->indices.reserve(mesh.indices.size());
}
#ifndef NDEBUG
size_t num_open_edges_old = triangulate_caps ? its_num_open_edges(mesh) : 0;
#endif // NDEBUG
// To triangulate the caps after slicing.
IntersectionLines upper_lines, lower_lines;
std::vector<int> upper_slice_vertices, lower_slice_vertices;
std::vector<Vec3i> facets_edge_ids = its_face_edge_ids(mesh);
std::map<int, Vec3f *> section_vertices_map;
for (int facet_idx = 0; facet_idx < int(mesh.indices.size()); ++ facet_idx) {
const stl_triangle_vertex_indices &facet = mesh.indices[facet_idx];
Vec3f vertices[3] { mesh.vertices[facet(0)], mesh.vertices[facet(1)], mesh.vertices[facet(2)] };
float min_z = std::min(vertices[0].z(), std::min(vertices[1].z(), vertices[2].z()));
float max_z = std::max(vertices[0].z(), std::max(vertices[1].z(), vertices[2].z()));
for (size_t i = 0; i < 3; i++) {
if (is_equal(z, vertices[i].z()) && section_vertices_map[facet(i)] == nullptr) {
section_vertices_map[facet(i)] = new Vec3f(vertices[i].x(), vertices[i].y(), vertices[i].z());
}
}
// intersect facet with cutting plane
IntersectionLine line;
int idx_vertex_lowest = is_equal(vertices[1].z(), min_z) ? 1 : (is_equal(vertices[2].z() , min_z) ? 2 : 0);
FacetSliceType slice_type = FacetSliceType::NoSlice;
if (z > min_z - EPSILON && z < max_z + EPSILON) {
Vec3f vertices_scaled[3];
for (int i = 0; i < 3; ++ i) {
const Vec3f &src = vertices[i];
Vec3f &dst = vertices_scaled[i];
dst.x() = scale_(src.x());
dst.y() = scale_(src.y());
dst.z() = src.z();
}
slice_type = slice_facet_for_cut_mesh(z, vertices_scaled, mesh.indices[facet_idx], facets_edge_ids[facet_idx], idx_vertex_lowest, is_equal(min_z, max_z), line);
}
if (slice_type != FacetSliceType::NoSlice) {
// Save intersection lines for generating correct triangulations.
if (line.edge_type == IntersectionLine::FacetEdgeType::Top) {
lower_lines.emplace_back(line);
lower_slice_vertices.emplace_back(line.a_id);
lower_slice_vertices.emplace_back(line.b_id);
} else if (line.edge_type == IntersectionLine::FacetEdgeType::Bottom) {
upper_lines.emplace_back(line);
upper_slice_vertices.emplace_back(line.a_id);
upper_slice_vertices.emplace_back(line.b_id);
} else if (line.edge_type == IntersectionLine::FacetEdgeType::General) {
lower_lines.emplace_back(line);
upper_lines.emplace_back(line);
}
}
if (min_z > z || (is_equal(min_z , z) && max_z > z)) {
// facet is above the cut plane and does not belong to it
if (upper != nullptr)
upper->indices.emplace_back(facet);
} else if (max_z < z || (is_equal(max_z, z) && min_z < z)) {
// facet is below the cut plane and does not belong to it
if (lower != nullptr)
lower->indices.emplace_back(facet);
} else if (min_z < z && max_z > z) {
// Facet is cut by the slicing plane.
assert(slice_type == FacetSliceType::Slicing);
assert(line.edge_type == IntersectionLine::FacetEdgeType::General);
assert(line.edge_a_id != -1);
assert(line.edge_b_id != -1);
// look for the vertex on whose side of the slicing plane there are no other vertices
int isolated_vertex, isolated_vertex_option = -1;
std::vector<int> list{0, 1, 2};
auto get_third = [&list](int isolated_vertex, int temp) {// not use vertex data
for (size_t i = 0; i < list.size(); i++) {
if (list[i] != isolated_vertex && list[i] != temp) {
return list[i];
}
}
return -1;
};
if (is_equal(vertices[0].z(), z)) {
isolated_vertex = vertices[1].z() > z ? 1 : 2;
isolated_vertex_option = get_third(isolated_vertex, 0);
} else if (is_equal(vertices[1].z(), z)) {
isolated_vertex = vertices[2].z() > z ? 2 : 0;
isolated_vertex_option = get_third(isolated_vertex, 1);
} else if (is_equal(vertices[2].z(), z)) {
isolated_vertex = vertices[0].z() > z ? 0 : 1;
isolated_vertex_option = get_third(isolated_vertex, 2);
} else {
isolated_vertex = (vertices[0].z() > z) == (vertices[1].z() > z) ? 2 : (vertices[1].z() > z) == (vertices[2].z() > z) ? 0 : 1;
}
// get vertices starting from the isolated one
stl_vertex v0v1, v2v0;
auto calc_isolated_vertex = [&v0v1, &v2v0, &line, &facet_idx, &facets_edge_ids, &z](int iv, bool &is_find) {
assert(facets_edge_ids[facet_idx](iv) == line.edge_a_id || facets_edge_ids[facet_idx](iv) == line.edge_b_id);
is_find = true;
if (facets_edge_ids[facet_idx](iv) == line.edge_a_id) {
// Unscale to doubles first, then to floats to reach the same accuracy as triangulate_expolygons_2d().
v0v1 = to_3d(unscaled<double>(line.a).cast<float>().eval(), z);
v2v0 = to_3d(unscaled<double>(line.b).cast<float>().eval(), z);
} else if (facets_edge_ids[facet_idx](iv) == line.edge_b_id) {
v0v1 = to_3d(unscaled<double>(line.b).cast<float>().eval(), z);
v2v0 = to_3d(unscaled<double>(line.a).cast<float>().eval(), z);
} else {
is_find = false;
}
};
bool find_isolated_vertex;
int iv;
calc_isolated_vertex(isolated_vertex, find_isolated_vertex);
if (!find_isolated_vertex && isolated_vertex_option != -1) {
calc_isolated_vertex(isolated_vertex_option, find_isolated_vertex);
if (!find_isolated_vertex) {
BOOST_LOG_TRIVIAL(trace) << "cut_mesh:error:could not find isolated_vertex";
continue;
}
iv = isolated_vertex_option;
} else {
iv = isolated_vertex;
}
const stl_vertex &v0 = vertices[iv];
const int iv0 = facet[iv];
if (++ iv == 3)
iv = 0;
const stl_vertex &v1 = vertices[iv];
const int iv1 = facet[iv];
if (++ iv == 3)
iv = 0;
const stl_vertex &v2 = vertices[iv];
const int iv2 = facet[iv];
// intersect v0-v1 and v2-v0 with cutting plane and make new vertices
auto new_vertex = [upper, lower, &upper_slice_vertices, &lower_slice_vertices](const Vec3f &a, const int ia, const Vec3f &b, const int ib, const Vec3f &c,
const int ic, const Vec3f &new_pt, bool &is_new_vertex) {
int iupper, ilower;
is_new_vertex = false;
if (is_equal(new_pt, a))
iupper = ilower = ia;
else if (is_equal(new_pt, b))
iupper = ilower = ib;
else if (is_equal(new_pt, c))
iupper = ilower = ic;
else {
// Insert a new vertex into upper / lower.
is_new_vertex = true;
if (upper) {
iupper = int(upper->vertices.size());
upper->vertices.emplace_back(new_pt);
upper_slice_vertices.emplace_back(iupper);
}
if (lower) {
ilower = int(lower->vertices.size());
lower->vertices.emplace_back(new_pt);
lower_slice_vertices.emplace_back(ilower);
}
}
return std::make_pair(iupper, ilower);
};
bool is_new_vertex_v0v1;
bool is_new_vertex_v2v0;
auto [iv0v1_upper, iv0v1_lower] = new_vertex(v1, iv1, v0, iv0, v2, iv2, v0v1, is_new_vertex_v0v1);
auto [iv2v0_upper, iv2v0_lower] = new_vertex(v2, iv2, v0, iv0, v1, iv1, v2v0, is_new_vertex_v2v0);
auto new_face = [](indexed_triangle_set *its, int i, int j, int k) {
if (its != nullptr && i != j && i != k && j != k) its->indices.emplace_back(i, j, k);
};
if (is_new_vertex_v0v1 && is_new_vertex_v2v0) {
if (v0.z() > z) {
new_face(upper, iv0, iv0v1_upper, iv2v0_upper);
new_face(lower, iv1, iv2, iv0v1_lower);
new_face(lower, iv2, iv2v0_lower, iv0v1_lower);
} else {
new_face(upper, iv1, iv2, iv0v1_upper);
new_face(upper, iv2, iv2v0_upper, iv0v1_upper);
new_face(lower, iv0, iv0v1_lower, iv2v0_lower);
}
} else if (is_new_vertex_v0v1) {
if (v0.z() > z) {
new_face(upper, iv0, iv0v1_upper, iv2);
new_face(lower, iv1, iv2, iv0v1_lower);
} else {
new_face(lower, iv0, iv0v1_lower, iv2);
new_face(upper, iv1, iv2, iv0v1_upper);
}
} else if (is_new_vertex_v2v0) {
if (v0.z() > z) {
new_face(upper, iv0, iv1, iv2v0_upper);
new_face(lower, iv1, iv2, iv2v0_lower);
} else {
new_face(lower, iv0, iv1, iv2v0_lower);
new_face(upper, iv1, iv2, iv2v0_upper);
}
}
}
}
if (upper != nullptr) {
triangulate_slice(*upper, upper_lines, upper_slice_vertices, int(mesh.vertices.size()), z, triangulate_caps, NORMALS_DOWN, section_vertices_map);
#ifndef NDEBUG
if (triangulate_caps) {
size_t num_open_edges_new = its_num_open_edges(*upper);
assert(num_open_edges_new <= num_open_edges_old);
}
#endif // NDEBUG
}
if (lower != nullptr) {
triangulate_slice(*lower, lower_lines, lower_slice_vertices, int(mesh.vertices.size()), z, triangulate_caps, NORMALS_UP, section_vertices_map);
#ifndef NDEBUG
if (triangulate_caps) {
size_t num_open_edges_new = its_num_open_edges(*lower);
assert(num_open_edges_new <= num_open_edges_old);
}
#endif // NDEBUG
}
std::map<int, Vec3f*>().swap(section_vertices_map);
}
} // namespace Slic3r