Utils.java 13.1 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.utils;

KingRainbow44's avatar
KingRainbow44 committed
3
import java.io.*;
4
import java.nio.charset.StandardCharsets;
KingRainbow44's avatar
KingRainbow44 committed
5
6
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
Kengxxiao's avatar
Kengxxiao committed
7
8
import java.time.*;
import java.time.temporal.TemporalAdjusters;
9
import java.util.*;
GanyusLeftHorn's avatar
GanyusLeftHorn committed
10
import java.util.concurrent.ThreadLocalRandom;
Melledy's avatar
Melledy committed
11
12

import emu.grasscutter.Grasscutter;
13
import emu.grasscutter.config.ConfigContainer;
14
import emu.grasscutter.data.DataLoader;
Melledy's avatar
Melledy committed
15
16
17
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
AnimeGitB's avatar
AnimeGitB committed
18
19
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
Melledy's avatar
Melledy committed
20

KingRainbow44's avatar
KingRainbow44 committed
21
import org.slf4j.Logger;
Melledy's avatar
Melledy committed
22

KingRainbow44's avatar
KingRainbow44 committed
23
24
import javax.annotation.Nullable;

25
26
import static emu.grasscutter.utils.Language.translate;

KingRainbow44's avatar
KingRainbow44 committed
27
28
@SuppressWarnings({"UnusedReturnValue", "BooleanMethodIsAlwaysInverted"})
public final class Utils {
Melledy's avatar
Melledy committed
29
	public static final Random random = new Random();
KingRainbow44's avatar
KingRainbow44 committed
30

Melledy's avatar
Melledy committed
31
32
33
	public static int randomRange(int min, int max) {
		return random.nextInt(max - min + 1) + min;
	}
KingRainbow44's avatar
KingRainbow44 committed
34

Melledy's avatar
Melledy committed
35
36
37
	public static float randomFloatRange(float min, float max) {
		return random.nextFloat() * (max - min) + min;
	}
KingRainbow44's avatar
KingRainbow44 committed
38

Melledy's avatar
Melledy committed
39
40
41
	public static double getDist(Position pos1, Position pos2) {
		double xs = pos1.getX() - pos2.getX();
		xs = xs * xs;
KingRainbow44's avatar
KingRainbow44 committed
42

Melledy's avatar
Melledy committed
43
44
45
46
47
48
49
50
51
		double ys = pos1.getY() - pos2.getY();
		ys = ys * ys;

		double zs = pos1.getZ() - pos2.getZ();
		zs = zs * zs;

		return Math.sqrt(xs + zs + ys);
	}

Melledy's avatar
Melledy committed
52
53
54
	public static int getCurrentSeconds() {
		return (int) (System.currentTimeMillis() / 1000.0);
	}
KingRainbow44's avatar
KingRainbow44 committed
55

Melledy's avatar
Melledy committed
56
57
58
59
60
	public static String lowerCaseFirstChar(String s) {
		StringBuilder sb = new StringBuilder(s);
		sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
		return sb.toString();
	}
KingRainbow44's avatar
KingRainbow44 committed
61

Melledy's avatar
Melledy committed
62
63
64
65
	public static String toString(InputStream inputStream) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(inputStream);
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		for (int result = bis.read(); result != -1; result = bis.read()) {
GanyusLeftHorn's avatar
GanyusLeftHorn committed
66
			buf.write((byte) result);
Melledy's avatar
Melledy committed
67
68
69
		}
		return buf.toString();
	}
KingRainbow44's avatar
KingRainbow44 committed
70

Melledy's avatar
Melledy committed
71
72
73
74
75
	public static void logByteArray(byte[] array) {
		ByteBuf b = Unpooled.wrappedBuffer(array);
		Grasscutter.getLogger().info("\n" + ByteBufUtil.prettyHexDump(b));
		b.release();
	}
KingRainbow44's avatar
KingRainbow44 committed
76

Melledy's avatar
Melledy committed
77
78
	private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
	public static String bytesToHex(byte[] bytes) {
Melledy's avatar
Melledy committed
79
		if (bytes == null) return "";
GanyusLeftHorn's avatar
GanyusLeftHorn committed
80
81
82
83
84
85
86
		char[] hexChars = new char[bytes.length * 2];
		for (int j = 0; j < bytes.length; j++) {
			int v = bytes[j] & 0xFF;
			hexChars[j * 2] = HEX_ARRAY[v >>> 4];
			hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
		}
		return new String(hexChars);
Melledy's avatar
Melledy committed
87
	}
