OSDN Git Service

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