2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
8 using System.Text.RegularExpressions;
9 using System.Threading;
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;
28 private Snapshotter snapshot;
29 private ICoreClientAPI ClientAPI { get; set; }
30 private ILogger Logger { get; set; }
31 private AChunkRenderer ChunkRenderer { get; set; }
32 private JsonGenerator JsonGenerator { get; set; }
34 internal const string _mapPath = @"Maps";
35 internal const string _chunkPath = @"Chunks";
36 internal const uint editThreshold = 9;
37 private const string _domain = @"automap";
38 private const string chunkFile_filter = @"*_*.png";
39 private const string poiFileName = @"poi_binary";
40 private const string eoiFileName = @"eoi_binary";
41 private const string pointsTsvFileName = @"points_of_interest.tsv";
42 private const string plainMetadataFileName = @"map_metadata.txt";
43 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
45 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
46 private ColumnsMetadata chunkTopMetadata;
47 internal PointsOfInterest POIs = new PointsOfInterest();
48 internal EntitiesOfInterest EOIs = new EntitiesOfInterest();
50 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
51 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
52 internal Dictionary<int, string> RockIdCodes { get; private set; }
53 internal Dictionary<int, string> AiryIdCodes { get; private set; }
55 internal CommandType CurrentState { get; set; }
56 //Run status, Chunks processed, stats, center of map....
57 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
58 private Vec2i startChunkColumn;
60 private readonly int chunkSize;
62 private IAsset staticMap;
63 private PersistedConfiguration configuration;
66 public static string AutomapStatusEventKey = @"AutomapStatus";
67 public static string AutomapCommandEventKey = @"AutomapCommand";
69 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
71 this.ClientAPI = clientAPI;
73 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
75 configuration = config;
76 ClientAPI.Event.LevelFinalize += EngageAutomap;
78 this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
80 //Listen on bus for commands
81 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
84 if (configuration.Autostart)
86 CurrentState = CommandType.Run;
87 Logger.Notification("Autostart is Enabled.");
94 private void EngageAutomap()
96 path = ClientAPI.GetOrCreateDataPath(_mapPath);
97 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
98 ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
100 JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
102 string mapFilename = Path.Combine(path, "automap.html");
103 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
105 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
106 outputText.Write(staticMap.ToText());
109 Prefill_POI_Designators();
110 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
111 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
112 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
115 ClientAPI.Event.ChunkDirty += ChunkAChanging;
117 cartographer_thread = new Thread(Cartographer)
119 Name = "Cartographer",
120 Priority = ThreadPriority.Lowest,
124 ClientAPI.Event.RegisterGameTickListener(ThreadDecider, 6000);
127 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
129 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
130 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
132 columnCounters.AddOrUpdate(topPosition,
133 new ColumnCounter(chunkSize, newOrEdit, chunkCoord),
134 (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
140 /// Cartographer Thread 'decider'
142 /// <param name="delayed">called delay offset</param>
143 private void ThreadDecider(float delayed)
146 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
149 Logger.VerboseDebug("ThreadDecider re-trigger from [{0}]", cartographer_thread.ThreadState);
152 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
154 cartographer_thread.Start();
156 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
158 //Time to (re)write chunk shards
159 cartographer_thread.Interrupt();
162 //ClientAPI.TriggerChatMessage($"Automap {updatedChunksTotal} Updates - MAX (N:{chunkTopMetadata.North_mostChunk},S:{chunkTopMetadata.South_mostChunk},E:{chunkTopMetadata.East_mostChunk}, W:{chunkTopMetadata.West_mostChunk} - TOTAL: {chunkTopMetadata.Count})");
165 else if (CurrentState == CommandType.Snapshot)
167 //Prepare for taking a snopshot
168 if (snapshot == null) {
169 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize, ClientAPI.World.Seed);
171 Logger.VerboseDebug("Starting new Snapshot: {0} Wx{1} Hx{2}", snapshot.fileName, snapshot.Width, snapshot.Height);
175 else if (snapshot != null && snapshot.Finished) {
177 Logger.VerboseDebug("COMPLETED Snapshot: {0} Wx{1} Hx{2}, taking {3}", snapshot.fileName, snapshot.Width, snapshot.Height, snapshot.Timer.Elapsed);
180 CurrentState = CommandType.Run;
186 private void Cartographer()
189 Logger.VerboseDebug("Cartographer thread awoken");
193 ColumnCounter ejectedItem ;
194 uint updatedChunks = 0;
195 uint updatedPixels = 0;
197 //-- Should dodge enumerator changing underfoot....at a cost.
198 if (!columnCounters.IsEmpty)
200 var tempSet = columnCounters.ToArray().Where(cks => cks.Value.WeightedSum > editThreshold) .OrderByDescending(kvp => kvp.Value.WeightedSum);
201 UpdateEntityMetadata();
203 foreach (var mostActiveCol in tempSet)
205 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
207 if (mapChunk == null)
209 //TODO: REVISIT THIS CHUNK!
211 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
214 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
218 ColumnMeta chunkMeta;
219 if (chunkTopMetadata.Contains(mostActiveCol.Key))
221 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
223 Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
228 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
230 Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
233 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
234 mostActiveCol.Value.SetCutoff(chunkMeta.YMax / chunkSize);
236 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
237 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
239 if (updatedPixels > 0)
242 Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
245 chunkTopMetadata.Update(chunkMeta);
246 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
250 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
252 Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
258 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
260 if (updatedChunks > 0)
262 //What about chunk updates themselves; a update bitmap isn't kept...
263 updatedChunksTotal += updatedChunks;
264 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
267 //Cleanup in-memory Metadata...
268 chunkTopMetadata.ClearMetadata( );
272 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
275 columnCounters.Clear( );
277 //Then sleep until interupted again, and repeat
279 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
281 Thread.Sleep(Timeout.Infinite);
284 catch (ThreadInterruptedException)
288 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
293 catch (ThreadAbortException)
296 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
302 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
305 Write_PlainMetadata( );
313 Logger.VerboseDebug("Snapshot started");
319 Logger.VerboseDebug("Snapshot sleeping");
321 CurrentState = CommandType.Run;
322 Thread.Sleep(Timeout.Infinite);
324 catch (ThreadInterruptedException)
327 Logger.VerboseDebug("Snapshot intertupted");
333 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
335 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
337 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
340 private void Prefill_POI_Designators()
343 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
344 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
345 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
347 var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
348 where airyBlock.MatterState == EnumMatterState.Solid
349 where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
350 where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 || airyBlock.RainPermeable == true
352 //^^ 'Solid' phase - 'Plant' Blocks without any bounding-box; OR 'Invisible' shapes...
353 var invisibleBlocksQuery = from novisBlock in ClientAPI.World.Blocks
354 where novisBlock.Shape == null || novisBlock.Shape.Base.EndsWith(GlobalConstants.DefaultDomain, @"invisible") //Whaat! [ base: "block/basic/invisible" ]
356 this.AiryIdCodes = airBlocksQuery.Union(invisibleBlocksQuery).ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
359 foreach (var fluffBlock in AiryIdCodes) {
360 Logger.VerboseDebug("ID#\t{0}:\t{1} IGNORED", fluffBlock.Key, fluffBlock.Value);
362 Logger.VerboseDebug("Ignoring {0} blocks", AiryIdCodes.Count);
365 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
366 Reload_POI_Designators();
369 private void Reload_POI_Designators()
371 uint poisSetup =0, eoiSetup = 0;
372 foreach (var designator in configuration.BlockDesignators)
374 if (designator.Enabled == false) continue;
375 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
376 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
377 foreach (var entry in blockIDs)
379 BlockID_Designators.Add(entry.Key, designator);
383 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
384 Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
387 foreach (var designator in configuration.EntityDesignators)
389 if (designator.Enabled == false) continue;
390 //Get Variants first, from EntityTypes...better be populated!
391 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
393 foreach (var match in matched)
395 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
396 this.Entity_Designators.Add(match.Code, designator);
400 Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
407 /// Store Points/Entity of Interest
409 private void PersistPointsData()
411 //POI and EOI raw dump files ~ WRITE em!
412 //var poiRawFile = File.
413 string poiPath = Path.Combine(path, poiFileName);
414 string eoiPath = Path.Combine(path, eoiFileName);
416 if (this.POIs.Count > 0)
418 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
420 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
425 if (this.EOIs.Count > 0)
427 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
429 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
434 //Create Easy to Parse TSV file for tool/human use....
435 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
437 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
439 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
440 foreach (var point in this.POIs)
442 tsvWriter.Write(point.Name + "\t");
443 var notes = point.Notes
444 .Replace('\n', '\x001f')
445 .Replace("\t", "\\t")
446 .Replace("\\", "\\\\");
447 tsvWriter.Write(notes + "\t");
448 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
449 tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
450 tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
451 tsvWriter.Write("null\t");
452 tsvWriter.WriteLine();
454 foreach (var entity in this.EOIs)
456 tsvWriter.Write(entity.Name + "\t");
457 var notes = entity.Notes
458 .Replace('\n', '\x001f')
459 .Replace("\t", "\\t")
460 .Replace("\\", "\\\\");
461 tsvWriter.Write(notes + "\t");
462 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
463 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
464 tsvWriter.Write("---\t");
465 tsvWriter.Write(entity.EntityId.ToString("D"));
466 tsvWriter.WriteLine();
468 tsvWriter.WriteLine();
474 private void Write_PlainMetadata( )
476 string metaPath = Path.Combine(path, plainMetadataFileName);
478 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
479 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII))
481 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
482 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
483 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
484 //mdWriter.WriteLine("CurrentPlayerSpawn", ClientAPI.World.Player.WorldData.EntityPlayer.);
485 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
486 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
487 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
488 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
489 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
490 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
491 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
492 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
493 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
494 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);
501 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
503 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
504 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
506 mostActiveCol.Key.Y * chunkSize);
508 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
509 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
515 /// Reload chunk bounds from chunk shards
517 /// <returns>The metadata.</returns>
518 private void Reload_Metadata()
520 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
522 if (!shardsDir.Exists)
525 Logger.VerboseDebug("Could not open world map (shards) directory");
529 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
531 if (shardFiles.Length > 0)
534 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
537 foreach (var shardFile in shardFiles)
540 if (shardFile.Length < 1024) continue;
541 var result = chunkShardRegex.Match(shardFile.Name);
542 if (!result.Success) continue;
544 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
545 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
549 using (var fileStream = shardFile.OpenRead())
552 PngReader pngRead = new PngReader(fileStream);
553 pngRead.ReadSkippingAllRows();
555 //Parse PNG chunks for METADATA in shard
556 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
557 var column = metadataFromPng.ChunkMetadata;
558 if (column.PrettyLocation == null)
559 column = column.Reload(ClientAPI);
560 chunkTopMetadata.Add(column);
564 catch (PngjException someEx)
566 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
569 catch (ProtoException protoEx)
571 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
577 //POI and EOI raw dump files ~ reload em!
578 //var poiRawFile = File.
579 string poiPath = Path.Combine(path, poiFileName);
580 string eoiPath = Path.Combine(path, eoiFileName);
582 if (File.Exists(poiPath))
584 using (var poiFile = File.OpenRead(poiPath))
586 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
587 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
591 if (File.Exists(eoiPath))
593 using (var eoiFile = File.OpenRead(eoiPath))
595 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
596 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
605 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
607 /// <param name="key">Chunk Coordinate</param>
608 /// <param name="mapChunk">Map chunk.</param>
609 /// <param name="chunkMeta">Chunk metadata</param>
610 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
612 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish...
616 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
619 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
621 for (; targetChunkY > 0; targetChunkY--)
623 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
625 if (worldChunk == null || worldChunk.BlockEntities == null)
628 Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
634 if (worldChunk.IsPacked())
637 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
639 worldChunk.Unpack( );//RESEARCH: Thread Unsafe?
642 /*************** Chunk Entities Scanning *********************/
643 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
646 Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
649 foreach (var blockEnt in worldChunk.BlockEntities)
651 if (blockEnt.Key != null && blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
653 var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
654 designator?.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
659 /********************* Chunk/Column BLOCKs scanning ****************/
660 //Heightmap, Stats, block tally
662 int X_index, Y_index, Z_index;
664 //First Chance fail-safe;
665 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
667 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
673 chunkMeta.ColumnPresense[targetChunkY] = true;
675 for (Y_index = 0; Y_index < chunkSize; Y_index++)
677 for (Z_index = 0; Z_index < chunkSize; Z_index++)
679 for (X_index = 0; X_index < chunkSize; X_index++)
681 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
683 //'Last' Chance fail-safe;
684 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
686 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
692 int aBlockId = worldChunk.Blocks[indicie];
694 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
695 chunkMeta.AirBlocks++;
699 if (RockIdCodes.ContainsKey(aBlockId)) {
700 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
701 chunkMeta.RockRatio[aBlockId]++;
703 chunkMeta.RockRatio.Add(aBlockId, 1);
706 chunkMeta.NonAirBlocks++;
708 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
709 //Heightmap - Need to ignore Grass & Snow
710 if (localHeight > chunkMeta.HeightMap[X_index, Z_index])
712 chunkMeta.HeightMap[X_index, Z_index] = localHeight;
713 if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
721 Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
725 private void UpdateEntityMetadata()
728 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
731 //Handles mutations better than a plain Iterator
732 for (int entIndex = 0; entIndex < ClientAPI.World.LoadedEntities.Count; entIndex++ )
734 var loadedEntity = ClientAPI.World.LoadedEntities.Values.ElementAt(entIndex);
737 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
740 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Code));
741 if (dMatch.Value != null)
743 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Pos.AsBlockPos.Copy( ), loadedEntity);
748 private void AddNote(string notation)
750 var playerNodePoi = new PointOfInterest()
753 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
755 Timestamp = DateTime.UtcNow,
758 this.POIs.AddReplace(playerNodePoi);
763 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
765 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
767 CommandData cmdData = data as CommandData;
769 switch (cmdData.State)
771 case CommandType.Run:
772 case CommandType.Stop:
773 case CommandType.Snapshot:
774 if (CurrentState != cmdData.State)
776 CurrentState = cmdData.State;
781 case CommandType.Notation:
782 //Add to POI list where player location
783 AddNote(cmdData.Notation);
787 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
792 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
794 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
795 switch (rendererName)
797 case StandardRenderer.Name:
798 return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
800 case AlternateRenderer.Name:
801 return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
803 case FlatRenderer.Name:
804 return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
807 throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");