2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
8 using System.Text.RegularExpressions;
9 using System.Threading;
12 using Mono.Collections.Generic;
15 using Vintagestory.API.Client;
16 using Vintagestory.API.Common;
17 using Vintagestory.API.Common.Entities;
18 using Vintagestory.API.Config;
19 using Vintagestory.API.Datastructures;
20 using Vintagestory.API.MathTools;
21 using Vintagestory.Common;
25 public class AutomapSystem
27 private Thread cartographer_thread;
29 private Snapshotter snapshot;
30 private ICoreClientAPI ClientAPI { get; set; }
31 private ILogger Logger { get; set; }
32 private AChunkRenderer ChunkRenderer { get; set; }
33 private JsonGenerator JsonGenerator { get; set; }
35 internal const string _mapPath = @"Maps";
36 internal const string _chunkPath = @"Chunks";
37 internal const uint editThreshold = 9;
38 private const string _domain = @"automap";
39 private const string chunkFile_filter = @"*_*.png";
40 private const string poiFileName = @"poi_binary";
41 private const string eoiFileName = @"eoi_binary";
42 private const string pointsTsvFileName = @"points_of_interest.tsv";
43 private const string plainMetadataFileName = @"map_metadata.txt";
44 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+)\.png", RegexOptions.Singleline);
46 private ConcurrentDictionary<Vec2i, ColumnCounter> columnCounters = new ConcurrentDictionary<Vec2i, ColumnCounter>(3, 150);
47 private ColumnsMetadata chunkTopMetadata;
48 internal PointsOfInterest POIs = new PointsOfInterest();
49 internal EntitiesOfInterest EOIs = new EntitiesOfInterest();
51 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
52 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
53 internal Dictionary<int, string> RockIdCodes { get; private set; }
54 internal Dictionary<int, string> AiryIdCodes { get; private set; }
56 internal CommandType CurrentState { get; set; }
57 //Run status, Chunks processed, stats, center of map....
58 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
59 private Vec2i startChunkColumn;
61 private readonly int chunkSize;
63 private IAsset staticMap;
64 private PersistedConfiguration configuration;
67 public static string AutomapStatusEventKey = @"AutomapStatus";
68 public static string AutomapCommandEventKey = @"AutomapCommand";
70 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
72 this.ClientAPI = clientAPI;
74 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
76 configuration = config;
77 ClientAPI.Event.LevelFinalize += EngageAutomap;
79 this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
81 //Listen on bus for commands
82 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
85 if (configuration.Autostart)
87 CurrentState = CommandType.Run;
88 Logger.Notification("Autostart is Enabled.");
95 private void EngageAutomap()
97 path = ClientAPI.GetOrCreateDataPath(_mapPath);
98 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
99 ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
101 JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
103 string mapFilename = Path.Combine(path, "automap.html");
104 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
106 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
107 outputText.Write(staticMap.ToText());
110 Prefill_POI_Designators();
111 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
112 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
113 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
116 ClientAPI.Event.ChunkDirty += ChunkAChanging;
118 cartographer_thread = new Thread(Cartographer)
120 Name = "Cartographer",
121 Priority = ThreadPriority.Lowest,
125 ClientAPI.Event.RegisterGameTickListener(ThreadDecider, 6000);
128 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
130 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
131 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
133 columnCounters.AddOrUpdate(topPosition,
134 new ColumnCounter(chunkSize, newOrEdit, chunkCoord),
135 (chkPos, chkChng) => chkChng.Update(chunkCoord, chunkSize, newOrEdit)
141 /// Cartographer Thread 'decider'
143 /// <param name="delayed">called delay offset</param>
144 private void ThreadDecider(float delayed)
147 if (CurrentState == CommandType.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
150 Logger.VerboseDebug("ThreadDecider re-trigger from [{0}]", cartographer_thread.ThreadState);
153 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
155 cartographer_thread.Start();
157 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
159 //Time to (re)write chunk shards
160 cartographer_thread.Interrupt();
163 //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})");
166 else if (CurrentState == CommandType.Snapshot)
168 //Prepare for taking a snopshot
169 if (snapshot == null) {
170 snapshot = new Snapshotter(path, chunkTopMetadata, chunkSize, ClientAPI.World.Seed);
172 Logger.VerboseDebug("Starting new Snapshot: {0} Wx{1} Hx{2}", snapshot.fileName, snapshot.Width, snapshot.Height);
176 else if (snapshot != null && snapshot.Finished) {
178 Logger.VerboseDebug("COMPLETED Snapshot: {0} Wx{1} Hx{2}, taking {3}", snapshot.fileName, snapshot.Width, snapshot.Height, snapshot.Timer.Elapsed);
181 CurrentState = CommandType.Run;
187 private void Cartographer()
190 Logger.VerboseDebug("Cartographer thread awoken");
194 ColumnCounter ejectedItem ;
195 uint updatedChunks = 0;
196 uint updatedPixels = 0;
198 //-- Should dodge enumerator changing underfoot....at a cost.
199 if (!columnCounters.IsEmpty)
201 var tempSet = columnCounters.ToArray().Where(cks => cks.Value.WeightedSum > editThreshold) .OrderByDescending(kvp => kvp.Value.WeightedSum);
202 UpdateEntityMetadata();
204 foreach (var mostActiveCol in tempSet)
206 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
208 if (mapChunk == null)
210 //TODO: REVISIT THIS CHUNK!
212 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
215 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
219 ColumnMeta chunkMeta;
220 if (chunkTopMetadata.Contains(mostActiveCol.Key))
222 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
224 Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
229 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
231 Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
234 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
235 mostActiveCol.Value.SetCutoff(chunkMeta.YMax / chunkSize);
237 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
238 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
240 if (updatedPixels > 0)
243 Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
246 chunkTopMetadata.Update(chunkMeta);
247 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
251 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
253 Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
259 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
261 if (updatedChunks > 0)
263 //What about chunk updates themselves; a update bitmap isn't kept...
264 updatedChunksTotal += updatedChunks;
265 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
268 //Cleanup in-memory Metadata...
269 chunkTopMetadata.ClearMetadata( );
273 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
276 columnCounters.Clear( );
278 //Then sleep until interupted again, and repeat
280 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
282 Thread.Sleep(Timeout.Infinite);
285 catch (ThreadInterruptedException)
289 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
294 catch (ThreadAbortException)
297 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
303 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
306 Write_PlainMetadata( );
314 Logger.VerboseDebug("Snapshot started");
320 Logger.VerboseDebug("Snapshot sleeping");
322 CurrentState = CommandType.Run;
323 Thread.Sleep(Timeout.Infinite);
325 catch (ThreadInterruptedException)
328 Logger.VerboseDebug("Snapshot intertupted");
334 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
336 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
338 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
341 private void Prefill_POI_Designators()
344 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
345 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
346 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
348 var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
349 where airyBlock.MatterState == EnumMatterState.Solid
350 where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
351 where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 || airyBlock.RainPermeable == true
353 //^^ 'Solid' phase - 'Plant' Blocks without any bounding-box; OR 'Invisible' shapes...
354 var invisibleBlocksQuery = from novisBlock in ClientAPI.World.Blocks
355 where novisBlock.Shape == null || novisBlock.Shape.Base.EndsWith(GlobalConstants.DefaultDomain, @"invisible") //Whaat! [ base: "block/basic/invisible" ]
357 this.AiryIdCodes = airBlocksQuery.Union(invisibleBlocksQuery).ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
360 foreach (var fluffBlock in AiryIdCodes) {
361 Logger.VerboseDebug("ID#\t{0}:\t{1} IGNORED", fluffBlock.Key, fluffBlock.Value);
363 Logger.VerboseDebug("Ignoring {0} blocks", AiryIdCodes.Count);
366 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
367 Reload_POI_Designators();
370 private void Reload_POI_Designators()
372 uint poisSetup =0, eoiSetup = 0;
373 foreach (var designator in configuration.BlockDesignators)
375 if (designator.Enabled == false) continue;
376 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
377 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
378 foreach (var entry in blockIDs)
380 BlockID_Designators.Add(entry.Key, designator);
384 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
385 Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
388 foreach (var designator in configuration.EntityDesignators)
390 if (designator.Enabled == false) continue;
391 //Get Variants first, from EntityTypes...better be populated!
392 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
394 foreach (var match in matched)
396 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
397 this.Entity_Designators.Add(match.Code, designator);
401 Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
408 /// Store Points/Entity of Interest
410 private void PersistPointsData()
412 //POI and EOI raw dump files ~ WRITE em!
413 //var poiRawFile = File.
414 string poiPath = Path.Combine(path, poiFileName);
415 string eoiPath = Path.Combine(path, eoiFileName);
417 if (this.POIs.Count > 0)
419 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
421 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
426 if (this.EOIs.Count > 0)
428 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
430 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
435 //Create Easy to Parse TSV file for tool/human use....
436 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
438 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
440 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
441 foreach (var point in this.POIs)
443 tsvWriter.Write(point.Name + "\t");
444 var notes = point.Notes
445 .Replace('\n', '\x001f')
446 .Replace("\t", "\\t")
447 .Replace("\\", "\\\\");
448 tsvWriter.Write(notes + "\t");
449 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
450 tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
451 tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
452 tsvWriter.Write("null\t");
453 tsvWriter.WriteLine();
455 foreach (var entity in this.EOIs)
457 tsvWriter.Write(entity.Name + "\t");
458 var notes = entity.Notes
459 .Replace('\n', '\x001f')
460 .Replace("\t", "\\t")
461 .Replace("\\", "\\\\");
462 tsvWriter.Write(notes + "\t");
463 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
464 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
465 tsvWriter.Write("---\t");
466 tsvWriter.Write(entity.EntityId.ToString("D"));
467 tsvWriter.WriteLine();
469 tsvWriter.WriteLine();
475 private void Write_PlainMetadata( )
477 string metaPath = Path.Combine(path, plainMetadataFileName);
479 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
480 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII))
482 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
483 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
484 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
485 //mdWriter.WriteLine("CurrentPlayerSpawn", ClientAPI.World.Player.WorldData.EntityPlayer.);
486 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
487 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
488 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
489 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
490 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
491 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
492 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
493 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
494 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
495 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);
502 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
504 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
505 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
507 mostActiveCol.Key.Y * chunkSize);
509 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
510 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
516 /// Reload chunk bounds from chunk shards
518 /// <returns>The metadata.</returns>
519 private void Reload_Metadata()
521 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
523 if (!shardsDir.Exists)
526 Logger.VerboseDebug("Could not open world map (shards) directory");
530 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
532 if (shardFiles.Length > 0)
535 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
538 foreach (var shardFile in shardFiles)
541 if (shardFile.Length < 1024) continue;
542 var result = chunkShardRegex.Match(shardFile.Name);
543 if (!result.Success) continue;
545 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
546 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
550 using (var fileStream = shardFile.OpenRead())
553 PngReader pngRead = new PngReader(fileStream);
554 pngRead.ReadSkippingAllRows();
556 //Parse PNG chunks for METADATA in shard
557 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
558 var column = metadataFromPng.ChunkMetadata;
559 if (column.PrettyLocation == null)
560 column = column.Reload(ClientAPI);
561 chunkTopMetadata.Add(column);
565 catch (PngjException someEx)
567 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
570 catch (ProtoException protoEx)
572 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
578 //POI and EOI raw dump files ~ reload em!
579 //var poiRawFile = File.
580 string poiPath = Path.Combine(path, poiFileName);
581 string eoiPath = Path.Combine(path, eoiFileName);
583 if (File.Exists(poiPath))
585 using (var poiFile = File.OpenRead(poiPath))
587 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
588 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
592 if (File.Exists(eoiPath))
594 using (var eoiFile = File.OpenRead(eoiPath))
596 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
597 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
606 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
608 /// <param name="key">Chunk Coordinate</param>
609 /// <param name="mapChunk">Map chunk.</param>
610 /// <param name="chunkMeta">Chunk metadata</param>
611 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
613 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish...
617 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
620 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
622 for (; targetChunkY > 0; targetChunkY--)
624 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
626 if (worldChunk == null || worldChunk.BlockEntities == null)
629 Logger.VerboseDebug("WORLD chunk: null or empty X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
635 if (worldChunk.IsPacked())
638 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
640 worldChunk.Unpack( );//RESEARCH: Thread Unsafe?
643 /*************** Chunk Entities Scanning *********************/
644 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
647 Logger.VerboseDebug("Scan pos.({0}) for BlockEntities# {1}", key, worldChunk.BlockEntities.Count);
650 foreach (var blockEnt in worldChunk.BlockEntities)
652 if (blockEnt.Key != null && blockEnt.Value != null && blockEnt.Value.Block != null && BlockID_Designators.ContainsKey(blockEnt.Value.Block.BlockId))
654 var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
655 designator?.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
660 /********************* Chunk/Column BLOCKs scanning ****************/
661 //Heightmap, Stats, block tally
663 int X_index, Y_index, Z_index;
665 //First Chance fail-safe;
666 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
668 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
674 chunkMeta.ColumnPresense[targetChunkY] = true;
676 for (Y_index = 0; Y_index < chunkSize; Y_index++)
678 for (Z_index = 0; Z_index < chunkSize; Z_index++)
680 for (X_index = 0; X_index < chunkSize; X_index++)
682 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
684 //'Last' Chance fail-safe;
685 if (worldChunk.Blocks == null || worldChunk.Blocks.Length <= 0) {
687 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
693 int aBlockId = worldChunk.Blocks[indicie];
695 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
696 chunkMeta.AirBlocks++;
700 if (RockIdCodes.ContainsKey(aBlockId)) {
701 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
702 chunkMeta.RockRatio[aBlockId]++;
704 chunkMeta.RockRatio.Add(aBlockId, 1);
707 chunkMeta.NonAirBlocks++;
709 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
710 //Heightmap - Need to ignore Grass & Snow
711 if (localHeight > chunkMeta.HeightMap[X_index, Z_index])
713 chunkMeta.HeightMap[X_index, Z_index] = localHeight;
714 if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
722 Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
726 private void UpdateEntityMetadata()
729 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
732 var keyList = new long[ClientAPI.World.LoadedEntities.Keys.Count];
733 ClientAPI.World.LoadedEntities.Keys.CopyTo(keyList, 0);
735 //'ElementAt'; worse! instead; walk fixed list...
737 foreach (var key in keyList)
739 if (ClientAPI.World.LoadedEntities.TryGetValue(key, out loadedEntity))
742 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
745 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Code));
746 if (dMatch.Value != null)
748 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Pos.AsBlockPos.Copy( ), loadedEntity);
754 private void AddNote(string notation)
756 var playerNodePoi = new PointOfInterest()
759 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
761 Timestamp = DateTime.UtcNow,
764 this.POIs.AddReplace(playerNodePoi);
769 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
771 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
773 CommandData cmdData = data as CommandData;
775 switch (cmdData.State)
777 case CommandType.Run:
778 case CommandType.Stop:
779 case CommandType.Snapshot:
780 if (CurrentState != cmdData.State)
782 CurrentState = cmdData.State;
787 case CommandType.Notation:
788 //Add to POI list where player location
789 AddNote(cmdData.Notation);
793 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
798 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
800 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
801 switch (rendererName)
803 case StandardRenderer.Name:
804 return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
806 case AlternateRenderer.Name:
807 return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
809 case FlatRenderer.Name:
810 return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
813 throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");