2 using System.Collections.Concurrent;
3 using System.Collections.Generic;
7 using System.Text.RegularExpressions;
8 using System.Threading;
11 using Hjg.Pngcs.Chunks;
12 using Newtonsoft.Json;
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;
152 uint updatedPixels = 0;
154 //-- Should dodge enumerator changing underfoot....at a cost.
155 if (!columnCounter.IsEmpty)
157 var tempSet = columnCounter.ToArray().OrderByDescending(kvp => kvp.Value);
158 foreach (var mostActiveCol in tempSet)
161 var mapChunk = ClientAPI.World.BlockAccessor.GetMapChunk(mostActiveCol.Key);
163 if (mapChunk == null)
165 Logger.Warning("SKIP CHUNK: ({0}) - Map Chunk NULL!", mostActiveCol.Key);
167 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
171 ColumnMeta chunkMeta;
172 if (chunkTopMetadata.Contains(mostActiveCol.Key)) {
173 chunkMeta = chunkTopMetadata[mostActiveCol.Key];
176 chunkMeta = CreateColumnMetadata(mostActiveCol, mapChunk);
179 UpdateEntityMetadata();
180 ProcessChunkBlocks(mostActiveCol.Key, mapChunk, chunkMeta);
182 PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
183 ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter, out updatedPixels);
185 if (updatedPixels > 0)
189 Logger.VerboseDebug("Wrote chunk shard: ({0}) - Edits#:{1}, Pixels#:{2}", mostActiveCol.Key, mostActiveCol.Value, updatedPixels);
192 chunkTopMetadata.Update(chunkMeta);
193 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
197 columnCounter.TryRemove(mostActiveCol.Key, out ejectedItem);
198 Logger.VerboseDebug("Un-painted chunk: ({0}) ", mostActiveCol.Key);
204 UpdateStatus(this.updatedChunksTotal, this.nullChunkCount, updatedChunks);
206 if (updatedChunks > 0)
208 //What about chunk updates themselves; a update bitmap isn't kept...
209 updatedChunksTotal += updatedChunks;
210 GenerateJSONMetadata();
214 //Then sleep until interupted again, and repeat
216 Logger.VerboseDebug("Thread '{0}' about to sleep indefinitely.", Thread.CurrentThread.Name);
218 Thread.Sleep(Timeout.Infinite);
221 catch (ThreadInterruptedException)
224 Logger.VerboseDebug("Thread '{0}' interupted [awoken]", Thread.CurrentThread.Name);
228 catch (ThreadAbortException)
230 Logger.VerboseDebug("Thread '{0}' aborted.", Thread.CurrentThread.Name);
235 Logger.VerboseDebug("Thread '{0}' executing finally block.", Thread.CurrentThread.Name);
239 private void UpdateStatus(uint totalUpdates, uint voidChunks, uint delta)
241 StatusData updateData = new StatusData(totalUpdates, voidChunks, delta, RunState.Run);
243 this.ClientAPI.Event.PushEvent(AutomapStatusEventKey, updateData);
246 private void Prefill_POI_Designators()
249 this.BlockID_Designators = new Dictionary<int, BlockDesignator>();
250 this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>();
251 this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock"), EnumBlockMaterial.Stone);
253 //Add special marker types for BlockID's of "Interest", overwrite colour, and method
255 Install_POI_Designators(DefaultDesignators.DefaultBlockDesignators(), DefaultDesignators.DefaultEntityDesignators());
258 private void Install_POI_Designators(ICollection<BlockDesignator> blockDesig, List<EntityDesignator> entDesig)
260 Logger.VerboseDebug("Connecting {0} standard Block-Designators", blockDesig.Count);
261 foreach (var designator in blockDesig)
263 var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
264 if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString(), blockIDs.Count); }
265 foreach (var entry in blockIDs)
267 BlockID_Designators.Add(entry.Key, designator);
270 this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
273 Logger.VerboseDebug("Connecting {0} standard Entity-Designators", entDesig.Count);
274 foreach (var designator in entDesig)
276 //Get Variants first, from EntityTypes...better be populated!
277 var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
279 foreach (var match in matched)
281 Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
282 this.Entity_Designators.Add(match.Code, designator);
287 //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
294 /// Generates the JSON Metadata. (in Map object format )
296 private void GenerateJSONMetadata()
298 string jsonFilename = Path.Combine(path, "Metadata.js");
300 StreamWriter jsonWriter = new StreamWriter(jsonFilename, false, Encoding.UTF8);
303 jsonWriter.Write("ViewFrame.chunks={};");
304 jsonWriter.Write("ViewFrame.chunks.worldSeedNum={0};", ClientAPI.World.Seed);
305 jsonWriter.Write("ViewFrame.chunks.genTime=new Date('{0}');", DateTimeOffset.UtcNow.ToString("O"));
306 jsonWriter.Write("ViewFrame.chunks.startCoords=[{0},{1}];", startChunkColumn.X, startChunkColumn.Y);
307 jsonWriter.Write("ViewFrame.chunks.chunkSize={0};", chunkSize);
308 jsonWriter.Write("ViewFrame.chunks.northMostChunk={0};", chunkTopMetadata.North_mostChunk);
309 jsonWriter.Write("ViewFrame.chunks.southMostChunk={0};", chunkTopMetadata.South_mostChunk);
310 jsonWriter.Write("ViewFrame.chunks.eastMostChunk={0};", chunkTopMetadata.East_mostChunk);
311 jsonWriter.Write("ViewFrame.chunks.westMostChunk={0};", chunkTopMetadata.West_mostChunk);
312 //MAP object format - [key, value]: key is "x_y"
313 jsonWriter.Write("ViewFrame.chunks.chunkMetadata=new Map([");
314 foreach (var shard in chunkTopMetadata)
316 jsonWriter.Write("['{0}_{1}',", shard.Location.X, shard.Location.Y);
317 jsonWriter.Write("{");
318 jsonWriter.Write("prettyCoord:'{0}',", shard.Location.PrettyCoords(ClientAPI));
319 jsonWriter.Write("chunkAge:'{0}',", shard.ChunkAge.ToString("g"));//World age - relative? or last edit ??
320 jsonWriter.Write("temp:'{0}',", shard.Temperature.ToString("F1"));
321 jsonWriter.Write("YMax:'{0}',", shard.YMax);
322 jsonWriter.Write("fert:'{0}',", shard.Fertility.ToString("F1"));
323 jsonWriter.Write("forestDens:'{0}',", shard.ForestDensity.ToString("F1"));
324 jsonWriter.Write("rain:'{0}',", shard.Rainfall.ToString("F1"));
325 jsonWriter.Write("shrubDens:'{0}',", shard.ShrubDensity.ToString("F1"));
326 jsonWriter.Write("airBlocks:'{0}',", shard.AirBlocks);
327 jsonWriter.Write("nonAirBlocks:'{0}',", shard.NonAirBlocks);
329 //TODO: Rock-ratio, also requires a BlockID => Name lookup table....elsewhere
330 jsonWriter.Write("}],");
332 jsonWriter.Write("]);");
335 jsonWriter.Write("ViewFrame.chunks.pointsOfInterest = new Map([");
336 foreach (var poi in POIs)
338 jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
339 jsonWriter.Write("{");
340 jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
341 jsonWriter.Write("notes:{0},", JsonConvert.ToString(poi.Notes, '\'', StringEscapeHandling.EscapeHtml));
342 jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
343 jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
344 jsonWriter.Write("}],");
347 foreach (var poi in EOIs)
349 jsonWriter.Write("['{0}_{1}',", poi.Location.X, poi.Location.Z);
350 jsonWriter.Write("{");
351 jsonWriter.Write("prettyCoord:'{0}',", poi.Location.PrettyCoords(ClientAPI));
352 jsonWriter.Write("notes:{0},", JsonConvert.ToString(poi.Notes, '\'', StringEscapeHandling.EscapeHtml));
353 jsonWriter.Write("time:new Date('{0}'),", poi.Timestamp.ToString("O"));
354 jsonWriter.Write("chunkPos:'{0}_{1}',", (poi.Location.X / chunkSize), (poi.Location.Z / chunkSize));
355 jsonWriter.Write("}],");
357 jsonWriter.Write("]);");
365 private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
367 ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), ( byte )chunkSize);
368 BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
370 mostActiveCol.Key.Y * chunkSize);
372 var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
373 data.UpdateFieldsFrom(climate, mapChunk, TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));
379 /// Reload chunk bounds from chunk shards
381 /// <returns>The metadata.</returns>
382 private void Reload_Metadata()
384 var worldmapDir = new DirectoryInfo(path);
386 if (worldmapDir.Exists)
389 var files = worldmapDir.GetFiles(chunkFile_filter);
391 if (files.Length > 0)
394 Logger.VerboseDebug("{0} Existing world chunk shards", files.Length);
397 foreach (var shardFile in files) {
399 if (shardFile.Length < 1024) continue;
400 var result = chunkShardRegex.Match(shardFile.Name);
401 if (result.Success) {
402 int X_chunk_pos = int.Parse(result.Groups["X"].Value);
403 int Z_chunk_pos = int.Parse(result.Groups["Z"].Value);
407 using (var fileStream = shardFile.OpenRead( )) {
409 PngReader pngRead = new PngReader(fileStream);
410 pngRead.ReadSkippingAllRows( );
412 //Parse PNG chunks for METADATA in shard
413 PngMetadataChunk metadataFromPng = pngRead.GetChunksList( ).GetById1(PngMetadataChunk.ID) as PngMetadataChunk;
415 chunkTopMetadata.Add(metadataFromPng.ChunkMetadata);
419 catch (PngjException someEx)
421 Logger.Error("PNG Corruption file '{0}' - Reason: {1}", shardFile.Name, someEx);
434 Logger.VerboseDebug("Could not open world map directory");
442 private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
444 ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
446 string filename = $"{coord.X}_{coord.Y}.png";
447 filename = Path.Combine(path, filename);
449 PngWriter pngWriter = FileHelper.CreatePngWriter(filename, imageInf, true);
450 PngMetadata meta = pngWriter.GetMetadata();
452 meta.SetText("Chunk_X", coord.X.ToString("D"));
453 meta.SetText("Chunk_Y", coord.Y.ToString("D"));
454 //Setup specialized meta-data PNG chunks here...
455 PngMetadataChunk pngChunkMeta = new PngMetadataChunk(pngWriter.ImgInfo)
457 ChunkMetadata = metadata
459 pngWriter.GetChunksList().Queue(pngChunkMeta);
460 pngWriter.CompLevel = 9;// 9 is the maximum compression
461 pngWriter.CompressionStrategy = Hjg.Pngcs.Zlib.EDeflateCompressStrategy.Huffman;
467 /// Does the heavy lifting of Scanning columns of chunks - scans for BlockEntity, creates Heightmap and stats...
469 /// <param name="key">Chunk Coordinate</param>
470 /// <param name="mapChunk">Map chunk.</param>
471 /// <param name="chunkMeta">Chunk metadata</param>
472 private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ColumnMeta chunkMeta)
475 int targetChunkY = mapChunk.YMax / chunkSize;//Surface ...
476 for (; targetChunkY > 0; targetChunkY--)
478 WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
480 if (chunkData == null || chunkData.BlockEntities == null) {
482 Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X, targetChunkY, key.Y);
487 /*************** Chunk Entities Scanning *********************/
488 if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0)
491 Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
494 foreach (var blockEnt in chunkData.BlockEntities)
497 if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId))
499 var designator = BlockID_Designators[blockEnt.Block.BlockId];
500 designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy(), blockEnt.Block);
505 /********************* Chunk/Column BLOCKs scanning ****************/
506 //Heightmap, Stats, block tally
509 int X_index, Y_index, Z_index;
510 X_index = Y_index = Z_index = 0;
518 /* Encode packed indicie
519 (y * chunksize + z) * chunksize + x
521 var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
522 int aBlockId = chunkData.Blocks[indicie];
526 chunkMeta.AirBlocks++;
530 if (RockIdCodes.ContainsKey(aBlockId))
532 if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }
535 chunkMeta.NonAirBlocks++;
538 if (chunkMeta.HeightMap[X_index, Z_index] == 0)
539 { chunkMeta.HeightMap[X_index, Z_index] = (ushort) (Y_index + (targetChunkY * chunkSize)); }
542 while (X_index++ < (chunkSize - 1));
545 while (Z_index++ < (chunkSize - 1));
548 while (Y_index++ < (chunkSize - 1));
553 private void UpdateEntityMetadata()
555 Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
556 //Mabey scan only for 'new' entities by tracking ID in set?
557 foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToList())
561 //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos} <<<<<<<<<<<<");
564 var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
565 if (dMatch.Value != null)
567 dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy(), loadedEntity.Value);
575 private void AddNote(string notation)
577 var playerNodePoi = new PointOfInterest()
579 Location = ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Copy(),
581 Timestamp = DateTimeOffset.UtcNow,
584 this.POIs.AddReplace(playerNodePoi);
589 private void CommandListener(string eventName, ref EnumHandling handling, IAttribute data)
591 Logger.VerboseDebug("MsgBus RX: AutomapCommandMsg: {0}", data.ToJsonToken());
593 CommandData cmdData = data as CommandData;
596 if (CurrentState != RunState.Snapshot)
598 switch (cmdData.State)
601 CurrentState = cmdData.State;
602 AwakenCartographer(0.0f);
606 CurrentState = cmdData.State;
609 case RunState.Snapshot:
610 CurrentState = RunState.Stop;
611 //Snapshot starts a second thread/process...
615 case RunState.Notation:
616 //Add to POI list where player location
617 AddNote(cmdData.Notation);
623 if (CurrentState != cmdData.State)
625 CurrentState = cmdData.State;
626 AwakenCartographer(0.0f);
630 Logger.VerboseDebug($"Automap commanded to: {cmdData.State} ");