OSDN Git Service

W.I.P. IV: More reliable entity / block scanning (full depth chunk scan), rock stats...
[automap/automap.git] / Automap / Subsystems / AutomapSystem.cs
index ece2be3..faea6b5 100644 (file)
@@ -15,9 +15,10 @@ using Hjg.Pngcs.Chunks;
 
 using Vintagestory.API.Client;
 using Vintagestory.API.Common;
+using Vintagestory.API.Common.Entities;
+using Vintagestory.API.Config;
 using Vintagestory.API.MathTools;
-
-
+using Vintagestory.Common;
 
 namespace Automap
 {
@@ -26,6 +27,7 @@ namespace Automap
                private Thread cartographer_thread;
                private ICoreClientAPI ClientAPI { get; set; }
                private ILogger Logger { get; set; }
+               private IChunkRenderer ChunkRenderer { get; set; }
 
                private const string _mapPath = @"Maps";
                private const string _chunkPath = @"Chunks";
@@ -36,15 +38,18 @@ namespace Automap
                private ConcurrentDictionary<Vec2i, uint> columnCounter = new ConcurrentDictionary<Vec2i, uint>(3, 150 );
                private ColumnsMetadata chunkTopMetadata;
                private PointsOfInterest POIs;
+               private EntitiesOfInterest EOIs;
+
+               internal Dictionary<int, BlockDesignator> BlockID_Designators { get; private set;}
+               internal Dictionary<AssetLocation, EntityDesignator> Entity_Designators { get; private set; }
+               internal Dictionary<int, string> RockIdCodes { get; private set; }
 
-               internal Dictionary<int, Designator> BlockID_Designators { get; private set;}
                internal bool Enabled { get; set; }
                //Run status, Chunks processed, stats, center of map....
-               internal uint nullChunkCount;
-               internal uint updatedChunksTotal;
+               internal uint nullChunkCount, updatedChunksTotal;
                internal Vec2i startChunkColumn;
 
-
+               private readonly int chunkSize;
                private string path;
                private IAsset stylesFile;
 
@@ -53,7 +58,11 @@ namespace Automap
                {
                this.ClientAPI = clientAPI;
                this.Logger = logger;
+               chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
                ClientAPI.Event.LevelFinalize += EngageAutomap;
+
+               //TODO:Choose which one from GUI 
+               this.ChunkRenderer = new StandardRenderer(clientAPI, logger);
                }
 
 
@@ -67,7 +76,7 @@ namespace Automap
                Logger.VerboseDebug("CSS loaded: {0} size: {1}",stylesFile.IsLoaded() ,stylesFile.ToText( ).Length);
 
                Prefill_POI_Designators( );
-               startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.X / ClientAPI.World.BlockAccessor.ChunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / ClientAPI.World.BlockAccessor.ChunkSize));
+               startChunkColumn = new Vec2i((ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.X / chunkSize), (ClientAPI.World.Player.Entity.LocalPos.AsBlockPos.Z / chunkSize));
                chunkTopMetadata = new ColumnsMetadata(startChunkColumn);
 
                Logger.Notification("AUTOMAP Start {0}", startChunkColumn);
@@ -105,7 +114,9 @@ namespace Automap
                //Time to (re)write chunk shards
                cartographer_thread.Interrupt( );
                }
+               #if DEBUG
                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})");
+               #endif
                }
 
                }
@@ -134,11 +145,14 @@ namespace Automap
                continue;
                }
                
-               ColumnMeta chunkMeta = UpdateColumnMetadata(mostActiveCol,mapChunk);
+               ColumnMeta chunkMeta = CreateColumnMetadata(mostActiveCol,mapChunk);
                PngWriter pngWriter = SetupPngImage(mostActiveCol.Key, chunkMeta);
+               UpdateEntityMetadata( );
+               ProcessChunkBlocks(mostActiveCol.Key, mapChunk, chunkMeta);
 
                uint updatedPixels = 0;
-               GenerateChunkImage(mostActiveCol.Key, mapChunk, pngWriter , out updatedPixels);
+
+               ChunkRenderer.GenerateChunkPngShard(mostActiveCol.Key, mapChunk, chunkMeta, pngWriter , out updatedPixels);
                
                if (updatedPixels > 0) {                
                
@@ -158,7 +172,7 @@ namespace Automap
                }
 
                if (updatedChunks > 0) {
-               //TODO: ONLY update if chunk bounds have changed!
+               //What about chunk updates themselves; a update bitmap isn't kept...
                updatedChunksTotal += updatedChunks;
                GenerateMapHTML( );
                updatedChunks = 0;
@@ -183,40 +197,51 @@ namespace Automap
                }
                }
 
