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

OperationRedrawModel.cs « Operations « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 479d51d76a44016a91e791fbc0c577a884dd6338 (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
/*
 *                     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 Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;

namespace UVtools.Core.Operations;

[Serializable]
public class OperationRedrawModel : Operation
{
    #region Members

    private string _filePath = null!;
    private byte _brightness = 220;
    private bool _contactPointsOnly = true;
    private RedrawTypes _redrawType = RedrawTypes.Supports;
    private bool _ignoreContactLessPixels = true;

    #endregion
        
    #region Overrides

    public override LayerRangeSelection StartLayerRangeSelection { get; } = LayerRangeSelection.None;
    public override string IconClass => "mdi-puzzle-edit";
    public override string Title => "Redraw model/supports";

    public override string Description =>
        "Redraw the model or supports with a set brightness. This requires an extra sliced file from same object but without any supports and raft, straight to the build plate.\n" +
        "Note: Run this tool prior to any made modification. You must find the optimal exposure/brightness combo, or supports can fail.";

    public override string ConfirmationText => "redraw the "+ (_redrawType == RedrawTypes.Supports ? "supports" : "model") + 
                                               $" with an brightness of {_brightness}?";

    public override string ProgressTitle => "Redrawing " + (_redrawType == RedrawTypes.Supports ? "supports" : "model");

    public override string ProgressAction => "Redraw layers";

    public override string? ValidateInternally()
    {
        var sb = new StringBuilder();

        if (IsFileValid() is null)
        {
            sb.AppendLine("The selected file is not valid.");
        }

        return sb.ToString();
    }


    public override string ToString()
    {
        var result = $"[{_redrawType}] [B: {_brightness}] [CS: {_contactPointsOnly}] [ICLP: {_ignoreContactLessPixels}]";
        if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
        return result;
    }
        

    #endregion

    #region Enums
    public enum RedrawTypes : byte
    {
        Supports,
        Model,
    }
    #endregion

    #region Constructor

    public OperationRedrawModel() { }

    public OperationRedrawModel(FileFormat slicerFile) : base(slicerFile) { }

    #endregion

    #region Properties

    [XmlIgnore]
    public string FilePath
    {
        get => _filePath;
        set => RaiseAndSetIfChanged(ref _filePath, value);
    }

    public RedrawTypes RedrawType
    {
        get => _redrawType;
        set => RaiseAndSetIfChanged(ref _redrawType, value);
    }

    public static Array RedrawTypesItems => Enum.GetValues(typeof(RedrawTypes));

    public byte Brightness
    {
        get => _brightness;
        set
        {
            if (!RaiseAndSetIfChanged(ref _brightness, value)) return;
            RaisePropertyChanged(nameof(BrightnessPercent));
        }
    }

    public decimal BrightnessPercent => Math.Round(_brightness * 100 / 255M, 2);

    public bool ContactPointsOnly
    {
        get => _contactPointsOnly;
        set => RaiseAndSetIfChanged(ref _contactPointsOnly, value);
    }

    public bool IgnoreContactLessPixels
    {
        get => _ignoreContactLessPixels;
        set => RaiseAndSetIfChanged(ref _ignoreContactLessPixels, value);
    }

    #endregion

    #region Equality

    protected bool Equals(OperationRedrawModel other)
    {
        return _brightness == other._brightness && _contactPointsOnly == other._contactPointsOnly && _redrawType == other._redrawType && _ignoreContactLessPixels == other._ignoreContactLessPixels;
    }

    public override bool Equals(object? obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((OperationRedrawModel) obj);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(_brightness, _contactPointsOnly, (int) _redrawType, _ignoreContactLessPixels);
    }

    #endregion

    #region Methods

    public FileFormat? IsFileValid(bool returnNewInstance = false) =>
        FileFormat.FindByExtensionOrFilePath(_filePath, returnNewInstance);

    protected override bool ExecuteInternally(OperationProgress progress)
    {
        var otherFile = IsFileValid(true);
        if (otherFile is null)
        {
            return false;
        }
        otherFile.Decode(_filePath, progress);

        progress.Reset(ProgressAction, otherFile.LayerCount);

        int startLayerIndex = (int)(SlicerFile.LayerCount - otherFile.LayerCount);
        if (startLayerIndex < 0) return false;
        Parallel.For(0, otherFile.LayerCount, CoreSettings.GetParallelOptions(progress), layerIndex =>
        {
            var fullMatLayerIndex = startLayerIndex + layerIndex;
            using var fullMat = SlicerFile[fullMatLayerIndex].LayerMat;
            using var original = fullMat.Clone();
            using var bodyMat = otherFile[layerIndex].LayerMat;
            using var fullMatRoi = GetRoiOrDefault(fullMat);
            using var bodyMatRoi = GetRoiOrDefault(bodyMat);
            using var patternMat = EmguExtensions.InitMat(fullMatRoi.Size, new MCvScalar(255 - _brightness));
            using var supportsMat = new Mat();

            bool modified = false;
            if (_redrawType == RedrawTypes.Supports && _contactPointsOnly)
            {
                if (layerIndex + 1 >= otherFile.LayerCount) return;
                CvInvoke.Subtract(fullMatRoi, bodyMatRoi, supportsMat); // Supports
                using var contours = supportsMat.FindContours(RetrType.List);
                if (contours.Size <= 0) return;
                using var nextLayerMat = otherFile[layerIndex + 1].LayerMat;
                using var nextLayerMatRoi = GetRoiOrDefault(nextLayerMat);
                var fullSpan = fullMatRoi.GetDataByteSpan();
                var supportsSpan = supportsMat.GetDataByteSpan();
                var nextSpan = nextLayerMatRoi.GetDataByteSpan();
                for (int i = 0; i < contours.Size; i++)
                {
                    var foundContour = false;
                    var rectangle = CvInvoke.BoundingRectangle(contours[i]);
                    for (int y = rectangle.Y; y < rectangle.Bottom && !foundContour; y++)
                    for (int x = rectangle.X; x < rectangle.Right; x++)
                    {
                        var pos = supportsMat.GetPixelPos(x, y);
                        if (_ignoreContactLessPixels)
                        {
                            if (supportsSpan[pos] <= 10) continue;
                            if (nextSpan[pos] <= 0) continue;
                            modified = true;
                            fullSpan[pos] = _brightness;
                        }
                        else
                        {
                            if (supportsSpan[pos] <= 100) continue;
                            if (nextSpan[pos] <= 150) continue;
                            CvInvoke.DrawContours(fullMatRoi, contours, i, new MCvScalar(_brightness), -1, LineType.AntiAlias);
                            modified = true;
                            foundContour = true;
                            break;
                        }
                               
                    }
                }
            }
            else
            {
                switch (_redrawType)
                {
                    case RedrawTypes.Supports:
                        CvInvoke.Subtract(fullMatRoi, bodyMatRoi, supportsMat); // Supports
                        break;
                    case RedrawTypes.Model:
                        CvInvoke.BitwiseAnd(fullMatRoi, bodyMatRoi, supportsMat); // Model
                        break;
                }

                CvInvoke.Subtract(fullMatRoi, patternMat, fullMatRoi, supportsMat);
                modified = true;
            }

            if (modified)
            {
                ApplyMask(original, fullMatRoi);
                SlicerFile[fullMatLayerIndex].LayerMat = fullMat;
            }

            progress.LockAndIncrement();
        });

        return !progress.Token.IsCancellationRequested;
    }

    #endregion
}