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

OperationCalibrateStressTower.cs « Operations « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ab14dec3b12bd41f57208d253e47532775f9873a (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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
 *                     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.Drawing;
using System.Text;
using System.Threading.Tasks;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;
using UVtools.Core.Layers;

namespace UVtools.Core.Operations;

[Serializable]
public sealed class OperationCalibrateStressTower : Operation
{
    #region Members
    private decimal _displayWidth;
    private decimal _displayHeight;
    private decimal _layerHeight;
    private ushort _bottomLayers;
    private decimal _bottomExposure;
    private decimal _normalExposure;
    private decimal _baseDiameter = 30;
    private decimal _baseHeight = 3;
    private decimal _bodyHeight = 50;
    private decimal _ceilHeight = 3;
    private byte _chamferLayers = 6;
    private bool _enableAntiAliasing = true;
    private bool _mirrorOutput;
    private byte _spirals = 2;
    private decimal _spiralDiameter = 2;
    private SpiralDirections _spiralDirection = SpiralDirections.Both;
    private decimal _spiralAngleStepPerLayer = 1;

    #endregion

    #region Overrides

    public override bool CanROI => false;

    public override bool CanCancel => false;

    public override LayerRangeSelection StartLayerRangeSelection => LayerRangeSelection.None;
    public override string IconClass => "fa-solid fa-chess-rook";
    public override string Title => "Stress tower";
    public override string Description =>
        "Generates a stress tower to test the printer capabilities.\n" +
        "Note: The current opened file will be overwritten with this test, use a dummy or a not needed file.";

    public override string ConfirmationText =>
        $"generate the stress tower?";

    public override string ProgressTitle =>
        $"Generating the stress tower";

    public override string ProgressAction => "Generated";

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

        if (_displayWidth <= 0)
        {
            sb.AppendLine("Display width must be a positive value.");
        }

        if (_displayHeight <= 0)
        {
            sb.AppendLine("Display height must be a positive value.");
        }
           
        return sb.ToString();
    }

    public override string ToString()
    {
        var result = $"[Layer Height: {_layerHeight}] " +
                     $"[Bottom layers: {_bottomLayers}] " +
                     $"[Exposure: {_bottomExposure}/{_normalExposure}] " +
                     $"[Base: H:{_baseHeight} D:{_baseDiameter}] " +
                     $"[Ceil: {_ceilHeight}] [Body: {_bodyHeight}] " +
                     $"[Chamfer: {_chamferLayers}] " +
                     $"[Spirals: {_spirals} Dir: {_spiralDirection} D:{_spiralDiameter} Angle: {_spiralAngleStepPerLayer}º]" +
                     $"[AA: {_enableAntiAliasing}] [Mirror: {_mirrorOutput}]";
        if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
        return result;
    }

    #endregion

    #region Constructor

    public OperationCalibrateStressTower() { }

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

    public override void InitWithSlicerFile()
    {
        base.InitWithSlicerFile();
        if(_layerHeight <= 0) _layerHeight = (decimal)SlicerFile.LayerHeight;
        if(_bottomLayers <= 0) _bottomLayers = SlicerFile.BottomLayerCount;
        if(_bottomExposure <= 0) _bottomExposure = (decimal)SlicerFile.BottomExposureTime;
        if(_normalExposure <= 0) _normalExposure = (decimal)SlicerFile.ExposureTime;
        _mirrorOutput = SlicerFile.DisplayMirror != FlipDirection.None;

        if (SlicerFile.DisplayWidth > 0)
            DisplayWidth = (decimal)SlicerFile.DisplayWidth;
        if (SlicerFile.DisplayHeight > 0)
            DisplayHeight = (decimal)SlicerFile.DisplayHeight;
    }

    #endregion

    #region Properties

    public decimal DisplayWidth
    {
        get => _displayWidth;
        set
        {
            if(!RaiseAndSetIfChanged(ref _displayWidth, Math.Round(value, 2))) return;
        }
    }

    public decimal DisplayHeight
    {
        get => _displayHeight;
        set
        {
            if(!RaiseAndSetIfChanged(ref _displayHeight, Math.Round(value, 2))) return;
        }
    }

    public decimal LayerHeight
    {
        get => _layerHeight;
        set
        {
            if(!RaiseAndSetIfChanged(ref _layerHeight, Layer.RoundHeight(value))) return;
            RaisePropertyChanged(nameof(BottomLayersMM));
            RaisePropertyChanged(nameof(LayerCount));
        }
    }

    public ushort Microns => (ushort)(LayerHeight * 1000);

    public ushort BottomLayers
    {
        get => _bottomLayers;
        set
        {
            if(!RaiseAndSetIfChanged(ref _bottomLayers, value)) return;
            RaisePropertyChanged(nameof(BottomLayersMM));
        }
    }

    public decimal BottomLayersMM => Layer.RoundHeight(LayerHeight * BottomLayers);

    public decimal BottomExposure
    {
        get => _bottomExposure;
        set => RaiseAndSetIfChanged(ref _bottomExposure, Math.Round(value, 2));
    }

    public decimal NormalExposure
    {
        get => _normalExposure;
        set => RaiseAndSetIfChanged(ref _normalExposure, Math.Round(value, 2));
    }

    public uint LayerCount => (uint)((_baseHeight + _bodyHeight + _ceilHeight) / LayerHeight);

    public decimal TotalHeight => _baseHeight + _bodyHeight + _ceilHeight;

    public decimal BaseDiameter
    {
        get => _baseDiameter;
        set => RaiseAndSetIfChanged(ref _baseDiameter, value);
    }

    public decimal BaseHeight
    {
        get => _baseHeight;
        set
        {
            if(!RaiseAndSetIfChanged(ref _baseHeight, value)) return;
            RaisePropertyChanged(nameof(TotalHeight));
        }
    }

    public decimal BodyHeight
    {
        get => _bodyHeight;
        set
        {
            if (!RaiseAndSetIfChanged(ref _bodyHeight, value)) return;
            RaisePropertyChanged(nameof(TotalHeight));
        }
    }

    public decimal CeilHeight
    {
        get => _ceilHeight;
        set
        {
            if(!RaiseAndSetIfChanged(ref _ceilHeight, value)) return;
            RaisePropertyChanged(nameof(TotalHeight));
        }
    }

    public byte ChamferLayers
    {
        get => _chamferLayers;
        set => RaiseAndSetIfChanged(ref _chamferLayers, value);
    }

    public bool EnableAntiAliasing
    {
        get => _enableAntiAliasing;
        set => RaiseAndSetIfChanged(ref _enableAntiAliasing, value);
    }

    public bool MirrorOutput
    {
        get => _mirrorOutput;
        set => RaiseAndSetIfChanged(ref _mirrorOutput, value);
    }

    public byte Spirals
    {
        get => _spirals;
        set => RaiseAndSetIfChanged(ref _spirals, value);
    }

    public decimal SpiralDiameter
    {
        get => _spiralDiameter;
        set => RaiseAndSetIfChanged(ref _spiralDiameter, value);
    }

    public SpiralDirections SpiralDirection
    {
        get => _spiralDirection;
        set => RaiseAndSetIfChanged(ref _spiralDirection, value);
    }

    public decimal SpiralAngleStepPerLayer
    {
        get => _spiralAngleStepPerLayer;
        set => RaiseAndSetIfChanged(ref _spiralAngleStepPerLayer, value);
    }

    #endregion

    #region Enums

    public enum SpiralDirections : byte
    {
        Clockwise,
        Alternate,
        Both
    }

    public static Array SpiralDirectionsItems => Enum.GetValues(typeof(SpiralDirections));
    #endregion

    #region Equality

    private bool Equals(OperationCalibrateStressTower other)
    {
        return _layerHeight == other._layerHeight && _bottomLayers == other._bottomLayers && _bottomExposure == other._bottomExposure && _normalExposure == other._normalExposure && _baseDiameter == other._baseDiameter && _baseHeight == other._baseHeight && _bodyHeight == other._bodyHeight && _ceilHeight == other._ceilHeight && _chamferLayers == other._chamferLayers && _enableAntiAliasing == other._enableAntiAliasing && _mirrorOutput == other._mirrorOutput && _spirals == other._spirals && _spiralDiameter == other._spiralDiameter && _spiralDirection == other._spiralDirection && _spiralAngleStepPerLayer == other._spiralAngleStepPerLayer;
    }

    public override bool Equals(object? obj)
    {
        return ReferenceEquals(this, obj) || obj is OperationCalibrateStressTower other && Equals(other);
    }

    public override int GetHashCode()
    {
        var hashCode = new HashCode();
        hashCode.Add(_layerHeight);
        hashCode.Add(_bottomLayers);
        hashCode.Add(_bottomExposure);
        hashCode.Add(_normalExposure);
        hashCode.Add(_baseDiameter);
        hashCode.Add(_baseHeight);
        hashCode.Add(_bodyHeight);
        hashCode.Add(_ceilHeight);
        hashCode.Add(_chamferLayers);
        hashCode.Add(_enableAntiAliasing);
        hashCode.Add(_mirrorOutput);
        hashCode.Add(_spirals);
        hashCode.Add(_spiralDiameter);
        hashCode.Add((int) _spiralDirection);
        hashCode.Add(_spiralAngleStepPerLayer);
        return hashCode.ToHashCode();
    }

    #endregion

    #region Methods
    public Mat[] GetLayers()
    {
        var layers = new Mat[LayerCount];
            
        Slicer.Slicer slicer = new(SlicerFile.Resolution, new SizeF((float) DisplayWidth, (float) DisplayHeight));
        Point center = new(SlicerFile.Resolution.Width / 2, SlicerFile.Resolution.Height / 2);
        uint baseRadius = slicer.PixelsFromMillimeters(_baseDiameter) / 2;
        uint baseLayers = (ushort)(_baseHeight / _layerHeight);
        uint bodyLayers = (ushort)(_bodyHeight / _layerHeight);
        uint spiralLayers = (uint)(_spiralDiameter / _layerHeight);
        uint ceilLayers = (ushort)(_ceilHeight / _layerHeight);
        uint currrentlayer = baseLayers;

        decimal spiralOffsetAngle = 360m / _spirals;
        uint spiralRadius = slicer.PixelsFromMillimeters(_spiralDiameter) / 2;

        /*const FontFace fontFace = FontFace.HersheyDuplex;
        const double fontScale = 1;
        const byte fontThickness = 2;
        LineType lineType = _enableAntiAliasing ? LineType.AntiAlias : LineType.EightConnected;

        var kernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3), EmguExtensions.AnchorCenter);*/
        Parallel.For(0, LayerCount, CoreSettings.ParallelOptions, layerIndex =>
        {
            layers[layerIndex] = EmguExtensions.InitMat(SlicerFile.Resolution);
        });
            
        Parallel.For(0, baseLayers, CoreSettings.ParallelOptions, layerIndex =>
        {
            int chamferOffset = (int) Math.Max(0, _chamferLayers - layerIndex);
            CvInvoke.Circle(layers[layerIndex], center, (int) baseRadius - chamferOffset, EmguExtensions.WhiteColor, -1, _enableAntiAliasing ? LineType.AntiAlias : LineType.EightConnected);
        });


        Parallel.For(0, baseLayers+bodyLayers, CoreSettings.ParallelOptions, layerIndex =>
        {
            decimal angle = (layerIndex * _spiralAngleStepPerLayer) % 360m;
            for (byte spiral = 0; spiral < _spirals; spiral++)
            {
                decimal spiralAngle = (spiralOffsetAngle * spiral + angle) % 360;
                if (_spiralDirection == SpiralDirections.Alternate && spiral % 2 == 0)
                {
                    spiralAngle = -spiralAngle;
                }
                Point location = new((int) (center.X - baseRadius + spiralRadius), center.Y);
                var locationCW = location.Rotate((double) spiralAngle, center);
                var locationCCW = location.Rotate((double) -spiralAngle, center);

                uint maxLayer = (uint) Math.Min(layerIndex + spiralLayers, baseLayers + bodyLayers);

                for (uint spiralLayerIndex = (uint) layerIndex; spiralLayerIndex < maxLayer; spiralLayerIndex++)
                {
                    CvInvoke.Circle(layers[spiralLayerIndex], locationCW, (int)spiralRadius, EmguExtensions.WhiteColor, -1, _enableAntiAliasing ? LineType.AntiAlias : LineType.EightConnected);
                    if (_spiralDirection == SpiralDirections.Both)
                    {
                        spiralAngle = -spiralAngle;
                        CvInvoke.Circle(layers[spiralLayerIndex], locationCCW, (int)spiralRadius, EmguExtensions.WhiteColor, -1, _enableAntiAliasing ? LineType.AntiAlias : LineType.EightConnected);
                    }
                }
            }
        });

        currrentlayer += bodyLayers;

        Parallel.For(0, ceilLayers, CoreSettings.ParallelOptions, i =>
        {
            uint layerIndex = (uint)(currrentlayer + i);
            CvInvoke.Circle(layers[layerIndex], center, (int)baseRadius, EmguExtensions.WhiteColor, -1, _enableAntiAliasing ? LineType.AntiAlias : LineType.EightConnected);
        });



        if (_mirrorOutput)
        {
            var flip = SlicerFile.DisplayMirror;
            if (flip == FlipDirection.None) flip = FlipDirection.Horizontally;
            Parallel.ForEach(layers, CoreSettings.ParallelOptions, mat => CvInvoke.Flip(mat, mat, (FlipType)flip));
        }

        return layers;
    }

    public Mat GetThumbnail()
    {
        Mat thumbnail = EmguExtensions.InitMat(new Size(400, 200), 3);
        var fontFace = FontFace.HersheyDuplex;
        var fontScale = 1;
        var fontThickness = 2;
        const byte xSpacing = 45;
        const byte ySpacing = 45;
        CvInvoke.PutText(thumbnail, "UVtools", new Point(140, 35), fontFace, fontScale, new MCvScalar(255, 27, 245), fontThickness + 1);
        CvInvoke.Line(thumbnail, new Point(xSpacing, 0), new Point(xSpacing, ySpacing + 5), new MCvScalar(255, 27, 245), 3);
        CvInvoke.Line(thumbnail, new Point(xSpacing, ySpacing + 5), new Point(thumbnail.Width - xSpacing, ySpacing + 5), new MCvScalar(255, 27, 245), 3);
        CvInvoke.Line(thumbnail, new Point(thumbnail.Width - xSpacing, 0), new Point(thumbnail.Width - xSpacing, ySpacing + 5), new MCvScalar(255, 27, 245), 3);
        CvInvoke.PutText(thumbnail, "Stress Tower", new Point(xSpacing, ySpacing * 2), fontFace, fontScale, new MCvScalar(0, 255, 255), fontThickness);
        CvInvoke.PutText(thumbnail, $"{Microns}um @ {BottomExposure}s/{NormalExposure}s", new Point(xSpacing, ySpacing * 3), fontFace, fontScale, EmguExtensions.WhiteColor, fontThickness);
        CvInvoke.PutText(thumbnail, $"{_spirals} Spirals @ {_spiralAngleStepPerLayer}deg", new Point(xSpacing, ySpacing * 4), fontFace, fontScale, EmguExtensions.WhiteColor, fontThickness);
        return thumbnail;
    }

    protected override bool ExecuteInternally(OperationProgress progress)
    {
        progress.ItemCount = LayerCount;
        var newLayers = new Layer[LayerCount];

        var layers = GetLayers();

        Parallel.For(0, LayerCount, CoreSettings.GetParallelOptions(progress), layerIndex =>
        {
            newLayers[layerIndex] = new Layer((uint)layerIndex, layers[layerIndex], SlicerFile) {IsModified = true};
            layers[layerIndex].Dispose();
            progress.LockAndIncrement();
        });

            
        if (SlicerFile.ThumbnailsCount > 0)
            SlicerFile.SetThumbnails(GetThumbnail());

        SlicerFile.SuppressRebuildPropertiesWork(() =>
        {
            SlicerFile.LayerHeight = (float)LayerHeight;
            SlicerFile.BottomExposureTime = (float)BottomExposure;
            SlicerFile.ExposureTime = (float)NormalExposure;
            SlicerFile.BottomLayerCount = BottomLayers;
            SlicerFile.Layers = newLayers;
        }, true);
            
        return !progress.Token.IsCancellationRequested;
    }

    #endregion
}