using System; using System.IO; using System.Threading; using UnityEngine; namespace AllocsFixes.MapRendering { public class MapRenderBlockBuffer { private int zoomLevel; private string currentBlockMap = string.Empty; private Texture2D blockMap = new Texture2D (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE); private Texture2D zoomBuffer = new Texture2D (1, 1); private Color nullColor = new Color (0, 0, 0, 0); public MapRenderBlockBuffer (int level) { zoomLevel = level; } public void SaveBlock () { try { if (currentBlockMap.Length > 0) saveTextureToFile (currentBlockMap); } catch (Exception e) { Log.Out ("Exception in MapRenderBlockBuffer.SaveBlock(): " + e); } } public void LoadBlock (Vector2i block) { Monitor.Enter (blockMap); try { string folder = Constants.MAP_DIRECTORY + "/" + (zoomLevel) + "/" + block.x; string fileName = folder + "/" + block.y + ".png"; Directory.CreateDirectory (folder); if (!fileName.Equals (currentBlockMap)) { if (currentBlockMap.Length > 0) saveTextureToFile (currentBlockMap); loadTextureFromFile (fileName); } currentBlockMap = fileName; } finally { Monitor.Exit (blockMap); } } public void SetPart (Vector2i offset, int partSize, Color[] pixels) { blockMap.SetPixels (offset.x, offset.y, partSize, partSize, pixels); } public Color[] GetHalfScaled () { zoomBuffer.Resize (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE); zoomBuffer.SetPixels (blockMap.GetPixels ()); TextureScale.Point (zoomBuffer, Constants.MAP_BLOCK_SIZE / 2, Constants.MAP_BLOCK_SIZE / 2); return zoomBuffer.GetPixels (); } private void loadTextureFromFile (string _fileName) { try { byte[] array = File.ReadAllBytes (_fileName); blockMap.LoadImage (array); } catch (Exception) { for (int x = 0; x < Constants.MAP_BLOCK_SIZE; x++) { for (int y = 0; y < Constants.MAP_BLOCK_SIZE; y++) { blockMap.SetPixel (x, y, nullColor); } } } } private void saveTextureToFile (string _fileName) { try { byte[] array = blockMap.EncodeToPNG (); File.WriteAllBytes (_fileName, array); } catch (Exception e) { Log.Out ("Exception in MapRenderBlockBuffer.saveTextureToFile(): " + e); } } } }