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 Queue<Vec2i> revisitChunkList = new Queue<Vec2i>();
48 private ColumnsMetadata chunkTopMetadata;
49 internal PointsOfInterest POIs = new PointsOfInterest();
50 internal EntitiesOfInterest EOIs = new EntitiesOfInterest();
52 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
53 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
54 internal Dictionary<int, string> RockIdCodes { get; private set; }
55 internal Dictionary<int, string> AiryIdCodes { get; private set; }
57 internal CommandType CurrentState { get; set; }
58 //Run status, Chunks processed, stats, center of map....
59 private uint nullChunkCount, nullMapCount, updatedChunksTotal;
60 private Vec2i startChunkColumn;
62 private readonly int chunkSize;
64 private IAsset staticMap;
65 private PersistedConfiguration configuration;
68 public static string AutomapStatusEventKey = @"AutomapStatus";
69 public static string AutomapCommandEventKey = @"AutomapCommand";
71 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger, PersistedConfiguration config)
73 this.ClientAPI = clientAPI;
75 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
77 configuration = config;
78 ClientAPI.Event.LevelFinalize += EngageAutomap;
80 this.ChunkRenderer = InstantiateChosenRenderer(config.RendererName);
82 //Listen on bus for commands
83 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
86 if (configuration.Autostart)
88 CurrentState = CommandType.Run;
89 Logger.Notification("Autostart is Enabled.");
96 private void EngageAutomap()
98 path = ClientAPI.GetOrCreateDataPath(_mapPath);
99 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
100 ClientAPI.GetOrCreateDataPath(Path.Combine(path, _chunkPath));
102 JsonGenerator = new JsonGenerator(ClientAPI, Logger, path);
104 string mapFilename = Path.Combine(path, "automap.html");
105 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
107 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
108 outputText.Write(staticMap.ToText());
111 Prefill_POI_Designators();
112 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.Pos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.Pos.AsBlockPos.Z / chunkSize));
113 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
114 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
117 ClientAPI.Event.ChunkDirty += ChunkAChanging;
119 cartographer_thread = new Thread(Cartographer)
121 Name = "Cartographer",
122 Priority = ThreadPriority.Lowest,
126 ClientAPI.Event.RegisterGameTickListener(ThreadDecider, 6000);
129 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
131 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
132 bool newOrEdit = (reason == EnumChunkDirtyReason.NewlyCreated || reason == EnumChunkDirtyReason.NewlyLoaded);
134 columnCounters.AddOrUpdate(topPosition,
135 new ColumnCounter(chunkSize, newOrEdit, chunkCoord),
136 (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;
199 //Revisit failed chunks first;
200 while (revisitChunkList.Count > 0)
202 var revisitCoord = revisitChunkList.Dequeue( );
203 var rv_mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(revisitCoord);
205 if (rv_mapChunk == null) continue;
207 ColumnMeta rv_chunkMeta;
208 if (chunkTopMetadata.Contains(revisitCoord))
210 rv_chunkMeta = chunkTopMetadata[revisitCoord];
212 Logger.VerboseDebug("(re)Loaded meta-chunk {0}", revisitCoord);
217 rv_chunkMeta = CreateColumnMetadata(revisitCoord, rv_mapChunk);
219 Logger.VerboseDebug("(re)Created meta-chunk {0}", revisitCoord);
222 //TODO: Double validation of....?
223 ProcessChunkBlocks(revisitCoord, rv_mapChunk, ref rv_chunkMeta);
225 ChunkRenderer.SetupPngImage(revisitCoord, path, _chunkPath, ref rv_chunkMeta);
226 ChunkRenderer.GenerateChunkPngShard(revisitCoord, rv_mapChunk, rv_chunkMeta, ref chunkTopMetadata, out updatedPixels);
228 if (updatedPixels > 0)
231 Logger.VerboseDebug("(re)Wrote top-chunk shard: ({0}), Pixels#:{2}", revisitCoord, updatedPixels);
234 chunkTopMetadata.Update(rv_chunkMeta);
236 }//*********** REVISIT'd ******************
238 if (!columnCounters.IsEmpty)
239 {//Resulting snapshot keys mabey NON-UNIQUE!!! a *FEATURE* of ConcurrentDict !
240 var columnsSnapshot = columnCounters.Where(cks => cks.Value.WeightedSum > editThreshold).OrderByDescending(kvp => kvp.Value.WeightedSum).ToArray( );
242 UpdateEntityMetadata();
244 foreach (var mostActiveCol in columnsSnapshot)
246 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
248 if (mapChunk == null)
251 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
254 columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
255 revisitChunkList.Enqueue(mostActiveCol.Key);
259 ColumnMeta chunkMeta;
260 if (chunkTopMetadata.Contains(mostActiveCol.Key))
262 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
264 Logger.VerboseDebug("Loaded meta-chunk {0}", mostActiveCol.Key);
269 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
271 Logger.VerboseDebug("Created meta-chunk {0}", mostActiveCol.Key);
275 /********* Special Interlock with C.D. *************/
276 if (columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem)) {
277 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, ref chunkMeta);
278 ejectedItem.SetCutoff(chunkMeta.YMax / chunkSize);
280 ChunkRenderer.SetupPngImage(mostActiveCol.Key, path, _chunkPath, ref chunkMeta);
281 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, ref chunkTopMetadata, out updatedPixels);
285 Logger.Warning("Prevented duplicate processing of: {0}",mostActiveCol.Key );
289 if (updatedPixels > 0)
292 Logger.VerboseDebug("Wrote top-chunk shard: ({0}) - Weight:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
295 chunkTopMetadata.Update(chunkMeta);
296 //columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
300 //columnCounters.TryRemove(mostActiveCol.Key, out ejectedItem);
302 Logger.VerboseDebug("Un-painted chunk shard: ({0}) ", mostActiveCol.Key);
304 revisitChunkList.Enqueue(mostActiveCol.Key);
309 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
311 if (updatedChunks > 0)
313 //What about chunk updates themselves; a update bitmap isn't kept...
314 updatedChunksTotal += updatedChunks;
315 JsonGenerator.GenerateJSONMetadata(chunkTopMetadata, startChunkColumn, POIs, EOIs, RockIdCodes);
318 //Cleanup in-memory Metadata...
319 chunkTopMetadata.ClearMetadata( );
323 Logger.VerboseDebug("Clearing Column Counters of: {0} non-written shards", columnCounters.Count);
326 columnCounters.Clear( );
328 //Then sleep until interupted again, and repeat
330 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
332 Thread.Sleep(Timeout.Infinite);
335 catch (ThreadInterruptedException)
339 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
344 catch (ThreadAbortException)
347 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
353 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
356 Write_PlainMetadata( );
364 Logger.VerboseDebug("Snapshot started");
370 Logger.VerboseDebug("Snapshot sleeping");
372 CurrentState = CommandType.Run;
373 Thread.Sleep(Timeout.Infinite);
375 catch (ThreadInterruptedException)
378 Logger.VerboseDebug("Snapshot intertupted");
384 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
386 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, CommandType.Run);
388 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
391 private void Prefill_POI_Designators()
394 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
395 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
396 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock-"), EnumBlockMaterial.Stone);
398 var airBlocksQuery = from airyBlock in ClientAPI.World.Blocks
399 where airyBlock.MatterState == EnumMatterState.Solid
400 where airyBlock.BlockMaterial == EnumBlockMaterial.Plant || airyBlock.BlockMaterial == EnumBlockMaterial.Leaves
401 where airyBlock.CollisionBoxes == null || airyBlock.CollisionBoxes.Length == 0 || airyBlock.RainPermeable == true
403 //^^ 'Solid' phase - 'Plant' Blocks without any bounding-box; OR 'Invisible' shapes...
404 var invisibleBlocksQuery = from novisBlock in ClientAPI.World.Blocks
405 where novisBlock.Shape == null || novisBlock.Shape.Base.EndsWith(GlobalConstants.DefaultDomain, @"invisible") //Whaat! [ base: "block/basic/invisible" ]
407 this.AiryIdCodes = airBlocksQuery.Union(invisibleBlocksQuery).ToDictionary(aBlk => aBlk.BlockId, aBlk => aBlk.Code.Path);
410 foreach (var fluffBlock in AiryIdCodes) {
411 Logger.VerboseDebug("ID#\t{0}:\t{1} IGNORED", fluffBlock.Key, fluffBlock.Value);
413 Logger.VerboseDebug("Ignoring {0} blocks", AiryIdCodes.Count);
416 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
417 Reload_POI_Designators();
420 private void Reload_POI_Designators()
422 uint poisSetup =0, eoiSetup = 0;
423 foreach (var designator in configuration.BlockDesignators)
425 if (designator.Enabled == false) continue;
426 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
427 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
428 foreach (var entry in blockIDs)
430 BlockID_Designators.Add(entry.Key, designator);
434 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
435 Logger.VerboseDebug("Connected {0} IDs from {1} Block-Designators", poisSetup, configuration.BlockDesignators.Count );
438 foreach (var designator in configuration.EntityDesignators)
440 if (designator.Enabled == false) continue;
441 //Get Variants first, from EntityTypes...better be populated!
442 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
444 foreach (var match in matched)
446 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
447 this.Entity_Designators.Add(match.Code, designator);
451 Logger.VerboseDebug("Connected {0} IDs from {1} Entity-Designators", eoiSetup, configuration.EntityDesignators.Count);
458 /// Store Points/Entity of Interest
460 private void PersistPointsData()
462 //POI and EOI raw dump files ~ WRITE em!
463 //var poiRawFile = File.
464 string poiPath = Path.Combine(path, poiFileName);
465 string eoiPath = Path.Combine(path, eoiFileName);
467 if (this.POIs.Count > 0)
469 using (var poiFile = File.Open(poiPath, FileMode.Create, FileAccess.Write, FileShare.None))
471 Serializer.Serialize<PointsOfInterest>(poiFile, this.POIs);
476 if (this.EOIs.Count > 0)
478 using (var eoiFile = File.Open(eoiPath, FileMode.Create, FileAccess.Write, FileShare.None))
480 Serializer.Serialize<EntitiesOfInterest>(eoiFile, this.EOIs);
485 //Create Easy to Parse TSV file for tool/human use....
486 string pointsTsvPath = Path.Combine(path, pointsTsvFileName);
488 using (var tsvWriter = new StreamWriter(pointsTsvPath, false, Encoding.UTF8))
490 tsvWriter.WriteLine("Name\tDescription\tLocation\tTime\tDestination\tEntity_UID");
491 foreach (var point in this.POIs)
493 tsvWriter.Write(point.Name + "\t");
494 var notes = point.Notes
495 .Replace('\n', '\x001f')
496 .Replace("\t", "\\t")
497 .Replace("\\", "\\\\");
498 tsvWriter.Write(notes + "\t");
499 tsvWriter.Write(point.Location.PrettyCoords(ClientAPI) + "\t");
500 tsvWriter.Write(point.Timestamp.ToString("u") + "\t");
501 tsvWriter.Write((point.Destination != null ? point.Destination.PrettyCoords(ClientAPI) : "---") +"\t");
502 tsvWriter.Write("null\t");
503 tsvWriter.WriteLine();
505 foreach (var entity in this.EOIs)
507 tsvWriter.Write(entity.Name + "\t");
508 var notes = entity.Notes
509 .Replace('\n', '\x001f')
510 .Replace("\t", "\\t")
511 .Replace("\\", "\\\\");
512 tsvWriter.Write(notes + "\t");
513 tsvWriter.Write(entity.Location.PrettyCoords(ClientAPI) + "\t");
514 tsvWriter.Write(entity.Timestamp.ToString("u") + "\t");
515 tsvWriter.Write("---\t");
516 tsvWriter.Write(entity.EntityId.ToString("D"));
517 tsvWriter.WriteLine();
519 tsvWriter.WriteLine();
525 private void Write_PlainMetadata( )
527 string metaPath = Path.Combine(path, plainMetadataFileName);
529 using (var metaDataFile = File.Open(metaPath,FileMode.Create)) {
530 using (var mdWriter = new StreamWriter(metaDataFile, Encoding.ASCII))
532 mdWriter.WriteLine("WorldSeed {0}", ClientAPI.World.Seed);
533 mdWriter.WriteLine("PlayerChunkCoords {0:D} {1:D}", startChunkColumn.X, startChunkColumn.Y);
534 mdWriter.WriteLine("DefaultSpawnPos {0:D} {1:D} {2:D}", ClientAPI.World.DefaultSpawnPosition.AsBlockPos.X,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Y,ClientAPI.World.DefaultSpawnPosition.AsBlockPos.Z);
535 //mdWriter.WriteLine("CurrentPlayerSpawn", ClientAPI.World.Player.WorldData.EntityPlayer.);
536 mdWriter.WriteLine("ChunkSize {0}", chunkSize);
537 mdWriter.WriteLine("SeaLevel {0:D}", ClientAPI.World.SeaLevel);
538 mdWriter.WriteLine("WorldSize {0:D} {1:D} {2:D}", ClientAPI.World.BulkBlockAccessor.MapSizeX, ClientAPI.World.BulkBlockAccessor.MapSizeY,ClientAPI.World.BulkBlockAccessor.MapSizeZ);
539 mdWriter.WriteLine("RegionSize {0:D}", ClientAPI.World.BulkBlockAccessor.RegionSize);
540 mdWriter.WriteLine("AMVersion '{0}'", ClientAPI.Self().Info.Version);
541 mdWriter.WriteLine("PlayTime {0:F1}", ClientAPI.InWorldEllapsedMilliseconds / 1000);
542 mdWriter.WriteLine("GameDate {0}", ClientAPI.World.Calendar.PrettyDate());
543 mdWriter.WriteLine("Chunks {0:D}", chunkTopMetadata.Count);
544 mdWriter.WriteLine("Chunks Updated {0:D}", updatedChunksTotal);
545 mdWriter.WriteLine("Null Chunks {0:D}", nullChunkCount);
552 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, ColumnCounter> mostActiveCol, IMapChunk mapChunk)
554 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ClientAPI, (byte) chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
555 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
557 mostActiveCol.Key.Y * chunkSize);
559 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
560 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
565 private ColumnMeta CreateColumnMetadata(Vec2i coords, IMapChunk mapChunk)
567 ColumnMeta data = new ColumnMeta(coords, ClientAPI, ( byte )chunkSize, (ClientAPI.World.BlockAccessor.MapSizeY / chunkSize));
568 BlockPos equivBP = new BlockPos(coords.X * chunkSize,
570 coords.Y * chunkSize);
572 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
573 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
579 /// Reload chunk bounds from chunk shards
581 /// <returns>The metadata.</returns>
582 private void Reload_Metadata()
584 var shardsDir = new DirectoryInfo( Path.Combine(path, _chunkPath) );
586 if (!shardsDir.Exists)
589 Logger.VerboseDebug("Could not open world map (shards) directory");
593 var shardFiles = shardsDir.GetFiles(chunkFile_filter);
595 if (shardFiles.Length > 0)
598 Logger.VerboseDebug("Metadata reloading from {0} shards", shardFiles.Length);
601 foreach (var shardFile in shardFiles)
604 if (shardFile.Length < 1024) continue;
605 var result = chunkShardRegex.Match(shardFile.Name);
606 if (!result.Success) continue;
608 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
609 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
613 using (var fileStream = shardFile.OpenRead())
616 PngReader pngRead = new PngReader(fileStream);
617 pngRead.ReadSkippingAllRows();
619 //Parse PNG chunks for METADATA in shard
620 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
621 var column = metadataFromPng.ChunkMetadata;
622 if (column.PrettyLocation == null)
623 column = column.Reload(ClientAPI);
624 chunkTopMetadata.Add(column);
628 catch (PngjException someEx)
630 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
633 catch (ProtoException protoEx)
635 Logger.Error("ProtoBuf invalid! file:'{0}' - Reason: {1}", shardFile.Name, protoEx);
641 //POI and EOI raw dump files ~ reload em!
642 //var poiRawFile = File.
643 string poiPath = Path.Combine(path, poiFileName);
644 string eoiPath = Path.Combine(path, eoiFileName);
646 if (File.Exists(poiPath))
648 using (var poiFile = File.OpenRead(poiPath))
650 this.POIs = Serializer.Deserialize<PointsOfInterest>(poiFile);
651 Logger.VerboseDebug("Reloaded {0} POIs from file.", this.POIs.Count);
655 if (File.Exists(eoiPath))
657 using (var eoiFile = File.OpenRead(eoiPath))
659 this.EOIs = Serializer.Deserialize<EntitiesOfInterest>(eoiFile);
660 Logger.VerboseDebug("Reloaded {0} EOIs from file.", this.EOIs.Count);
669 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
671 /// <param name="key">Chunk Coordinate</param>
672 /// <param name="mapChunk">Map chunk.</param>
673 /// <param name="chunkMeta">Chunk metadata</param>
674 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ref ColumnMeta chunkMeta)
676 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ish...
680 Logger.VerboseDebug("Start col @ X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
683 chunkMeta.ResetMetadata(ClientAPI.World.BlockAccessor.MapSizeY);
685 for (; targetChunkY > 0; targetChunkY--)
687 WorldChunk worldChunk = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
689 if (worldChunk == null || worldChunk.BlockEntities == null || worldChunk.Disposed)
692 Logger.VerboseDebug("WORLD chunk, null/disposed OR B.E. null: X{0} Y{1} Z{2} !", key.X, targetChunkY, key.Y);
698 if (worldChunk.IsPacked())
701 Logger.VerboseDebug("WORLD chunk: Compressed: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
703 //VALIDATE: check Read-only applicable
704 if (worldChunk.Unpack_ReadOnly( ) == false)
706 Logger.Warning("Failed to unpack chunk: X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
712 /*************** Chunk Entities Scanning *********************/
713 if (worldChunk.BlockEntities != null && worldChunk.BlockEntities.Count > 0)
716 Logger.VerboseDebug("Scan in Chunk:({0}, Y {2}): found {1} BlockEntities", key, worldChunk.BlockEntities.Count,targetChunkY);
719 foreach (var blockEnt in worldChunk.BlockEntities)
721 var blockEntityPos = blockEnt.Key;
722 var blockEntity = blockEnt.Value;
723 if (blockEntityPos == null || blockEntity == null ) continue;
724 if (blockEntity.Block != null && !blockEntity.Block.IsMissing && BlockID_Designators.ContainsKey(blockEntity.Block.BlockId))
726 var designator = BlockID_Designators[blockEnt.Value.Block.BlockId];
727 if (designator != null && designator.SpecialAction != null) designator.SpecialAction(ClientAPI, POIs, blockEnt.Value.Pos.Copy(), blockEnt.Value.Block);
732 /********************* Chunk/Column BLOCKs scanning ****************/
733 //Heightmap, Stats, block tally
735 int X_index, Y_index, Z_index;
737 //First Chance fail-safe;
738 if (worldChunk.MaybeBlocks == null || worldChunk.MaybeBlocks.Length <= 0) {
740 Logger.VerboseDebug("WORLD chunk; Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", key.X, targetChunkY, key.Y);
746 chunkMeta.ColumnPresense[targetChunkY] = true;
748 for (Y_index = 0; Y_index < chunkSize; Y_index++)
750 for (Z_index = 0; Z_index < chunkSize; Z_index++)
752 for (X_index = 0; X_index < chunkSize; X_index++)
754 var indicie = MapUtil.Index3d(X_index, Y_index, Z_index, chunkSize, chunkSize);
756 //'Last' Chance fail-safe;
757 if (worldChunk.MaybeBlocks == null || worldChunk.MaybeBlocks.Length <= 0) {
759 Logger.VerboseDebug("Processing Block: Missing block DATA⁈ X{0} Y{1} Z{2} ⁈", X_index, Y_index, Z_index);
765 int aBlockId = worldChunk.MaybeBlocks[indicie];
767 if (aBlockId == 0 || AiryIdCodes.ContainsKey(aBlockId)) {//Airy blocks,,,
768 chunkMeta.AirBlocks++;
772 if (RockIdCodes.ContainsKey(aBlockId)) {
773 if (chunkMeta.RockRatio.ContainsKey(aBlockId))
774 chunkMeta.RockRatio[aBlockId]++;
776 chunkMeta.RockRatio.Add(aBlockId, 1);
779 chunkMeta.NonAirBlocks++;
781 ushort localHeight = ( ushort )(Y_index + (targetChunkY * chunkSize));
782 //Heightmap - Need to ignore Grass & Snow
783 if (localHeight > chunkMeta.HeightMap[X_index, Z_index])
785 chunkMeta.HeightMap[X_index, Z_index] = localHeight;
786 if (localHeight > chunkMeta.YMax) chunkMeta.YMax = localHeight;
794 Logger.VerboseDebug("COLUMN X{0} Z{1}: {2}, processed.", key.X , key.Y, chunkTally + 1);
798 private void UpdateEntityMetadata()
801 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
804 var keyList = new long[ClientAPI.World.LoadedEntities.Keys.Count];
805 ClientAPI.World.LoadedEntities.Keys.CopyTo(keyList, 0);
807 //'ElementAt'; worse! instead; walk fixed list...
809 foreach (var key in keyList)
811 if (ClientAPI.World.LoadedEntities.TryGetValue(key, out loadedEntity))
814 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
817 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Code));
818 if (dMatch.Value != null)
820 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Pos.AsBlockPos.Copy( ), loadedEntity);
826 private void AddNote(string notation)
828 var playerNodePoi = new PointOfInterest()
831 Location = ClientAPI.World.Player.Entity.Pos.AsBlockPos.Copy(),
833 Timestamp = DateTime.UtcNow,
836 this.POIs.AddReplace(playerNodePoi);
841 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
843 //Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
845 CommandData cmdData = data as CommandData;
847 switch (cmdData.State)
849 case CommandType.Run:
850 case CommandType.Stop:
851 case CommandType.Snapshot:
852 if (CurrentState != cmdData.State)
854 CurrentState = cmdData.State;
859 case CommandType.Notation:
860 //Add to POI list where player location
861 AddNote(cmdData.Notation);
865 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");
870 private AChunkRenderer InstantiateChosenRenderer(string rendererName )
872 Logger.VerboseDebug("Using '{0}' style Shard Renderer", rendererName);
873 switch (rendererName)
875 case StandardRenderer.Name:
876 return new StandardRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
878 case AlternateRenderer.Name:
879 return new AlternateRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
881 case FlatRenderer.Name:
882 return new FlatRenderer(ClientAPI, Logger, this.configuration.SeasonalColors);
885 throw new ArgumentOutOfRangeException("rendererName",rendererName,"That value isn't supported or known...");