-
-
-
                private void Prefill_POI_Designators( )
                {
                this.POIs = new PointsOfInterest( );
-               this.BlockID_Designators = new Dictionary<int, Designator>( );
+               this.EOIs = new EntitiesOfInterest( );
+               this.BlockID_Designators = new Dictionary<int, BlockDesignator>( );
+               this.Entity_Designators = new Dictionary<AssetLocation, EntityDesignator>( );
+               this.RockIdCodes = Helpers.ArbitrarytBlockIdHunter(ClientAPI, new AssetLocation(GlobalConstants.DefaultDomain, "rock"), EnumBlockMaterial.Stone);
 
                //Add special marker types for BlockID's of "Interest", overwrite colour, and method
 
-               var theDesignators = new List<Designator>{
-                               DefaultDesignators.Roads,
-                DefaultDesignators.GroundSigns,
-                DefaultDesignators.WallSigns,
-                DefaultDesignators.PostSigns,
-                               };
-
-               Install_POI_Designators(theDesignators);
+               Install_POI_Designators(DefaultDesignators.DefaultBlockDesignators(), DefaultDesignators.DefaultEntityDesignators());
                }
 
-               private void Install_POI_Designators(ICollection<Designator> designators)
+               private void Install_POI_Designators(ICollection<BlockDesignator> blockDesig, List<EntityDesignator> entDesig)
                {
-               Logger.VerboseDebug("Connecting {0} configured Designators", designators.Count);
-               foreach (var designator in designators) {                               
+               Logger.VerboseDebug("Connecting {0} standard Block-Designators", blockDesig.Count);
+               foreach (var designator in blockDesig) {                                
                        var blockIDs = Helpers.ArbitrarytBlockIdHunter(ClientAPI, designator.Pattern, designator.Material);
                                if (blockIDs.Count > 0) { Logger.VerboseDebug("Designator {0} has {1} associated blockIDs", designator.ToString( ), blockIDs.Count); }
                        foreach (var entry in blockIDs) {
                        BlockID_Designators.Add(entry.Key, designator);
                        }
                }
+               this.ChunkRenderer.BlockID_Designators = BlockID_Designators;
+               
+               
+               Logger.VerboseDebug("Connecting {0} standard Entity-Designators", entDesig.Count);
+               foreach (var designator in entDesig) {
+               //Get Variants first, from EntityTypes...better be populated!
+               var matched = ClientAPI.World.EntityTypes.FindAll(entp => entp.Code.BeginsWith(designator.Pattern.Domain, designator.Pattern.Path));
+
+               foreach (var match in matched) {
+               Logger.VerboseDebug("Linked Entity: {0} Designator: {1}", match.Code, designator);
+               this.Entity_Designators.Add(match.Code, designator);
+               }
+               
+               
 
+               //EntityProperties props = ClientAPI.World.GetEntityType(designator.Pattern);
                }
 
 
+               }
+
+               //TODO: Convert to RAZOR model
                private void GenerateMapHTML( )
                {
                string mapFilename = Path.Combine(path, "Automap.html");
@@ -380,14 +405,25 @@ namespace Automap
 
 
                tableWriter.RenderEndTag( );//</table>
-               
+
                //############## POI list #####################
+               tableWriter.RenderBeginTag(HtmlTextWriterTag.P);
+               tableWriter.WriteLine("Points of Interest");
+               tableWriter.RenderEndTag( );
                tableWriter.RenderBeginTag(HtmlTextWriterTag.Ul);
                foreach (var poi in this.POIs) {
                tableWriter.RenderBeginTag(HtmlTextWriterTag.Li);
+               tableWriter.WriteEncodedText(poi.Location.PrettyCoords(this.ClientAPI)+"\t");
+               tableWriter.WriteEncodedText(poi.Notes+ "\t");
                tableWriter.WriteEncodedText(poi.Timestamp.ToString("u"));
-               tableWriter.WriteEncodedText(poi.Notes);
-               tableWriter.WriteEncodedText(poi.Location.PrettyCoords(this.ClientAPI));
+               tableWriter.RenderEndTag( );
+               }
+
+               foreach (var eoi in this.EOIs.PointsList) {
+               tableWriter.RenderBeginTag(HtmlTextWriterTag.Li);
+               tableWriter.WriteEncodedText(eoi.Location.PrettyCoords(this.ClientAPI)+ "\t");
+               tableWriter.WriteEncodedText(eoi.Notes+ "\t");
+               tableWriter.WriteEncodedText(eoi.Timestamp.ToString("u") );
                tableWriter.RenderEndTag( );
                }
 
@@ -409,33 +445,15 @@ namespace Automap
 
 
 
-               private ColumnMeta UpdateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
+               private ColumnMeta CreateColumnMetadata(KeyValuePair<Vec2i, uint> mostActiveCol, IMapChunk mapChunk)
                {
-               ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy());
-               BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * ClientAPI.World.BlockAccessor.ChunkSize,
+               ColumnMeta data = new ColumnMeta(mostActiveCol.Key.Copy(), chunkSize);
+               BlockPos equivBP = new BlockPos(mostActiveCol.Key.X * chunkSize,
                                                                                mapChunk.YMax,
-                                                                               mostActiveCol.Key.Y * ClientAPI.World.BlockAccessor.ChunkSize);
+                                                                               mostActiveCol.Key.Y * chunkSize);
 
                var climate = ClientAPI.World.BlockAccessor.GetClimateAt(equivBP);
-               data.ChunkAge = TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours);
-               data.Temperature = climate.Temperature;
-               data.Fertility = climate.Fertility;
-               data.ForestDensity = climate.ForestDensity;
-               data.Rainfall = climate.Rainfall;
-               data.ShrubDensity = climate.ShrubDensity;
-
-               data.YMax = mapChunk.YMax;
-
-               
-               /* Only present on server....
-               if (mapChunk.TopRockIdMap != null) {
-               foreach (var topRockId in mapChunk.TopRockIdMap) {
-
-               if (data.RockRatio.ContainsKey(topRockId)) { data.RockRatio[topRockId]++; }
-               else { data.RockRatio.Add(topRockId, 1); }
-               }
-               }*/
-
+               data.UpdateFieldsFrom(climate, mapChunk,TimeSpan.FromHours(ClientAPI.World.Calendar.TotalHours));               
 
                return data;
                }
