/
Program.cs
313 lines (255 loc) · 10.5 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// Copyright (C) Ethan Shaw
// This program is licensed under the MIT License.
// See the accompanying LICENSE file for more information.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Drawing.Imaging;
using System.Linq;
using System.Net;
namespace AvatarGetter
{
interface Avatar
{
void DrawToSpritesheet(Image<Rgba32> spriteSheet, int x, int y);
int TeamNumber { get; }
}
class Base64Avatar : Avatar
{
byte[] _Data;
public int TeamNumber { get; private set; }
public Base64Avatar(int teamNum, string base64)
{
TeamNumber = teamNum;
_Data = Convert.FromBase64String(base64);
}
public void DrawToSpritesheet(Image<Rgba32> spriteSheet, int x, int y)
{
Image<Rgba32> img;
try
{
// Just let ImageSharp detect the image codec. Don't specify that it is PNG.
// I found that when some people upload their avatars, instead of saving as
// .png, they save as a jpeg and then just change the file extension, so
// some of the avatars are actually JPEGs disguised as PNGs. Please, if you're
// reading this, upload your avatar as a PNG like FIRST tells you to, don't just
// upload a jpeg with a .png file extension.
img = Image.Load<Rgba32>(_Data);
}
catch
{
// Occasionally, ImageSharp can't handle the images (has not happened since I last updated it).
Console.WriteLine($"Failed to load avatar for {TeamNumber} with ImageSharp, decoding with System.Drawing.Common");
using MemoryStream input = new MemoryStream();
using MemoryStream output = new MemoryStream();
input.Write(_Data, 0, _Data.Length);
input.Position = 0;
System.Drawing.Image.FromStream(input).Save(output, ImageFormat.Bmp);
output.Position = 0;
img = Image.Load<Rgba32>(output);
}
spriteSheet.Mutate(sheet =>
sheet.DrawImage(
img,
new Point(x, y),
1
)
);
img.Dispose();
}
}
class SpriteAvatar : Avatar
{
public int TeamNumber { get; private set; }
private Image<Rgba32> _Sheet;
Loc _Loc;
public SpriteAvatar(int teamNum, Image<Rgba32> spriteSheet, Loc loc)
{
TeamNumber = teamNum;
_Sheet = spriteSheet;
_Loc = loc;
}
public void DrawToSpritesheet(Image<Rgba32> spriteSheet, int x, int y)
{
using Image<Rgba32> avatar = _Sheet.Clone();
avatar.Mutate(oldSheet =>
oldSheet.Crop(new Rectangle(_Loc.x, _Loc.y, Program.AVATAR_SIZE, Program.AVATAR_SIZE))
);
spriteSheet.Mutate(sheet =>
sheet.DrawImage(
avatar,
new Point(x, y),
1
)
);
}
}
// A team from teams.json
class Team
{
public int team_number;
public double lat;
public double lng;
}
// Represents the information in avatars.json
class AvatarInfo
{
public int sheet_size;
public Dictionary<int, Loc> locations;
public AvatarInfo(int sheetSize)
{
sheet_size = sheetSize;
locations = new Dictionary<int, Loc>();
}
}
// Location of a team's avatar in the sprite sheet
struct Loc
{
public int x;
public int y;
public Loc(int xIn, int yIn)
{
x = xIn;
y = yIn;
}
}
class Program
{
private static readonly HttpClient _Client = new HttpClient();
private static HashSet<int> _ValidTeams;
// All FRC avatars are 40x40.
public const int AVATAR_SIZE = 40;
// Each sprite has a 2 pixel border between it and the next sprite
// so that when the whole sprite sheet is resized the avatars
// do not bleed into each other. Otherwise borders appear on some
// avatars on certain displays.
public const int AVATAR_BORDER = 2;
static async Task<List<Avatar>> DownloadAvatars()
{
Console.WriteLine("Downloading avatars from the FRC API (https://frc-events.firstinspires.org/services/API)");
string FRC_API_KEY = Convert.ToBase64String(File.ReadAllBytes("FRC_API_KEY"));
string YEAR;
// YEAR file can be used to specify the year to get avatars for
if (File.Exists("YEAR"))
{
YEAR = File.ReadAllText("YEAR").Trim();
}
else
{
Console.WriteLine("YEAR file does not exist, getting year from DateTime.");
YEAR = DateTime.Now.Year.ToString();
}
_Client.DefaultRequestHeaders.Add("Authorization", "Basic " + FRC_API_KEY);
_Client.DefaultRequestHeaders.Add("Accept", "application/json");
int page = 1;
int pageTotal = 99;
List<Avatar> avatars = new List<Avatar>();
while (page <= pageTotal)
{
HttpResponseMessage msg = await _Client.GetAsync("https://frc-api.firstinspires.org/v2.0/" + YEAR + "/avatars?page=" + page.ToString());
if (msg.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Error: Attempt to access FRC API resulted in a 401 Unauthorized!");
}
string jsonStr = await msg.Content.ReadAsStringAsync();
JObject obj = JObject.Parse(jsonStr);
JArray teams = (JArray)obj["teams"];
foreach (JObject team in teams)
{
int teamNum = team.Value<int>("teamNumber");
if (_ValidTeams.Contains(teamNum))
{
if (team.TryGetValue("encodedAvatar", out JToken avatar))
{
string base64 = avatar.Value<string>();
if (!string.IsNullOrEmpty(base64))
{
_ValidTeams.Remove(teamNum);
avatars.Add(new Base64Avatar(teamNum, base64));
}
}
}
}
pageTotal = obj.Value<int>("pageTotal");
Console.WriteLine($"Downloaded page {page}/{pageTotal}");
page++;
}
return avatars;
}
private static async Task GetAllAvatars(string dataFolder)
{
// Get a list of all the teams on the map
Team[] teamData = JsonConvert.DeserializeObject<Team[]>(File.ReadAllText(
Path.Combine(dataFolder, "teams.json")));
_ValidTeams = teamData.Select(team => team.team_number).ToHashSet();
// Download all of the current avatars
List<Avatar> avatars = await DownloadAvatars();
string oldAvatarsDataFile = Path.Combine(dataFolder, "avatars.json");
string oldAvatarsSheetFile = Path.Combine(dataFolder, "avatars.png");
// Load all the old avatars
if (!File.Exists(oldAvatarsDataFile) || !File.Exists(oldAvatarsSheetFile))
{
Console.WriteLine("Warning: old avatars.json or avatars.png not found in data folder.");
Console.WriteLine("Skipping import of old avatars.");
}
else
{
AvatarInfo oldAvatars = JsonConvert.DeserializeObject<AvatarInfo>(File.ReadAllText(oldAvatarsDataFile));
Image<Rgba32> oldSheet = Image.Load<Rgba32>(oldAvatarsSheetFile);
foreach (KeyValuePair<int, Loc> teamLocPair in oldAvatars.locations)
{
// Only include avatars that do not have new avatars downloaded
if (_ValidTeams.Contains(teamLocPair.Key))
{
_ValidTeams.Remove(teamLocPair.Key);
avatars.Add(new SpriteAvatar(teamLocPair.Key, oldSheet, teamLocPair.Value));
}
if (_ValidTeams.Count == 0)
break;
}
}
int sheetSize = (int)Math.Ceiling(Math.Sqrt(avatars.Count));
Image<Rgba32> sheet = new Image<Rgba32>(sheetSize * (AVATAR_SIZE + AVATAR_BORDER), sheetSize * (AVATAR_SIZE + AVATAR_BORDER));
// The (new) avatar locations in the spritesheet
AvatarInfo avatarInfo = new AvatarInfo(sheetSize);
Console.WriteLine("Stitching " + avatars.Count + " avatars...");
for (int i = 0; i < avatars.Count; i++)
{
Avatar avatar = avatars[i];
int x = (i % sheetSize) * (AVATAR_SIZE + AVATAR_BORDER);
int y = (i / sheetSize) * (AVATAR_SIZE + AVATAR_BORDER);
avatar.DrawToSpritesheet(sheet, x, y);
avatarInfo.locations.Add(avatar.TeamNumber, new Loc(x, y));
}
Console.WriteLine("Saving...");
using (StreamWriter sw = new StreamWriter(File.Open("avatars.json", FileMode.Create)))
sw.Write(JsonConvert.SerializeObject(avatarInfo));
using (FileStream fs = File.Open("avatars.png", FileMode.Create))
sheet.SaveAsPng(fs);
Console.WriteLine("Done!");
}
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Error: wrong number of arguments: " + args.Length);
Console.WriteLine("Usage: AvatarGetter [firstmap data directory]");
Console.WriteLine("Generates a spritesheet from images that are all the same size and are square.");
return;
}
if (!Directory.Exists(args[0]))
{
Console.WriteLine("Error: data directory " + args[0] + " does not exist!");
return;
}
GetAllAvatars(args[0]).Wait();
}
}
}