OSDN Git Service

Resinous Resources Revealed
[automap/automap.git] / Automap / Subsystems / AutomapSystem.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
5 using System.IO;
6 using System.Linq;
7 using System.Text;
8 using System.Text.RegularExpressions;
9 using System.Threading;
10
11 using Hjg.Pngcs;
12
13 using ProtoBuf;
14
15 using Vintagestory.API.Client;
16 using Vintagestory.API.Common;
17 using Vintagestory.API.Config;
18 using Vintagestory.API.Datastructures;
19 using Vintagestory.API.MathTools;
20 using Vintagestory.Common;
21
22 namespace Automap
23 {
24         public class AutomapSystem
25         {
26                 private Thread cartographer_thread;
27                 private Thread snapshotThread;
28                 private Snapshotter snapshot;
29                 private ICoreClientAPI ClientAPI { get; set; }
30                 private ILogger Logger { get; set; }
31                 private AChunkRenderer ChunkRenderer { get; set; }
32                 private JsonGenerator JsonGenerator { get; set; }
33
34                 internal const string _mapPath = @"Maps";
35                 internal const string _chunkPath = @"Chunks";
36                 internal const uint editThreshold = 9;
37                 private const string _domain = @"automap";
38                 private const string chunkFile_filter = @"*_*.png";
39                 private const string poiFileName = @"poi_binary";
40                 private const string eoiFileName = @"eoi_binary";
41                 private const string pointsTsvFileName = @"points_of_interest.tsv";
42                 private const string plainMetadataFileName = @"map_metadata.txt";
43                 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
44
45                 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
46                 private ColumnsMetadata chunkTopMetadata;
47                 internal PointsOfInterest POIs = new PointsOfInterest();
48                 internal EntitiesOfInterest EOIs = new EntitiesOfInterest();
49
50                 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
51                 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
52                 internal Dictionary<int, string> RockIdCodes { get; private set; }
53                 internal Dictionary<int, string> AiryIdCodes { get; private set; }
54
55                 internal CommandType CurrentState { get; set; }
56                 //Run status, Chunks processed, stats, center of map....
57                 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
58                 private Vec2i startChunkColumn;
59
60                 private readonly int chunkSize;
61                 private string path;
62                 private IAsset staticMap;
63                 private PersistedConfiguration configuration;
64
65
66                 public static string AutomapStatusEventKey = @"AutomapStatus";
67                 public static string AutomapCommandEventKey = @"AutomapCommand";
68
69                 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
70                 {
71                         this.ClientAPI = clientAPI;
72                         this.Logger = logger;
73                         chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
74
75                         configuration = config;
76                         ClientAPI.Event.LevelFinalize += EngageAutomap;
77
78                         this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
79
80                         //Listen on bus for commands
81                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
82
83
84                         if (configuration.Autostart)
85                         {
86                                 CurrentState = CommandType.Run;
87                                 Logger.Debug("Autostart is Enabled.");
88                         }
89
90                 }
91
92
93                 #region Internals
94                 private void EngageAutomap()
95                 {
96                         path = ClientAPI.GetOrCreateDataPath(_mapPath);
97                         path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
98                         ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
99                                                   
100                         JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
101
102                         string mapFilename = Path.Combine(path, "automap.html");
103                         StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
104
105                         staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
106                         outputText.Write(staticMap.ToText());
107                         outputText.Flush();
108
109                         Prefill_POI_Designators();
110                         startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
111                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
112                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
113                         Reload_Metadata();
114
115                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
116
117                         cartographer_thread = new Thread(Cartographer)
118                         {
119                                 Name = "Cartographer",
120                                 Priority = ThreadPriority.Lowest,
121                                 IsBackground = true
122                         };
123
124                         snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize,ClientAPI.World.Seed );
125                         snapshotThread = new Thread(Snap)
126                         {
127                                 Name = "Snapshot",
128                                 Priority = ThreadPriority.Lowest,
129                                 IsBackground = true
130                         };
131
132                         ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
133                 }
134
135                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
136                 {
137                 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);              
138                 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
139                 
140                 columnCounters.AddOrUpdate(topPosition, 
141                                               new ColumnCounter(chunkSize, newOrEdit, chunkCoord), 
142                                               (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
143                                              );
144                 
145                 }
146
147                 private void AwakenCartographer(float delayed)
148                 {
149
150                         if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
151                         {
152 #if DEBUG
153                                 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
154 #endif
155
156                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
157                                 {
158                                         cartographer_thread.Start();
159                                 }
160                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
161                                 {
162                                         //Time to (re)write chunk shards
163                                         cartographer_thread.Interrupt();
164                                 }
165                                 //#if DEBUG
166                                 //ClientAPI.TriggerChatMessage($"Automap {updatedChunksTotal} Updates - MAX (N:{chunkTopMetadata.North_mostChunk},S:{chunkTopMetadata.South_mostChunk},E:{chunkTopMetadata.East_mostChunk}, W:{chunkTopMetadata.West_mostChunk} - TOTAL: {chunkTopMetadata.Count})");
167                                 //#endif
168                         }
169                         else if (CurrentState == CommandType.Snapshot)
170                         {
171                                 if (snapshotThread.ThreadState.HasFlag(ThreadState.Unstarted))
172                                 {
173                                         snapshotThread.Start();
174                                 } else if (snapshotThread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
175                                 {
176                                         snapshotThread.Interrupt();
177                                 }
178                         }
179
180                 }
181
182
183                 private void Cartographer()
184                 {
185                         wake:
186                         Logger.VerboseDebug("Cartographer thread awoken");
187
188                         try
189                         {
190                                 ColumnCounter ejectedItem ;
191                                 uint updatedChunks = 0;
192                                 uint updatedPixels = 0;
193
194                                 //-- Should dodge enumerator changing underfoot....at a cost.
195                                 if (!columnCounters.IsEmpty)
196                                 {
197                                         var tempSet = columnCounters.ToArray().Where(cks => cks.Value.WeightedSum > editThreshold) .OrderByDescending(kvp => kvp.Value.WeightedSum);
198                                         UpdateEntityMetadata();
199
200                                         foreach (var mostActiveCol in tempSet)
201                                         {
202                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
203
204                                                 if (mapChunk == null)
205                                                 {
206                                                         //TODO: REVISIT THIS CHUNK!
207                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
208                                                         nullMapCount++;
209                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
210                                                         continue;
211                                                 }
212
213                                                 ColumnMeta chunkMeta;
214                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
215                                                 {
216                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
217                                                         #if DEBUG
218                                                         Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
219                                                         #endif
220                                                 }
221                                                 else
222                                                 {
223                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
224                                                         #if DEBUG
225                                                         Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
226                                                         #endif
227                                                 }
228                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
229                                                 mostActiveCol.Value.SetCutoff(chunkMeta.YMax / chunkSize);
230
231                                                 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
232                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
233
234                                                 if (updatedPixels > 0)
235                                                 {
236                                                         #if DEBUG
237                                                         Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
238                                                         #endif
239                                                         updatedChunks++;
240                                                         chunkTopMetadata.Update(chunkMeta);
241                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
242                                                 }
243                                                 else
244                                                 {
245                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
246                                                         #if DEBUG
247                                                         Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
248                                                         #endif
249                                                 }
250                                         }
251                                 }
252
253                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
254
255                                 if (updatedChunks > 0)
256                                 {
257                                         //What about chunk updates themselves; a update bitmap isn't kept...
258                                         updatedChunksTotal += updatedChunks;
259                                         JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
260                                         updatedChunks = 0;
261
262                                         //Cleanup in-memory Metadata...
263                                         chunkTopMetadata.ClearMetadata( );
264                                 }
265
266                                 #if DEBUG
267                                 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
268                                 #endif
269
270                                 columnCounters.Clear( );
271
272                                 //Then sleep until interupted again, and repeat
273 #if DEBUG
274                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
275 #endif
276                                 Thread.Sleep(Timeout.Infinite);
277
278                         }
279                         catch (ThreadInterruptedException)
280                         {
281
282 #if DEBUG
283                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
284 #endif
285                                 goto wake;
286
287                         }
288                         catch (ThreadAbortException)
289                         {
290 #if DEBUG
291                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
292 #endif
293                         }
294                         finally
295                         {
296 #if DEBUG
297                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
298 #endif
299                                 PersistPointsData();
300                                 Write_PlainMetadata( );
301                         }
302                 }
303
304                 private void Snap()
305                 {
306                         snapshotTake:
307 #if DEBUG
308                         Logger.VerboseDebug("Snapshot started");
309 #endif
310                         try
311                         {
312                                 snapshot.Take();
313 #if DEBUG
314                                 Logger.VerboseDebug("Snapshot sleeping");
315 #endif
316                                 CurrentState = CommandType.Run;
317                                 Thread.Sleep(Timeout.Infinite);
318                         }
319                         catch (ThreadInterruptedException)
320                         {
321 #if DEBUG
322                                 Logger.VerboseDebug("Snapshot intertupted");
323 #endif
324                                 goto snapshotTake;
325                         }
326                 }
327
328                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
329                 {
330                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
331
332                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
333                 }
334
335                 private void Prefill_POI_Designators()
336                 {
337
338                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
339                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
340                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
341
342                         var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
343                                                          where airyBlock.MatterState == EnumMatterState.Solid
344                                                          where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
345                                                          where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 ||airyBlock.RainPermeable == true                                                        
346                                                          select airyBlock;                      
347                         //^^ 'Solid' phase - 'Plant' Blocks without any boundg box ? Except water...
348                         this.AiryIdCodes = airBlocksQuery.ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
349
350                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
351                         Reload_POI_Designators();
352                 }
353
354                 private void Reload_POI_Designators()
355                 {
356                 uint poisSetup =0, eoiSetup = 0;
357                         foreach (var designator in configuration.BlockDesignators)
358                         {
359                                 if (designator.Enabled == false) continue;
360                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
361                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
362                                 foreach (var entry in blockIDs)
363                                 {
364                                         BlockID_Designators.Add(entry.Key, designator);
365                                         poisSetup++;
366                                 }
367                         }
368                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
369                         Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
370
371
372                         foreach (var designator in configuration.EntityDesignators)
373                         {
374                                 if (designator.Enabled == false) continue;
375                                 //Get Variants first, from EntityTypes...better be populated!
376                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
377
378                                 foreach (var match in matched)
379                                 {                                       
380                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
381                                         this.Entity_Designators.Add(match.Code, designator);
382                                         eoiSetup++;
383                                 }
384                         }
385                         Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
386
387                 }
388
389
390
391                 /// <summary>
392                 /// Store Points/Entity of Interest
393                 /// </summary>
394                 private void PersistPointsData()
395                 {
396                         //POI and EOI raw dump files ~ WRITE em!
397                         //var poiRawFile = File.
398                         string poiPath = Path.Combine(path, poiFileName);
399                         string eoiPath = Path.Combine(path, eoiFileName);
400
401                         if (this.POIs.Count > 0)
402                         {
403                                 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
404                                 {
405                                         Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
406                                 }
407                         }
408
409                         if (this.EOIs.Count > 0)
410                         {
411                                 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
412                                 {
413                                         Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
414                                 }
415                         }
416
417                         //Create Easy to Parse TSV file for tool/human use....
418                         string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
419
420                         using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
421                         {
422                                 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
423                                 foreach (var point in this.POIs)
424                                 {
425                                         tsvWriter.Write(point.Name + "\t");
426                                         var notes = point.Notes
427                                                 .Replace('\n', '\x001f')
428                                                 .Replace("\t", "\\t")
429                                                 .Replace("\\", "\\\\");
430                                         tsvWriter.Write(notes + "\t");
431                                         tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
432                                         tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
433                                         tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
434                                         tsvWriter.Write("null\t");
435                                         tsvWriter.WriteLine();
436                                 }
437                                 foreach (var entity in this.EOIs)
438                                 {
439                                         tsvWriter.Write(entity.Name + "\t");
440                                         var notes = entity.Notes
441                                                 .Replace('\n', '\x001f')
442                                                 .Replace("\t", "\\t")
443                                                 .Replace("\\", "\\\\");
444                                         tsvWriter.Write(notes + "\t");
445                                         tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
446                                         tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
447                                         tsvWriter.Write("---\t");
448                                         tsvWriter.Write(entity.EntityId.ToString("D"));
449                                         tsvWriter.WriteLine();
450                                 }
451                                 tsvWriter.WriteLine();
452                                 tsvWriter.Flush();
453                         }
454
455                 }
456
457                 private void Write_PlainMetadata( )
458                 { 
459                 string metaPath = Path.Combine(path, plainMetadataFileName);
460
461                 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
462                 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII)) 
463                         {
464                                 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
465                                 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
466                                 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
467                                 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
468                                 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
469                                 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
470                                 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
471                                 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
472                                 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
473                                 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
474                                 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
475                                 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
476                                 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);        
477                                 mdWriter.Flush( );
478                         }
479                 }
480                 }
481                         
482
483                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
484                 {
485                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
486                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
487                                                                                         mapChunk.YMax,
488                                                                                         mostActiveCol.Key.Y * chunkSize);
489
490                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
491                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
492
493                         return data;
494                 }
495
496                 /// <summary>
497                 /// Reload chunk bounds from chunk shards
498                 /// </summary>
499                 /// <returns>The metadata.</returns>
500                 private void Reload_Metadata()
501                 {
502                         var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
503
504                         if (!shardsDir.Exists)
505                         {
506                                 #if DEBUG
507                                 Logger.VerboseDebug("Could not open world map (shards) directory");
508                                 #endif
509                                 return;
510                         }
511                         var shardFiles = shardsDir.GetFiles(chunkFile_filter);
512
513                         if (shardFiles.Length > 0)
514                         {
515                                 #if DEBUG
516                                 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
517                                 #endif
518
519                                 foreach (var shardFile in shardFiles)
520                                 {
521
522                                         if (shardFile.Length < 1024) continue;
523                                         var result = chunkShardRegex.Match(shardFile.Name);
524                                         if (!result.Success) continue;
525
526                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
527                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
528
529                                         try
530                                         {
531                                                 using (var fileStream = shardFile.OpenRead())
532                                                 {
533
534                                                         PngReader pngRead = new PngReader(fileStream);
535                                                         pngRead.ReadSkippingAllRows();
536                                                         pngRead.End();
537                                                         //Parse PNG chunks for METADATA in shard
538                                                         PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
539                                                         var column = metadataFromPng.ChunkMetadata;
540                                                         if (column.PrettyLocation == null)
541                                                                 column = column.Reload(ClientAPI);
542                                                         chunkTopMetadata.Add(column);
543                                                 }
544
545                                         }
546                                         catch (PngjException someEx)
547                                         {
548                                                 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
549                                                 continue;
550                                         }
551                                         catch (ProtoException protoEx) 
552                                         {
553                                                 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
554                                                 continue;
555                                         }
556                                 }
557                         }
558
559                         //POI and EOI raw dump files ~ reload em!
560                         //var poiRawFile = File.
561                         string poiPath = Path.Combine(path, poiFileName);
562                         string eoiPath = Path.Combine(path, eoiFileName);
563
564                         if (File.Exists(poiPath))
565                         {
566                                 using (var poiFile = File.OpenRead(poiPath))
567                                 {
568                                         this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
569                                         Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
570                                 }
571                         }
572
573                         if (File.Exists(eoiPath))
574                         {
575                                 using (var eoiFile = File.OpenRead(eoiPath))
576                                 {
577                                         this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
578                                         Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
579                                 }
580                         }
581
582                 }
583
584
585
586                 /// <summary>
587                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
588                 /// </summary>
589                 /// <param name="key">Chunk Coordinate</param>
590                 /// <param name="mapChunk">Map chunk.</param>
591                 /// <param name="chunkMeta">Chunk metadata</param>
592                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
593                 {
594                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish... 
595                         byte chunkTally = 0;
596
597                 #if DEBUG
598                 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
599                 #endif
600
601                 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
602
603                 for (; targetChunkY > 0; targetChunkY--)
604                         {
605                                 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
606
607                                 if (worldChunk == null || worldChunk.BlockEntities == null)
608                                 {
609                                         #if DEBUG
610                                         Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
611                                         #endif
612                                         nullChunkCount++;
613                                         continue;
614                                 }
615
616                                 if (worldChunk.IsPacked()) 
617                                 {
618                                 #if DEBUG
619                                 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
620                                 #endif
621                                 worldChunk.Unpack( );//RESEARCH: Thread Unsafe? 
622                                 }
623
624                                 /*************** Chunk Entities Scanning *********************/
625                                 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
626                                 {
627                                         #if DEBUG
628                                         Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
629                                         #endif
630
631                                         foreach (var blockEnt in worldChunk.BlockEntities)
632                                         {
633                                                 if (blockEnt.Key != null && blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
634                                                 {
635                                                         var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
636                                                         designator?.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
637                                                 }
638                                         }
639                                 }
640
641                                 /********************* Chunk/Column BLOCKs scanning ****************/
642                                 //Heightmap, Stats, block tally
643
644                                 int X_index, Y_index, Z_index;
645
646                                 //First Chance fail-safe;
647                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
648                                 #if DEBUG
649                                 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
650                                 #endif
651                                 nullChunkCount++;
652                                 continue;
653                                 }               
654
655                                 chunkMeta.ColumnPresense[targetChunkY] = true;
656                                 chunkTally++;
657                                 for (Y_index = 0; Y_index < chunkSize; Y_index++)
658                                 {
659                                         for (Z_index = 0; Z_index < chunkSize; Z_index++)
660                                         {
661                                                 for (X_index = 0; X_index < chunkSize; X_index++) 
662                                                 {
663                                                 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
664
665                                                 //'Last' Chance fail-safe;
666                                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
667                                                 #if DEBUG
668                                                 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
669                                                 #endif
670                                                 nullChunkCount++;
671                                                 goto loop_bustout; 
672                                                 }
673
674                                                 int aBlockId = worldChunk.Blocks[indicie];
675
676                                                 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
677                                                 chunkMeta.AirBlocks++;
678                                                 continue;
679                                                 }
680
681                                                 if (RockIdCodes.ContainsKey(aBlockId)) {
682                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
683                                                         chunkMeta.RockRatio[aBlockId]++;
684                                                 else
685                                                         chunkMeta.RockRatio.Add(aBlockId, 1);
686                                                 }
687
688                                                 chunkMeta.NonAirBlocks++;
689
690                                                 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
691                                                 //Heightmap - Need to ignore Grass & Snow
692                                                 if (localHeight > chunkMeta.HeightMap[X_index, Z_index]) 
693                                                         {
694                                                         chunkMeta.HeightMap[X_index, Z_index] = localHeight;
695                                                         if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
696                                                         }
697                                                 }
698                                         }
699                                 }
700                                 loop_bustout:;
701                         }
702                         #if DEBUG
703                         Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
704                         #endif
705                 }
706
707                 private void UpdateEntityMetadata()
708                 {
709                         #if DEBUG
710                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
711                         #endif
712                         //Mabey scan only for 'new' entities by tracking ID in set?
713                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
714                         {
715
716                                 #if DEBUG
717                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
718                                 #endif
719
720                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
721                                 if (dMatch.Value != null)
722                                 {
723                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.Pos.AsBlockPos.Copy(), loadedEntity.Value);
724                                 }
725
726                         }
727
728
729                 }
730
731                 private void AddNote(string notation)
732                 {
733                         var playerNodePoi = new PointOfInterest()
734                         {
735                                 Name = "Note",
736                                 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
737                                 Notes = notation,
738                                 Timestamp = DateTime.UtcNow,
739                         };
740
741                         this.POIs.AddReplace(playerNodePoi);
742                 }
743
744
745
746                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
747                 {
748                         //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
749
750                         CommandData cmdData = data as CommandData;
751
752                         switch (cmdData.State)
753                         {
754                                 case CommandType.Run:
755                                 case CommandType.Stop:
756                                 case CommandType.Snapshot:
757                                         if (CurrentState != cmdData.State)
758                                         {
759                                                 CurrentState = cmdData.State;
760                                                 AwakenCartographer(0.0f);
761                                         }
762                                         break;
763
764                                 case CommandType.Notation:
765                                         //Add to POI list where player location
766                                         AddNote(cmdData.Notation);
767                                         break;
768                         }
769
770                         ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
771
772                 }
773 #endregion
774
775                 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
776                 {
777                 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
778                 switch (rendererName) 
779                 {                               
780                 case StandardRenderer.Name:
781                         return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
782                 
783                 case AlternateRenderer.Name:
784                         return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
785         
786                 case FlatRenderer.Name:
787                         return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);  
788
789                 default:
790                         throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");
791                 }
792
793                 return null;
794                 }
795         }
796
797 }