Welcome to mirror list, hosted at ThFree Co, Russian Federation.

OperationRepairLayers.cs « Operations « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e46d3c2bf58e2d0d4a6bc5fae375d5e9fa8d151a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
 *                     GNU AFFERO GENERAL PUBLIC LICENSE
 *                       Version 3, 19 November 2007
 *  Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 *  Everyone is permitted to copy and distribute verbatim copies
 *  of this license document, but changing it is not allowed.
 */

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;
using UVtools.Core.Objects;

namespace UVtools.Core.Operations
{
    [Serializable]
    public class OperationRepairLayers : Operation
    {
        #region Members
        private bool _repairIslands = true;
        private bool _repairResinTraps = true;
        private bool _removeEmptyLayers = true;
        private byte _removeIslandsBelowEqualPixelCount = 5;
        private ushort _removeIslandsRecursiveIterations = 4;
        private uint _gapClosingIterations = 1;
        private uint _noiseRemovalIterations;
        #endregion

        #region Overrides
        public override bool CanROI => false;
        public override string Title => "Repair layers and issues";
        public override string Description => null;

        public override string ConfirmationText => "attempt  this repair?";

        public override string ProgressTitle =>
            $"Reparing layers {LayerIndexStart} through {LayerIndexEnd}";

        public override string ProgressAction => "Repaired layers";

        public override bool CanHaveProfiles => false;

        public override StringTag Validate(params object[] parameters)
        {
            var sb = new StringBuilder();

            if (!RepairIslands && !RemoveEmptyLayers && !RepairResinTraps)
            {
                sb.AppendLine("You must select at least one repair operation.");
            }

            return new StringTag(sb.ToString());
        }
        #endregion

        #region Properties
        public bool RepairIslands
        {
            get => _repairIslands;
            set => RaiseAndSetIfChanged(ref _repairIslands, value);
        }

        public bool RepairResinTraps
        {
            get => _repairResinTraps;
            set => RaiseAndSetIfChanged(ref _repairResinTraps, value);
        }

        public bool RemoveEmptyLayers
        {
            get => _removeEmptyLayers;
            set => RaiseAndSetIfChanged(ref _removeEmptyLayers, value);
        }

        public byte RemoveIslandsBelowEqualPixelCount
        {
            get => _removeIslandsBelowEqualPixelCount;
            set => RaiseAndSetIfChanged(ref _removeIslandsBelowEqualPixelCount, value);
        }

        public ushort RemoveIslandsRecursiveIterations
        {
            get => _removeIslandsRecursiveIterations;
            set => RaiseAndSetIfChanged(ref _removeIslandsRecursiveIterations, value);
        }

        public uint GapClosingIterations
        {
            get => _gapClosingIterations;
            set => RaiseAndSetIfChanged(ref _gapClosingIterations, value);
        }

        public uint NoiseRemovalIterations
        {
            get => _noiseRemovalIterations;
            set => RaiseAndSetIfChanged(ref _noiseRemovalIterations, value);
        }

        [XmlIgnore]
        public IslandDetectionConfiguration IslandDetectionConfig { get; set; }

        [XmlIgnore]
        public List<LayerIssue> Issues { get; set; }
        #endregion

        #region Methods

