source: binary-improvements/7dtd-server-fixes/src/FileCache/MapTileCache.cs@ 326

Last change on this file since 326 was 326, checked in by alloc, 6 years ago

More cleanup, allocation improvements

File size: 2.3 KB
RevLine 
[199]1using System;
2using System.IO;
[324]3using UnityEngine;
[325]4using Object = UnityEngine.Object;
[199]5
[325]6namespace AllocsFixes.FileCache {
[199]7 // Special "cache" for map tile folder as both map rendering and webserver access files in there.
8 // Only map rendering tiles are cached. Writing is done by WriteThrough.
[325]9 public class MapTileCache : AbstractCache {
10 private readonly byte[] transparentTile;
[199]11 private CurrentZoomFile[] cache;
12
[325]13 public MapTileCache (int _tileSize) {
[324]14 Texture2D tex = new Texture2D (_tileSize, _tileSize);
15 Color nullColor = new Color (0, 0, 0, 0);
[269]16 for (int x = 0; x < _tileSize; x++) {
17 for (int y = 0; y < _tileSize; y++) {
18 tex.SetPixel (x, y, nullColor);
19 }
20 }
[325]21
[269]22 transparentTile = tex.EncodeToPNG ();
[325]23 Object.Destroy (tex);
[199]24 }
25
[325]26 public void SetZoomCount (int count) {
[199]27 cache = new CurrentZoomFile[count];
28 }
29
[325]30 public byte[] LoadTile (int zoomlevel, string filename) {
[199]31 try {
32 lock (cache) {
33 if (cache [zoomlevel].filename == null || !cache [zoomlevel].filename.Equals (filename)) {
34 cache [zoomlevel].filename = filename;
35
36 if (!File.Exists (filename)) {
37 cache [zoomlevel].data = null;
38 return null;
39 }
40
41 cache [zoomlevel].data = File.ReadAllBytes (filename);
42 }
[325]43
[199]44 return cache [zoomlevel].data;
45 }
46 } catch (Exception e) {
47 Log.Out ("Error in MapTileCache.LoadTile: " + e);
48 }
[325]49
[199]50 return null;
51 }
52
[325]53 public void SaveTile (int zoomlevel, byte[] content) {
[199]54 try {
55 lock (cache) {
[326]56 if (cache [zoomlevel].filename == null) {
57 return;
[199]58 }
[326]59
60 cache [zoomlevel].data = content;
61 File.WriteAllBytes (cache [zoomlevel].filename, content);
[199]62 }
63 } catch (Exception e) {
64 Log.Out ("Error in MapTileCache.SaveTile: " + e);
65 }
66 }
67
[325]68 public override byte[] GetFileContent (string filename) {
[199]69 try {
70 lock (cache) {
71 foreach (CurrentZoomFile czf in cache) {
[325]72 if (czf.filename != null && czf.filename.Equals (filename)) {
[199]73 return czf.data;
[325]74 }
[199]75 }
76
77 if (!File.Exists (filename)) {
[269]78 return transparentTile;
[199]79 }
[325]80
[199]81 return File.ReadAllBytes (filename);
82 }
83 } catch (Exception e) {
84 Log.Out ("Error in MapTileCache.GetFileContent: " + e);
85 }
[325]86
[199]87 return null;
88 }
89
[325]90 private struct CurrentZoomFile {
91 public string filename;
92 public byte[] data;
93 }
[199]94 }
[325]95}
Note: See TracBrowser for help on using the repository browser.