2 using System.Collections.Concurrent;
3 using System.Collections.Generic;
7 using System.Text.RegularExpressions;
8 using System.Threading;
11 using Hjg.Pngcs.Chunks;
13 using Newtonsoft.Json;
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;
24 public class AutomapSystem
26 private Thread cartographer_thread;
27 private ICoreClientAPI ClientAPI { get; set; }
28 private ILogger Logger { get; set; }
29 private IChunkRenderer ChunkRenderer { get; set; }
31 private const string _mapPath = @"Maps";
32 private const string _chunkPath = @"Chunks";
33 private const string _domain = @"automap";
34 private const string chunkFile_filter = @"*_*.png";
35 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+).png", RegexOptions.Singleline);
37 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
38 private ColumnsMetadata chunkTopMetadata;
39 private PointsOfInterest POIs = new PointsOfInterest();
40 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
42 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
43 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
44 internal Dictionary<int, string> RockIdCodes { get; private set; }
46 internal CommandType CurrentState { get; set; }
47 //Run status, Chunks processed, stats, center of map....
48 private uint nullChunkCount, updatedChunksTotal;
49 private Vec2i startChunkColumn;
51 private readonly int chunkSize;
53 private IAsset staticMap;
54 private PersistedConfiguration configuration;
57 public static string AutomapStatusEventKey = @"AutomapStatus";
58 public static string AutomapCommandEventKey = @"AutomapCommand";
59 PersistedConfiguration cachedConfiguration;
61 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
63 this.ClientAPI = clientAPI;
65 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
66 ClientAPI.Event.LevelFinalize += EngageAutomap;
67 configuration = config;
71 //TODO:Choose which one from GUI
72 this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
74 //Listen on bus for commands
75 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
77 if (configuration.Autostart)
79 CurrentState = CommandType.Run;
80 Logger.Debug("Autostart is Enabled.");
87 private void EngageAutomap()
89 path = ClientAPI.GetOrCreateDataPath(_mapPath);
90 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
93 string mapFilename = Path.Combine(path, "automap.html");
94 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
96 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
97 outputText.Write(staticMap.ToText());
100 Prefill_POI_Designators();
101 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
102 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
104 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
107 ClientAPI.Event.ChunkDirty += ChunkAChanging;
109 cartographer_thread = new Thread(Cartographer)
111 Name = "Cartographer",
112 Priority = ThreadPriority.Lowest,
116 ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
119 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
121 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
123 columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
126 private void AwakenCartographer(float delayed)
129 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
132 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
135 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
137 cartographer_thread.Start();
139 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
141 //Time to (re)write chunk shards
142 cartographer_thread.Interrupt();
145 //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})");
148 else if (CurrentState == CommandType.Snapshot)
150 //TODO: Snapshot generator second thread...
156 private void Cartographer()
159 Logger.VerboseDebug("Cartographer thread awoken");
163 uint ejectedItem = 0;
164 uint updatedChunks = 0;
165 uint updatedPixels = 0;
167 //-- Should dodge enumerator changing underfoot....at a cost.
168 if (!columnCounter.IsEmpty)
170 var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
171 UpdateEntityMetadata( );
173 foreach (var mostActiveCol in tempSet)
175 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
177 if (mapChunk == null)
179 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
181 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
185 ColumnMeta chunkMeta;
186 if (chunkTopMetadata.Contains(mostActiveCol.Key))
188 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
192 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
195 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
197 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
198 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
200 if (updatedPixels > 0)
204 Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
207 chunkTopMetadata.Update(chunkMeta);
208 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
212 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
213 Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
219 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
221 if (updatedChunks > 0)
223 //What about chunk updates themselves; a update bitmap isn't kept...
224 updatedChunksTotal += updatedChunks;
225 GenerateJSONMetadata();
229 //Then sleep until interupted again, and repeat
231 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
233 Thread.Sleep(Timeout.Infinite);
236 catch (ThreadInterruptedException)
239 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
243 catch (ThreadAbortException)
245 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
250 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
254 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
256 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
258 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
261 private void Prefill_POI_Designators()
264 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
265 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
266 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
268 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
270 Reload_POI_Designators();
273 private void Reload_POI_Designators()
275 Logger.VerboseDebug("Connecting {0} Configured Block-Designators", configuration.BlockDesignators.Count);
276 foreach (var designator in configuration.BlockDesignators)
278 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
279 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
280 foreach (var entry in blockIDs)
282 BlockID_Designators.Add(entry.Key, designator);
285 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
288 Logger.VerboseDebug("Connecting {0} Configured Entity-Designators", configuration.EntityDesignators.Count);
289 foreach (var designator in configuration.EntityDesignators)
291 //Get Variants first, from EntityTypes...better be populated!
292 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
294 foreach (var match in matched)
296 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
297 this.Entity_Designators.Add(match.Code, designator);
302 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
308 //TODO: Rewrite as Newtonsoft JsonTextWriter !!!
310 /// Generates the JSON Metadata. (in Map object format )
312 private void GenerateJSONMetadata()
314 string jsonFilename = Path.Combine(path, "Metadata.js");
316 StreamWriter stream = new StreamWriter(jsonFilename, false, Encoding.UTF8);
319 JsonTextWriter jsonWriter = new JsonTextWriter(stream);
321 jsonWriter.Formatting = Formatting.None;
322 jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
323 jsonWriter.Indentation = 0;
324 //jsonWriter.AutoCompleteOnClose = true;
325 jsonWriter.QuoteChar = '\'';
326 jsonWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;
327 jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
331 jsonWriter.WriteRaw("ViewFrame.chunks={};\n");
332 jsonWriter.WriteRaw("ViewFrame.chunks.worldSeedNum=" );
333 jsonWriter.WriteValue(ClientAPI.World.Seed);
334 jsonWriter.WriteRaw(";\n");
336 jsonWriter.WriteRaw("ViewFrame.chunks.genTime=");
337 jsonWriter.WriteValue(DateTimeOffset.UtcNow);
338 jsonWriter.WriteRaw(";\n");
340 jsonWriter.WriteRaw("ViewFrame.chunks.startCoords=");
341 jsonWriter.WriteStartArray( );
342 jsonWriter.WriteValue(startChunkColumn.X);
343 jsonWriter.WriteValue(startChunkColumn.Y);
344 jsonWriter.WriteEndArray( );
345 jsonWriter.WriteRaw(";\n");
347 jsonWriter.WriteRaw("ViewFrame.chunks.chunkSize=");
348 jsonWriter.WriteValue(chunkSize);
349 jsonWriter.WriteRaw(";\n");
351 jsonWriter.WriteRaw("ViewFrame.chunks.northMostChunk=");
352 jsonWriter.WriteValue(chunkTopMetadata.North_mostChunk);
353 jsonWriter.WriteRaw(";\n");
355 jsonWriter.WriteRaw("ViewFrame.chunks.southMostChunk=");
356 jsonWriter.WriteValue(chunkTopMetadata.South_mostChunk);
357 jsonWriter.WriteRaw(";\n");
359 jsonWriter.WriteRaw("ViewFrame.chunks.westMostChunk=");
360 jsonWriter.WriteValue(chunkTopMetadata.West_mostChunk);
361 jsonWriter.WriteRaw(";\n");
363 jsonWriter.WriteRaw("ViewFrame.chunks.eastMostChunk=");
364 jsonWriter.WriteValue(chunkTopMetadata.East_mostChunk);
365 jsonWriter.WriteRaw(";\n");
368 //MAP object format - [key, value]: key is "x_y"
369 jsonWriter.WriteRaw("ViewFrame.chunks.chunkMetadata=");
370 jsonWriter.WriteStartConstructor("Map");
371 jsonWriter.WriteStartArray( );//An array of... 2-component arrays
374 foreach (var shard in chunkTopMetadata)
376 jsonWriter.WriteStartArray( );//Start tuple
377 jsonWriter.WriteValue($"{shard.Location.X}_{shard.Location.Y}");//Key of Tuple
379 jsonWriter.WriteStartObject( );
380 jsonWriter.WritePropertyName("prettyCoord");
381 jsonWriter.WriteValue( shard.Location.PrettyCoords(ClientAPI));
383 jsonWriter.WritePropertyName("chunkAge");
384 jsonWriter.WriteValue(shard.ChunkAge);
386 jsonWriter.WritePropertyName("temp");
387 jsonWriter.WriteValue(shard.Temperature);
389 jsonWriter.WritePropertyName("YMax");
390 jsonWriter.WriteValue(shard.YMax);
392 jsonWriter.WritePropertyName("fert");
393 jsonWriter.WriteValue(shard.Fertility);
395 jsonWriter.WritePropertyName("forestDens");
396 jsonWriter.WriteValue( shard.ForestDensity);
398 jsonWriter.WritePropertyName("rain");
399 jsonWriter.WriteValue( shard.Rainfall);
401 jsonWriter.WritePropertyName("shrubDens");
402 jsonWriter.WriteValue( shard.ShrubDensity);
404 jsonWriter.WritePropertyName("airBlocks");
405 jsonWriter.WriteValue( shard.AirBlocks);
407 jsonWriter.WritePropertyName("nonAirBlocks");
408 jsonWriter.WriteValue( shard.NonAirBlocks);
411 //Start rockMap ; FOR a Ratio....on tooltip GUI
412 jsonWriter.WritePropertyName("rockRatio");
413 jsonWriter.WriteStartConstructor("Map");
414 jsonWriter.WriteStartArray( );
415 foreach (var rockEntry in shard.RockRatio) {
416 var rockBlock = ClientAPI.World.GetBlock(rockEntry.Key);
417 jsonWriter.WriteStartArray( );
418 jsonWriter.WriteValue(rockBlock.Code.Path);
419 jsonWriter.WriteValue(rockEntry.Value);//Total per chunk-column
420 jsonWriter.WriteEndArray( );
422 jsonWriter.WriteEndArray( );
423 jsonWriter.WriteEndConstructor( );//end rock-map
425 jsonWriter.WriteEndObject( );//end Map value: {Object}
426 jsonWriter.WriteEndArray( );//end Tuple
429 jsonWriter.WriteEndArray( );//Enclose tuples of chunkMetadata
430 jsonWriter.WriteEndConstructor( );//Close constructor of Map (chunkMetadata)
431 jsonWriter.WriteRaw(";\n");
433 jsonWriter.WriteRaw("ViewFrame.chunks.pointsOfInterest=");
434 jsonWriter.WriteStartConstructor("Map");
435 jsonWriter.WriteStartArray( );//An array of... 2-component arrays
437 foreach (var poi in POIs)
439 jsonWriter.WriteStartArray( );
440 jsonWriter.WriteValue($"{poi.Location.X}_{poi.Location.Z}");
442 jsonWriter.WriteStartObject();
443 jsonWriter.WritePropertyName("prettyCoord");
444 jsonWriter.WriteValue(poi.Location.PrettyCoords(ClientAPI) );
446 jsonWriter.WritePropertyName("notes");
447 jsonWriter.WriteValue(poi.Notes);//Encoded to HTML Entities
449 jsonWriter.WritePropertyName("time");
450 jsonWriter.WriteValue(poi.Timestamp);
452 jsonWriter.WritePropertyName("chunkPos");
453 jsonWriter.WriteValue($"{(poi.Location.X / chunkSize)}_{(poi.Location.Z / chunkSize)}");
455 jsonWriter.WriteEndObject( );
456 jsonWriter.WriteEndArray( );
458 jsonWriter.Write("]);");
460 jsonWriter.Write("ViewFrame.chunks.entitiesOfInterest=new Map([");
461 foreach (var eoi in EOIs)
463 jsonWriter.WriteStartArray( );
464 jsonWriter.WriteValue($"{poi.Location.X}_{poi.Location.Z}");
466 jsonWriter.WriteStartObject( );
467 jsonWriter.WritePropertyName("prettyCoord");
468 jsonWriter.WriteValue(poi.Location.PrettyCoords(ClientAPI));
470 jsonWriter.WritePropertyName("notes");
471 jsonWriter.WriteValue(poi.Notes);//Encoded to HTML Entities
473 jsonWriter.WritePropertyName("time");
474 jsonWriter.WriteValue(poi.Timestamp);
476 jsonWriter.WritePropertyName("chunkPos");
477 jsonWriter.WriteValue($"{(poi.Location.X / chunkSize)}_{(poi.Location.Z / chunkSize)}");
479 jsonWriter.WriteEndObject( );
480 jsonWriter.WriteEndArray( );
483 jsonWriter.WriteEndArray( );
484 jsonWriter.WriteEndConstructor( );
485 jsonWriter.WriteRaw(";\n");
487 jsonWriter.WriteWhitespace("\n");
488 jsonWriter.WriteComment("============= BlockID's for Rockmap / Rock-ratios ===============");
489 jsonWriter.WriteWhitespace("\n");
491 jsonWriter.WriteRaw("ViewFrame.chunks.rock_Lookup =");
492 jsonWriter.WriteStartConstructor("Map");
493 jsonWriter.WriteStartArray( );//An array of... 2-component arrays
495 foreach (var entry in RockIdCodes) {
496 var block = ClientAPI.World.GetBlock(entry.Key);
498 jsonWriter.WriteStartArray( );
499 jsonWriter.WriteValue(block.Code.Path);
501 jsonWriter.WriteStartObject( );
502 jsonWriter.WritePropertyName("assetCode");
503 jsonWriter.WriteValue(entry.Value);
505 jsonWriter.WritePropertyName("name");
506 jsonWriter.WriteValue(Lang.GetUnformatted(block.Code.Path));
509 jsonWriter.WriteEndObject( );
510 jsonWriter.WriteEndArray( );
512 jsonWriter.WriteEndArray( );
513 jsonWriter.WriteEndConstructor();
515 jsonWriter.WriteRaw(";\n");
524 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
526 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), (byte) chunkSize);
527 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
529 mostActiveCol.Key.Y * chunkSize);
531 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
532 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
538 /// Reload chunk bounds from chunk shards
540 /// <returns>The metadata.</returns>
541 private void Reload_Metadata()
543 var worldmapDir = new DirectoryInfo(path);
545 if (worldmapDir.Exists)
548 var files = worldmapDir.GetFiles(chunkFile_filter);
550 if (files.Length > 0)
553 Logger.VerboseDebug("{0} Existing world chunk shards", files.Length);
556 foreach (var shardFile in files)
559 if (shardFile.Length < 1024) continue;
560 var result = chunkShardRegex.Match(shardFile.Name);
563 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
564 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
568 using (var fileStream = shardFile.OpenRead())
571 PngReader pngRead = new PngReader(fileStream);
572 pngRead.ReadSkippingAllRows();
574 //Parse PNG chunks for METADATA in shard
575 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
577 chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
581 catch (PngjException someEx)
583 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
596 Logger.VerboseDebug("Could not open world map directory");
604 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
606 ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
608 string filename = $"{coord.X}_{coord.Y}.png";
609 filename = Path.Combine(path, filename);
611 PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
612 PngMetadata meta = pngWriter.GetMetadata();
614 meta.SetText("Chunk_X", coord.X.ToString("D"));
615 meta.SetText("Chunk_Y", coord.Y.ToString("D"));
616 //Setup specialized meta-data PNG chunks here...
617 PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
619 ChunkMetadata = metadata
621 pngWriter.GetChunksList().Queue(pngChunkMeta);
622 pngWriter.CompLevel = 9;// 9 is the maximum compression
623 pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
629 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
631 /// <param name="key">Chunk Coordinate</param>
632 /// <param name="mapChunk">Map chunk.</param>
633 /// <param name="chunkMeta">Chunk metadata</param>
634 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
637 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ...
638 for (; targetChunkY > 0; targetChunkY--)
640 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
641 if (chunkData == null || chunkData.BlockEntities == null)
644 Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
649 /*************** Chunk Entities Scanning *********************/
650 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
653 Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
656 foreach (var blockEnt in chunkData.BlockEntities)
659 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
661 var designator = BlockID_Designators[blockEnt.Block.BlockId];
662 designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
667 /********************* Chunk/Column BLOCKs scanning ****************/
668 //Heightmap, Stats, block tally
671 int X_index, Y_index, Z_index;
672 X_index = Y_index = Z_index = 0;
680 /* Encode packed indicie
681 (y * chunksize + z) * chunksize + x
683 var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
684 int aBlockId = chunkData.Blocks[indicie];
688 chunkMeta.AirBlocks++;
692 if (RockIdCodes.ContainsKey(aBlockId))
694 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
697 chunkMeta.NonAirBlocks++;
700 //if (chunkMeta.HeightMap[X_index, Z_index] == 0)
702 // chunkMeta.HeightMap[X_index, Z_index]
703 // = (ushort) (Y_index + (targetChunkY * chunkSize));
706 while (X_index++ < (chunkSize - 1));
709 while (Z_index++ < (chunkSize - 1));
712 while (Y_index++ < (chunkSize - 1));
717 private void UpdateEntityMetadata()
719 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
720 //Mabey scan only for 'new' entities by tracking ID in set?
721 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToArray())
725 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
728 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
729 if (dMatch.Value != null)
731 Logger.Chat("Entity designator hit!");
732 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
740 private void AddNote(string notation)
742 var playerNodePoi = new PointOfInterest()
744 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
746 Timestamp = DateTimeOffset.UtcNow,
749 this.POIs.AddReplace(playerNodePoi);
754 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
756 Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
758 CommandData cmdData = data as CommandData;
761 if (CurrentState != CommandType.Snapshot)
763 switch (cmdData.State)
765 case CommandType.Run:
766 CurrentState = cmdData.State;
767 AwakenCartographer(0.0f);
770 case CommandType.Stop:
771 CurrentState = cmdData.State;
774 case CommandType.Snapshot:
775 CurrentState = CommandType.Stop;
776 //Snapshot starts a second thread/process...
780 case CommandType.Notation:
781 //Add to POI list where player location
782 AddNote(cmdData.Notation);
788 if (CurrentState != cmdData.State)
790 CurrentState = cmdData.State;
791 AwakenCartographer(0.0f);
795 Logger.VerboseDebug($"Automap commanded to: {cmdData.State} ");