        public override bool Execute(FileFormat slicerFile, OperationProgress progress = null)
        {
            progress ??= new OperationProgress();



            // Remove islands
            if (!ReferenceEquals(Issues, null)
                && !ReferenceEquals(IslandDetectionConfig, null)
                && RepairIslands
                && RemoveIslandsBelowEqualPixelCount > 0
                && RemoveIslandsRecursiveIterations != 1)
            {
                progress.Reset("Removed recursive islands", 0);
                ushort limit = RemoveIslandsRecursiveIterations == 0
                    ? ushort.MaxValue
                    : RemoveIslandsRecursiveIterations;

                var recursiveIssues = Issues;
                ConcurrentBag<uint> islandsToRecompute = null;

                var islandConfig = IslandDetectionConfig;
                var overhangConfig = new OverhangDetectionConfiguration(false);
                var touchingBoundsConfig = new TouchingBoundDetectionConfiguration(false);
                var resinTrapsConfig = new ResinTrapDetectionConfiguration(false);
                var emptyLayersConfig = false;

                islandConfig.Enabled = true;
                islandConfig.RequiredAreaToProcessCheck = (byte)Math.Ceiling(RemoveIslandsBelowEqualPixelCount / 2m);

                for (uint i = 0; i < limit; i++)
                {
                    if (i > 0)
                    {
                        /*var whiteList = islandsToRecompute.GroupBy(u => u)
                            .Select(grp => grp.First())
                            .ToList();*/
                        islandConfig.WhiteListLayers = islandsToRecompute.ToList();
                        recursiveIssues = slicerFile.LayerManager.GetAllIssues(islandConfig, overhangConfig, resinTrapsConfig, touchingBoundsConfig, emptyLayersConfig);
                        //Debug.WriteLine(i);
                    }

                    var issuesGroup =
                        recursiveIssues
                        .Where(issue => issue.Type == LayerIssue.IssueType.Island &&
                                        issue.Pixels.Length <= RemoveIslandsBelowEqualPixelCount)
                        .GroupBy(issue => issue.LayerIndex);

                    if (!issuesGroup.Any()) break; // Nothing to process
                    islandsToRecompute = new ConcurrentBag<uint>();
                    Parallel.ForEach(issuesGroup, group =>
                    {
                        if (progress.Token.IsCancellationRequested) return;
                        Layer layer = slicerFile[group.Key];
                        Mat image = layer.LayerMat;
                        Span<byte> bytes = image.GetPixelSpan<byte>();
                        foreach (var issue in group)
                        {
                            foreach (var issuePixel in issue.Pixels)
                            {
                                bytes[image.GetPixelPos(issuePixel)] = 0;
                            }

                            lock (progress.Mutex)
                            {
                                progress++;
                            }
                        }

                        var nextLayerIndex = group.Key + 1;
                        if (nextLayerIndex < slicerFile.LayerCount)
                            islandsToRecompute.Add(nextLayerIndex);

                        layer.LayerMat = image;
                    });

                    if (islandsToRecompute.IsEmpty) break; // No more leftovers
                }
            }

            progress.Reset(ProgressAction, LayerRangeCount);
            if (RepairIslands || RepairResinTraps)
            {
                Parallel.For(LayerIndexStart, LayerIndexEnd, layerIndex =>
                {
                    if (progress.Token.IsCancellationRequested) return;
                    Layer layer = slicerFile[layerIndex];
                    Mat image = null;

                    void initImage()
                    {
                        image ??= layer.LayerMat;
                    }

                    if (Issues is not null)
                    {
                        if (RepairIslands && RemoveIslandsBelowEqualPixelCount > 0 && RemoveIslandsRecursiveIterations == 1)
                        {
                            Span<byte> bytes = null;
                            foreach (var issue in Issues)
                            {
                                if (
                                    issue.LayerIndex != layerIndex ||
                                    issue.Type != LayerIssue.IssueType.Island ||
                                    issue.Pixels.Length > RemoveIslandsBelowEqualPixelCount) continue;

                                initImage();
                                if (bytes == null)
                                    bytes = image.GetPixelSpan<byte>();

                                foreach (var issuePixel in issue.Pixels)
                                {
                                    bytes[image.GetPixelPos(issuePixel)] = 0;
                                }
                            }
                            /*if (issues.TryGetValue((uint)layerIndex, out var issueList))
                            {
                                var bytes = image.GetPixelSpan<byte>();
                                foreach (var issue in issueList.Where(issue =>
                                    issue.Type == LayerIssue.IssueType.Island && issue.Pixels.Length <= removeIslandsBelowEqualPixels))
                                {
                                    foreach (var issuePixel in issue.Pixels)
                                    {
                                        bytes[image.GetPixelPos(issuePixel)] = 0;
                                    }
                                }
                            }*/
                        }

                        if (RepairResinTraps)
                        {
                            foreach (var issue in Issues.Where(issue => issue.LayerIndex == layerIndex && issue.Type == LayerIssue.IssueType.ResinTrap))
                            {
                                initImage();
                                using var vec = new VectorOfVectorOfPoint(new VectorOfPoint(issue.Pixels));
                                CvInvoke.DrawContours(image,
                                    vec,
                                    -1,
                                    EmguExtensions.WhiteByte,
                                    -1);
                            }
                        }
                    }

                    if (RepairIslands && (GapClosingIterations > 0 || NoiseRemovalIterations > 0))
                    {
                        initImage();
                        using Mat kernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3),
                            new Point(-1, -1));
                        if (GapClosingIterations > 0)
                        {
                            CvInvoke.MorphologyEx(image, image, MorphOp.Close, kernel, new Point(-1, -1),
                                (int)GapClosingIterations, BorderType.Default, default);
                        }

                        if (NoiseRemovalIterations > 0)
                        {
                            CvInvoke.MorphologyEx(image, image, MorphOp.Open, kernel, new Point(-1, -1),
                                (int)NoiseRemovalIterations, BorderType.Default, default);
                        }
                    }

                    if (!ReferenceEquals(image, null))
                    {
                        layer.LayerMat = image;
                        image.Dispose();
                    }

                    lock (progress.Mutex)
                    {
                        progress++;
                    }
                });
            }

            if (RemoveEmptyLayers)
            {
                List<uint> removeLayers = new List<uint>();
                for (uint layerIndex = LayerIndexStart; layerIndex <= LayerIndexEnd; layerIndex++)
                {
                    if (slicerFile[layerIndex].NonZeroPixelCount == 0)
                    {
                        removeLayers.Add(layerIndex);
                    }
                }

                if (removeLayers.Count > 0)
                {
                    OperationLayerRemove.RemoveLayers(slicerFile, removeLayers, progress);
                }
            }

            progress.Token.ThrowIfCancellationRequested();

            return true;
        }

        #endregion
    }
}