2 using System.Collections.Generic;
3 using System.Diagnostics;
6 using System.Threading;
7 using System.Threading.Tasks;
12 public class Snapshotter
15 public string chunkPath;
16 public ColumnsMetadata cols;
18 public int NorthEdge => cols.North_mostChunk;
19 public int WestEdge => cols.West_mostChunk;
20 public int Width => (cols.East_mostChunk - WestEdge + 1);
21 public int Height => (cols.South_mostChunk - NorthEdge + 1);
23 public Snapshotter(string path, string chunkPath, ColumnsMetadata cols, int chunkSize)
25 this.path = Path.Combine(path, "snapshot.png");
26 this.chunkPath = Path.Combine(path, chunkPath);
28 this.chunkSize = chunkSize;
32 /// takes a snapshot. this should be called from an extra thread.
34 /// <param name="path">path to the map dir</param>
35 /// <param name="chunkPath">name of the chunks dir part thing</param>
36 /// <param name="cols"></param>
37 /// <param name="chunkSize"></param>
38 public async void Take()
40 var t = new Stopwatch();
42 Console.WriteLine("snapshot started");
44 ImageInfo info = new ImageInfo(Width * chunkSize, Height * chunkSize, 8, false);
45 PngWriter snapWriter = FileHelper.CreatePngWriter(path, info, true);
46 snapWriter.CompLevel = 5;
47 snapWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
51 group ch by ch.Location.Y into g
54 // that sorts things in ascending order so we can only create (chunkSize) lines at once
56 foreach (var chunkGroup in orderedList)
58 var posY = chunkGroup.Key - NorthEdge;
59 var inGroup = (await ReadAllInGroup(chunkGroup)).ToArray();
60 // oh god here we go...
61 for (int r = 0; r < chunkSize; r++)
63 var line = new byte[info.BytesPerRow];
64 for (int chunk = 0; chunk < inGroup.Length; chunk++)
66 var posX = inGroup[chunk].Key * chunkSize * info.BytesPixel;
67 inGroup[chunk].Value?[r].CopyTo(line, posX);
69 snapWriter.WriteRowByte(line, row++);
72 snapWriter.ShouldCloseStream = true;
74 Console.WriteLine($"snapshot finished in {t.ElapsedMilliseconds}");
77 private async Task<Dictionary<int, byte[][]>> ReadAllInGroup(IGrouping<int, ColumnMeta> group)
79 var taskGroup = new Dictionary<int, byte[][]>(group.Count());
80 foreach (var shardMeta in group)
82 var shardPath = Path.Combine(chunkPath, $"{shardMeta.Location.X}_{shardMeta.Location.Y}.png");
83 taskGroup.Add(shardMeta.Location.X - WestEdge, await ReadNoThrow(shardPath));
88 private async Task<byte[][]> ReadNoThrow(string readPath)
92 return await Task.Run(() => FileHelper.CreatePngReader(readPath).ReadRowsByte().ScanlinesB);
96 Console.WriteLine(e.Message);
98 } // do nothing on error