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

ChituboxZipFile.cs « FileFormats « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c6d04483dd0374dfa134e2fca7c8540c8e9804fc (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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/*
 *                     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.Util;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using UVtools.Core.Extensions;
using UVtools.Core.GCode;
using UVtools.Core.Layers;
using UVtools.Core.Operations;

namespace UVtools.Core.FileFormats;

public class ChituboxZipFile : FileFormat
{
    #region Constants

    public const string GCodeFilename = "run.gcode";
    #endregion

    #region Sub Classes

    public class Header
    {
        // ;(****Build and Slicing Parameters****)
        [DisplayName("fileName")] public string Filename { get; set; } = string.Empty;
        [DisplayName("machineType")] public string MachineType { get; set; } = "Default";
        [DisplayName("estimatedPrintTime")] public float EstimatedPrintTime { get; set; }
        [DisplayName("volume")] public float VolumeMl { get; set; }
        [DisplayName("resin")] public string? Resin { get; set; } = "Normal";
        [DisplayName("weight")] public float WeightG { get; set; }
        [DisplayName("price")] public float Price { get; set; }
        [DisplayName("layerHeight")] public float LayerHeight { get; set; }
        [DisplayName("resolutionX")] public uint ResolutionX { get; set; }
        [DisplayName("resolutionY")] public uint ResolutionY { get; set; }
        [DisplayName("machineX")] public float MachineX { get; set; }
        [DisplayName("machineY")] public float MachineY { get; set; }
        [DisplayName("machineZ")] public float MachineZ { get; set; }
        [DisplayName("projectType")] public string ProjectType { get; set; } = "Normal";
        [DisplayName("normalExposureTime")] public float ExposureTime { get; set; } = 7; // 35s
        [DisplayName("bottomLayExposureTime")] public float BottomLayExposureTime { get; set; } = 35; // 35s
        [DisplayName("bottomLayerExposureTime")] public float BottomExposureTime { get; set; } = 35; // 35s
        [DisplayName("normalDropSpeed")] public float RetractSpeed { get; set; } = 150; // 150 mm/m
        [DisplayName("normalLayerLiftSpeed")] public float LiftSpeed { get; set; } = 60; // 60 mm/m
        [DisplayName("normalLayerLiftHeight")] public float LiftHeight { get; set; } = 5; // 5 mm
        [DisplayName("zSlowUpDistance")] public float ZSlowUpDistance { get; set; }
        [DisplayName("bottomLayCount")] public ushort BottomLayCount { get; set; } = 4;
        [DisplayName("bottomLayerCount")] public ushort BottomLayerCount { get; set; } = 4;
        [DisplayName("mirror")] public byte Mirror { get; set; } // 0/1
        [DisplayName("totalLayer")] public uint LayerCount { get; set; }
        [DisplayName("bottomLayerLiftHeight")] public float BottomLiftHeight { get; set; } = 5;
        [DisplayName("bottomLayerLiftSpeed")] public float BottomLiftSpeed { get; set; } = 60;
        [DisplayName("bottomLightOffTime")] public float BottomLightOffDelay { get; set; }
        [DisplayName("lightOffTime")] public float LightOffDelay { get; set; }
        [DisplayName("bottomPWMLight")] public byte BottomLightPWM { get; set; } = 255;
        [DisplayName("PWMLight")] public byte LightPWM { get; set; } = 255;
        [DisplayName("antiAliasLevel")] public byte AntiAliasing { get; set; } = 1;
    }

    #endregion

    #region Properties
    public Header HeaderSettings { get; } = new();
        
    public override FileFormatType FileType => FileFormatType.Archive;

    public override string ConvertMenuGroup => "Chitubox";

    public override FileExtension[] FileExtensions { get; } = {
        new(typeof(ChituboxZipFile), "zip", "Chitubox Zip")
    };

    public override PrintParameterModifier[]? PrintParameterModifiers { get; } = {
        PrintParameterModifier.BottomLayerCount,
        PrintParameterModifier.TransitionLayerCount,

        PrintParameterModifier.BottomWaitTimeBeforeCure,
        PrintParameterModifier.WaitTimeBeforeCure,
            
        PrintParameterModifier.BottomExposureTime,
        PrintParameterModifier.ExposureTime,

        PrintParameterModifier.BottomWaitTimeAfterCure,
        PrintParameterModifier.WaitTimeAfterCure,

        PrintParameterModifier.BottomLiftHeight,
        PrintParameterModifier.BottomLiftSpeed,
        PrintParameterModifier.LiftHeight,
        PrintParameterModifier.LiftSpeed,

        PrintParameterModifier.BottomLiftHeight2,
        PrintParameterModifier.BottomLiftSpeed2,
        PrintParameterModifier.LiftHeight2,
        PrintParameterModifier.LiftSpeed2,

        PrintParameterModifier.BottomWaitTimeAfterLift,
        PrintParameterModifier.WaitTimeAfterLift,

        PrintParameterModifier.BottomRetractSpeed,
        PrintParameterModifier.RetractSpeed,

        PrintParameterModifier.BottomRetractHeight2,
        PrintParameterModifier.BottomRetractSpeed2,
        PrintParameterModifier.RetractHeight2,
        PrintParameterModifier.RetractSpeed2,

        PrintParameterModifier.BottomLightPWM,
        PrintParameterModifier.LightPWM,
    };

    public override PrintParameterModifier[]? PrintParameterPerLayerModifiers { get; } = {
        PrintParameterModifier.PositionZ,
        PrintParameterModifier.WaitTimeBeforeCure,
        PrintParameterModifier.ExposureTime,
        PrintParameterModifier.WaitTimeAfterCure,
        PrintParameterModifier.LiftHeight,
        PrintParameterModifier.LiftSpeed,
        PrintParameterModifier.LiftHeight2,
        PrintParameterModifier.LiftSpeed2,
        PrintParameterModifier.WaitTimeAfterLift,
        PrintParameterModifier.RetractSpeed,
        PrintParameterModifier.RetractHeight2,
        PrintParameterModifier.RetractSpeed2,
        PrintParameterModifier.LightPWM,
    };

    public override Size[]? ThumbnailsOriginalSize { get; } =
    {
        new(954, 850), 
        new(168, 150)
    };

    public override uint ResolutionX
    {
        get => HeaderSettings.ResolutionX;
        set
        {
            HeaderSettings.ResolutionX = value;
            RaisePropertyChanged();
        }
    }

    public override uint ResolutionY
    {
        get => HeaderSettings.ResolutionY;
        set
        {
            HeaderSettings.ResolutionY = value;
            RaisePropertyChanged();
        }
    }

    public override float DisplayWidth
    {
        get => HeaderSettings.MachineX;
        set
        {
            HeaderSettings.MachineX = value;
            RaisePropertyChanged();
        }
    }

    public override float DisplayHeight
    {
        get => HeaderSettings.MachineY;
        set
        {
            HeaderSettings.MachineY = value;
            RaisePropertyChanged();
        }
    }

    public override float MachineZ
    {
        get => HeaderSettings.MachineZ > 0 ? HeaderSettings.MachineZ : base.MachineZ;
        set => base.MachineZ = HeaderSettings.MachineZ = (float)Math.Round(value, 2);
    }

    public override FlipDirection DisplayMirror
    {
        get => HeaderSettings.Mirror == 0 ? FlipDirection.None : FlipDirection.Horizontally;
        set
        {
            HeaderSettings.ProjectType = value == FlipDirection.None ? "Normal" : "LCD_mirror";
            HeaderSettings.Mirror = (byte)(value == FlipDirection.None ? 0 : 1);
            RaisePropertyChanged();
        }
    }

    public override byte AntiAliasing
    {
        get => HeaderSettings.AntiAliasing;
        set => base.AntiAliasing = HeaderSettings.AntiAliasing = value.Clamp(1, 16);
    }

    public override float LayerHeight
    {
        get => HeaderSettings.LayerHeight;
        set
        {
            HeaderSettings.LayerHeight = Layer.RoundHeight(value);
            RaisePropertyChanged();
        }
    }

    public override uint LayerCount
    {
        get => base.LayerCount;
        set => base.LayerCount = HeaderSettings.LayerCount = base.LayerCount;
    }

    public override ushort BottomLayerCount
    {
        get => HeaderSettings.BottomLayerCount;
        set => base.BottomLayerCount = HeaderSettings.BottomLayerCount = HeaderSettings.BottomLayCount = value;
    }

    public override float BottomLightOffDelay
    {
        get => BottomWaitTimeBeforeCure;
        set => BottomWaitTimeBeforeCure = value;
    }

    public override float LightOffDelay
    {
        get => WaitTimeBeforeCure;
        set => WaitTimeBeforeCure = value;
    }

    public override float BottomWaitTimeBeforeCure
    {
        get => HeaderSettings.BottomLightOffDelay;
        set => base.BottomWaitTimeBeforeCure = HeaderSettings.BottomLightOffDelay = (float)Math.Round(value, 2);
    }

    public override float WaitTimeBeforeCure
    {
        get => HeaderSettings.LightOffDelay;
        set => base.WaitTimeBeforeCure = HeaderSettings.LightOffDelay = (float)Math.Round(value, 2);
    }

    public override float BottomExposureTime
    {
        get => HeaderSettings.BottomExposureTime;
        set => base.BottomExposureTime = HeaderSettings.BottomExposureTime = HeaderSettings.BottomLayExposureTime = (float)Math.Round(value, 2);
    }

    public override float ExposureTime
    {
        get => HeaderSettings.ExposureTime;
        set => base.ExposureTime = HeaderSettings.ExposureTime = (float)Math.Round(value, 2);
    }

    public override float BottomLiftHeight
    {
        get => HeaderSettings.BottomLiftHeight;
        set => base.BottomLiftHeight = HeaderSettings.BottomLiftHeight = (float)Math.Round(value, 2);
    }

    public override float LiftHeight
    {
        get => HeaderSettings.LiftHeight;
        set => base.LiftHeight = HeaderSettings.LiftHeight = (float)Math.Round(value, 2);
    }

    public override float BottomLiftSpeed
    {
        get => HeaderSettings.BottomLiftSpeed;
        set => base.BottomLiftSpeed = HeaderSettings.BottomLiftSpeed = (float)Math.Round(value, 2);
    }

    public override float LiftSpeed
    {
        get => HeaderSettings.LiftSpeed;
        set => base.LiftSpeed = HeaderSettings.LiftSpeed = (float)Math.Round(value, 2);
    }

    public override float RetractSpeed
    {
        get => HeaderSettings.RetractSpeed;
        set => base.RetractSpeed = HeaderSettings.RetractSpeed = (float)Math.Round(value, 2);
    }

    public override byte BottomLightPWM
    {
        get => HeaderSettings.BottomLightPWM;
        set => base.BottomLightPWM = HeaderSettings.BottomLightPWM = value;
    }

    public override byte LightPWM
    {
        get => HeaderSettings.LightPWM;
        set => base.LightPWM = HeaderSettings.LightPWM = value;
    }

    public override float PrintTime
    {
        get => base.PrintTime;
        set
        {
            base.PrintTime = value;
            HeaderSettings.EstimatedPrintTime = base.PrintTime;
        }
    }

    public override float MaterialMilliliters
    {
        get => base.MaterialMilliliters;
        set
        {
            base.MaterialMilliliters = value;
            HeaderSettings.VolumeMl = base.MaterialMilliliters;
        }
    }

    public override float MaterialGrams
    {
        get => (float) Math.Round(HeaderSettings.WeightG, 3);
        set
        {
            HeaderSettings.WeightG = (float)Math.Round(value, 3);
            RaisePropertyChanged();
        }
    }

    public override float MaterialCost
    {
        get => (float) Math.Round(HeaderSettings.Price, 3);
        set
        {
            HeaderSettings.Price = (float)Math.Round(value, 3);
            RaisePropertyChanged();
        }
    }

    public override string? MaterialName
    {
        get => HeaderSettings.Resin;
        set
        {
            HeaderSettings.Resin = value;
            RaisePropertyChanged();
        }
    }

    public override string MachineName
    {
        get => HeaderSettings.MachineType;
        set => base.MachineName = HeaderSettings.MachineType = value;
    }

    public override object[] Configs => new object[] { HeaderSettings };

    public override bool SupportsGCode => base.SupportsGCode && !IsPHZZip;

    public bool IsPHZZip;
    #endregion

    #region Constructor
    public ChituboxZipFile()
    {
        GCode = new GCodeBuilder
        {
            UseComments = true,
            GCodePositioningType = GCodeBuilder.GCodePositioningTypes.Absolute,
            GCodeSpeedUnit = GCodeBuilder.GCodeSpeedUnits.MillimetersPerMinute,
            GCodeTimeUnit = GCodeBuilder.GCodeTimeUnits.Milliseconds,
            GCodeShowImageType = GCodeBuilder.GCodeShowImageTypes.FilenamePng1Started,
            LayerMoveCommand = GCodeBuilder.GCodeMoveCommands.G0,
            EndGCodeMoveCommand = GCodeBuilder.GCodeMoveCommands.G1
        };
    }
    #endregion

    #region Methods

    public override bool CanProcess(string? fileFullPath)
    {
        if (!base.CanProcess(fileFullPath)) return false;

        try
        {
            var zip = ZipFile.Open(fileFullPath!, ZipArchiveMode.Read);
            if (zip.Entries.Any(entry => entry.Name.EndsWith(".gcode"))) return true;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
        }


        return false;
    }

    protected override void EncodeInternally(OperationProgress progress)
    {
        using var outputFile = ZipFile.Open(TemporaryOutputFileFullPath, ZipArchiveMode.Create);
        if (Thumbnails is not null && Thumbnails.Length > 0 && Thumbnails[0] is not null)
        {
            using var stream = outputFile.CreateEntry("preview.png").Open();
            stream.WriteBytes(Thumbnails[0]!.GetPngByes());
            stream.Close();
        }

        if (Thumbnails is not null  && Thumbnails.Length > 1 && Thumbnails[1] is not null)
        {
            using var stream = outputFile.CreateEntry("preview_cropping.png").Open();
            using var vec = new VectorOfByte();
            stream.WriteBytes(Thumbnails[1]!.GetPngByes());
            stream.Close();
        }

        if (!IsPHZZip)
        {
            RebuildGCode();
            outputFile.PutFileContent(GCodeFilename, GCodeStr, ZipArchiveMode.Create);
        }

        EncodeLayersInZip(outputFile, IndexStartNumber.One, progress);
    }

    protected override void DecodeInternally(OperationProgress progress)
    {
        using var inputFile = ZipFile.Open(FileFullPath!, ZipArchiveMode.Read);
        var entry = inputFile.GetEntry(GCodeFilename);
        if (entry is not null)
        {
            //Clear();
            //throw new FileLoadException("run.gcode not found", fileFullPath);
            using TextReader tr = new StreamReader(entry.Open());
            string? line;
            GCode!.Clear();
            while ((line = tr.ReadLine()) != null)
            {
                GCode.AppendLine(line);
                if (string.IsNullOrEmpty(line)) continue;

                if (line[0] != ';')
                {
                    continue;
                }

                var splitLine = line.Split(':');
                if (splitLine.Length < 2) continue;

                foreach (var propertyInfo in HeaderSettings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    var displayNameAttribute = propertyInfo.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault();
                    if (displayNameAttribute is null) continue;
                    if (!splitLine[0].Trim(' ', ';').Equals(displayNameAttribute.DisplayName)) continue;
                    Helpers.SetPropertyValue(propertyInfo, HeaderSettings, splitLine[1].Trim());
                }
            }
            tr.Close();
        }
        else
        {
            IsPHZZip = true;
        }

        if (HeaderSettings.LayerCount == 0)
        {
            foreach (var zipEntry in inputFile.Entries)
            {
                if(!zipEntry.Name.EndsWith(".png")) continue;
                var filename = Path.GetFileNameWithoutExtension(zipEntry.Name);
                if (!filename.All(char.IsDigit)) continue;
                if (!uint.TryParse(filename, out var layerIndex)) continue;
                HeaderSettings.LayerCount = Math.Max(HeaderSettings.LayerCount, layerIndex);
            }
        }

        Init(HeaderSettings.LayerCount, DecodeType == FileDecodeType.Partial);

        DecodeLayersFromZip(inputFile, IndexStartNumber.One, progress);

        if (IsPHZZip) // PHZ file
        {
            RebuildLayersProperties();
        }
        else
        {
            GCode?.ParseLayersFromGCode(this);
        }

        entry = inputFile.GetEntry("preview.png");
        if (entry is not null)
        {
            Thumbnails![0] = new Mat();
            CvInvoke.Imdecode(entry.Open().ToArray(), ImreadModes.AnyColor, Thumbnails[0]);
        }

        entry = inputFile.GetEntry("preview_cropping.png");
        if (entry is not null)
        {
            var count = CreatedThumbnailsCount;
            Thumbnails![count] = new Mat();
            CvInvoke.Imdecode(entry.Open().ToArray(), ImreadModes.AnyColor, Thumbnails[count]);
        }
    }

    public override void RebuildGCode()
    {
        if (!SupportsGCode || SuppressRebuildGCode) return;
        GCode?.RebuildGCode(this, new object[]{ HeaderSettings });
        RaisePropertyChanged(nameof(GCodeStr));
    }

    protected override void PartialSaveInternally(OperationProgress progress)
    {
        using var outputFile = ZipFile.Open(TemporaryOutputFileFullPath, ZipArchiveMode.Update);
        var entriesToRemove = outputFile.Entries.Where(zipEntry => zipEntry.Name.EndsWith(".gcode")).ToArray();
        foreach (var zipEntry in entriesToRemove)
        {
            zipEntry.Delete();
        }

        if (!IsPHZZip)
        {
            outputFile.PutFileContent(GCodeFilename, GCodeStr, ZipArchiveMode.Update);
        }

        //Decode(FileFullPath, progress);
    }
    #endregion
}