KingRainbow44's avatar
KingRainbow44 committed
88

Melledy's avatar
Melledy committed
89
	public static String bytesToHex(ByteBuf buf) {
GanyusLeftHorn's avatar
GanyusLeftHorn committed
90
		return bytesToHex(byteBufToArray(buf));
Melledy's avatar
Melledy committed
91
	}
KingRainbow44's avatar
KingRainbow44 committed
92

Melledy's avatar
Melledy committed
93
94
95
96
97
	public static byte[] byteBufToArray(ByteBuf buf) {
		byte[] bytes = new byte[buf.capacity()];
		buf.getBytes(0, bytes);
		return bytes;
	}
KingRainbow44's avatar
KingRainbow44 committed
98

Melledy's avatar
Melledy committed
99
100
101
	public static int abilityHash(String str) {
		int v7 = 0;
		int v8 = 0;
GanyusLeftHorn's avatar
GanyusLeftHorn committed
102
103
104
105
		while (v8 < str.length()) {
			v7 = str.charAt(v8++) + 131 * v7;
		}
		return v7;
Melledy's avatar
Melledy committed
106
	}
KingRainbow44's avatar
KingRainbow44 committed
107

Melledy's avatar
Melledy committed
108
109
110
111
112
113
114
115
116
	/**
	 * Creates a string with the path to a file.
	 * @param path The path to the file.
	 * @return A path using the operating system's file separator.
	 */
	public static String toFilePath(String path) {
		return path.replace("/", File.separator);
	}

KingRainbow44's avatar
KingRainbow44 committed
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
	/**
	 * Checks if a file exists on the file system.
	 * @param path The path to the file.
	 * @return True if the file exists, false otherwise.
	 */
	public static boolean fileExists(String path) {
		return new File(path).exists();
	}

	/**
	 * Creates a folder on the file system.
	 * @param path The path to the folder.
	 * @return True if the folder was created, false otherwise.
	 */
	public static boolean createFolder(String path) {
		return new File(path).mkdirs();
	}

	/**
	 * Copies a file from the archive's resources to the file system.
	 * @param resource The path to the resource.
	 * @param destination The path to copy the resource to.
	 * @return True if the file was copied, false otherwise.
	 */
	public static boolean copyFromResources(String resource, String destination) {
		try (InputStream stream = Grasscutter.class.getResourceAsStream(resource)) {
			if(stream == null) {
				Grasscutter.getLogger().warn("Could not find resource: " + resource);
				return false;
			}

			Files.copy(stream, new File(destination).toPath(), StandardCopyOption.REPLACE_EXISTING);
			return true;
KingRainbow44's avatar
KingRainbow44 committed
150
151
		} catch (Exception exception) {
			Grasscutter.getLogger().warn("Unable to copy resource " + resource + " to " + destination, exception);
KingRainbow44's avatar
KingRainbow44 committed
152
153
154
155
			return false;
		}
	}

KingRainbow44's avatar
KingRainbow44 committed
156
157
158
159
160
161
162
163
	/**
	 * Logs an object to the console.
	 * @param object The object to log.
	 */
	public static void logObject(Object object) {
		String asJson = Grasscutter.getGsonFactory().toJson(object);
		Grasscutter.getLogger().info(asJson);
	}
KingRainbow44's avatar
KingRainbow44 committed
164

KingRainbow44's avatar
KingRainbow44 committed
165
166
167
168
	/**
	 * Checks for required files and folders before startup.
	 */
	public static void startupCheck() {
169
		ConfigContainer config = Grasscutter.getConfig();
KingRainbow44's avatar
KingRainbow44 committed
170
171
172
		Logger logger = Grasscutter.getLogger();
		boolean exit = false;

173
174
		String resourcesFolder = config.folderStructure.resources;
		String dataFolder = config.folderStructure.data;
KingRainbow44's avatar
KingRainbow44 committed
175
176
177

		// Check for resources folder.
		if(!fileExists(resourcesFolder)) {
178
179
			logger.info(translate("messages.status.create_resources"));
			logger.info(translate("messages.status.resources_error"));
KingRainbow44's avatar
KingRainbow44 committed
180
181
182
			createFolder(resourcesFolder); exit = true;
		}

183
		// Check for BinOutput + ExcelBinOutput.
KingRainbow44's avatar
KingRainbow44 committed
184
185
		if(!fileExists(resourcesFolder + "BinOutput") ||
				!fileExists(resourcesFolder + "ExcelBinOutput")) {
186
			logger.info(translate("messages.status.resources_error"));
KingRainbow44's avatar
KingRainbow44 committed
187
188
189
190
191
192
193
			exit = true;
		}

		// Check for game data.
		if(!fileExists(dataFolder))
			createFolder(dataFolder);

194
		// Make sure the data folder is populated, if there are any missing files copy them from resources
195
		DataLoader.checkAllFiles();
196

KingRainbow44's avatar
KingRainbow44 committed
197
198
		if(exit) System.exit(1);
	}
