OSDN Git Service

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