OSDN Git Service

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