Kengxxiao's avatar
Kengxxiao committed
199

200
201
202
203
204
	/**
	 * Gets the timestamp of the next hour.
	 * @return The timestamp in UNIX seconds.
	 */
	public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
Kengxxiao's avatar
Kengxxiao committed
205
206
207
208
209
210
211
212
		ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
		for (int i = 0; i < param; i ++){
			if (zonedDateTime.getHour() < hour) {
				zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
			} else {
				zonedDateTime = zonedDateTime.plusDays(1).withHour(hour).withMinute(0).withSecond(0);
			}
		}
213
		return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
Kengxxiao's avatar
Kengxxiao committed
214
215
	}

216
217
218
219
220
	/**
	 * Gets the timestamp of the next hour in a week.
	 * @return The timestamp in UNIX seconds.
	 */
	public static int getNextTimestampOfThisHourInNextWeek(int hour, String timeZone, int param) {
Kengxxiao's avatar
Kengxxiao committed
221
222
223
224
225
226
227
228
		ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
		for (int i = 0; i < param; i++) {
			if (zonedDateTime.getDayOfWeek() == DayOfWeek.MONDAY && zonedDateTime.getHour() < hour) {
				zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
			} else {
				zonedDateTime = zonedDateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).withHour(hour).withMinute(0).withSecond(0);
			}
		}
229
		return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
Kengxxiao's avatar
Kengxxiao committed
230
231
	}

232
233
234
235
236
	/**
	 * Gets the timestamp of the next hour in a month.
	 * @return The timestamp in UNIX seconds.
	 */
	public static int getNextTimestampOfThisHourInNextMonth(int hour, String timeZone, int param) {
Kengxxiao's avatar
Kengxxiao committed
237
238
239
240
241
242
243
244
		ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone));
		for (int i = 0; i < param; i++) {
			if (zonedDateTime.getDayOfMonth() == 1 && zonedDateTime.getHour() < hour) {
				zonedDateTime = ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
			} else {
				zonedDateTime = zonedDateTime.with(TemporalAdjusters.firstDayOfNextMonth()).withHour(hour).withMinute(0).withSecond(0);
			}
		}
245
246
247
248
249
250
251
252
		return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
	}

	/**
	 * Retrieves a string from an input stream.
	 * @param stream The input stream.
	 * @return The string.
	 */
KingRainbow44's avatar
KingRainbow44 committed
253
254
	public static String readFromInputStream(@Nullable InputStream stream) {
		if(stream == null) return "empty";
KingRainbow44's avatar
KingRainbow44 committed
255

256
		StringBuilder stringBuilder = new StringBuilder();
257
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
258
259
260
261
262
			String line; while ((line = reader.readLine()) != null) {
				stringBuilder.append(line);
			} stream.close();
		} catch (IOException e) {
			Grasscutter.getLogger().warn("Failed to read from input stream.");
KingRainbow44's avatar
KingRainbow44 committed
263
264
		} catch (NullPointerException ignored) {
			return "empty";
265
		} return stringBuilder.toString();
Kengxxiao's avatar
Kengxxiao committed
266
	}
KingRainbow44's avatar
KingRainbow44 committed
267

