OSDN Git Service

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