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 Vintagestory.API.Client;
14 using Vintagestory.API.Common;
15 using Vintagestory.API.Config;
16 using Vintagestory.API.Datastructures;
17 using Vintagestory.API.MathTools;
18 using Vintagestory.Common;
22 public class AutomapSystem
24 private Thread cartographer_thread;
25 private ICoreClientAPI ClientAPI { get; set; }
26 private ILogger Logger { get; set; }
27 private IChunkRenderer ChunkRenderer { get; set; }
29 private const string _mapPath = @"Maps";
30 private const string _chunkPath = @"Chunks";
31 private const string _domain = @"automap";
32 private const string chunkFile_filter = @"*_*.png";
33 private static Regex chunkShardRegex = new Regex(@"(?<X>[\d]+)_(?<Z>[\d]+).png", RegexOptions.Singleline);
35 private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150);
36 private ColumnsMetadata chunkTopMetadata;
37 private PointsOfInterest POIs = new PointsOfInterest();
38 private EntitiesOfInterest EOIs = new EntitiesOfInterest();
40 internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set; }
41 internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
42 internal Dictionary<int, string> RockIdCodes { get; private set; }
44 internal RunState CurrentState { get; set; }
45 //Run status, Chunks processed, stats, center of map....
46 private uint nullChunkCount, updatedChunksTotal;
47 private Vec2i startChunkColumn;
49 private readonly int chunkSize;
51 private IAsset staticMap;
53 public static string AutomapStatusEventKey = @"AutomapStatus";
54 public static string AutomapCommandEventKey = @"AutomapCommand";
57 public AutomapSystem(ICoreClientAPI clientAPI, ILogger logger)
59 this.ClientAPI = clientAPI;
61 chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
62 ClientAPI.Event.LevelFinalize += EngageAutomap;
64 //TODO:Choose which one from GUI
65 this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
67 //Listen on bus for commands
68 ClientAPI.Event.RegisterEventBusListener(CommandListener, 1.0, AutomapSystem.AutomapCommandEventKey);
74 private void EngageAutomap()
76 path = ClientAPI.GetOrCreateDataPath(_mapPath);
77 path = ClientAPI.GetOrCreateDataPath(Path.Combine(path, "World_" + ClientAPI.World.Seed));//Add name of World too...'ServerApi.WorldManager.CurrentWorldName'
80 string mapFilename = Path.Combine(path, "automap.html");
81 StreamWriter outputText = new StreamWriter(File.Open(mapFilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
83 staticMap = ClientAPI.World.AssetManager.Get(new AssetLocation(_domain, "config/automap.html"));
84 outputText.Write(staticMap.ToText());
87 Prefill_POI_Designators();
88 startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
89 chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
91 Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
94 ClientAPI.Event.ChunkDirty += ChunkAChanging;
96 cartographer_thread = new Thread(Cartographer)
98 Name = "Cartographer",
99 Priority = ThreadPriority.Lowest,
103 ClientAPI.Event.RegisterGameTickListener(AwakenCartographer, 6000);
106 private void ChunkAChanging(Vec3i chunkCoord, IWorldChunk chunk, EnumChunkDirtyReason reason)
108 Vec2i topPosition = new Vec2i(chunkCoord.X, chunkCoord.Z);
110 columnCounter.AddOrUpdate(topPosition, 1, (key, colAct) => colAct + 1);
113 private void AwakenCartographer(float delayed)
116 if (CurrentState == RunState.Run && (ClientAPI.IsGamePaused != false || ClientAPI.IsShuttingDown != true))
119 Logger.VerboseDebug("Cartographer re-trigger from [{0}]", cartographer_thread.ThreadState);
122 if (cartographer_thread.ThreadState.HasFlag(ThreadState.Unstarted))
124 cartographer_thread.Start();
126 else if (cartographer_thread.ThreadState.HasFlag(ThreadState.WaitSleepJoin))
128 //Time to (re)write chunk shards
129 cartographer_thread.Interrupt();
132 //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})");
135 else if (CurrentState == RunState.Snapshot)
137 //TODO: Snapshot generator second thread...
143 private void Cartographer()
146 Logger.VerboseDebug("Cartographer thread awoken");
150 uint ejectedItem = 0;
151 uint updatedChunks = 0;
153 //-- Should dodge enumerator changing underfoot....at a cost.
154 if (!columnCounter.IsEmpty)
156 var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
157 foreach (var mostActiveCol in tempSet)
160 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
162 if (mapChunk == null)
164 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
166 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
170 ColumnMeta chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
171 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
172 UpdateEntityMetadata();
173 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, chunkMeta);
176 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out uint updatedPixels);
178 if (updatedPixels > 0)
182 Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
185 chunkTopMetadata.Update(chunkMeta);
186 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
190 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
191 Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
197 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
199 if (updatedChunks > 0)
201 //What about chunk updates themselves; a update bitmap isn't kept...
202 updatedChunksTotal += updatedChunks;
203 GenerateJSONMetadata();
207 //Then sleep until interupted again, and repeat
209 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
211 Thread.Sleep(Timeout.Infinite);
214 catch (ThreadInterruptedException)
217 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
221 catch (ThreadAbortException)
223 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
228 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
232 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
234 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, RunState.Run);
236 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
239 private void Prefill_POI_Designators()
242 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
243 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
244 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock"), EnumBlockMaterial.Stone);
246 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
248 Install_POI_Designators(DefaultDesignators.DefaultBlockDesignators(), DefaultDesignators.DefaultEntityDesignators());
251 private void Install_POI_Designators(ICollection<BlockDesignator> blockDesig, List<EntityDesignator> entDesig)
253 Logger.VerboseDebug("Connecting {0} standard Block-Designators", blockDesig.Count);
254 foreach (var designator in blockDesig)
256 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
257 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
258 foreach (var entry in blockIDs)
260 BlockID_Designators.Add(entry.Key, designator);
263 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
266 Logger.VerboseDebug("Connecting {0} standard Entity-Designators", entDesig.Count);
267 foreach (var designator in entDesig)
269 //Get Variants first, from EntityTypes...better be populated!
270 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
272 foreach (var match in matched)
274 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
275 this.Entity_Designators.Add(match.Code, designator);
280 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
287 /// Generates the JSON Metadata. (in Map object format )
289 private void GenerateJSONMetadata()
291 string jsonFilename = Path.Combine(path, "Metadata.js");
293 StreamWriter jsonWriter = new StreamWriter(jsonFilename, false, Encoding.UTF8);
296 jsonWriter.Write("ViewFrame.chunks={};");
297 jsonWriter.Write("ViewFrame.chunks.worldSeedNum={0};", ClientAPI.World.Seed);
298 jsonWriter.Write("ViewFrame.chunks.genTime=new Date('{0}');", DateTimeOffset.UtcNow.ToString("O"));
299 jsonWriter.Write("ViewFrame.chunks.startCoords=[{0},{1}];", startChunkColumn.X, startChunkColumn.Y);
300 jsonWriter.Write("ViewFrame.chunks.chunkSize={0};", chunkSize);
301 jsonWriter.Write("ViewFrame.chunks.northMostChunk={0};", chunkTopMetadata.North_mostChunk);
302 jsonWriter.Write("ViewFrame.chunks.southMostChunk={0};", chunkTopMetadata.South_mostChunk);
303 jsonWriter.Write("ViewFrame.chunks.eastMostChunk={0};", chunkTopMetadata.East_mostChunk);
304 jsonWriter.Write("ViewFrame.chunks.westMostChunk={0};", chunkTopMetadata.West_mostChunk);
305 //MAP object format - [key, value]: key is "x_y"
306 jsonWriter.Write("ViewFrame.chunks.chunkMetadata=new Map([");
307 foreach (var shard in chunkTopMetadata)
309 jsonWriter.Write("['{0}_{1}',", shard.Location.X, shard.Location.Y);
310 jsonWriter.Write("{");
311 jsonWriter.Write("prettyCoord:'{0}',", shard.Location.PrettyCoords(ClientAPI));
312 jsonWriter.Write("chunkAge:'{0}',", shard.ChunkAge.ToString("g"));//World age - relative? or last edit ??
313 jsonWriter.Write("temp:'{0}',", shard.Temperature.ToString("F1"));
314 jsonWriter.Write("YMax:'{0}',", shard.YMax);
315 jsonWriter.Write("fert:'{0}',", shard.Fertility.ToString("F1"));
316 jsonWriter.Write("forestDens:'{0}',", shard.ForestDensity.ToString("F1"));
317 jsonWriter.Write("rain:'{0}',", shard.Rainfall.ToString("F1"));
318 jsonWriter.Write("shrubDens:'{0}',", shard.ShrubDensity.ToString("F1"));
319 jsonWriter.Write("airBlocks:'{0}',", shard.AirBlocks);
320 jsonWriter.Write("nonAirBlocks:'{0}',", shard.NonAirBlocks);
323 jsonWriter.Write("}],");
325 jsonWriter.Write("]);");
328 jsonWriter.Write("ViewFrame.chunks.pointsOfInterest = new Map([");
329 foreach (var poi in POIs)
331 jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
332 jsonWriter.Write("{");
333 jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
334 jsonWriter.Write("notes:'{0}',", poi.Notes.Replace("'", "\'").Replace("\n","\\n"));
335 jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
336 jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
337 jsonWriter.Write("}],");
340 foreach (var poi in EOIs)
342 jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
343 jsonWriter.Write("{");
344 jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
345 jsonWriter.Write("notes:'{0}',", poi.Notes.Replace("'", "\'"));
346 jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
347 jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
348 jsonWriter.Write("}],");
350 jsonWriter.Write("]);");
358 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
360 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), chunkSize);
361 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
363 mostActiveCol.Key.Y * chunkSize);
365 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
366 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
372 /// Reload chunk bounds from chunk shards
374 /// <returns>The metadata.</returns>
375 private void Reload_Metadata()
377 var worldmapDir = new DirectoryInfo(path);
379 if (worldmapDir.Exists)
382 var files = worldmapDir.GetFiles(chunkFile_filter);
384 if (files.Length > 0)
387 Logger.VerboseDebug("{0} Existing world chunk shards", files.Length);
392 foreach (var shardFile in files)
395 if (shardFile.Length < 512) continue;
396 var result = chunkShardRegex.Match(shardFile.Name);
399 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
400 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
402 //Parse PNG chunks for METADATA in shard
403 using var fileStream = shardFile.OpenRead();
404 //TODO: Add corrupted PNG Exception handing HERE !
405 PngReader pngRead = new PngReader(fileStream);
406 pngRead.ReadSkippingAllRows();
409 PngMetadataChunk metadataFromPng = pngRead.GetChunksList().GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
411 chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
421 Logger.VerboseDebug("Could not open world map directory");
429 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
431 ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
433 string filename = $"{coord.X}_{coord.Y}.png";
434 filename = Path.Combine(path, filename);
436 PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
437 PngMetadata meta = pngWriter.GetMetadata();
439 meta.SetText("Chunk_X", coord.X.ToString("D"));
440 meta.SetText("Chunk_Y", coord.Y.ToString("D"));
441 //Setup specialized meta-data PNG chunks here...
442 PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
444 ChunkMetadata = metadata
446 pngWriter.GetChunksList().Queue(pngChunkMeta);
452 /// Does the heavy lifting of Scanning columns of chunks - creates Heightmap and Processes POIs, Entities, and stats...
454 /// <param name="key">Chunk Coordinate</param>
455 /// <param name="mapChunk">Map chunk.</param>
456 /// <param name="chunkMeta">Chunk metadata</param>
457 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ColumnMeta chunkMeta)
460 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ...
461 for (; targetChunkY > 0; targetChunkY--)
463 if (!(ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) is WorldChunk chunkData) || chunkData.BlockEntities == null)
466 Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
471 /*************** Chunk Entities Scanning *********************/
472 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
475 Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
478 foreach (var blockEnt in chunkData.BlockEntities)
481 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
483 var designator = BlockID_Designators[blockEnt.Block.BlockId];
484 designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
489 /********************* Chunk/Column BLOCKs scanning ****************/
490 //Heightmap, Stats, block tally
493 int X_index, Y_index, Z_index;
494 X_index = Y_index = Z_index = 0;
502 /* Encode packed indicie
503 (y * chunksize + z) * chunksize + x
505 var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
506 int aBlockId = chunkData.Blocks[indicie];
510 chunkMeta.AirBlocks++;
514 if (RockIdCodes.ContainsKey(aBlockId))
516 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
519 chunkMeta.NonAirBlocks++;
522 if (chunkMeta.HeightMap[X_index, Z_index] == 0)
523 { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
526 while (X_index++ < (chunkSize - 1));
529 while (Z_index++ < (chunkSize - 1));
532 while (Y_index++ < (chunkSize - 1));
537 private void UpdateEntityMetadata()
539 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
540 //Mabey scan only for 'new' entities by tracking ID in set?
541 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToList())
545 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
548 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
549 if (dMatch.Value != null)
551 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
559 private void AddNote(string notation)
561 var playerNodePoi = new PointOfInterest()
563 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
565 Timestamp = DateTimeOffset.UtcNow,
568 this.POIs.AddReplace(playerNodePoi);
573 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
575 Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
577 CommandData cmdData = data as CommandData;
580 if (CurrentState != RunState.Snapshot)
582 switch (cmdData.State)
585 CurrentState = cmdData.State;
586 AwakenCartographer(0.0f);
590 CurrentState = cmdData.State;
593 case RunState.Snapshot:
594 CurrentState = RunState.Stop;
595 //Snapshot starts a second thread/process...
599 case RunState.Notation:
600 //Add to POI list where player location
601 AddNote(cmdData.Notation);
607 if (CurrentState != cmdData.State)
609 CurrentState = cmdData.State;
610 AwakenCartographer(0.0f);
614 ClientAPI.TriggerChatMessage($"Automap commanded to: {cmdData.State} ");