OSDN Git Service

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