source: TFP-WebServer/WebServer/src/UrlHandlers/ItemIconHandler.cs@ 505

Last change on this file since 505 was 505, checked in by alloc, 4 days ago

Changed: Load item icons in a coroutine to reduce time needed to get server in a connectable state
Fixed: WebAPI "Player" returns player levels again

File size: 6.2 KB
Line 
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.IO;
5using System.Net;
6using UnityEngine;
7using Object = UnityEngine.Object;
8
9namespace Webserver.UrlHandlers {
10 public class ItemIconHandler : AbsHandler {
11 private readonly Dictionary<string, byte[]> icons = new Dictionary<string, byte[]> ();
12 private readonly bool logMissingFiles;
13
14 private bool loaded;
15
16 static ItemIconHandler () {
17 Instance = null;
18 }
19
20 public ItemIconHandler (bool _logMissingFiles, string _moduleName = null) : base (_moduleName) {
21 logMissingFiles = _logMissingFiles;
22 Instance = this;
23 }
24
25 public static ItemIconHandler Instance { get; private set; }
26
27 public override void HandleRequest (RequestContext _context) {
28 if (!loaded) {
29 _context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
30 Log.Out ("[Web] IconHandler: Icons not loaded");
31 return;
32 }
33
34 if (!_context.RequestPath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {
35 _context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
36 return;
37 }
38
39 string requestFileName = _context.RequestPath.Remove (0, urlBasePath.Length);
40 int indexOfExtSep = requestFileName.LastIndexOf ('.');
41 if (indexOfExtSep < 0) {
42 _context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
43 return;
44 }
45
46 requestFileName = requestFileName.Remove (indexOfExtSep);
47
48 if (!icons.TryGetValue (requestFileName, out byte[] icon)) {
49 _context.Response.StatusCode = (int)HttpStatusCode.NotFound;
50 if (logMissingFiles) {
51 Log.Out ($"[Web] IconHandler: FileNotFound: \"{_context.RequestPath}\" ");
52 }
53 return;
54 }
55
56 _context.Response.ContentType = MimeType.GetMimeType (".png");
57
58 _context.Response.ContentLength64 = icon.Length;
59 _context.Response.OutputStream.Write (icon, 0, icon.Length);
60 }
61
62 private class LoadingStats {
63 public int Files;
64 public int Tints;
65 public readonly MicroStopwatch MswTotal = new MicroStopwatch (false);
66 public readonly MicroStopwatch MswLoading = new MicroStopwatch (false);
67 public readonly MicroStopwatch MswEncoding = new MicroStopwatch (false);
68 public readonly MicroStopwatch MswTinting = new MicroStopwatch (false);
69 }
70
71 private const int LoadingMaxMsPerFrame = 100;
72 private bool loading;
73 public IEnumerator LoadIcons () {
74
75 lock (icons) {
76 if (loading || loaded) {
77 yield break;
78 }
79
80 loading = true;
81
82 MicroStopwatch mswPerFrame = new MicroStopwatch (true);
83
84 LoadingStats stats = new LoadingStats ();
85 stats?.MswTotal.Start ();
86
87 // Get list of used tints for all items
88 Dictionary<string, List<Color>> tintedIcons = new Dictionary<string, List<Color>> ();
89 foreach (ItemClass ic in ItemClass.list) {
90 if (ic == null) {
91 continue;
92 }
93
94 Color tintColor = ic.GetIconTint ();
95 if (tintColor == Color.white) {
96 continue;
97 }
98
99 string name = ic.GetIconName ();
100 if (!tintedIcons.TryGetValue (name, out List<Color> tintsList)) {
101 tintsList = new List<Color> ();
102 tintedIcons.Add (name, tintsList);
103 }
104
105 tintsList.Add (tintColor);
106 }
107
108 yield return loadIconsFromFolder (GameIO.GetGameDir ("Data/ItemIcons"), tintedIcons, stats, mswPerFrame);
109
110 // Load icons from mods
111 foreach (Mod mod in ModManager.GetLoadedMods ()) {
112 string modIconsPath = $"{mod.Path}/ItemIcons";
113 yield return loadIconsFromFolder (modIconsPath, tintedIcons, stats, mswPerFrame);
114 }
115
116 loaded = true;
117
118 if (stats == null) {
119 Log.Out ($"[Web] IconHandler: Loaded {icons.Count} icons");
120 } else {
121 stats.MswTotal.Stop ();
122 Log.Out ($"[Web] IconHandler: Loaded {icons.Count} icons ({stats.Files} source images with {stats.Tints} tints applied)");
123 Log.Out ($"[Web] IconHandler: Total time {stats.MswTotal.ElapsedMilliseconds} ms, loading files {stats.MswLoading.ElapsedMilliseconds} ms, tinting files {stats.MswTinting.ElapsedMilliseconds} ms, encoding files {stats.MswEncoding.ElapsedMilliseconds} ms");
124
125 int totalSize = 0;
126 foreach ((string _, byte[] iconData) in icons) {
127 totalSize += iconData.Length;
128 }
129
130 Log.Out ($"[Web] IconHandler: Cached {totalSize / 1024} KiB");
131 }
132 }
133 }
134
135 private IEnumerator loadIconsFromFolder (string _path, Dictionary<string, List<Color>> _tintedIcons, LoadingStats _stats,
136 MicroStopwatch _mswPerFrame) {
137 if (!Directory.Exists (_path)) {
138 yield break;
139 }
140
141 _mswPerFrame.ResetAndRestart ();
142
143 foreach (string file in Directory.GetFiles (_path)) {
144 try {
145 if (!file.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {
146 continue;
147 }
148
149 string name = Path.GetFileNameWithoutExtension (file);
150 Texture2D tex = new Texture2D (1, 1, TextureFormat.ARGB32, false);
151
152 _stats?.MswLoading.Start ();
153 byte[] sourceBytes = File.ReadAllBytes (file);
154 if (!tex.LoadImage (sourceBytes)) {
155 _stats?.MswLoading.Stop ();
156 continue;
157 }
158 _stats?.MswLoading.Stop ();
159
160 AddIcon (name, sourceBytes, tex, _tintedIcons, _stats);
161
162 Object.Destroy (tex);
163 } catch (Exception e) {
164 Log.Error ($"[Web] Failed loading icon from {_path}");
165 Log.Exception (e);
166 }
167
168 if (_mswPerFrame.ElapsedMilliseconds >= LoadingMaxMsPerFrame) {
169 yield return null;
170 _mswPerFrame.ResetAndRestart ();
171 }
172 }
173 }
174
175 private void AddIcon (string _name, byte[] _sourceBytes, Texture2D _tex, Dictionary<string, List<Color>> _tintedIcons, LoadingStats _stats) {
176 _stats?.MswEncoding.Start ();
177 icons [$"{_name}__FFFFFF"] = _sourceBytes;
178 _stats?.MswEncoding.Stop ();
179
180 if (_stats != null) {
181 _stats.Files++;
182 }
183
184 if (!_tintedIcons.TryGetValue (_name, out List<Color> tintsList)) {
185 return;
186 }
187
188 foreach (Color c in tintsList) {
189 string tintedName = $"{_name}__{c.ToHexCode ()}";
190 if (icons.ContainsKey (tintedName)) {
191 continue;
192 }
193
194 Texture2D tintedTex = new Texture2D (_tex.width, _tex.height, TextureFormat.ARGB32, false);
195
196 _stats?.MswTinting.Start ();
197 TextureUtils.ApplyTint (_tex, tintedTex, c);
198 _stats?.MswTinting.Stop ();
199
200 _stats?.MswEncoding.Start ();
201 icons [tintedName] = tintedTex.EncodeToPNG ();
202 _stats?.MswEncoding.Stop ();
203
204 Object.Destroy (tintedTex);
205
206 if (_stats != null) {
207 _stats.Tints++;
208 }
209 }
210 }
211
212 }
213}
Note: See TracBrowser for help on using the repository browser.