OSDN Git Service

2997ec6a19f3e386fd4ec09dab68137458191b09
[automap/automap.git] / Automap / Subsystems / AutomapSystem.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
5 using System.IO;
6 using System.Linq;
7 using System.Text;
8 using System.Text.RegularExpressions;
9 using System.Threading;
10
11 using Hjg.Pngcs;
12
13 using ProtoBuf;
14
15 using Vintagestory.API.Client;
16 using Vintagestory.API.Common;
17 using Vintagestory.API.Config;
18 using Vintagestory.API.Datastructures;
19 using Vintagestory.API.MathTools;
20 using Vintagestory.Common;
21
22 namespace Automap
23 {
24         public class AutomapSystem
25         {
26                 private Thread cartographer_thread;
27
28                 private Snapshotter snapshot;
29                 private ICoreClientAPI ClientAPI { get; set; }
30                 private ILogger Logger { get; set; }
31                 private AChunkRenderer ChunkRenderer { get; set; }
32                 private JsonGenerator JsonGenerator { get; set; }
33
34                 internal const string _mapPath = @"Maps";
35                 internal const string _chunkPath = @"Chunks";
36                 internal const uint editThreshold = 9;
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 const string plainMetadataFileName = @"map_metadata.txt";
43                 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
44
45                 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
46                 private ColumnsMetadata chunkTopMetadata;
47                 internal PointsOfInterest POIs = new PointsOfInterest();
48                 internal EntitiesOfInterest EOIs = new EntitiesOfInterest();
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                 internal Dictionary<int, string> AiryIdCodes { get; private set; }
54
55                 internal CommandType CurrentState { get; set; }
56                 //Run status, Chunks processed, stats, center of map....
57                 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
58                 private Vec2i startChunkColumn;
59
60                 private readonly int chunkSize;
61                 private string path;
62                 private IAsset staticMap;
63                 private PersistedConfiguration configuration;
64
65
66                 public static string AutomapStatusEventKey = @"AutomapStatus";
67                 public static string AutomapCommandEventKey = @"AutomapCommand";
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
75                         configuration = config;
76                         ClientAPI.Event.LevelFinalize += EngageAutomap;
77
78                         this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
79
80                         //Listen on bus for commands
81                         ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
82
83
84                         if (configuration.Autostart)
85                         {
86                                 CurrentState = CommandType.Run;
87                                 Logger.Notification("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                         ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
99                                                   
100                         JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
101
102                         string mapFilename = Path.Combine(path, "automap.html");
103                         StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
104
105                         staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
106                         outputText.Write(staticMap.ToText());
107                         outputText.Flush();
108
109                         Prefill_POI_Designators();
110                         startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
111                         chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
112                         Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
113                         Reload_Metadata();
114
115                         ClientAPI.Event.ChunkDirty += ChunkAChanging;
116
117                         cartographer_thread = new Thread(Cartographer)
118                         {
119                                 Name = "Cartographer",
120                                 Priority = ThreadPriority.Lowest,
121                                 IsBackground = true
122                         };
123
124                         ClientAPI.Event.RegisterGameTickListener(ThreadDecider, 6000);
125                 }
126
127                 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
128                 {
129                 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);              
130                 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
131                 
132                 columnCounters.AddOrUpdate(topPosition, 
133                                               new ColumnCounter(chunkSize, newOrEdit, chunkCoord), 
134                                               (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
135                                              );
136                 
137                 }
138
139                 /// <summary>
140                 /// Cartographer Thread 'decider'
141                 /// </summary>
142                 /// <param name="delayed">called delay offset</param>
143                 private void ThreadDecider(float delayed)
144                 {
145
146                         if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
147                         {
148                                 #if DEBUG
149                                 Logger.VerboseDebug("ThreadDecider re-trigger from [{0}]", cartographer_thread.ThreadState);
150                                 #endif
151
152                                 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
153                                 {
154                                         cartographer_thread.Start();
155                                 }
156                                 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
157                                 {
158                                         //Time to (re)write chunk shards
159                                         cartographer_thread.Interrupt();
160                                 }
161                                 //#if DEBUG
162                                 //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})");
163                                 //#endif
164                         }
165                         else if (CurrentState == CommandType.Snapshot)
166                         {
167                         //Prepare for taking a snopshot
168                         if (snapshot == null) {         
169                                 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize, ClientAPI.World.Seed);
170                                 #if DEBUG
171                                 Logger.VerboseDebug("Starting new Snapshot: {0} Wx{1} Hx{2}", snapshot.fileName, snapshot.Width, snapshot.Height);
172                                 #endif
173                                 snapshot.Take( );
174                                 }
175                         else if (snapshot != null && snapshot.Finished) {
176                                 #if DEBUG
177                                         Logger.VerboseDebug("COMPLETED Snapshot: {0} Wx{1} Hx{2}, taking {3}", snapshot.fileName, snapshot.Width, snapshot.Height, snapshot.Timer.Elapsed);
178                                 #endif
179                                 snapshot = null;
180                                 CurrentState = CommandType.Run;
181                                 }
182                         }
183                 }
184
185
186                 private void Cartographer()
187                 {
188                         wake:
189                         Logger.VerboseDebug("Cartographer thread awoken");
190
191                         try
192                         {
193                                 ColumnCounter ejectedItem ;
194                                 uint updatedChunks = 0;
195                                 uint updatedPixels = 0;
196
197                                 //-- Should dodge enumerator changing underfoot....at a cost.
198                                 if (!columnCounters.IsEmpty)
199                                 {
200                                         var tempSet = columnCounters.ToArray().Where(cks => cks.Value.WeightedSum > editThreshold) .OrderByDescending(kvp => kvp.Value.WeightedSum);
201                                         UpdateEntityMetadata();
202
203                                         foreach (var mostActiveCol in tempSet)
204                                         {
205                                                 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
206
207                                                 if (mapChunk == null)
208                                                 {
209                                                         //TODO: REVISIT THIS CHUNK!
210                                                         #if DEBUG
211                                                         Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
212                                                         #endif
213                                                         nullMapCount++;
214                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
215                                                         continue;
216                                                 }
217
218                                                 ColumnMeta chunkMeta;
219                                                 if (chunkTopMetadata.Contains(mostActiveCol.Key))
220                                                 {
221                                                         chunkMeta = chunkTopMetadata[mostActiveCol.Key];
222                                                         #if DEBUG
223                                                         Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
224                                                         #endif
225                                                 }
226                                                 else
227                                                 {
228                                                         chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
229                                                         #if DEBUG
230                                                         Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
231                                                         #endif
232                                                 }
233                                                 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
234                                                 mostActiveCol.Value.SetCutoff(chunkMeta.YMax / chunkSize);
235
236                                                 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
237                                                 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
238
239                                                 if (updatedPixels > 0)
240                                                 {
241                                                         #if DEBUG
242                                                         Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
243                                                         #endif
244                                                         updatedChunks++;
245                                                         chunkTopMetadata.Update(chunkMeta);
246                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
247                                                 }
248                                                 else
249                                                 {
250                                                         columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
251                                                         #if DEBUG
252                                                         Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
253                                                         #endif
254                                                 }
255                                         }
256                                 }
257
258                                 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
259
260                                 if (updatedChunks > 0)
261                                 {
262                                         //What about chunk updates themselves; a update bitmap isn't kept...
263                                         updatedChunksTotal += updatedChunks;
264                                         JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
265                                         updatedChunks = 0;
266
267                                         //Cleanup in-memory Metadata...
268                                         chunkTopMetadata.ClearMetadata( );
269                                 }
270
271                                 #if DEBUG
272                                 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
273                                 #endif
274
275                                 columnCounters.Clear( );
276
277                                 //Then sleep until interupted again, and repeat
278 #if DEBUG
279                                 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
280 #endif
281                                 Thread.Sleep(Timeout.Infinite);
282
283                         }
284                         catch (ThreadInterruptedException)
285                         {
286
287 #if DEBUG
288                                 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
289 #endif
290                                 goto wake;
291
292                         }
293                         catch (ThreadAbortException)
294                         {
295 #if DEBUG
296                                 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
297 #endif
298                         }
299                         finally
300                         {
301 #if DEBUG
302                                 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
303 #endif
304                                 PersistPointsData();
305                                 Write_PlainMetadata( );
306                         }
307                 }
308
309                 private void Snap()
310                 {
311                         snapshotTake:
312 #if DEBUG
313                         Logger.VerboseDebug("Snapshot started");
314 #endif
315                         try
316                         {
317                                 snapshot.Take();
318 #if DEBUG
319                                 Logger.VerboseDebug("Snapshot sleeping");
320 #endif
321                                 CurrentState = CommandType.Run;
322                                 Thread.Sleep(Timeout.Infinite);
323                         }
324                         catch (ThreadInterruptedException)
325                         {
326 #if DEBUG
327                                 Logger.VerboseDebug("Snapshot intertupted");
328 #endif
329                                 goto snapshotTake;
330                         }
331                 }
332
333                 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
334                 {
335                         StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
336
337                         this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
338                 }
339
340                 private void Prefill_POI_Designators()
341                 {
342
343                         this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
344                         this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
345                         this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
346
347                         var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
348                                                          where airyBlock.MatterState == EnumMatterState.Solid
349                                                          where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
350                                                          where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 ||airyBlock.RainPermeable == true                                                        
351                                                          select airyBlock;                      
352                         //^^ 'Solid' phase - 'Plant' Blocks without any boundg box ? Except water...
353                         this.AiryIdCodes = airBlocksQuery.ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
354
355                         //Add special marker types for BlockID's of "Interest", overwrite colour, and method
356                         Reload_POI_Designators();
357                 }
358
359                 private void Reload_POI_Designators()
360                 {
361                 uint poisSetup =0, eoiSetup = 0;
362                         foreach (var designator in configuration.BlockDesignators)
363                         {
364                                 if (designator.Enabled == false) continue;
365                                 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
366                                 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
367                                 foreach (var entry in blockIDs)
368                                 {
369                                         BlockID_Designators.Add(entry.Key, designator);
370                                         poisSetup++;
371                                 }
372                         }
373                         this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
374                         Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
375
376
377                         foreach (var designator in configuration.EntityDesignators)
378                         {
379                                 if (designator.Enabled == false) continue;
380                                 //Get Variants first, from EntityTypes...better be populated!
381                                 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
382
383                                 foreach (var match in matched)
384                                 {                                       
385                                         Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
386                                         this.Entity_Designators.Add(match.Code, designator);
387                                         eoiSetup++;
388                                 }
389                         }
390                         Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
391
392                 }
393
394
395
396                 /// <summary>
397                 /// Store Points/Entity of Interest
398                 /// </summary>
399                 private void PersistPointsData()
400                 {
401                         //POI and EOI raw dump files ~ WRITE em!
402                         //var poiRawFile = File.
403                         string poiPath = Path.Combine(path, poiFileName);
404                         string eoiPath = Path.Combine(path, eoiFileName);
405
406                         if (this.POIs.Count > 0)
407                         {
408                                 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
409                                 {
410                                         Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
411                                         poiFile.Flush(true);
412                                 }
413                         }
414
415                         if (this.EOIs.Count > 0)
416                         {
417                                 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
418                                 {
419                                         Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
420                                         eoiFile.Flush(true);
421                                 }
422                         }
423
424                         //Create Easy to Parse TSV file for tool/human use....
425                         string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
426
427                         using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
428                         {
429                                 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
430                                 foreach (var point in this.POIs)
431                                 {
432                                         tsvWriter.Write(point.Name + "\t");
433                                         var notes = point.Notes
434                                                 .Replace('\n', '\x001f')
435                                                 .Replace("\t", "\\t")
436                                                 .Replace("\\", "\\\\");
437                                         tsvWriter.Write(notes + "\t");
438                                         tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
439                                         tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
440                                         tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
441                                         tsvWriter.Write("null\t");
442                                         tsvWriter.WriteLine();
443                                 }
444                                 foreach (var entity in this.EOIs)
445                                 {
446                                         tsvWriter.Write(entity.Name + "\t");
447                                         var notes = entity.Notes
448                                                 .Replace('\n', '\x001f')
449                                                 .Replace("\t", "\\t")
450                                                 .Replace("\\", "\\\\");
451                                         tsvWriter.Write(notes + "\t");
452                                         tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
453                                         tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
454                                         tsvWriter.Write("---\t");
455                                         tsvWriter.Write(entity.EntityId.ToString("D"));
456                                         tsvWriter.WriteLine();
457                                 }
458                                 tsvWriter.WriteLine();
459                                 tsvWriter.Flush();
460                         }
461
462                 }
463
464                 private void Write_PlainMetadata( )
465                 { 
466                 string metaPath = Path.Combine(path, plainMetadataFileName);
467
468                 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
469                 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII)) 
470                         {
471                                 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
472                                 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
473                                 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
474                                 //mdWriter.WriteLine("CurrentPlayerSpawn", ClientAPI.World.Player.WorldData.EntityPlayer.);
475                                 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
476                                 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
477                                 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
478                                 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
479                                 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
480                                 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
481                                 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
482                                 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
483                                 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
484                                 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);        
485                                 mdWriter.Flush( );
486                         }
487                 }
488                 }
489                         
490
491                 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
492                 {
493                         ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
494                         BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
495                                                                                         mapChunk.YMax,
496                                                                                         mostActiveCol.Key.Y * chunkSize);
497
498                         var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
499                         data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
500
501                         return data;
502                 }
503
504                 /// <summary>
505                 /// Reload chunk bounds from chunk shards
506                 /// </summary>
507                 /// <returns>The metadata.</returns>
508                 private void Reload_Metadata()
509                 {
510                         var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
511
512                         if (!shardsDir.Exists)
513                         {
514                                 #if DEBUG
515                                 Logger.VerboseDebug("Could not open world map (shards) directory");
516                                 #endif
517                                 return;
518                         }
519                         var shardFiles = shardsDir.GetFiles(chunkFile_filter);
520
521                         if (shardFiles.Length > 0)
522                         {
523                                 #if DEBUG
524                                 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
525                                 #endif
526
527                                 foreach (var shardFile in shardFiles)
528                                 {
529
530                                         if (shardFile.Length < 1024) continue;
531                                         var result = chunkShardRegex.Match(shardFile.Name);
532                                         if (!result.Success) continue;
533
534                                         int X_chunk_pos = int.Parse(result.Groups["X"].Value);
535                                         int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
536
537                                         try
538                                         {
539                                                 using (var fileStream = shardFile.OpenRead())
540                                                 {
541
542                                                         PngReader pngRead = new PngReader(fileStream);
543                                                         pngRead.ReadSkippingAllRows();
544                                                         pngRead.End();
545                                                         //Parse PNG chunks for METADATA in shard
546                                                         PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
547                                                         var column = metadataFromPng.ChunkMetadata;
548                                                         if (column.PrettyLocation == null)
549                                                                 column = column.Reload(ClientAPI);
550                                                         chunkTopMetadata.Add(column);
551                                                 }
552
553                                         }
554                                         catch (PngjException someEx)
555                                         {
556                                                 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
557                                                 continue;
558                                         }
559                                         catch (ProtoException protoEx) 
560                                         {
561                                                 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
562                                                 continue;
563                                         }
564                                 }
565                         }
566
567                         //POI and EOI raw dump files ~ reload em!
568                         //var poiRawFile = File.
569                         string poiPath = Path.Combine(path, poiFileName);
570                         string eoiPath = Path.Combine(path, eoiFileName);
571
572                         if (File.Exists(poiPath))
573                         {
574                                 using (var poiFile = File.OpenRead(poiPath))
575                                 {
576                                         this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
577                                         Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
578                                 }
579                         }
580
581                         if (File.Exists(eoiPath))
582                         {
583                                 using (var eoiFile = File.OpenRead(eoiPath))
584                                 {
585                                         this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
586                                         Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
587                                 }
588                         }
589
590                 }
591
592
593
594                 /// <summary>
595                 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
596                 /// </summary>
597                 /// <param name="key">Chunk Coordinate</param>
598                 /// <param name="mapChunk">Map chunk.</param>
599                 /// <param name="chunkMeta">Chunk metadata</param>
600                 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
601                 {
602                         int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish... 
603                         byte chunkTally = 0;
604
605                 #if DEBUG
606                 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
607                 #endif
608
609                 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
610
611                 for (; targetChunkY > 0; targetChunkY--)
612                         {
613                                 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
614
615                                 if (worldChunk == null || worldChunk.BlockEntities == null)
616                                 {
617                                         #if DEBUG
618                                         Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
619                                         #endif
620                                         nullChunkCount++;
621                                         continue;
622                                 }
623
624                                 if (worldChunk.IsPacked()) 
625                                 {
626                                 #if DEBUG
627                                 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
628                                 #endif
629                                 worldChunk.Unpack( );//RESEARCH: Thread Unsafe? 
630                                 }
631
632                                 /*************** Chunk Entities Scanning *********************/
633                                 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
634                                 {
635                                         #if DEBUG
636                                         Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
637                                         #endif
638
639                                         foreach (var blockEnt in worldChunk.BlockEntities)
640                                         {
641                                                 if (blockEnt.Key != null && blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
642                                                 {
643                                                         var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
644                                                         designator?.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
645                                                 }
646                                         }
647                                 }
648
649                                 /********************* Chunk/Column BLOCKs scanning ****************/
650                                 //Heightmap, Stats, block tally
651
652                                 int X_index, Y_index, Z_index;
653
654                                 //First Chance fail-safe;
655                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
656                                 #if DEBUG
657                                 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
658                                 #endif
659                                 nullChunkCount++;
660                                 continue;
661                                 }               
662
663                                 chunkMeta.ColumnPresense[targetChunkY] = true;
664                                 chunkTally++;
665                                 for (Y_index = 0; Y_index < chunkSize; Y_index++)
666                                 {
667                                         for (Z_index = 0; Z_index < chunkSize; Z_index++)
668                                         {
669                                                 for (X_index = 0; X_index < chunkSize; X_index++) 
670                                                 {
671                                                 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
672
673                                                 //'Last' Chance fail-safe;
674                                                 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
675                                                 #if DEBUG
676                                                 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
677                                                 #endif
678                                                 nullChunkCount++;
679                                                 goto loop_bustout; 
680                                                 }
681
682                                                 int aBlockId = worldChunk.Blocks[indicie];
683
684                                                 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
685                                                 chunkMeta.AirBlocks++;
686                                                 continue;
687                                                 }
688
689                                                 if (RockIdCodes.ContainsKey(aBlockId)) {
690                                                 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
691                                                         chunkMeta.RockRatio[aBlockId]++;
692                                                 else
693                                                         chunkMeta.RockRatio.Add(aBlockId, 1);
694                                                 }
695
696                                                 chunkMeta.NonAirBlocks++;
697
698                                                 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
699                                                 //Heightmap - Need to ignore Grass & Snow
700                                                 if (localHeight > chunkMeta.HeightMap[X_index, Z_index]) 
701                                                         {
702                                                         chunkMeta.HeightMap[X_index, Z_index] = localHeight;
703                                                         if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
704                                                         }
705                                                 }
706                                         }
707                                 }
708                                 loop_bustout:;
709                         }
710                         #if DEBUG
711                         Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
712                         #endif
713                 }
714
715                 private void UpdateEntityMetadata()
716                 {
717                         #if DEBUG
718                         Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
719                         #endif
720                         //Mabey scan only for 'new' entities by tracking ID in set?
721                         foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
722                         {
723
724                                 #if DEBUG
725                                 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
726                                 #endif
727
728                                 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
729                                 if (dMatch.Value != null)
730                                 {
731                                         dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.Pos.AsBlockPos.Copy(), loadedEntity.Value);
732                                 }
733
734                         }
735
736
737                 }
738
739                 private void AddNote(string notation)
740                 {
741                         var playerNodePoi = new PointOfInterest()
742                         {
743                                 Name = "Note",
744                                 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
745                                 Notes = notation,
746                                 Timestamp = DateTime.UtcNow,
747                         };
748
749                         this.POIs.AddReplace(playerNodePoi);
750                 }
751
752
753
754                 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
755                 {
756                         //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
757
758                         CommandData cmdData = data as CommandData;
759
760                         switch (cmdData.State)
761                         {
762                                 case CommandType.Run:
763                                 case CommandType.Stop:
764                                 case CommandType.Snapshot:
765                                         if (CurrentState != cmdData.State)
766                                         {
767                                                 CurrentState = cmdData.State;
768                                                 ThreadDecider(0.0f);
769                                         }
770                                         break;
771
772                                 case CommandType.Notation:
773                                         //Add to POI list where player location
774                                         AddNote(cmdData.Notation);
775                                         break;
776                         }
777
778                         ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
779
780                 }
781 #endregion
782
783                 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
784                 {
785                 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
786                 switch (rendererName) 
787                 {                               
788                 case StandardRenderer.Name:
789                         return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
790                 
791                 case AlternateRenderer.Name:
792                         return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
793         
794                 case FlatRenderer.Name:
795                         return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);  
796
797                 default:
798                         throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");
799                 }
800
801                 return null;
802                 }
803         }
804
805 }