OSDN Git Service

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