OSDN Git Service

abbfc44ecb1fe155f5a93f3893e8f1011e9a6115
[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                                                         #if DEBUG
208                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
209                                                         #endif
210                                                         nullMapCount++;
211                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
212                                                         continue;
213                                                 }
214
215                                                 ColumnMeta chunkMeta;
216                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
217                                                 {
218                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
219                                                         #if DEBUG
220                                                         Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
221                                                         #endif
222                                                 }
223                                                 else
224                                                 {
225                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
226                                                         #if DEBUG
227                                                         Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
228                                                         #endif
229                                                 }
230                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
231                                                 mostActiveCol.Value.SetCutoff(chunkMeta.YMax / chunkSize);
232
233                                                 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
234                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
235
236                                                 if (updatedPixels > 0)
237                                                 {
238                                                         #if DEBUG
239                                                         Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
240                                                         #endif
241                                                         updatedChunks++;
242                                                         chunkTopMetadata.Update(chunkMeta);
243                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
244                                                 }
245                                                 else
246                                                 {
247                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
248                                                         #if DEBUG
249                                                         Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
250                                                         #endif
251                                                 }
252                                         }
253                                 }
254
255                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
256
257                                 if (updatedChunks > 0)
258                                 {
259                                         //What about chunk updates themselves; a update bitmap isn't kept...
260                                         updatedChunksTotal += updatedChunks;
261                                         JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
262                                         updatedChunks = 0;
263
264                                         //Cleanup in-memory Metadata...
265                                         chunkTopMetadata.ClearMetadata( );
266                                 }
267
268                                 #if DEBUG
269                                 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
270                                 #endif
271
272                                 columnCounters.Clear( );
273
274                                 //Then sleep until interupted again, and repeat
275 #if DEBUG
276                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
277 #endif
278                                 Thread.Sleep(Timeout.Infinite);
279
280                         }
281                         catch (ThreadInterruptedException)
282                         {
283
284 #if DEBUG
285                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
286 #endif
287                                 goto wake;
288
289                         }
290                         catch (ThreadAbortException)
291                         {
292 #if DEBUG
293                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
294 #endif
295                         }
296                         finally
297                         {
298 #if DEBUG
299                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
300 #endif
301                                 PersistPointsData();
302                                 Write_PlainMetadata( );
303                         }
304                 }
305
306                 private void Snap()
307                 {
308                         snapshotTake:
309 #if DEBUG
310                         Logger.VerboseDebug("Snapshot started");
311 #endif
312                         try
313                         {
314                                 snapshot.Take();
315 #if DEBUG
316                                 Logger.VerboseDebug("Snapshot sleeping");
317 #endif
318                                 CurrentState = CommandType.Run;
319                                 Thread.Sleep(Timeout.Infinite);
320                         }
321                         catch (ThreadInterruptedException)
322                         {
323 #if DEBUG
324                                 Logger.VerboseDebug("Snapshot intertupted");
325 #endif
326                                 goto snapshotTake;
327                         }
328                 }
329
330                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
331                 {
332                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
333
334                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
335                 }
336
337                 private void Prefill_POI_Designators()
338                 {
339
340                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
341                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
342                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
343
344                         var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
345                                                          where airyBlock.MatterState == EnumMatterState.Solid
346                                                          where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
347                                                          where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 ||airyBlock.RainPermeable == true                                                        
348                                                          select airyBlock;                      
349                         //^^ 'Solid' phase - 'Plant' Blocks without any boundg box ? Except water...
350                         this.AiryIdCodes = airBlocksQuery.ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
351
352                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
353                         Reload_POI_Designators();
354                 }
355
356                 private void Reload_POI_Designators()
357                 {
358                 uint poisSetup =0, eoiSetup = 0;
359                         foreach (var designator in configuration.BlockDesignators)
360                         {
361                                 if (designator.Enabled == false) continue;
362                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
363                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
364                                 foreach (var entry in blockIDs)
365                                 {
366                                         BlockID_Designators.Add(entry.Key, designator);
367                                         poisSetup++;
368                                 }
369                         }
370                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
371                         Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
372
373
374                         foreach (var designator in configuration.EntityDesignators)
375                         {
376                                 if (designator.Enabled == false) continue;
377                                 //Get Variants first, from EntityTypes...better be populated!
378                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
379
380                                 foreach (var match in matched)
381                                 {                                       
382                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
383                                         this.Entity_Designators.Add(match.Code, designator);
384                                         eoiSetup++;
385                                 }
386                         }
387                         Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
388
389                 }
390
391
392
393                 /// <summary>
394                 /// Store Points/Entity of Interest
395                 /// </summary>
396                 private void PersistPointsData()
397                 {
398                         //POI and EOI raw dump files ~ WRITE em!
399                         //var poiRawFile = File.
400                         string poiPath = Path.Combine(path, poiFileName);
401                         string eoiPath = Path.Combine(path, eoiFileName);
402
403                         if (this.POIs.Count > 0)
404                         {
405                                 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
406                                 {
407                                         Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
408                                         poiFile.Flush(true);
409                                 }
410                         }
411
412                         if (this.EOIs.Count > 0)
413                         {
414                                 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
415                                 {
416                                         Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
417                                         eoiFile.Flush(true);
418                                 }
419                         }
420
421                         //Create Easy to Parse TSV file for tool/human use....
422                         string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
423
424                         using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
425                         {
426                                 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
427                                 foreach (var point in this.POIs)
428                                 {
429                                         tsvWriter.Write(point.Name + "\t");
430                                         var notes = point.Notes
431                                                 .Replace('\n', '\x001f')
432                                                 .Replace("\t", "\\t")
433                                                 .Replace("\\", "\\\\");
434                                         tsvWriter.Write(notes + "\t");
435                                         tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
436                                         tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
437                                         tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
438                                         tsvWriter.Write("null\t");
439                                         tsvWriter.WriteLine();
440                                 }
441                                 foreach (var entity in this.EOIs)
442                                 {
443                                         tsvWriter.Write(entity.Name + "\t");
444                                         var notes = entity.Notes
445                                                 .Replace('\n', '\x001f')
446                                                 .Replace("\t", "\\t")
447                                                 .Replace("\\", "\\\\");
448                                         tsvWriter.Write(notes + "\t");
449                                         tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
450                                         tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
451                                         tsvWriter.Write("---\t");
452                                         tsvWriter.Write(entity.EntityId.ToString("D"));
453                                         tsvWriter.WriteLine();
454                                 }
455                                 tsvWriter.WriteLine();
456                                 tsvWriter.Flush();
457                         }
458
459                 }
460
461                 private void Write_PlainMetadata( )
462                 { 
463                 string metaPath = Path.Combine(path, plainMetadataFileName);
464
465                 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
466                 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII)) 
467                         {
468                                 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
469                                 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
470                                 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
471                                 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
472                                 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
473                                 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
474                                 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
475                                 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
476                                 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
477                                 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
478                                 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
479                                 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
480                                 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);        
481                                 mdWriter.Flush( );
482                         }
483                 }
484                 }
485                         
486
487                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
488                 {
489                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
490                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
491                                                                                         mapChunk.YMax,
492                                                                                         mostActiveCol.Key.Y * chunkSize);
493
494                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
495                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
496
497                         return data;
498                 }
499
500                 /// <summary>
501                 /// Reload chunk bounds from chunk shards
502                 /// </summary>
503                 /// <returns>The metadata.</returns>
504                 private void Reload_Metadata()
505                 {
506                         var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
507
508                         if (!shardsDir.Exists)
509                         {
510                                 #if DEBUG
511                                 Logger.VerboseDebug("Could not open world map (shards) directory");
512                                 #endif
513                                 return;
514                         }
515                         var shardFiles = shardsDir.GetFiles(chunkFile_filter);
516
517                         if (shardFiles.Length > 0)
518                         {
519                                 #if DEBUG
520                                 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
521                                 #endif
522
523                                 foreach (var shardFile in shardFiles)
524                                 {
525
526                                         if (shardFile.Length < 1024) continue;
527                                         var result = chunkShardRegex.Match(shardFile.Name);
528                                         if (!result.Success) continue;
529
530                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
531                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
532
533                                         try
534                                         {
535                                                 using (var fileStream = shardFile.OpenRead())
536                                                 {
537
538                                                         PngReader pngRead = new PngReader(fileStream);
539                                                         pngRead.ReadSkippingAllRows();
540                                                         pngRead.End();
541                                                         //Parse PNG chunks for METADATA in shard
542                                                         PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
543                                                         var column = metadataFromPng.ChunkMetadata;
544                                                         if (column.PrettyLocation == null)
545                                                                 column = column.Reload(ClientAPI);
546                                                         chunkTopMetadata.Add(column);
547                                                 }
548
549                                         }
550                                         catch (PngjException someEx)
551                                         {
552                                                 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
553                                                 continue;
554                                         }
555                                         catch (ProtoException protoEx) 
556                                         {
557                                                 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
558                                                 continue;
559                                         }
560                                 }
561                         }
562
563                         //POI and EOI raw dump files ~ reload em!
564                         //var poiRawFile = File.
565                         string poiPath = Path.Combine(path, poiFileName);
566                         string eoiPath = Path.Combine(path, eoiFileName);
567
568                         if (File.Exists(poiPath))
569                         {
570                                 using (var poiFile = File.OpenRead(poiPath))
571                                 {
572                                         this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
573                                         Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
574                                 }
575                         }
576
577                         if (File.Exists(eoiPath))
578                         {
579                                 using (var eoiFile = File.OpenRead(eoiPath))
580                                 {
581                                         this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
582                                         Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
583                                 }
584                         }
585
586                 }
587
588
589
590                 /// <summary>
591                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
592                 /// </summary>
593                 /// <param name="key">Chunk Coordinate</param>
594                 /// <param name="mapChunk">Map chunk.</param>
595                 /// <param name="chunkMeta">Chunk metadata</param>
596                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
597                 {
598                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish... 
599                         byte chunkTally = 0;
600
601                 #if DEBUG
602                 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
603                 #endif
604
605                 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
606
607                 for (; targetChunkY > 0; targetChunkY--)
608                         {
609                                 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
610
611                                 if (worldChunk == null || worldChunk.BlockEntities == null)
612                                 {
613                                         #if DEBUG
614                                         Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
615                                         #endif
616                                         nullChunkCount++;
617                                         continue;
618                                 }
619
620                                 if (worldChunk.IsPacked()) 
621                                 {
622                                 #if DEBUG
623                                 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
624                                 #endif
625                                 worldChunk.Unpack( );//RESEARCH: Thread Unsafe? 
626                                 }
627
628                                 /*************** Chunk Entities Scanning *********************/
629                                 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
630                                 {
631                                         #if DEBUG
632                                         Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
633                                         #endif
634
635                                         foreach (var blockEnt in worldChunk.BlockEntities)
636                                         {
637                                                 if (blockEnt.Key != null && blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
638                                                 {
639                                                         var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
640                                                         designator?.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
641                                                 }
642                                         }
643                                 }
644
645                                 /********************* Chunk/Column BLOCKs scanning ****************/
646                                 //Heightmap, Stats, block tally
647
648                                 int X_index, Y_index, Z_index;
649
650                                 //First Chance fail-safe;
651                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
652                                 #if DEBUG
653                                 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
654                                 #endif
655                                 nullChunkCount++;
656                                 continue;
657                                 }               
658
659                                 chunkMeta.ColumnPresense[targetChunkY] = true;
660                                 chunkTally++;
661                                 for (Y_index = 0; Y_index < chunkSize; Y_index++)
662                                 {
663                                         for (Z_index = 0; Z_index < chunkSize; Z_index++)
664                                         {
665                                                 for (X_index = 0; X_index < chunkSize; X_index++) 
666                                                 {
667                                                 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
668
669                                                 //'Last' Chance fail-safe;
670                                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
671                                                 #if DEBUG
672                                                 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
673                                                 #endif
674                                                 nullChunkCount++;
675                                                 goto loop_bustout; 
676                                                 }
677
678                                                 int aBlockId = worldChunk.Blocks[indicie];
679
680                                                 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
681                                                 chunkMeta.AirBlocks++;
682                                                 continue;
683                                                 }
684
685                                                 if (RockIdCodes.ContainsKey(aBlockId)) {
686                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
687                                                         chunkMeta.RockRatio[aBlockId]++;
688                                                 else
689                                                         chunkMeta.RockRatio.Add(aBlockId, 1);
690                                                 }
691
692                                                 chunkMeta.NonAirBlocks++;
693
694                                                 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
695                                                 //Heightmap - Need to ignore Grass & Snow
696                                                 if (localHeight > chunkMeta.HeightMap[X_index, Z_index]) 
697                                                         {
698                                                         chunkMeta.HeightMap[X_index, Z_index] = localHeight;
699                                                         if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
700                                                         }
701                                                 }
702                                         }
703                                 }
704                                 loop_bustout:;
705                         }
706                         #if DEBUG
707                         Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
708                         #endif
709                 }
710
711                 private void UpdateEntityMetadata()
712                 {
713                         #if DEBUG
714                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
715                         #endif
716                         //Mabey scan only for 'new' entities by tracking ID in set?
717                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
718                         {
719
720                                 #if DEBUG
721                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
722                                 #endif
723
724                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
725                                 if (dMatch.Value != null)
726                                 {
727                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.Pos.AsBlockPos.Copy(), loadedEntity.Value);
728                                 }
729
730                         }
731
732
733                 }
734
735                 private void AddNote(string notation)
736                 {
737                         var playerNodePoi = new PointOfInterest()
738                         {
739                                 Name = "Note",
740                                 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
741                                 Notes = notation,
742                                 Timestamp = DateTime.UtcNow,
743                         };
744
745                         this.POIs.AddReplace(playerNodePoi);
746                 }
747
748
749
750                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
751                 {
752                         //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
753
754                         CommandData cmdData = data as CommandData;
755
756                         switch (cmdData.State)
757                         {
758                                 case CommandType.Run:
759                                 case CommandType.Stop:
760                                 case CommandType.Snapshot:
761                                         if (CurrentState != cmdData.State)
762                                         {
763                                                 CurrentState = cmdData.State;
764                                                 AwakenCartographer(0.0f);
765                                         }
766                                         break;
767
768                                 case CommandType.Notation:
769                                         //Add to POI list where player location
770                                         AddNote(cmdData.Notation);
771                                         break;
772                         }
773
774                         ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
775
776                 }
777 #endregion
778
779                 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
780                 {
781                 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
782                 switch (rendererName) 
783                 {                               
784                 case StandardRenderer.Name:
785                         return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
786                 
787                 case AlternateRenderer.Name:
788                         return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
789         
790                 case FlatRenderer.Name:
791                         return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);  
792
793                 default:
794                         throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");
795                 }
796
797                 return null;
798                 }
799         }
800
801 }