AnimeGitB's avatar
AnimeGitB committed
268
269
	/**
	 * Performs a linear interpolation using a table of fixed points to create an effective piecewise f(x) = y function.
KingRainbow44's avatar
KingRainbow44 committed
270
	 * @param x The x value.
AnimeGitB's avatar
AnimeGitB committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
	 * @param xyArray Array of points in [[x0,y0], ... [xN, yN]] format
	 * @return f(x) = y
	 */
	public static int lerp(int x, int[][] xyArray) {
		try {
			if (x <= xyArray[0][0]){  // Clamp to first point
				return xyArray[0][1];
			} else if (x >= xyArray[xyArray.length-1][0]) {  // Clamp to last point
				return xyArray[xyArray.length-1][1];
			}
			// At this point we're guaranteed to have two lerp points, and pity be somewhere between them.
			for (int i=0; i < xyArray.length-1; i++) {
				if (x == xyArray[i+1][0]) {
					return xyArray[i+1][1];
				}
				if (x < xyArray[i+1][0]) {
					// We are between [i] and [i+1], interpolation time!
KingRainbow44's avatar
KingRainbow44 committed
288
					// Using floats would be slightly cleaner but we can just as easily use ints if we're careful with order of operations.
AnimeGitB's avatar
AnimeGitB committed
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
					int position = x - xyArray[i][0];
					int fullDist = xyArray[i+1][0] - xyArray[i][0];
					int prevValue = xyArray[i][1];
					int fullDelta = xyArray[i+1][1] - prevValue;
					return prevValue + ( (position * fullDelta) / fullDist );
				}
			}
		} catch (IndexOutOfBoundsException e) {
			Grasscutter.getLogger().error("Malformed lerp point array. Must be of form [[x0, y0], ..., [xN, yN]].");
		}
		return 0;
	}

	/**
	 * Checks if an int is in an int[]
	 * @param key int to look for
	 * @param array int[] to look in
	 * @return key in array
	 */
	public static boolean intInArray(int key, int[] array) {
		for (int i : array) {
			if (i == key) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Return a copy of minuend without any elements found in subtrahend.
	 * @param minuend The array we want elements from
	 * @param subtrahend The array whose elements we don't want
	 * @return The array with only the elements we want, in the order that minuend had them
	 */
	public static int[] setSubtract(int[] minuend, int[] subtrahend) {
		IntList temp = new IntArrayList();
		for (int i : minuend) {
			if (!intInArray(i, subtrahend)) {
				temp.add(i);
			}
		}
		return temp.toIntArray();
	}
332

Secretboy-SMR's avatar
Secretboy-SMR committed
333
	/**
334
335
336
	 * Gets the language code from a given locale.
	 * @param locale A locale.
	 * @return A string in the format of 'XX-XX'.
Secretboy-SMR's avatar
Secretboy-SMR committed
337
	 */
338
339
340
	public static String getLanguageCode(Locale locale) {
		return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
	}
Secretboy-SMR's avatar
Secretboy-SMR committed
341

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
	/**
	 * Base64 encodes a given byte array.
	 * @param toEncode An array of bytes.
	 * @return A base64 encoded string.
	 */
	public static String base64Encode(byte[] toEncode) {
		return Base64.getEncoder().encodeToString(toEncode);
	}

	/**
	 * Base64 decodes a given string.
	 * @param toDecode A base64 encoded string.
	 * @return An array of bytes.
	 */
	public static byte[] base64Decode(String toDecode) {
		return Base64.getDecoder().decode(toDecode);
	}

	/**
	 * Safely JSON decodes a given string.
	 * @param jsonData The JSON-encoded data.
	 * @return JSON decoded data, or null if an exception occurred.
	 */
	public static <T> T jsonDecode(String jsonData, Class<T> classType) {
		try {
			return Grasscutter.getGsonFactory().fromJson(jsonData, classType);
		} catch (Exception ignored) {
			return null;
		}
	}
GanyusLeftHorn's avatar
GanyusLeftHorn committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

	/***
	 * Draws a random element from the given list, following the given probability distribution, if given.
	 * @param list The list from which to draw the element.
	 * @param probabilities The probability distribution. This is given as a list of probabilities of the same length it `list`.
	 * @return A randomly drawn element from the given list.
	 */
	public static <T> T drawRandomListElement(List<T> list, List<Integer> probabilities) {
		// If we don't have a probability distribution, or the size of the distribution does not match
		// the size of the list, we assume uniform distribution.
		if (probabilities == null || probabilities.size() <= 1 || probabilities.size() != list.size()) {
			int index = ThreadLocalRandom.current().nextInt(0, list.size());
			return list.get(index);
		}

		// Otherwise, we roll with the given distribution.
		int totalProbabilityMass = probabilities.stream().reduce(Integer::sum).get();
		int roll = ThreadLocalRandom.current().nextInt(1, totalProbabilityMass + 1);

		int currentTotalChance = 0;
		for (int i = 0; i < list.size(); i++) {
			currentTotalChance += probabilities.get(i);

			if (roll <= currentTotalChance) {
				return list.get(i);
			}
		}

		// Should never happen.
		return list.get(0);
	}
403
404
405
406
407
408
409
410
411

	/***
	 * Draws a random element from the given list, following a uniform probability distribution.
	 * @param list The list from which to draw the element.
	 * @return A randomly drawn element from the given list.
	 */
	public static <T> T drawRandomListElement(List<T> list) {
		return drawRandomListElement(list, null);
	}
Melledy's avatar
Melledy committed
412
}