OSDN Git Service

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