OSDN Git Service

Merge branch 'Split_renderers' into vgd
[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.Text;
7 using System.Text.RegularExpressions;
8 using System.Threading;
9
10 using Hjg.Pngcs;
11 using Hjg.Pngcs.Chunks;
12 using Newtonsoft.Json;
13 using Vintagestory.API.Client;
14 using Vintagestory.API.Common;
15 using Vintagestory.API.Config;
16 using Vintagestory.API.Datastructures;
17 using Vintagestory.API.MathTools;
18 using Vintagestory.Common;
19
20 namespace Automap
21 {
22         public class AutomapSystem
23         {
24                 private Thread cartographer_thread;
25                 private ICoreClientAPI ClientAPI { get; set; }
26                 private ILogger Logger { get; set; }
27                 private IChunkRenderer ChunkRenderer { get; set; }
28
29                 private const string _mapPath = @"Maps";
30                 private const string _chunkPath = @"Chunks";
31                 private const string _domain = @"automap";
32                 private const string chunkFile_filter = @"*_*.png";
33                 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+).png", RegexOptions.Singleline);
34
35                 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
36                 private ColumnsMetadata chunkTopMetadata;
37                 private PointsOfInterest POIs = new PointsOfInterest();
38                 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
39
40                 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
41                 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
42                 internal Dictionary<int, string> RockIdCodes { get; private set; }
43
44                 internal RunState CurrentState { get; set; }
45                 //Run status, Chunks processed, stats, center of map....
46                 private uint nullChunkCount, updatedChunksTotal;
47                 private Vec2i startChunkColumn;
48
49                 private readonly int chunkSize;
50                 private string path;
51                 private IAsset staticMap;
52
53                 public static string AutomapStatusEventKey = @"AutomapStatus";
54                 public static string AutomapCommandEventKey = @"AutomapCommand";
55
56
57                 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger)
58                 {
59                         this.ClientAPI = clientAPI;
60                         this.Logger = logger;
61                         chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
62                         ClientAPI.Event.LevelFinalize += EngageAutomap;
63
64                         //TODO:Choose which one from GUI 
65                         this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
66
67                         //Listen on bus for commands
68                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
69
70                 }
71
72
73                 #region Internals
74                 private void EngageAutomap()
75                 {
76                         path = ClientAPI.GetOrCreateDataPath(_mapPath);
77                         path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
78
79
80                         string mapFilename = Path.Combine(path, "automap.html");
81                         StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
82
83                         staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
84                         outputText.Write(staticMap.ToText());
85                         outputText.Flush();
86
87                         Prefill_POI_Designators();
88                         startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
89                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
90
91                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
92                         Reload_Metadata();
93
94                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
95
96                         cartographer_thread = new Thread(Cartographer)
97                         {
98                                 Name = "Cartographer",
99                                 Priority = ThreadPriority.Lowest,
100                                 IsBackground = true
101                         };
102
103                         ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
104                 }
105
106                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
107                 {
108                         Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
109
110                         columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
111                 }
112
113                 private void AwakenCartographer(float delayed)
114                 {
115
116                         if (CurrentState == RunState.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
117                         {
118 #if DEBUG
119                                 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
120 #endif
121
122                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
123                                 {
124                                         cartographer_thread.Start();
125                                 }
126                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
127                                 {
128                                         //Time to (re)write chunk shards
129                                         cartographer_thread.Interrupt();
130                                 }
131                                 //#if DEBUG
132                                 //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})");
133                                 //#endif
134                         }
135                         else if (CurrentState == RunState.Snapshot)
136                         {
137                                 //TODO: Snapshot generator second thread...
138                         }
139
140                 }
141
142
143                 private void Cartographer()
144                 {
145                         wake:
146                         Logger.VerboseDebug("Cartographer thread awoken");
147
148                         try
149                         {
150                                 uint ejectedItem = 0;
151                                 uint updatedChunks = 0;
152                                 uint updatedPixels = 0;
153
154                                 //-- Should dodge enumerator changing underfoot....at a cost.
155                                 if (!columnCounter.IsEmpty)
156                                 {
157                                         var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
158                                         foreach (var mostActiveCol in tempSet)
159                                         {
160
161                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
162
163                                                 if (mapChunk == null)
164                                                 {
165                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
166                                                         nullChunkCount++;
167                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
168                                                         continue;
169                                                 }
170
171                                                 ColumnMeta chunkMeta;
172                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key)) {
173                                                 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
174                                                 }
175                                                 else {
176                                                 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
177                                                 }
178
179                                                 UpdateEntityMetadata();
180                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, chunkMeta);
181
182                                                 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
183                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
184
185                                                 if (updatedPixels > 0)
186                                                 {
187
188 #if DEBUG
189                                                         Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
190 #endif
191                                                         updatedChunks++;
192                                                         chunkTopMetadata.Update(chunkMeta);
193                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
194                                                 }
195                                                 else
196                                                 {
197                                                         columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
198                                                         Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
199                                                 }
200
201                                         }
202                                 }
203
204                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
205
206                                 if (updatedChunks > 0)
207                                 {
208                                         //What about chunk updates themselves; a update bitmap isn't kept...
209                                         updatedChunksTotal += updatedChunks;
210                                         GenerateJSONMetadata();
211                                         updatedChunks = 0;
212                                 }
213
214                                 //Then sleep until interupted again, and repeat
215
216                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
217
218                                 Thread.Sleep(Timeout.Infinite);
219
220                         }
221                         catch (ThreadInterruptedException)
222                         {
223
224                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
225                                 goto wake;
226
227                         }
228                         catch (ThreadAbortException)
229                         {
230                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
231
232                         }
233                         finally
234                         {
235                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
236                         }
237                 }
238
239                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
240                 {
241                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, RunState.Run);
242
243                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
244                 }
245
246                 private void Prefill_POI_Designators()
247                 {
248
249                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
250                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
251                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock"), EnumBlockMaterial.Stone);
252
253                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
254
255                         Install_POI_Designators(DefaultDesignators.DefaultBlockDesignators(), DefaultDesignators.DefaultEntityDesignators());
256                 }
257
258                 private void Install_POI_Designators(ICollection<BlockDesignator> blockDesig, List<EntityDesignator> entDesig)
259                 {
260                         Logger.VerboseDebug("Connecting {0} standard Block-Designators", blockDesig.Count);
261                         foreach (var designator in blockDesig)
262                         {
263                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
264                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
265                                 foreach (var entry in blockIDs)
266                                 {
267                                         BlockID_Designators.Add(entry.Key, designator);
268                                 }
269                         }
270                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
271
272
273                         Logger.VerboseDebug("Connecting {0} standard Entity-Designators", entDesig.Count);
274                         foreach (var designator in entDesig)
275                         {
276                                 //Get Variants first, from EntityTypes...better be populated!
277                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
278
279                                 foreach (var match in matched)
280                                 {
281                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
282                                         this.Entity_Designators.Add(match.Code, designator);
283                                 }
284
285
286
287                                 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
288                         }
289
290
291                 }
292
293                 /// <summary>
294                 /// Generates the JSON Metadata. (in Map object format )
295                 /// </summary>
296                 private void GenerateJSONMetadata()
297                 {
298                         string jsonFilename = Path.Combine(path, "Metadata.js");
299
300                         StreamWriter jsonWriter = new StreamWriter(jsonFilename, false, Encoding.UTF8);
301                         using (jsonWriter)
302                         {
303                                 jsonWriter.Write("ViewFrame.chunks={};");
304                                 jsonWriter.Write("ViewFrame.chunks.worldSeedNum={0};", ClientAPI.World.Seed);
305                                 jsonWriter.Write("ViewFrame.chunks.genTime=new Date('{0}');", DateTimeOffset.UtcNow.ToString("O"));
306                                 jsonWriter.Write("ViewFrame.chunks.startCoords=[{0},{1}];", startChunkColumn.X, startChunkColumn.Y);
307                                 jsonWriter.Write("ViewFrame.chunks.chunkSize={0};", chunkSize);
308                                 jsonWriter.Write("ViewFrame.chunks.northMostChunk={0};", chunkTopMetadata.North_mostChunk);
309                                 jsonWriter.Write("ViewFrame.chunks.southMostChunk={0};", chunkTopMetadata.South_mostChunk);
310                                 jsonWriter.Write("ViewFrame.chunks.eastMostChunk={0};", chunkTopMetadata.East_mostChunk);
311                                 jsonWriter.Write("ViewFrame.chunks.westMostChunk={0};", chunkTopMetadata.West_mostChunk);
312                                 //MAP object format - [key, value]: key is "x_y"
313                                 jsonWriter.Write("ViewFrame.chunks.chunkMetadata=new Map([");
314                                 foreach (var shard in chunkTopMetadata)
315                                 {
316                                         jsonWriter.Write("['{0}_{1}',", shard.Location.X, shard.Location.Y);
317                                         jsonWriter.Write("{");
318                                         jsonWriter.Write("prettyCoord:'{0}',", shard.Location.PrettyCoords(ClientAPI));
319                                         jsonWriter.Write("chunkAge:'{0}',", shard.ChunkAge.ToString("g"));//World age - relative? or last edit ??
320                                         jsonWriter.Write("temp:'{0}',", shard.Temperature.ToString("F1"));
321                                         jsonWriter.Write("YMax:'{0}',", shard.YMax);
322                                         jsonWriter.Write("fert:'{0}',", shard.Fertility.ToString("F1"));
323                                         jsonWriter.Write("forestDens:'{0}',", shard.ForestDensity.ToString("F1"));
324                                         jsonWriter.Write("rain:'{0}',", shard.Rainfall.ToString("F1"));
325                                         jsonWriter.Write("shrubDens:'{0}',", shard.ShrubDensity.ToString("F1"));
326                                         jsonWriter.Write("airBlocks:'{0}',", shard.AirBlocks);
327                                         jsonWriter.Write("nonAirBlocks:'{0}',", shard.NonAirBlocks);
328                                         //TODO: Heightmap
329                                         //TODO: Rock-ratio, also requires a BlockID => Name lookup table....elsewhere
330                                         jsonWriter.Write("}],");
331                                 }
332                                 jsonWriter.Write("]);");
333
334
335                                 jsonWriter.Write("ViewFrame.chunks.pointsOfInterest = new Map([");
336                                 foreach (var poi in POIs)
337                                 {
338                                         jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
339                                         jsonWriter.Write("{");
340                                         jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
341                                         jsonWriter.Write("notes:{0},", JsonConvert.ToString(poi.Notes, '\'', StringEscapeHandling.EscapeHtml));
342                                         jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
343                                         jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
344                                         jsonWriter.Write("}],");
345                                 }
346
347                                 foreach (var poi in EOIs)
348                                 {
349                                         jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
350                                         jsonWriter.Write("{");
351                                         jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
352                                         jsonWriter.Write("notes:{0},", JsonConvert.ToString(poi.Notes, '\'', StringEscapeHandling.EscapeHtml));
353                                         jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
354                                         jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
355                                         jsonWriter.Write("}],");
356                                 }
357                                 jsonWriter.Write("]);");
358
359                                 jsonWriter.Flush();
360                         }
361
362                 }
363
364
365                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
366                 {
367                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ( byte )chunkSize);
368                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
369                                                                                         mapChunk.YMax,
370                                                                                         mostActiveCol.Key.Y * chunkSize);
371
372                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
373                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
374
375                         return data;
376                 }
377
378                 /// <summary>
379                 /// Reload chunk bounds from chunk shards
380                 /// </summary>
381                 /// <returns>The metadata.</returns>
382                 private void Reload_Metadata()
383                 {
384                         var worldmapDir = new DirectoryInfo(path);
385
386                         if (worldmapDir.Exists)
387                         {
388
389                                 var files = worldmapDir.GetFiles(chunkFile_filter);
390
391                                 if (files.Length > 0)
392                                 {
393                                         #if DEBUG
394                                         Logger.VerboseDebug("{0} Existing world chunk shards", files.Length);
395                                         #endif
396                                          
397                                         foreach (var shardFile in files) {
398
399                                         if (shardFile.Length < 1024) continue;
400                                         var result = chunkShardRegex.Match(shardFile.Name);
401                                         if (result.Success) {
402                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
403                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
404
405                                         try 
406                                                 {
407                                                 using (var fileStream = shardFile.OpenRead( )) {
408
409                                                 PngReader pngRead = new PngReader(fileStream);
410                                                 pngRead.ReadSkippingAllRows( );
411                                                 pngRead.End( );
412                                                 //Parse PNG chunks for METADATA in shard
413                                                 PngMetadataChunk metadataFromPng = pngRead.GetChunksList( ).GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
414
415                                                 chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
416                                                 }
417
418                                                 }
419                                                 catch (PngjException someEx) 
420                                                 {
421                                                         Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
422                                                         continue;
423                                                 }
424                                         }
425
426                                         }
427                                 }
428
429
430                         }
431                         else
432                         {
433 #if DEBUG
434                                 Logger.VerboseDebug("Could not open world map directory");
435 #endif
436                         }
437
438
439
440                 }
441
442                 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
443                 {
444                         ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
445
446                         string filename = $"{coord.X}_{coord.Y}.png";
447                         filename = Path.Combine(path, filename);
448
449                         PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
450                         PngMetadata meta = pngWriter.GetMetadata();
451                         meta.SetTimeNow();
452                         meta.SetText("Chunk_X", coord.X.ToString("D"));
453                         meta.SetText("Chunk_Y", coord.Y.ToString("D"));
454                         //Setup specialized meta-data PNG chunks here...
455                         PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
456                         {
457                                 ChunkMetadata = metadata
458                         };
459                         pngWriter.GetChunksList().Queue(pngChunkMeta);
460                         pngWriter.CompLevel = 9;// 9 is the maximum compression
461                         pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
462
463                         return pngWriter;
464                 }
465
466                 /// <summary>
467                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
468                 /// </summary>
469                 /// <param name="key">Chunk Coordinate</param>
470                 /// <param name="mapChunk">Map chunk.</param>
471                 /// <param name="chunkMeta">Chunk metadata</param>
472                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ColumnMeta chunkMeta)
473                 {
474
475                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ... 
476                         for (; targetChunkY > 0; targetChunkY--)
477                         {
478                         WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
479
480                         if (chunkData == null || chunkData.BlockEntities == null) {
481                         #if DEBUG
482                         Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
483                         #endif
484                         continue;
485                         }
486
487                                 /*************** Chunk Entities Scanning *********************/
488                                 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
489                                 {
490                                 #if DEBUG
491                                         Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
492                                 #endif
493
494                                         foreach (var blockEnt in chunkData.BlockEntities)
495                                         {
496
497                                                 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
498                                                 {
499                                                         var designator = BlockID_Designators[blockEnt.Block.BlockId];
500                                                         designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
501                                                 }
502                                         }
503
504                                 }
505                                 /********************* Chunk/Column BLOCKs scanning ****************/
506                                 //Heightmap, Stats, block tally
507                                 chunkData.Unpack();
508
509                                 int X_index, Y_index, Z_index;
510                                 X_index = Y_index = Z_index = 0;
511
512                                 do
513                                 {
514                                         do
515                                         {
516                                                 do
517                                                 {
518                                                         /* Encode packed indicie
519                                                         (y * chunksize + z) * chunksize + x
520                                                         */
521                                                         var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
522                                                         int aBlockId = chunkData.Blocks[indicie];
523
524                                                         if (aBlockId == 0)
525                                                         {//Air
526                                                                 chunkMeta.AirBlocks++;
527                                                                 continue;
528                                                         }
529
530                                                         if (RockIdCodes.ContainsKey(aBlockId))
531                                                         {
532                                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
533                                                         }
534
535                                                         chunkMeta.NonAirBlocks++;
536
537                                                         //Heightmap 
538                                                         if (chunkMeta.HeightMap[X_index, Z_index] == 0)
539                                                         { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
540
541                                                 }
542                                                 while (X_index++ < (chunkSize - 1));
543                                                 X_index = 0;
544                                         }
545                                         while (Z_index++ < (chunkSize - 1));
546                                         Z_index = 0;
547                                 }
548                                 while (Y_index++ < (chunkSize - 1));
549
550                         }
551                 }
552
553                 private void UpdateEntityMetadata()
554                 {
555                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
556                         //Mabey scan only for 'new' entities by tracking ID in set?
557                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToList())
558                         {
559
560 #if DEBUG
561                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
562 #endif
563
564                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
565                                 if (dMatch.Value != null)
566                                 {
567                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
568                                 }
569
570                         }
571
572
573                 }
574
575                 private void AddNote(string notation)
576                 {
577                         var playerNodePoi = new PointOfInterest()
578                         {
579                                 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
580                                 Notes = notation,
581                                 Timestamp = DateTimeOffset.UtcNow,
582                         };
583
584                         this.POIs.AddReplace(playerNodePoi);
585                 }
586
587
588
589                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
590                 {
591                         Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
592
593                         CommandData cmdData = data as CommandData;
594
595
596                         if (CurrentState != RunState.Snapshot)
597                         {
598                                 switch (cmdData.State)
599                                 {
600                                         case RunState.Run:
601                                                 CurrentState = cmdData.State;
602                                                 AwakenCartographer(0.0f);
603                                                 break;
604
605                                         case RunState.Stop:
606                                                 CurrentState = cmdData.State;
607                                                 break;
608
609                                         case RunState.Snapshot:
610                                                 CurrentState = RunState.Stop;
611                                                 //Snapshot starts a second thread/process...
612
613                                                 break;
614
615                                         case RunState.Notation:
616                                                 //Add to POI list where player location
617                                                 AddNote(cmdData.Notation);
618                                                 break;
619                                 }
620
621                         }
622
623                         if (CurrentState != cmdData.State)
624                         {
625                                 CurrentState = cmdData.State;
626                                 AwakenCartographer(0.0f);
627                         }
628
629 #if DEBUG
630                         Logger.VerboseDebug($"Automap commanded to: {cmdData.State} ");
631 #endif
632
633                 }
634
635
636                 #endregion
637
638         }
639
640 }