OSDN Git Service

Changed shard (png) output to its own "Chunks" directory path
[automap/automap.git] / Automap / Subsystems / AutomapSystem.cs
1 using System;
2 using System.Collections.Concurrent;
3 using System.Collections.Generic;
4 using System.IO;
5 using System.Linq;
6 using System.Reflection;
7 using System.Text;
8 using System.Text.RegularExpressions;
9 using System.Threading;
10
11 using Hjg.Pngcs;
12 using Hjg.Pngcs.Chunks;
13
14 using Newtonsoft.Json;
15
16 using ProtoBuf;
17
18 using Vintagestory.API.Client;
19 using Vintagestory.API.Common;
20 using Vintagestory.API.Config;
21 using Vintagestory.API.Datastructures;
22 using Vintagestory.API.MathTools;
23 using Vintagestory.Common;
24
25 namespace Automap
26 {
27         public class AutomapSystem
28         {
29                 private Thread cartographer_thread;
30                 private ICoreClientAPI ClientAPI { get; set; }
31                 private ILogger Logger { get; set; }
32                 private IChunkRenderer ChunkRenderer { get; set; }
33                 private JsonGenerator JsonGenerator { get; set; }
34
35                 private const string _mapPath = @"Maps";
36                 private const string _chunkPath = @"Chunks";
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 static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+).png", RegexOptions.Singleline);
43
44                 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
45                 private ColumnsMetadata chunkTopMetadata;
46                 private PointsOfInterest POIs = new PointsOfInterest();
47                 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
48
49                 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
50                 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
51                 internal Dictionary<int, string> RockIdCodes { 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
76                         //TODO:Choose which one from GUI 
77                         this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
78
79                         //Listen on bus for commands
80                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
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.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
109                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
110
111                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
112                         Reload_Metadata();
113
114                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
115
116                         cartographer_thread = new Thread(Cartographer)
117                         {
118                                 Name = "Cartographer",
119                                 Priority = ThreadPriority.Lowest,
120                                 IsBackground = true
121                         };
122
123                         ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
124                 }
125
126                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
127                 {
128                         Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
129
130                         columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
131                 }
132
133                 private void AwakenCartographer(float delayed)
134                 {
135
136                         if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
137                         {
138                                 #if DEBUG
139                                 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
140                                 #endif
141
142                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
143                                 {
144                                         cartographer_thread.Start();
145                                 }
146                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
147                                 {
148                                         //Time to (re)write chunk shards
149                                         cartographer_thread.Interrupt();
150                                 }
151                                 //#if DEBUG
152                                 //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})");
153                                 //#endif
154                         }
155                         else if (CurrentState == CommandType.Snapshot)
156                         {
157                                 //TODO: Snapshot generator second thread...
158                         }
159
160                 }
161
162
163                 private void Cartographer()
164                 {
165                         wake:
166                         Logger.VerboseDebug("Cartographer thread awoken");
167
168                         try
169                         {
170                                 uint ejectedItem = 0;
171                                 uint updatedChunks = 0;
172                                 uint updatedPixels = 0;
173
174                                 //-- Should dodge enumerator changing underfoot....at a cost.
175                                 if (!columnCounter.IsEmpty)
176                                 {
177                                         var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
178                                         UpdateEntityMetadata();
179
180                                         foreach (var mostActiveCol in tempSet)
181                                         {
182                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
183
184                                                 if (mapChunk == null)
185                                                 {
186                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
187                                                         nullMapCount++;
188                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
189                                                         continue;
190                                                 }
191
192                                                 ColumnMeta chunkMeta;
193                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
194                                                 {
195                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
196 #if DEBUG
197                                                         Logger.VerboseDebug("Loaded chunk {0}", mostActiveCol.Key);
198                                                         //Console.WriteLine($"Load {mostActiveCol.Key}");
199 #endif
200                                                 }
201                                                 else
202                                                 {
203                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
204 #if DEBUG
205                                                         Logger.VerboseDebug("Created chunk {0}", mostActiveCol.Key);
206                                                         //Console.WriteLine($"Created chunk {mostActiveCol.Key}");
207 #endif
208                                                 }
209
210                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
211
212                                                 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, ref chunkMeta);
213                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
214
215                                                 if (updatedPixels > 0)
216                                                 {
217 #if DEBUG
218                                                         Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
219 #endif
220                                                         updatedChunks++;
221                                                         chunkTopMetadata.Update(chunkMeta);
222                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
223                                                 }
224                                                 else
225                                                 {
226                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
227                                                         Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
228                                                 }
229                                         }
230                                 //Cleanup persisted Metadata...
231                                 chunkTopMetadata.ClearMetadata( );
232                                 }
233
234                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
235
236                                 if (updatedChunks > 0)
237                                 {
238                                         //What about chunk updates themselves; a update bitmap isn't kept...
239                                         updatedChunksTotal += updatedChunks;
240                                         JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
241                                         updatedChunks = 0;
242                                 }
243
244                                 //Then sleep until interupted again, and repeat
245
246                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
247
248                                 Thread.Sleep(Timeout.Infinite);
249
250                         }
251                         catch (ThreadInterruptedException)
252                         {
253
254                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
255                                 goto wake;
256
257                         }
258                         catch (ThreadAbortException)
259                         {
260                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
261
262                         }
263                         finally
264                         {
265                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
266                                 PersistPointsData();
267                         }
268                 }
269
270                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
271                 {
272                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
273
274                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
275                 }
276
277                 private void Prefill_POI_Designators()
278                 {
279
280                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
281                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
282                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
283
284                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
285
286                         Reload_POI_Designators();
287                 }
288
289                 private void Reload_POI_Designators()
290                 {
291                         Logger.VerboseDebug("Connecting {0} Configured Block-Designators", configuration.BlockDesignators.Count);
292                         foreach (var designator in configuration.BlockDesignators)
293                         {
294                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
295                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
296                                 foreach (var entry in blockIDs)
297                                 {
298                                         BlockID_Designators.Add(entry.Key, designator);
299                                 }
300                         }
301                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
302
303
304                         Logger.VerboseDebug("Connecting {0} Configured Entity-Designators", configuration.EntityDesignators.Count);
305                         foreach (var designator in configuration.EntityDesignators)
306                         {
307                                 //Get Variants first, from EntityTypes...better be populated!
308                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
309
310                                 foreach (var match in matched)
311                                 {
312                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
313                                         this.Entity_Designators.Add(match.Code, designator);
314                                 }
315
316
317
318                                 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
319                         }
320
321
322                 }
323
324
325
326                 /// <summary>
327                 /// Store Points/Entity of Interest
328                 /// </summary>
329                 private void PersistPointsData( )
330                 {
331                 //POI and EOI raw dump files ~ WRITE em!
332                 //var poiRawFile = File.
333                 string poiPath = Path.Combine(path, poiFileName);
334                 string eoiPath = Path.Combine(path, eoiFileName);
335
336                 if (this.POIs.Count > 0) {
337                 using (var poiFile = File.OpenWrite(poiPath)) {
338                         Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
339                 }
340                 }
341
342                 if (this.EOIs.Count > 0) {
343                 using (var eoiFile = File.OpenWrite(eoiPath)) {
344                         Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
345                 }
346                 }
347
348                 //Create Easy to Parse TSV file for tool/human use....
349                 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
350
351                 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
352                 {
353                 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\t");
354                         foreach (var point in this.POIs) {
355                                         tsvWriter.Write(point.Name + "\t");
356                                         tsvWriter.Write(point.Notes + "\t");
357                                         tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
358                                         tsvWriter.Write(point.Timestamp.ToString("u")+"\t");
359                                         tsvWriter.WriteLine();
360                         }
361                         foreach (var entity in this.EOIs) {
362                                         tsvWriter.Write(entity.Name + "\t");
363                                         tsvWriter.Write(entity.Notes + "\t");
364                                         tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
365                                         tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
366                                         tsvWriter.WriteLine( );
367                         }
368                 tsvWriter.WriteLine();
369                 tsvWriter.Flush( );
370                 }
371
372                 }
373
374                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
375                 {
376                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize);
377                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
378                                                                                         mapChunk.YMax,
379                                                                                         mostActiveCol.Key.Y * chunkSize);
380
381                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
382                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
383
384                         return data;
385                 }
386
387                 /// <summary>
388                 /// Reload chunk bounds from chunk shards
389                 /// </summary>
390                 /// <returns>The metadata.</returns>
391                 private void Reload_Metadata()
392                 {
393                         var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
394
395                         if (!shardsDir.Exists)
396                         {
397                                 #if DEBUG
398                                 Logger.VerboseDebug("Could not open world map (shards) directory");
399                                 #endif
400                                 return;
401                         }
402                         var shardFiles = shardsDir.GetFiles(chunkFile_filter);
403
404                         if (shardFiles.Length > 0)
405                         {
406                                 #if DEBUG
407                                 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
408                                 #endif
409
410                                 foreach (var shardFile in shardFiles)
411                                 {
412
413                                         if (shardFile.Length < 1024) continue;
414                                         var result = chunkShardRegex.Match(shardFile.Name);
415                                         if (result.Success)
416                                         {
417                                                 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
418                                                 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
419
420                                                 try
421                                                 {
422                                                         using (var fileStream = shardFile.OpenRead())
423                                                         {
424
425                                                                 PngReader pngRead = new PngReader(fileStream);
426                                                                 pngRead.ReadSkippingAllRows();
427                                                                 pngRead.End();
428                                                                 //Parse PNG chunks for METADATA in shard
429                                                                 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
430                                                                 var column = metadataFromPng.ChunkMetadata;
431                                                                 if (column.PrettyLocation == null)
432                                                                         column = column.Reload(ClientAPI);
433                                                                 chunkTopMetadata.Add(column);
434                                                         }
435
436                                                 }
437                                                 catch (PngjException someEx)
438                                                 {
439                                                         Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
440                                                         continue;
441                                                 }
442                                         }
443
444                                 }
445                         }
446
447                         //POI and EOI raw dump files ~ reload em!
448                         //var poiRawFile = File.
449                         string poiPath = Path.Combine(path, poiFileName);
450                         string eoiPath = Path.Combine(path, eoiFileName);
451
452                         if (File.Exists(poiPath))
453                         {
454                                 using (var poiFile = File.OpenRead(poiPath))
455                                 {
456                                         this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
457                                         Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
458                                 }
459                         }
460
461                         if (File.Exists(eoiPath))
462                         {
463                                 using (var eoiFile = File.OpenRead(eoiPath))
464                                 {
465                                         this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
466                                         Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
467                                 }
468                         }
469
470                 }
471
472                 private PngWriter SetupPngImage(Vec2i coord, ref ColumnMeta metadata)
473                 {
474                         ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
475
476                         string filename = $"{coord.X}_{coord.Y}.png";
477                         filename = Path.Combine(path, _chunkPath ,filename);
478
479                         PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
480                         PngMetadata meta = pngWriter.GetMetadata();
481                         meta.SetTimeNow();
482                         meta.SetText("Chunk_X", coord.X.ToString("D"));
483                         meta.SetText("Chunk_Y", coord.Y.ToString("D"));
484                         //Setup specialized meta-data PNG chunks here...
485                         PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
486                         {
487                                 ChunkMetadata = metadata
488                         };
489                         pngWriter.GetChunksList().Queue(pngChunkMeta);
490                         pngWriter.CompLevel = 5;// 9 is the maximum compression but thats too high for the small benefit it gives
491                         pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
492
493                         return pngWriter;
494                 }
495
496                 /// <summary>
497                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
498                 /// </summary>
499                 /// <param name="key">Chunk Coordinate</param>
500                 /// <param name="mapChunk">Map chunk.</param>
501                 /// <param name="chunkMeta">Chunk metadata</param>
502                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
503                 {
504
505                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ... 
506                         for (; targetChunkY > 0; targetChunkY--)
507                         {
508                                 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
509
510                         if (chunkData == null || chunkData.BlockEntities == null) {
511                         #if DEBUG
512                         Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
513                         #endif
514                         nullChunkCount++;
515                         continue;
516                         }
517
518                                 /*************** Chunk Entities Scanning *********************/
519                                 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
520                                 {
521 #if DEBUG
522                                         Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
523 #endif
524
525                                         foreach (var blockEnt in chunkData.BlockEntities)
526                                         {
527                                                 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
528                                                 {
529                                                         var designator = BlockID_Designators[blockEnt.Block.BlockId];
530                                                         designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
531                                                 }
532                                         }
533                                 }
534                                 /********************* Chunk/Column BLOCKs scanning ****************/
535                                 //Heightmap, Stats, block tally
536                                 chunkData.Unpack();
537
538                                 int X_index, Y_index, Z_index;
539                                 X_index = Y_index = Z_index = 0;
540
541                                 //Ensure ChunkData Metadata fields arn't null...due to being tossed out
542                                 if (chunkMeta.HeightMap == null) { chunkMeta.HeightMap = new ushort[chunkSize, chunkSize]; }
543                                 if (chunkMeta.RockRatio == null) { chunkMeta.RockRatio = new Dictionary<int, uint>(10); }
544
545                                 do
546                                 {
547                                         do
548                                         {
549                                                 do
550                                                 {
551                                                         /* Encode packed indicie
552                                                         (y * chunksize + z) * chunksize + x
553                                                         */
554                                                         var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
555                                                         int aBlockId = chunkData.Blocks[indicie];
556
557                                                         if (aBlockId == 0)
558                                                         {//Air
559                                                                 chunkMeta.AirBlocks++;
560                                                                 continue;
561                                                         }
562
563                                                         if (RockIdCodes.ContainsKey(aBlockId))
564                                                         {
565                                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
566                                                         }
567
568                                                         chunkMeta.NonAirBlocks++;
569
570                                                         //Heightmap 
571                                                         if (chunkMeta.HeightMap[X_index, Z_index] == 0)
572                                                         { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
573
574                                                 }
575                                                 while (X_index++ < (chunkSize - 1));
576                                                 X_index = 0;
577                                         }
578                                         while (Z_index++ < (chunkSize - 1));
579                                         Z_index = 0;
580                                 }
581                                 while (Y_index++ < (chunkSize - 1));
582
583                         }
584                 }
585
586                 private void UpdateEntityMetadata()
587                 {
588                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
589                         //Mabey scan only for 'new' entities by tracking ID in set?
590                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
591                         {
592
593 #if DEBUG
594                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
595 #endif
596
597                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
598                                 if (dMatch.Value != null)
599                                 {
600                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
601                                 }
602
603                         }
604
605
606                 }
607
608                 private void AddNote(string notation)
609                 {
610                         var playerNodePoi = new PointOfInterest()
611                         {
612                                 Name = "Note",
613                                 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
614                                 Notes = notation,
615                                 Timestamp = DateTime.UtcNow,
616                         };
617
618                         this.POIs.AddReplace(playerNodePoi);
619                 }
620
621
622
623                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
624                 {
625                         Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
626
627                         CommandData cmdData = data as CommandData;
628
629
630                         if (CurrentState != CommandType.Snapshot)
631                         {
632                                 switch (cmdData.State)
633                                 {
634                                         case CommandType.Run:
635                                         case CommandType.Stop:
636                                                 if (CurrentState != cmdData.State)
637                                                 {
638                                                         CurrentState = cmdData.State;
639                                                         AwakenCartographer(0.0f);
640                                                 }
641                                                 break;
642
643                                         case CommandType.Snapshot:
644                                                 CurrentState = CommandType.Stop;
645                                                 //Snapshot starts a second thread/process...
646
647                                                 break;
648
649                                         case CommandType.Notation:
650                                                 //Add to POI list where player location
651                                                 AddNote(cmdData.Notation);
652                                                 break;
653                                 }
654                         }
655
656
657
658 #if DEBUG
659                         ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
660 #endif
661
662                 }
663
664
665
666
667                 #endregion
668
669         }
670
671 }