@@ -460,6 +478,8 @@ namespace Automap
                
 
                foreach (var shardFile in files) {
+
+               if (shardFile.Length < 512) continue;
                var result = chunkShardRegex.Match(shardFile.Name);
                if (result.Success) {
                int X_chunk_pos = int.Parse(result.Groups["X"].Value );
@@ -494,7 +514,7 @@ namespace Automap
 
                private PngWriter SetupPngImage(Vec2i coord, ColumnMeta metadata)
                {
-               ImageInfo imageInf = new ImageInfo(ClientAPI.World.BlockAccessor.ChunkSize, ClientAPI.World.BlockAccessor.ChunkSize, 8, false);
+               ImageInfo imageInf = new ImageInfo(chunkSize, chunkSize, 8, false);
                
                string filename = $"{coord.X}_{coord.Y}.png";
                filename = Path.Combine(path, filename);
@@ -512,137 +532,112 @@ namespace Automap
                return pngWriter;
                }
 
-               #endregion
-
-
-               #region COPYPASTA
-               //TODO: rewrite - with vertical ray caster, down to bottom-most chunk (for object detection...)
-               //A partly re-written; ChunkMapLayer :: public int[] GenerateChunkImage(Vec2i chunkPos, IMapChunk mc)
-               private void GenerateChunkImage(Vec2i chunkPos, IMapChunk mc, PngWriter pngWriter, out uint pixelCount)
-               {
-               pixelCount = 0;
-               BlockPos tmpPos = new BlockPos( );
-               Vec2i localpos = new Vec2i( );
-               int chunkSize = ClientAPI.World.BlockAccessor.ChunkSize;
-               var chunksColumn = new IWorldChunk[ClientAPI.World.BlockAccessor.MapSizeY / chunkSize];
-
-               int topChunkY = mc.YMax / chunkSize;//Heywaitaminute -- this isn't a highest FEATURE, if Rainmap isn't accurate!
-                                                                                       //Metadata of DateTime chunk was edited, chunk coords.,world-seed? Y-Max feature height
-                                                                                       //Grab a chunk COLUMN... Topmost Y down...
-               for (int chunkY = 0; chunkY <= topChunkY; chunkY++) {
-               chunksColumn[chunkY] = ClientAPI.World.BlockAccessor.GetChunk(chunkPos.X, chunkY, chunkPos.Y);
-               //What to do if chunk is a void? invalid?
-               }
-
-               // Prefetch map chunks, in pattern
-               IMapChunk[ ] mapChunks = new IMapChunk[ ]
+               /// <summary>
+               /// Does the heavy lifting of Scanning columns of chunks - creates Heightmap and Processes POIs, Entities, and stats...
+               /// </summary>
+               /// <param name="key">Chunk Coordinate</param>
+               /// <param name="mapChunk">Map chunk.</param>
+               /// <param name="chunkMeta">Chunk metadata</param>
+               private void ProcessChunkBlocks(Vec2i key, IMapChunk mapChunk, ColumnMeta chunkMeta)
                {
-                       ClientAPI.World.BlockAccessor.GetMapChunk(chunkPos.X - 1, chunkPos.Y - 1),
-                       ClientAPI.World.BlockAccessor.GetMapChunk(chunkPos.X - 1, chunkPos.Y),
-                       ClientAPI.World.BlockAccessor.GetMapChunk(chunkPos.X, chunkPos.Y - 1)
-               };
-
-               //pre-create PNG line slices...
-               ImageLine[ ] lines = Enumerable.Repeat(new object( ), chunkSize).Select(l => new ImageLine(pngWriter.ImgInfo)).ToArray( );
-
-               for (int posIndex = 0; posIndex < (chunkSize * chunkSize); posIndex++) {
-               int mapY = mc.RainHeightMap[posIndex];
-               int localChunkY = mapY / chunkSize;
-               if (localChunkY >= (chunksColumn.Length)) continue;//Out of range!
 
-               MapUtil.PosInt2d(posIndex, chunkSize, localpos);
-               int localX = localpos.X;
-               int localZ = localpos.Y;
+               int targetChunkY = mapChunk.YMax / chunkSize;//Surface ... 
+               for (; targetChunkY > 0; targetChunkY--) {
+               WorldChunk chunkData = ClientAPI.World.BlockAccessor.GetChunk(key.X, targetChunkY, key.Y) as WorldChunk;
 
-               float b = 1;
-               int leftTop, rightTop, leftBot;
-
-               IMapChunk leftTopMapChunk = mc;
-               IMapChunk rightTopMapChunk = mc;
-               IMapChunk leftBotMapChunk = mc;
+               if (chunkData == null || chunkData.BlockEntities == null) {
+               #if DEBUG
+               Logger.VerboseDebug("Chunk null or empty X{0} Y{1} Z{2}", key.X,targetChunkY,key.Y);
+               #endif
+               continue;
+               }
 
-               int topX = localX - 1;
-               int botX = localX;
-               int leftZ = localZ - 1;
-               int rightZ = localZ;
+               /*************** Chunk Entities Scanning *********************/
+               if (chunkData.BlockEntities != null && chunkData.BlockEntities.Length > 0) {
+               #if DEBUG
+               Logger.VerboseDebug("Surface@ {0} = BlockEntities: {1}", key, chunkData.BlockEntities.Length);
+               #endif
 
-               if (topX < 0 && leftZ < 0) {
-               leftTopMapChunk = mapChunks[0];
-               rightTopMapChunk = mapChunks[1];
-               leftBotMapChunk = mapChunks[2];
-               }
-               else {
-               if (topX < 0) {
-               leftTopMapChunk = mapChunks[1];
-               rightTopMapChunk = mapChunks[1];
+               foreach (var blockEnt in chunkData.BlockEntities) {
+               
+                       if (blockEnt != null && blockEnt.Block != null && BlockID_Designators.ContainsKey(blockEnt.Block.BlockId)) 
+                       {
+                       var designator = BlockID_Designators[blockEnt.Block.BlockId];
+                       designator.SpecialAction(ClientAPI, POIs, blockEnt.Pos.Copy( ), blockEnt.Block);
+                       }
                }
-               if (leftZ < 0) {
-               leftTopMapChunk = mapChunks[2];
-               leftBotMapChunk = mapChunks[2];
+               
                }
+               /********************* Chunk/Column BLOCKs scanning ****************/
+               //Heightmap, Stats, block tally
+               chunkData.Unpack( );
+
+               int X_index, Y_index, Z_index;
+               X_index = Y_index = Z_index = 0;
+
+               do {
+               do {
+               do {
+               /* Encode packed indicie
+               (y * chunksize + z) * chunksize + x
+               */
+               var indicie = Helpers.ChunkBlockIndicie16(X_index, Y_index, Z_index);
+               int aBlockId = chunkData.Blocks[indicie];
+                                                                       
+               if (aBlockId == 0) {//Air
+               chunkMeta.AirBlocks++;
+               continue;
                }
 
-               topX = GameMath.Mod(topX, chunkSize);
-               leftZ = GameMath.Mod(leftZ, chunkSize);
-
-               leftTop = leftTopMapChunk == null ? 0 : Math.Sign(mapY - leftTopMapChunk.RainHeightMap[leftZ * chunkSize + topX]);
-               rightTop = rightTopMapChunk == null ? 0 : Math.Sign(mapY - rightTopMapChunk.RainHeightMap[rightZ * chunkSize + topX]);
-               leftBot = leftBotMapChunk == null ? 0 : Math.Sign(mapY - leftBotMapChunk.RainHeightMap[leftZ * chunkSize + botX]);
-
-               float slopeness = (leftTop + rightTop + leftBot);
-
-               if (slopeness > 0) b = 1.2f;
-               if (slopeness < 0) b = 0.8f;
+               if (RockIdCodes.ContainsKey(aBlockId)) {
+               if (chunkMeta.RockRatio.ContainsKey(aBlockId)) { chunkMeta.RockRatio[aBlockId]++; } else { chunkMeta.RockRatio.Add(aBlockId, 1); }              
+               }
+               
+               chunkMeta.NonAirBlocks++;               
 
-               b -= 0.15f; //Slope boost value 
+               //Heightmap 
+               if (chunkMeta.HeightMap[X_index, Z_index] == 0) 
+               { chunkMeta.HeightMap[X_index, Z_index] = ( ushort )(Y_index + (targetChunkY * chunkSize)); }
 
-               if (chunksColumn[localChunkY] == null) {
+               }
+               while (X_index++ < (chunkSize - 1));
+               X_index = 0;
+               }
+               while (Z_index++ < (chunkSize - 1));
+               Z_index = 0;
+               }
+               while (Y_index++ < (chunkSize - 1));
 
-               continue;
+               }
                }
 
-               chunksColumn[localChunkY].Unpack( );
-               int blockId = chunksColumn[localChunkY].Blocks[MapUtil.Index3d(localpos.X, mapY % chunkSize, localpos.Y, chunkSize, chunkSize)];
+               private void UpdateEntityMetadata( )
+               {
+               Logger.Debug("Presently {0} Entities", ClientAPI.World.LoadedEntities.Count);
+               //Mabey scan only for 'new' entities by tracking ID in set?
+               foreach (var loadedEntity in ClientAPI.World.LoadedEntities.ToList()) {
+               
+               #if DEBUG
+               //Logger.VerboseDebug($"ENTITY: ({loadedEntity.Value.Code}) = #{loadedEntity.Value.EntityId} {loadedEntity.Value.State} {loadedEntity.Value.LocalPos}    <<<<<<<<<<<<");
+               #endif
 
-               Block block = ClientAPI.World.Blocks[blockId];
+               var dMatch = Entity_Designators.SingleOrDefault(se => se.Key.Equals(loadedEntity.Value.Code));
+               if (dMatch.Value != null) {                     
+                       dMatch.Value.SpecialAction(ClientAPI, this.EOIs, loadedEntity.Value.LocalPos.AsBlockPos.Copy( ), loadedEntity.Value);                                           
+               }
 
-               tmpPos.Set(chunkSize * chunkPos.X + localpos.X, mapY, chunkSize * chunkPos.Y + localpos.Y);
+               }
 
-               int avgCol = block.GetColor(ClientAPI, tmpPos);
-               int rndCol = block.GetRandomColor(ClientAPI, tmpPos, BlockFacing.UP);
-               int col = ColorUtil.ColorOverlay(avgCol, rndCol, 0.125f);
-               var packedFormat = ColorUtil.ColorMultiply3Clamped(col, b);
 
-               int red = ColorUtil.ColorB(packedFormat);
-               int green = ColorUtil.ColorG(packedFormat);
-               int blue = ColorUtil.ColorR(packedFormat);
+               }
 
 
-               //============ POI Population =================
-               if (BlockID_Designators.ContainsKey(blockId)) {
-               var desig = BlockID_Designators[blockId];
-               red = desig.OverwriteColor.R;
-               green = desig.OverwriteColor.G;
-               blue = desig.OverwriteColor.B;
 
-               if (desig.SpecialAction != null) {
-               desig.SpecialAction(ClientAPI, this.POIs, tmpPos, block);
-               }
-               }
 
-               ImageLineHelper.SetPixel(lines[localZ], localX, red, green, blue);
 
-               //chunkImage.SetPixel(localX, localZ, pixelColor);
-               pixelCount++;
-               }
+               #endregion
 
-               for (int row = 0; row < pngWriter.ImgInfo.Rows; row++) {
-               pngWriter.WriteRow(lines[row], row);
-               }
 
-               pngWriter.End( );
-               }
-               #endregion
        }
 
 }
\ No newline at end of file