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

Last change on this file since 325 was 325, checked in by alloc, 7 years ago

Code style cleanup (mostly whitespace changes, enforcing braces, using cleanup)

File size: 2.3 KB
Line 
1using System;
2using System.IO;
3using UnityEngine;
4using Object = UnityEngine.Object;
5
6namespace AllocsFixes.FileCache {
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.
9 public class MapTileCache : AbstractCache {
10 private readonly byte[] transparentTile;
11 private CurrentZoomFile[] cache;
12
13 public MapTileCache (int _tileSize) {
14 Texture2D tex = new Texture2D (_tileSize, _tileSize);
15 Color nullColor = new Color (0, 0, 0, 0);
16 for (int x = 0; x < _tileSize; x++) {
17 for (int y = 0; y < _tileSize; y++) {
18 tex.SetPixel (x, y, nullColor);
19 }
20 }
21
22 transparentTile = tex.EncodeToPNG ();
23 Object.Destroy (tex);
24 }
25
26 public void SetZoomCount (int count) {
27 cache = new CurrentZoomFile[count];
28 }
29
30 public byte[] LoadTile (int zoomlevel, string filename) {
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 }
43
44 return cache [zoomlevel].data;
45 }
46 } catch (Exception e) {
47 Log.Out ("Error in MapTileCache.LoadTile: " + e);
48 }
49
50 return null;
51 }
52
53 public void SaveTile (int zoomlevel, byte[] content) {
54 try {
55 lock (cache) {
56 if (cache [zoomlevel].filename != null) {
57 cache [zoomlevel].data = content;
58 File.WriteAllBytes (cache [zoomlevel].filename, content);
59 }
60 }
61 } catch (Exception e) {
62 Log.Out ("Error in MapTileCache.SaveTile: " + e);
63 }
64 }
65
66 public override byte[] GetFileContent (string filename) {
67 try {
68 lock (cache) {
69 foreach (CurrentZoomFile czf in cache) {
70 if (czf.filename != null && czf.filename.Equals (filename)) {
71 return czf.data;
72 }
73 }
74
75 if (!File.Exists (filename)) {
76 return transparentTile;
77 }
78
79 return File.ReadAllBytes (filename);
80 }
81 } catch (Exception e) {
82 Log.Out ("Error in MapTileCache.GetFileContent: " + e);
83 }
84
85 return null;
86 }
87
88 private struct CurrentZoomFile {
89 public string filename;
90 public byte[] data;
91 }
92 }
93}
Note: See TracBrowser for help on using the repository browser.