mirror of
https://github.com/Grasscutters/Grasscutter.git
synced 2025-12-19 18:34:49 +01:00
Run Spotless on src/main
This commit is contained in:
@@ -1,75 +1,77 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class Crypto {
|
||||
private static final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
public static byte[] DISPATCH_KEY;
|
||||
public static byte[] DISPATCH_SEED;
|
||||
|
||||
public static byte[] ENCRYPT_KEY;
|
||||
public static long ENCRYPT_SEED = Long.parseUnsignedLong("11468049314633205968");
|
||||
public static byte[] ENCRYPT_SEED_BUFFER = new byte[0];
|
||||
|
||||
public static PrivateKey CUR_SIGNING_KEY;
|
||||
|
||||
public static Map<Integer, PublicKey> EncryptionKeys = new HashMap<>();
|
||||
|
||||
public static void loadKeys() {
|
||||
DISPATCH_KEY = FileUtils.readResource("/keys/dispatchKey.bin");
|
||||
DISPATCH_SEED = FileUtils.readResource("/keys/dispatchSeed.bin");
|
||||
|
||||
ENCRYPT_KEY = FileUtils.readResource("/keys/secretKey.bin");
|
||||
ENCRYPT_SEED_BUFFER = FileUtils.readResource("/keys/secretKeyBuffer.bin");
|
||||
|
||||
try {
|
||||
CUR_SIGNING_KEY = KeyFactory.getInstance("RSA")
|
||||
.generatePrivate(new PKCS8EncodedKeySpec(FileUtils.readResource("/keys/SigningKey.der")));
|
||||
|
||||
Pattern pattern = Pattern.compile("([0-9]*)_Pub\\.der");
|
||||
for (Path path : FileUtils.getPathsFromResource("/keys/game_keys")) {
|
||||
if (path.toString().endsWith("_Pub.der")) {
|
||||
|
||||
var m = pattern.matcher(path.getFileName().toString());
|
||||
|
||||
if (m.matches()) {
|
||||
var key = KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(FileUtils.read(path)));
|
||||
|
||||
EncryptionKeys.put(Integer.valueOf(m.group(1)), key);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("An error occurred while loading keys.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void xor(byte[] packet, byte[] key) {
|
||||
try {
|
||||
for (int i = 0; i < packet.length; i++) {
|
||||
packet[i] ^= key[i % key.length];
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("Crypto error.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] createSessionKey(int length) {
|
||||
byte[] bytes = new byte[length];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class Crypto {
|
||||
private static final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
public static byte[] DISPATCH_KEY;
|
||||
public static byte[] DISPATCH_SEED;
|
||||
|
||||
public static byte[] ENCRYPT_KEY;
|
||||
public static long ENCRYPT_SEED = Long.parseUnsignedLong("11468049314633205968");
|
||||
public static byte[] ENCRYPT_SEED_BUFFER = new byte[0];
|
||||
|
||||
public static PrivateKey CUR_SIGNING_KEY;
|
||||
|
||||
public static Map<Integer, PublicKey> EncryptionKeys = new HashMap<>();
|
||||
|
||||
public static void loadKeys() {
|
||||
DISPATCH_KEY = FileUtils.readResource("/keys/dispatchKey.bin");
|
||||
DISPATCH_SEED = FileUtils.readResource("/keys/dispatchSeed.bin");
|
||||
|
||||
ENCRYPT_KEY = FileUtils.readResource("/keys/secretKey.bin");
|
||||
ENCRYPT_SEED_BUFFER = FileUtils.readResource("/keys/secretKeyBuffer.bin");
|
||||
|
||||
try {
|
||||
CUR_SIGNING_KEY =
|
||||
KeyFactory.getInstance("RSA")
|
||||
.generatePrivate(
|
||||
new PKCS8EncodedKeySpec(FileUtils.readResource("/keys/SigningKey.der")));
|
||||
|
||||
Pattern pattern = Pattern.compile("([0-9]*)_Pub\\.der");
|
||||
for (Path path : FileUtils.getPathsFromResource("/keys/game_keys")) {
|
||||
if (path.toString().endsWith("_Pub.der")) {
|
||||
|
||||
var m = pattern.matcher(path.getFileName().toString());
|
||||
|
||||
if (m.matches()) {
|
||||
var key =
|
||||
KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(FileUtils.read(path)));
|
||||
|
||||
EncryptionKeys.put(Integer.valueOf(m.group(1)), key);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("An error occurred while loading keys.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void xor(byte[] packet, byte[] key) {
|
||||
try {
|
||||
for (int i = 0; i < packet.length; i++) {
|
||||
packet[i] ^= key[i % key.length];
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("Crypto error.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] createSessionKey(int length) {
|
||||
byte[] bytes = new byte[length];
|
||||
secureRandom.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public final class DateHelper {
|
||||
public static Date onlyYearMonthDay(Date now) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(now);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static int getUnixTime(Date localDateTime) {
|
||||
return (int) (localDateTime.getTime() / 1000L);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public final class DateHelper {
|
||||
public static Date onlyYearMonthDay(Date now) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(now);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static int getUnixTime(Date localDateTime) {
|
||||
return (int) (localDateTime.getTime() / 1000L);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,250 +1,265 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import lombok.val;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public final class FileUtils {
|
||||
private static final Path DATA_DEFAULT_PATH;
|
||||
private static final Path DATA_USER_PATH = Path.of(Grasscutter.config.folderStructure.data);
|
||||
private static final Path PACKETS_PATH = Path.of(Grasscutter.config.folderStructure.packets);
|
||||
private static final Path PLUGINS_PATH = Path.of(Grasscutter.config.folderStructure.plugins);
|
||||
private static final Path RESOURCES_PATH;
|
||||
private static final Path SCRIPTS_PATH;
|
||||
private static final String[] TSJ_JSON_TSV = {"tsj", "json", "tsv"};
|
||||
|
||||
static {
|
||||
FileSystem fs = null;
|
||||
Path path = null;
|
||||
// Setup access to jar resources
|
||||
try {
|
||||
var uri = Grasscutter.class.getResource("/defaults/data").toURI();
|
||||
switch (uri.getScheme()) {
|
||||
case "jar": // When running normally, as a jar
|
||||
case "zip": // Honestly I have no idea what setup would result in this, but this should work regardless
|
||||
fs = FileSystems.newFileSystem(uri, Map.of()); // Have to mount zip filesystem. This leaks, but we want to keep it forever anyway.
|
||||
// Fall-through
|
||||
case "file": // When running in an IDE
|
||||
path = Path.of(uri); // Can access directly
|
||||
break;
|
||||
default:
|
||||
Grasscutter.getLogger().error("Invalid URI scheme for class resources: " + uri.getScheme());
|
||||
break;
|
||||
}
|
||||
} catch (URISyntaxException | IOException e) {
|
||||
// Failed to load this jar. How?
|
||||
Grasscutter.getLogger().error("Failed to load jar?!");
|
||||
} finally {
|
||||
DATA_DEFAULT_PATH = path;
|
||||
Grasscutter.getLogger().debug("Setting path for default data: " + path.toAbsolutePath());
|
||||
}
|
||||
|
||||
// Setup Resources path
|
||||
final String resources = Grasscutter.config.folderStructure.resources;
|
||||
fs = null;
|
||||
path = Path.of(resources);
|
||||
if (resources.endsWith(".zip")) { // Would be nice to support .tar.gz too at some point, but it doesn't come for free in Java
|
||||
try {
|
||||
fs = FileSystems.newFileSystem(path);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to load resources zip \"" + resources + "\"");
|
||||
}
|
||||
}
|
||||
|
||||
if (fs != null) {
|
||||
var root = fs.getPath("");
|
||||
try (Stream<Path> pathStream = Files.find(root, 3, (p, a) -> {
|
||||
var filename = p.getFileName();
|
||||
if (filename == null) return false;
|
||||
return filename.toString().equals("ExcelBinOutput");
|
||||
})) {
|
||||
var excelBinOutput = pathStream.findFirst();
|
||||
if (excelBinOutput.isPresent()) {
|
||||
path = excelBinOutput.get().getParent();
|
||||
if (path == null)
|
||||
path = root;
|
||||
Grasscutter.getLogger().debug("Resources will be loaded from \"" + resources + "/" + path + "\"");
|
||||
} else {
|
||||
Grasscutter.getLogger().error("Failed to find ExcelBinOutput in resources zip \"" + resources + "\"");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to scan resources zip \"" + resources + "\"");
|
||||
}
|
||||
}
|
||||
RESOURCES_PATH = path;
|
||||
|
||||
// Setup Scripts path
|
||||
final String scripts = Grasscutter.config.folderStructure.scripts;
|
||||
SCRIPTS_PATH = (scripts.startsWith("resources:"))
|
||||
? RESOURCES_PATH.resolve(scripts.substring("resources:".length()))
|
||||
: Path.of(scripts);
|
||||
}
|
||||
|
||||
/* Apply after initialization. */
|
||||
private static final Path[] DATA_PATHS = {DATA_USER_PATH, DATA_DEFAULT_PATH};
|
||||
|
||||
public static Path getDataPathTsjJsonTsv(String filename) {
|
||||
return getDataPathTsjJsonTsv(filename, true);
|
||||
}
|
||||
|
||||
public static Path getDataPathTsjJsonTsv(String filename, boolean fallback) {
|
||||
val name = getFilenameWithoutExtension(filename);
|
||||
for (val data_path : DATA_PATHS) {
|
||||
for (val ext : TSJ_JSON_TSV) {
|
||||
val path = data_path.resolve(name + "." + ext);
|
||||
if (Files.exists(path)) return path;
|
||||
}
|
||||
}
|
||||
return fallback ? DATA_USER_PATH.resolve(name + ".tsj") : null; // Maybe they want to write to a new file
|
||||
}
|
||||
|
||||
public static Path getDataPath(String path) {
|
||||
Path userPath = DATA_USER_PATH.resolve(path);
|
||||
if (Files.exists(userPath)) return userPath;
|
||||
Path defaultPath = DATA_DEFAULT_PATH.resolve(path);
|
||||
if (Files.exists(defaultPath)) return defaultPath;
|
||||
return userPath; // Maybe they want to write to a new file
|
||||
}
|
||||
|
||||
public static Path getDataUserPath(String path) {
|
||||
return DATA_USER_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getPacketPath(String path) {
|
||||
return PACKETS_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getPluginPath(String path) {
|
||||
return PLUGINS_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getResourcePath(String path) {
|
||||
return RESOURCES_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getExcelPath(String filename) {
|
||||
return getTsjJsonTsv(RESOURCES_PATH.resolve("ExcelBinOutput"), filename);
|
||||
}
|
||||
|
||||
// Gets path of a resource.
|
||||
// If multiple formats of it exist, priority is TSJ > JSON > TSV
|
||||
// If none exist, return the TSJ path, in case it wants to create a file
|
||||
public static Path getTsjJsonTsv(Path root, String filename) {
|
||||
val name = getFilenameWithoutExtension(filename);
|
||||
for (val ext : TSJ_JSON_TSV) {
|
||||
val path = root.resolve(name + "." + ext);
|
||||
if (Files.exists(path)) return path;
|
||||
}
|
||||
return root.resolve(name + ".tsj");
|
||||
}
|
||||
|
||||
public static Path getScriptPath(String path) {
|
||||
return SCRIPTS_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static void write(String dest, byte[] bytes) {
|
||||
Path path = Path.of(dest);
|
||||
|
||||
try {
|
||||
Files.write(path, bytes);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to write file: " + dest);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] read(String dest) {
|
||||
return read(Path.of(dest));
|
||||
}
|
||||
|
||||
public static byte[] read(Path path) {
|
||||
try {
|
||||
return Files.readAllBytes(path);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read file: " + path);
|
||||
}
|
||||
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
public static InputStream readResourceAsStream(String resourcePath) {
|
||||
return Grasscutter.class.getResourceAsStream(resourcePath);
|
||||
}
|
||||
|
||||
public static byte[] readResource(String resourcePath) {
|
||||
try (InputStream is = Grasscutter.class.getResourceAsStream(resourcePath)) {
|
||||
return is.readAllBytes();
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to read resource: " + resourcePath);
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
public static byte[] read(File file) {
|
||||
return read(file.getPath());
|
||||
}
|
||||
|
||||
public static void copyResource(String resourcePath, String destination) {
|
||||
try {
|
||||
byte[] resource = FileUtils.readResource(resourcePath);
|
||||
FileUtils.write(destination, resource);
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to copy resource: " + resourcePath + "\n" + exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated // Misnamed legacy function
|
||||
public static String getFilenameWithoutPath(String filename) {
|
||||
return getFilenameWithoutExtension(filename);
|
||||
}
|
||||
|
||||
public static String getFilenameWithoutExtension(String filename) {
|
||||
int i = filename.lastIndexOf(".");
|
||||
return (i < 0) ? filename : filename.substring(0, i);
|
||||
}
|
||||
|
||||
public static String getFileExtension(Path path) {
|
||||
val filename = path.toString();
|
||||
int i = filename.lastIndexOf(".");
|
||||
return (i < 0) ? "" : filename.substring(i + 1);
|
||||
}
|
||||
|
||||
public static List<Path> getPathsFromResource(String folder) throws URISyntaxException {
|
||||
try {
|
||||
// file walks JAR
|
||||
return Files.walk(Path.of(Grasscutter.class.getResource(folder).toURI()))
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
// Eclipse puts resources in its bin folder
|
||||
try {
|
||||
return Files.walk(Path.of(System.getProperty("user.dir"), folder))
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public static String readToString(InputStream file) throws IOException {
|
||||
byte[] content = file.readAllBytes();
|
||||
|
||||
return new String(content, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.val;
|
||||
|
||||
public final class FileUtils {
|
||||
private static final Path DATA_DEFAULT_PATH;
|
||||
private static final Path DATA_USER_PATH = Path.of(Grasscutter.config.folderStructure.data);
|
||||
private static final Path PACKETS_PATH = Path.of(Grasscutter.config.folderStructure.packets);
|
||||
private static final Path PLUGINS_PATH = Path.of(Grasscutter.config.folderStructure.plugins);
|
||||
private static final Path RESOURCES_PATH;
|
||||
private static final Path SCRIPTS_PATH;
|
||||
private static final String[] TSJ_JSON_TSV = {"tsj", "json", "tsv"};
|
||||
|
||||
static {
|
||||
FileSystem fs = null;
|
||||
Path path = null;
|
||||
// Setup access to jar resources
|
||||
try {
|
||||
var uri = Grasscutter.class.getResource("/defaults/data").toURI();
|
||||
switch (uri.getScheme()) {
|
||||
case "jar": // When running normally, as a jar
|
||||
case "zip": // Honestly I have no idea what setup would result in this, but this should work
|
||||
// regardless
|
||||
fs =
|
||||
FileSystems.newFileSystem(
|
||||
uri,
|
||||
Map.of()); // Have to mount zip filesystem. This leaks, but we want to keep it
|
||||
// forever anyway.
|
||||
// Fall-through
|
||||
case "file": // When running in an IDE
|
||||
path = Path.of(uri); // Can access directly
|
||||
break;
|
||||
default:
|
||||
Grasscutter.getLogger()
|
||||
.error("Invalid URI scheme for class resources: " + uri.getScheme());
|
||||
break;
|
||||
}
|
||||
} catch (URISyntaxException | IOException e) {
|
||||
// Failed to load this jar. How?
|
||||
Grasscutter.getLogger().error("Failed to load jar?!");
|
||||
} finally {
|
||||
DATA_DEFAULT_PATH = path;
|
||||
Grasscutter.getLogger().debug("Setting path for default data: " + path.toAbsolutePath());
|
||||
}
|
||||
|
||||
// Setup Resources path
|
||||
final String resources = Grasscutter.config.folderStructure.resources;
|
||||
fs = null;
|
||||
path = Path.of(resources);
|
||||
if (resources.endsWith(
|
||||
".zip")) { // Would be nice to support .tar.gz too at some point, but it doesn't come for
|
||||
// free in Java
|
||||
try {
|
||||
fs = FileSystems.newFileSystem(path);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to load resources zip \"" + resources + "\"");
|
||||
}
|
||||
}
|
||||
|
||||
if (fs != null) {
|
||||
var root = fs.getPath("");
|
||||
try (Stream<Path> pathStream =
|
||||
Files.find(
|
||||
root,
|
||||
3,
|
||||
(p, a) -> {
|
||||
var filename = p.getFileName();
|
||||
if (filename == null) return false;
|
||||
return filename.toString().equals("ExcelBinOutput");
|
||||
})) {
|
||||
var excelBinOutput = pathStream.findFirst();
|
||||
if (excelBinOutput.isPresent()) {
|
||||
path = excelBinOutput.get().getParent();
|
||||
if (path == null) path = root;
|
||||
Grasscutter.getLogger()
|
||||
.debug("Resources will be loaded from \"" + resources + "/" + path + "\"");
|
||||
} else {
|
||||
Grasscutter.getLogger()
|
||||
.error("Failed to find ExcelBinOutput in resources zip \"" + resources + "\"");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to scan resources zip \"" + resources + "\"");
|
||||
}
|
||||
}
|
||||
RESOURCES_PATH = path;
|
||||
|
||||
// Setup Scripts path
|
||||
final String scripts = Grasscutter.config.folderStructure.scripts;
|
||||
SCRIPTS_PATH =
|
||||
(scripts.startsWith("resources:"))
|
||||
? RESOURCES_PATH.resolve(scripts.substring("resources:".length()))
|
||||
: Path.of(scripts);
|
||||
}
|
||||
|
||||
/* Apply after initialization. */
|
||||
private static final Path[] DATA_PATHS = {DATA_USER_PATH, DATA_DEFAULT_PATH};
|
||||
|
||||
public static Path getDataPathTsjJsonTsv(String filename) {
|
||||
return getDataPathTsjJsonTsv(filename, true);
|
||||
}
|
||||
|
||||
public static Path getDataPathTsjJsonTsv(String filename, boolean fallback) {
|
||||
val name = getFilenameWithoutExtension(filename);
|
||||
for (val data_path : DATA_PATHS) {
|
||||
for (val ext : TSJ_JSON_TSV) {
|
||||
val path = data_path.resolve(name + "." + ext);
|
||||
if (Files.exists(path)) return path;
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
? DATA_USER_PATH.resolve(name + ".tsj")
|
||||
: null; // Maybe they want to write to a new file
|
||||
}
|
||||
|
||||
public static Path getDataPath(String path) {
|
||||
Path userPath = DATA_USER_PATH.resolve(path);
|
||||
if (Files.exists(userPath)) return userPath;
|
||||
Path defaultPath = DATA_DEFAULT_PATH.resolve(path);
|
||||
if (Files.exists(defaultPath)) return defaultPath;
|
||||
return userPath; // Maybe they want to write to a new file
|
||||
}
|
||||
|
||||
public static Path getDataUserPath(String path) {
|
||||
return DATA_USER_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getPacketPath(String path) {
|
||||
return PACKETS_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getPluginPath(String path) {
|
||||
return PLUGINS_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getResourcePath(String path) {
|
||||
return RESOURCES_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getExcelPath(String filename) {
|
||||
return getTsjJsonTsv(RESOURCES_PATH.resolve("ExcelBinOutput"), filename);
|
||||
}
|
||||
|
||||
// Gets path of a resource.
|
||||
// If multiple formats of it exist, priority is TSJ > JSON > TSV
|
||||
// If none exist, return the TSJ path, in case it wants to create a file
|
||||
public static Path getTsjJsonTsv(Path root, String filename) {
|
||||
val name = getFilenameWithoutExtension(filename);
|
||||
for (val ext : TSJ_JSON_TSV) {
|
||||
val path = root.resolve(name + "." + ext);
|
||||
if (Files.exists(path)) return path;
|
||||
}
|
||||
return root.resolve(name + ".tsj");
|
||||
}
|
||||
|
||||
public static Path getScriptPath(String path) {
|
||||
return SCRIPTS_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static void write(String dest, byte[] bytes) {
|
||||
Path path = Path.of(dest);
|
||||
|
||||
try {
|
||||
Files.write(path, bytes);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to write file: " + dest);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] read(String dest) {
|
||||
return read(Path.of(dest));
|
||||
}
|
||||
|
||||
public static byte[] read(Path path) {
|
||||
try {
|
||||
return Files.readAllBytes(path);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read file: " + path);
|
||||
}
|
||||
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
public static InputStream readResourceAsStream(String resourcePath) {
|
||||
return Grasscutter.class.getResourceAsStream(resourcePath);
|
||||
}
|
||||
|
||||
public static byte[] readResource(String resourcePath) {
|
||||
try (InputStream is = Grasscutter.class.getResourceAsStream(resourcePath)) {
|
||||
return is.readAllBytes();
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to read resource: " + resourcePath);
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
public static byte[] read(File file) {
|
||||
return read(file.getPath());
|
||||
}
|
||||
|
||||
public static void copyResource(String resourcePath, String destination) {
|
||||
try {
|
||||
byte[] resource = FileUtils.readResource(resourcePath);
|
||||
FileUtils.write(destination, resource);
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to copy resource: " + resourcePath + "\n" + exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated // Misnamed legacy function
|
||||
public static String getFilenameWithoutPath(String filename) {
|
||||
return getFilenameWithoutExtension(filename);
|
||||
}
|
||||
|
||||
public static String getFilenameWithoutExtension(String filename) {
|
||||
int i = filename.lastIndexOf(".");
|
||||
return (i < 0) ? filename : filename.substring(0, i);
|
||||
}
|
||||
|
||||
public static String getFileExtension(Path path) {
|
||||
val filename = path.toString();
|
||||
int i = filename.lastIndexOf(".");
|
||||
return (i < 0) ? "" : filename.substring(i + 1);
|
||||
}
|
||||
|
||||
public static List<Path> getPathsFromResource(String folder) throws URISyntaxException {
|
||||
try {
|
||||
// file walks JAR
|
||||
return Files.walk(Path.of(Grasscutter.class.getResource(folder).toURI()))
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
// Eclipse puts resources in its bin folder
|
||||
try {
|
||||
return Files.walk(Path.of(System.getProperty("user.dir"), folder))
|
||||
.filter(Files::isRegularFile)
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
public static String readToString(InputStream file) throws IOException {
|
||||
byte[] content = file.readAllBytes();
|
||||
|
||||
return new String(content, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.ConsoleAppender;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class JlineLogbackAppender extends ConsoleAppender<ILoggingEvent> {
|
||||
@Override
|
||||
protected void append(ILoggingEvent eventObject) {
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
Arrays.stream(
|
||||
new String(encoder.encode(eventObject)).split("\n\r")
|
||||
).forEach(Grasscutter.getConsole()::printAbove);
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.ConsoleAppender;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class JlineLogbackAppender extends ConsoleAppender<ILoggingEvent> {
|
||||
@Override
|
||||
protected void append(ILoggingEvent eventObject) {
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
Arrays.stream(new String(encoder.encode(eventObject)).split("\n\r"))
|
||||
.forEach(Grasscutter.getConsole()::printAbove);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,177 +1,171 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.TypeAdapterFactory;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import lombok.val;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
|
||||
public class JsonAdapters {
|
||||
static class DynamicFloatAdapter extends TypeAdapter<DynamicFloat> {
|
||||
@Override
|
||||
public DynamicFloat read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case STRING:
|
||||
return new DynamicFloat(reader.nextString());
|
||||
case NUMBER:
|
||||
return new DynamicFloat((float) reader.nextDouble());
|
||||
case BOOLEAN:
|
||||
return new DynamicFloat(reader.nextBoolean());
|
||||
case BEGIN_ARRAY:
|
||||
reader.beginArray();
|
||||
val opStack = new ArrayList<DynamicFloat.StackOp>();
|
||||
while (reader.hasNext()) {
|
||||
opStack.add(switch (reader.peek()) {
|
||||
case STRING -> new DynamicFloat.StackOp(reader.nextString());
|
||||
case NUMBER -> new DynamicFloat.StackOp((float) reader.nextDouble());
|
||||
case BOOLEAN -> new DynamicFloat.StackOp(reader.nextBoolean());
|
||||
default ->
|
||||
throw new IOException("Invalid DynamicFloat definition - " + reader.peek().name());
|
||||
});
|
||||
}
|
||||
reader.endArray();
|
||||
return new DynamicFloat(opStack);
|
||||
default:
|
||||
throw new IOException("Invalid DynamicFloat definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, DynamicFloat f) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class IntListAdapter extends TypeAdapter<IntList> {
|
||||
@Override
|
||||
public IntList read(JsonReader reader) throws IOException {
|
||||
if (Objects.requireNonNull(reader.peek()) == JsonToken.BEGIN_ARRAY) {
|
||||
reader.beginArray();
|
||||
val i = new IntArrayList();
|
||||
while (reader.hasNext())
|
||||
i.add(reader.nextInt());
|
||||
reader.endArray();
|
||||
i.trim(); // We might have a ton of these from resources and almost all of them immutable, don't overprovision!
|
||||
return i;
|
||||
}
|
||||
throw new IOException("Invalid IntList definition - " + reader.peek().name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, IntList l) throws IOException {
|
||||
writer.beginArray();
|
||||
for (val i : l) // .forEach() doesn't appreciate exceptions
|
||||
writer.value(i);
|
||||
writer.endArray();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class PositionAdapter extends TypeAdapter<Position> {
|
||||
@Override
|
||||
public Position read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case BEGIN_ARRAY: // "pos": [x,y,z]
|
||||
reader.beginArray();
|
||||
val array = new FloatArrayList(3);
|
||||
while (reader.hasNext())
|
||||
array.add(reader.nextInt());
|
||||
reader.endArray();
|
||||
return new Position(array);
|
||||
case BEGIN_OBJECT: // "pos": {"x": x, "y": y, "z": z}
|
||||
float x = 0f;
|
||||
float y = 0f;
|
||||
float z = 0f;
|
||||
reader.beginObject();
|
||||
for (var next = reader.peek(); next != JsonToken.END_OBJECT; next = reader.peek()) {
|
||||
val name = reader.nextName();
|
||||
switch (name) {
|
||||
case "x", "X", "_x" -> x = (float) reader.nextDouble();
|
||||
case "y", "Y", "_y" -> y = (float) reader.nextDouble();
|
||||
case "z", "Z", "_z" -> z = (float) reader.nextDouble();
|
||||
default -> throw new IOException("Invalid field in Position definition - " + name);
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
return new Position(x, y, z);
|
||||
default:
|
||||
throw new IOException("Invalid Position definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, Position i) throws IOException {
|
||||
writer.beginArray();
|
||||
writer.value(i.getX());
|
||||
writer.value(i.getY());
|
||||
writer.value(i.getZ());
|
||||
writer.endArray();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class EnumTypeAdapterFactory implements TypeAdapterFactory {
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
|
||||
Class<T> enumClass = (Class<T>) type.getRawType();
|
||||
if (!enumClass.isEnum()) return null;
|
||||
|
||||
// Make mappings of (string) names to enum constants
|
||||
val map = new HashMap<String, T>();
|
||||
val enumConstants = enumClass.getEnumConstants();
|
||||
for (val constant : enumConstants)
|
||||
map.put(constant.toString(), constant);
|
||||
|
||||
// If the enum also has a numeric value, map those to the constants too
|
||||
// System.out.println("Looking for enum value field");
|
||||
for (Field f : enumClass.getDeclaredFields()) {
|
||||
if (switch (f.getName()) {
|
||||
case "value", "id" -> true;
|
||||
default -> false;
|
||||
}) {
|
||||
// System.out.println("Enum value field found - " + f.getName());
|
||||
boolean acc = f.isAccessible();
|
||||
f.setAccessible(true);
|
||||
try {
|
||||
for (val constant : enumConstants)
|
||||
map.put(String.valueOf(f.getInt(constant)), constant);
|
||||
} catch (IllegalAccessException e) {
|
||||
// System.out.println("Failed to access enum id field.");
|
||||
}
|
||||
f.setAccessible(acc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new TypeAdapter<T>() {
|
||||
public T read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case STRING:
|
||||
return map.get(reader.nextString());
|
||||
case NUMBER:
|
||||
return map.get(String.valueOf(reader.nextInt()));
|
||||
default:
|
||||
throw new IOException("Invalid Enum definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
public void write(JsonWriter writer, T value) throws IOException {
|
||||
writer.value(value.toString());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.TypeAdapterFactory;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
import lombok.val;
|
||||
|
||||
public class JsonAdapters {
|
||||
static class DynamicFloatAdapter extends TypeAdapter<DynamicFloat> {
|
||||
@Override
|
||||
public DynamicFloat read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case STRING:
|
||||
return new DynamicFloat(reader.nextString());
|
||||
case NUMBER:
|
||||
return new DynamicFloat((float) reader.nextDouble());
|
||||
case BOOLEAN:
|
||||
return new DynamicFloat(reader.nextBoolean());
|
||||
case BEGIN_ARRAY:
|
||||
reader.beginArray();
|
||||
val opStack = new ArrayList<DynamicFloat.StackOp>();
|
||||
while (reader.hasNext()) {
|
||||
opStack.add(
|
||||
switch (reader.peek()) {
|
||||
case STRING -> new DynamicFloat.StackOp(reader.nextString());
|
||||
case NUMBER -> new DynamicFloat.StackOp((float) reader.nextDouble());
|
||||
case BOOLEAN -> new DynamicFloat.StackOp(reader.nextBoolean());
|
||||
default -> throw new IOException(
|
||||
"Invalid DynamicFloat definition - " + reader.peek().name());
|
||||
});
|
||||
}
|
||||
reader.endArray();
|
||||
return new DynamicFloat(opStack);
|
||||
default:
|
||||
throw new IOException("Invalid DynamicFloat definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, DynamicFloat f) {}
|
||||
}
|
||||
|
||||
static class IntListAdapter extends TypeAdapter<IntList> {
|
||||
@Override
|
||||
public IntList read(JsonReader reader) throws IOException {
|
||||
if (Objects.requireNonNull(reader.peek()) == JsonToken.BEGIN_ARRAY) {
|
||||
reader.beginArray();
|
||||
val i = new IntArrayList();
|
||||
while (reader.hasNext()) i.add(reader.nextInt());
|
||||
reader.endArray();
|
||||
i.trim(); // We might have a ton of these from resources and almost all of them
|
||||
// immutable, don't overprovision!
|
||||
return i;
|
||||
}
|
||||
throw new IOException("Invalid IntList definition - " + reader.peek().name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, IntList l) throws IOException {
|
||||
writer.beginArray();
|
||||
for (val i : l) // .forEach() doesn't appreciate exceptions
|
||||
writer.value(i);
|
||||
writer.endArray();
|
||||
}
|
||||
}
|
||||
|
||||
static class PositionAdapter extends TypeAdapter<Position> {
|
||||
@Override
|
||||
public Position read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case BEGIN_ARRAY: // "pos": [x,y,z]
|
||||
reader.beginArray();
|
||||
val array = new FloatArrayList(3);
|
||||
while (reader.hasNext()) array.add(reader.nextInt());
|
||||
reader.endArray();
|
||||
return new Position(array);
|
||||
case BEGIN_OBJECT: // "pos": {"x": x, "y": y, "z": z}
|
||||
float x = 0f;
|
||||
float y = 0f;
|
||||
float z = 0f;
|
||||
reader.beginObject();
|
||||
for (var next = reader.peek(); next != JsonToken.END_OBJECT; next = reader.peek()) {
|
||||
val name = reader.nextName();
|
||||
switch (name) {
|
||||
case "x", "X", "_x" -> x = (float) reader.nextDouble();
|
||||
case "y", "Y", "_y" -> y = (float) reader.nextDouble();
|
||||
case "z", "Z", "_z" -> z = (float) reader.nextDouble();
|
||||
default -> throw new IOException("Invalid field in Position definition - " + name);
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
return new Position(x, y, z);
|
||||
default:
|
||||
throw new IOException("Invalid Position definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, Position i) throws IOException {
|
||||
writer.beginArray();
|
||||
writer.value(i.getX());
|
||||
writer.value(i.getY());
|
||||
writer.value(i.getZ());
|
||||
writer.endArray();
|
||||
}
|
||||
}
|
||||
|
||||
static class EnumTypeAdapterFactory implements TypeAdapterFactory {
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
|
||||
Class<T> enumClass = (Class<T>) type.getRawType();
|
||||
if (!enumClass.isEnum()) return null;
|
||||
|
||||
// Make mappings of (string) names to enum constants
|
||||
val map = new HashMap<String, T>();
|
||||
val enumConstants = enumClass.getEnumConstants();
|
||||
for (val constant : enumConstants) map.put(constant.toString(), constant);
|
||||
|
||||
// If the enum also has a numeric value, map those to the constants too
|
||||
// System.out.println("Looking for enum value field");
|
||||
for (Field f : enumClass.getDeclaredFields()) {
|
||||
if (switch (f.getName()) {
|
||||
case "value", "id" -> true;
|
||||
default -> false;
|
||||
}) {
|
||||
// System.out.println("Enum value field found - " + f.getName());
|
||||
boolean acc = f.isAccessible();
|
||||
f.setAccessible(true);
|
||||
try {
|
||||
for (val constant : enumConstants)
|
||||
map.put(String.valueOf(f.getInt(constant)), constant);
|
||||
} catch (IllegalAccessException e) {
|
||||
// System.out.println("Failed to access enum id field.");
|
||||
}
|
||||
f.setAccessible(acc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new TypeAdapter<T>() {
|
||||
public T read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case STRING:
|
||||
return map.get(reader.nextString());
|
||||
case NUMBER:
|
||||
return map.get(String.valueOf(reader.nextInt()));
|
||||
default:
|
||||
throw new IOException("Invalid Enum definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
public void write(JsonWriter writer, T value) throws IOException {
|
||||
writer.value(value.toString());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,118 +1,129 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import emu.grasscutter.utils.JsonAdapters.DynamicFloatAdapter;
|
||||
import emu.grasscutter.utils.JsonAdapters.EnumTypeAdapterFactory;
|
||||
import emu.grasscutter.utils.JsonAdapters.IntListAdapter;
|
||||
import emu.grasscutter.utils.JsonAdapters.PositionAdapter;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class JsonUtils {
|
||||
static final Gson gson = new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.registerTypeAdapter(DynamicFloat.class, new DynamicFloatAdapter())
|
||||
.registerTypeAdapter(IntList.class, new IntListAdapter())
|
||||
.registerTypeAdapter(Position.class, new PositionAdapter())
|
||||
.registerTypeAdapterFactory(new EnumTypeAdapterFactory())
|
||||
.create();
|
||||
|
||||
/*
|
||||
* Encode an object to a JSON string
|
||||
*/
|
||||
public static String encode(Object object) {
|
||||
return gson.toJson(object);
|
||||
}
|
||||
|
||||
public static <T> T decode(JsonElement jsonElement, Class<T> classType) throws JsonSyntaxException {
|
||||
return gson.fromJson(jsonElement, classType);
|
||||
}
|
||||
|
||||
public static <T> T loadToClass(Reader fileReader, Class<T> classType) throws IOException {
|
||||
return gson.fromJson(fileReader, classType);
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static <T> T loadToClass(String filename, Class<T> classType) throws IOException {
|
||||
try (InputStreamReader fileReader = new InputStreamReader(new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToClass(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T loadToClass(Path filename, Class<T> classType) throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return loadToClass(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> loadToList(Reader fileReader, Class<T> classType) throws IOException {
|
||||
return gson.fromJson(fileReader, TypeToken.getParameterized(List.class, classType).getType());
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static <T> List<T> loadToList(String filename, Class<T> classType) throws IOException {
|
||||
try (InputStreamReader fileReader = new InputStreamReader(new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToList(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> loadToList(Path filename, Class<T> classType) throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return loadToList(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(Reader fileReader, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
return gson.fromJson(fileReader, TypeToken.getParameterized(Map.class, keyType, valueType).getType());
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(String filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
try (InputStreamReader fileReader = new InputStreamReader(new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToMap(fileReader, keyType, valueType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(Path filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return loadToMap(fileReader, keyType, valueType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 decode(String jsonData, Class<T> classType) {
|
||||
try {
|
||||
return gson.fromJson(jsonData, classType);
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T decode(String jsonData, Type type) {
|
||||
try {
|
||||
return gson.fromJson(jsonData, type);
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import emu.grasscutter.utils.JsonAdapters.DynamicFloatAdapter;
|
||||
import emu.grasscutter.utils.JsonAdapters.EnumTypeAdapterFactory;
|
||||
import emu.grasscutter.utils.JsonAdapters.IntListAdapter;
|
||||
import emu.grasscutter.utils.JsonAdapters.PositionAdapter;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class JsonUtils {
|
||||
static final Gson gson =
|
||||
new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.registerTypeAdapter(DynamicFloat.class, new DynamicFloatAdapter())
|
||||
.registerTypeAdapter(IntList.class, new IntListAdapter())
|
||||
.registerTypeAdapter(Position.class, new PositionAdapter())
|
||||
.registerTypeAdapterFactory(new EnumTypeAdapterFactory())
|
||||
.create();
|
||||
|
||||
/*
|
||||
* Encode an object to a JSON string
|
||||
*/
|
||||
public static String encode(Object object) {
|
||||
return gson.toJson(object);
|
||||
}
|
||||
|
||||
public static <T> T decode(JsonElement jsonElement, Class<T> classType)
|
||||
throws JsonSyntaxException {
|
||||
return gson.fromJson(jsonElement, classType);
|
||||
}
|
||||
|
||||
public static <T> T loadToClass(Reader fileReader, Class<T> classType) throws IOException {
|
||||
return gson.fromJson(fileReader, classType);
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static <T> T loadToClass(String filename, Class<T> classType) throws IOException {
|
||||
try (InputStreamReader fileReader =
|
||||
new InputStreamReader(
|
||||
new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToClass(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T loadToClass(Path filename, Class<T> classType) throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return loadToClass(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> loadToList(Reader fileReader, Class<T> classType) throws IOException {
|
||||
return gson.fromJson(fileReader, TypeToken.getParameterized(List.class, classType).getType());
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static <T> List<T> loadToList(String filename, Class<T> classType) throws IOException {
|
||||
try (InputStreamReader fileReader =
|
||||
new InputStreamReader(
|
||||
new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToList(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> loadToList(Path filename, Class<T> classType) throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return loadToList(fileReader, classType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(
|
||||
Reader fileReader, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
return gson.fromJson(
|
||||
fileReader, TypeToken.getParameterized(Map.class, keyType, valueType).getType());
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(
|
||||
String filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
try (InputStreamReader fileReader =
|
||||
new InputStreamReader(
|
||||
new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToMap(fileReader, keyType, valueType);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(
|
||||
Path filename, Class<T1> keyType, Class<T2> valueType) throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return loadToMap(fileReader, keyType, valueType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 decode(String jsonData, Class<T> classType) {
|
||||
try {
|
||||
return gson.fromJson(jsonData, classType);
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T decode(String jsonData, Type type) {
|
||||
try {
|
||||
return gson.fromJson(jsonData, type);
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,466 +1,513 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.data.GameData;
|
||||
import emu.grasscutter.data.ResourceLoader;
|
||||
import emu.grasscutter.data.excels.AchievementData;
|
||||
import emu.grasscutter.game.player.Player;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
|
||||
import it.unimi.dsi.fastutil.ints.IntSet;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.FALLBACK_LANGUAGE;
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
|
||||
public final class Language {
|
||||
private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
|
||||
private static final int TEXTMAP_CACHE_VERSION = 0x9CCACE04;
|
||||
private static final Pattern textMapKeyValueRegex = Pattern.compile("\"(\\d+)\": \"(.+)\"");
|
||||
private static final Path TEXTMAP_CACHE_PATH = Path.of(Utils.toFilePath("cache/TextMapCache.bin"));
|
||||
private static boolean scannedTextmaps = false; // Ensure that we don't infinitely rescan on cache misses that don't exist
|
||||
private static Int2ObjectMap<TextStrings> textMapStrings;
|
||||
private final String languageCode;
|
||||
private final Map<String, String> translations = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Reads a file and creates a language instance.
|
||||
*/
|
||||
private Language(LanguageStreamDescription description) {
|
||||
languageCode = description.getLanguageCode();
|
||||
|
||||
try {
|
||||
var object = JsonUtils.decode(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
|
||||
object.entrySet().forEach(entry -> putFlattenedKey(translations, entry.getKey(), entry.getValue()));
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to load language file: " + description.getLanguageCode(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a language instance from a code.
|
||||
*
|
||||
* @param langCode The language code.
|
||||
* @return A language instance.
|
||||
*/
|
||||
public static Language getLanguage(String langCode) {
|
||||
if (cachedLanguages.containsKey(langCode)) {
|
||||
return cachedLanguages.get(langCode);
|
||||
}
|
||||
|
||||
var fallbackLanguageCode = Utils.getLanguageCode(FALLBACK_LANGUAGE);
|
||||
var description = getLanguageFileDescription(langCode, fallbackLanguageCode);
|
||||
var actualLanguageCode = description.getLanguageCode();
|
||||
|
||||
Language languageInst;
|
||||
if (description.getLanguageFile() != null) {
|
||||
languageInst = new Language(description);
|
||||
cachedLanguages.put(actualLanguageCode, languageInst);
|
||||
} else {
|
||||
languageInst = cachedLanguages.get(actualLanguageCode);
|
||||
cachedLanguages.put(langCode, languageInst);
|
||||
}
|
||||
|
||||
return languageInst;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the translated value from the key while substituting arguments.
|
||||
*
|
||||
* @param key The key of the translated value to return.
|
||||
* @param args The arguments to substitute.
|
||||
* @return A translated value with arguments substituted.
|
||||
*/
|
||||
public static String translate(String key, Object... args) {
|
||||
String translated = Grasscutter.getLanguage().get(key);
|
||||
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] = switch (args[i].getClass().getSimpleName()) {
|
||||
case "String" -> args[i];
|
||||
case "TextStrings" ->
|
||||
((TextStrings) args[i]).get(0).replace("\\\\n", "\\n"); // TODO: Change this to server language
|
||||
default -> args[i].toString();
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return translated.formatted(args);
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Failed to format string: " + key, exception);
|
||||
return translated;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the translated value from the key while substituting arguments.
|
||||
*
|
||||
* @param player Target player
|
||||
* @param key The key of the translated value to return.
|
||||
* @param args The arguments to substitute.
|
||||
* @return A translated value with arguments substituted.
|
||||
*/
|
||||
public static String translate(Player player, String key, Object... args) {
|
||||
if (player == null) {
|
||||
return translate(key, args);
|
||||
}
|
||||
|
||||
var langCode = Utils.getLanguageCode(player.getAccount().getLocale());
|
||||
String translated = getLanguage(langCode).get(key);
|
||||
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] = switch (args[i].getClass().getSimpleName()) {
|
||||
case "String" -> args[i];
|
||||
case "TextStrings" ->
|
||||
((TextStrings) args[i]).getGC(langCode).replace("\\\\n", "\n"); // Note that we don't unescape \n for server console
|
||||
default -> args[i].toString();
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return translated.formatted(args);
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Failed to format string: " + key, exception);
|
||||
return translated;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive helper function to flatten a Json tree
|
||||
* Converts input like {"foo": {"bar": "baz"}} to {"foo.bar": "baz"}
|
||||
*
|
||||
* @param map The map to insert the keys into
|
||||
* @param key The flattened key of the current element
|
||||
* @param element The current element
|
||||
*/
|
||||
private static void putFlattenedKey(Map<String, String> map, String key, JsonElement element) {
|
||||
if (element.isJsonObject()) {
|
||||
element.getAsJsonObject().entrySet().forEach(entry -> {
|
||||
String keyPrefix = key.isEmpty() ? "" : key + ".";
|
||||
putFlattenedKey(map, keyPrefix + entry.getKey(), entry.getValue());
|
||||
});
|
||||
} else {
|
||||
map.put(key, element.getAsString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* create a LanguageStreamDescription
|
||||
*
|
||||
* @param languageCode The name of the language code.
|
||||
* @param fallbackLanguageCode The name of the fallback language code.
|
||||
*/
|
||||
private static LanguageStreamDescription getLanguageFileDescription(String languageCode, String fallbackLanguageCode) {
|
||||
var fileName = languageCode + ".json";
|
||||
var fallback = fallbackLanguageCode + ".json";
|
||||
|
||||
String actualLanguageCode = languageCode;
|
||||
InputStream file = Grasscutter.class.getResourceAsStream("/languages/" + fileName);
|
||||
|
||||
if (file == null) { // Provided fallback language.
|
||||
Grasscutter.getLogger().warn("Failed to load language file: " + fileName + ", falling back to: " + fallback);
|
||||
actualLanguageCode = fallbackLanguageCode;
|
||||
if (cachedLanguages.containsKey(actualLanguageCode)) {
|
||||
return new LanguageStreamDescription(actualLanguageCode, null);
|
||||
}
|
||||
|
||||
file = Grasscutter.class.getResourceAsStream("/languages/" + fallback);
|
||||
}
|
||||
|
||||
if (file == null) { // Fallback the fallback language.
|
||||
Grasscutter.getLogger().warn("Failed to load language file: " + fallback + ", falling back to: en-US.json");
|
||||
actualLanguageCode = "en-US";
|
||||
if (cachedLanguages.containsKey(actualLanguageCode)) {
|
||||
return new LanguageStreamDescription(actualLanguageCode, null);
|
||||
}
|
||||
|
||||
file = Grasscutter.class.getResourceAsStream("/languages/en-US.json");
|
||||
}
|
||||
|
||||
if (file == null)
|
||||
throw new RuntimeException("Unable to load the primary, fallback, and 'en-US' language files.");
|
||||
|
||||
return new LanguageStreamDescription(actualLanguageCode, file);
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<String> loadTextMapFile(String language, IntSet nameHashes) {
|
||||
Int2ObjectMap<String> output = new Int2ObjectOpenHashMap<>();
|
||||
try (BufferedReader file = Files.newBufferedReader(getResourcePath("TextMap/TextMap" + language + ".json"), StandardCharsets.UTF_8)) {
|
||||
Matcher matcher = textMapKeyValueRegex.matcher("");
|
||||
return new Int2ObjectOpenHashMap<>(
|
||||
file.lines()
|
||||
.sequential()
|
||||
.map(matcher::reset) // Side effects, but it's faster than making a new one
|
||||
.filter(Matcher::find)
|
||||
.filter(m -> nameHashes.contains((int) Long.parseLong(m.group(1)))) // TODO: Cache this parse somehow
|
||||
.collect(Collectors.toMap(
|
||||
m -> (int) Long.parseLong(m.group(1)),
|
||||
m -> m.group(2).replace("\\\"", "\""))));
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("Error loading textmap: " + language);
|
||||
Grasscutter.getLogger().error(e.toString());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapFiles(IntSet nameHashes) {
|
||||
Map<Integer, Int2ObjectMap<String>> mapLanguageMaps = // Separate step to process the textmaps in parallel
|
||||
TextStrings.LIST_LANGUAGES.parallelStream().collect(
|
||||
Collectors.toConcurrentMap(s -> TextStrings.MAP_LANGUAGES.getInt(s), s -> loadTextMapFile(s, nameHashes)));
|
||||
List<Int2ObjectMap<String>> languageMaps =
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> mapLanguageMaps.get(i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Map<TextStrings, TextStrings> canonicalTextStrings = new HashMap<>();
|
||||
return new Int2ObjectOpenHashMap<TextStrings>(
|
||||
nameHashes
|
||||
.intStream()
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(key -> key, key -> {
|
||||
TextStrings t = new TextStrings(
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> languageMaps.get(i).get((int) key))
|
||||
.collect(Collectors.toList()), key);
|
||||
return canonicalTextStrings.computeIfAbsent(t, x -> t);
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapsCache() throws Exception {
|
||||
try (ObjectInputStream file = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(TEXTMAP_CACHE_PATH), 0x100000))) {
|
||||
final int fileVersion = file.readInt();
|
||||
if (fileVersion != TEXTMAP_CACHE_VERSION)
|
||||
throw new Exception("Invalid cache version");
|
||||
return (Int2ObjectMap<TextStrings>) file.readObject();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveTextMapsCache(Int2ObjectMap<TextStrings> input) throws IOException {
|
||||
try {
|
||||
Files.createDirectory(Path.of("cache"));
|
||||
} catch (FileAlreadyExistsException ignored) {
|
||||
}
|
||||
try (ObjectOutputStream file = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(TEXTMAP_CACHE_PATH, StandardOpenOption.CREATE), 0x100000))) {
|
||||
file.writeInt(TEXTMAP_CACHE_VERSION);
|
||||
file.writeObject(input);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static Int2ObjectMap<TextStrings> getTextMapStrings() {
|
||||
if (textMapStrings == null)
|
||||
loadTextMaps();
|
||||
return textMapStrings;
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(int key) {
|
||||
if ((textMapStrings == null) || (!scannedTextmaps && !textMapStrings.containsKey(key)))
|
||||
loadTextMaps();
|
||||
return textMapStrings.get(key);
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(long hash) {
|
||||
return getTextMapKey((int) hash);
|
||||
}
|
||||
|
||||
public static void loadTextMaps() {
|
||||
// Check system timestamps on cache and resources
|
||||
try {
|
||||
long cacheModified = Files.getLastModifiedTime(TEXTMAP_CACHE_PATH).toMillis();
|
||||
|
||||
long textmapsModified = Files.list(getResourcePath("TextMap"))
|
||||
.filter(path -> path.toString().endsWith(".json"))
|
||||
.map(path -> {
|
||||
try {
|
||||
return Files.getLastModifiedTime(path).toMillis();
|
||||
} catch (Exception ignored) {
|
||||
Grasscutter.getLogger().debug("Exception while checking modified time: ", path);
|
||||
return Long.MAX_VALUE; // Don't use cache, something has gone wrong
|
||||
}
|
||||
})
|
||||
.max(Long::compare)
|
||||
.get();
|
||||
|
||||
Grasscutter.getLogger().debug("Cache modified %d, textmap modified %d".formatted(cacheModified, textmapsModified));
|
||||
if (textmapsModified < cacheModified) {
|
||||
// Try loading from cache
|
||||
Grasscutter.getLogger().info("Loading cached 'TextMaps'...");
|
||||
textMapStrings = loadTextMapsCache();
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().debug("Exception while checking cache: ", e);
|
||||
}
|
||||
|
||||
// Regenerate cache
|
||||
Grasscutter.getLogger().debug("Generating TextMaps cache");
|
||||
ResourceLoader.loadAll();
|
||||
IntSet usedHashes = new IntOpenHashSet();
|
||||
GameData.getAchievementDataMap().values().stream()
|
||||
.filter(AchievementData::isUsed)
|
||||
.forEach(a -> {
|
||||
usedHashes.add((int) a.getTitleTextMapHash());
|
||||
usedHashes.add((int) a.getDescTextMapHash());
|
||||
});
|
||||
GameData.getAvatarDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getAvatarSkillDataMap().forEach((k, v) -> {
|
||||
usedHashes.add((int) v.getNameTextMapHash());
|
||||
usedHashes.add((int) v.getDescTextMapHash());
|
||||
});
|
||||
GameData.getItemDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getHomeWorldBgmDataMap().forEach((k, v) -> usedHashes.add((int) v.getBgmNameTextMapHash()));
|
||||
GameData.getMonsterDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getMainQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getTitleTextMapHash()));
|
||||
GameData.getQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getDescTextMapHash()));
|
||||
// Incidental strings
|
||||
usedHashes.add((int) 4233146695L); // Character
|
||||
usedHashes.add((int) 4231343903L); // Weapon
|
||||
usedHashes.add((int) 332935371L); // Standard Wish
|
||||
usedHashes.add((int) 2272170627L); // Character Event Wish
|
||||
usedHashes.add((int) 3352513147L); // Character Event Wish-2
|
||||
usedHashes.add((int) 2864268523L); // Weapon Event Wish
|
||||
|
||||
textMapStrings = loadTextMapFiles(usedHashes);
|
||||
scannedTextmaps = true;
|
||||
try {
|
||||
saveTextMapsCache(textMapStrings);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to save TextMap cache: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get language code
|
||||
*/
|
||||
public String getLanguageCode() {
|
||||
return languageCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value (as a string) from a nested key.
|
||||
*
|
||||
* @param key The key to look for.
|
||||
* @return The value (as a string) from a nested key.
|
||||
*/
|
||||
public String get(String key) {
|
||||
if (translations.containsKey(key)) return translations.get(key);
|
||||
String valueNotFoundPattern = "This value does not exist. Please report this to the Discord: ";
|
||||
String result = valueNotFoundPattern + key;
|
||||
if (!languageCode.equals("en-US")) {
|
||||
String englishValue = getLanguage("en-US").get(key);
|
||||
if (!englishValue.contains(valueNotFoundPattern)) {
|
||||
result += "\nhere is english version:\n" + englishValue;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static class LanguageStreamDescription {
|
||||
private final String languageCode;
|
||||
private final InputStream languageFile;
|
||||
|
||||
public LanguageStreamDescription(String languageCode, InputStream languageFile) {
|
||||
this.languageCode = languageCode;
|
||||
this.languageFile = languageFile;
|
||||
}
|
||||
|
||||
public String getLanguageCode() {
|
||||
return languageCode;
|
||||
}
|
||||
|
||||
public InputStream getLanguageFile() {
|
||||
return languageFile;
|
||||
}
|
||||
}
|
||||
|
||||
@EqualsAndHashCode
|
||||
public static class TextStrings implements Serializable {
|
||||
public static final String[] ARR_LANGUAGES = {"EN", "CHS", "CHT", "JP", "KR", "DE", "ES", "FR", "ID", "PT", "RU", "TH", "VI"};
|
||||
public static final String[] ARR_GC_LANGUAGES = {"en-US", "zh-CN", "zh-TW", "ja-JP", "ko-KR", "en-US", "es-ES", "fr-FR", "en-US", "en-US", "ru-RU", "en-US", "en-US"}; // TODO: Update the placeholder en-US entries if we ever add GC translations for the missing client languages
|
||||
public static final int NUM_LANGUAGES = ARR_LANGUAGES.length;
|
||||
public static final List<String> LIST_LANGUAGES = Arrays.asList(ARR_LANGUAGES);
|
||||
public static final Object2IntMap<String> MAP_LANGUAGES = // Map "EN": 0, "CHS": 1, ..., "VI": 12
|
||||
new Object2IntOpenHashMap<>(
|
||||
IntStream.range(0, ARR_LANGUAGES.length)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(i -> ARR_LANGUAGES[i], i -> i)));
|
||||
public static final Object2IntMap<String> MAP_GC_LANGUAGES = // Map "en-US": 0, "zh-CN": 1, ...
|
||||
new Object2IntOpenHashMap<>(
|
||||
IntStream.range(0, ARR_GC_LANGUAGES.length)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(i -> ARR_GC_LANGUAGES[i], i -> i, (i1, i2) -> i1))); // Have to handle duplicates referring back to the first
|
||||
public String[] strings = new String[ARR_LANGUAGES.length];
|
||||
|
||||
public TextStrings() {
|
||||
}
|
||||
|
||||
public TextStrings(String init) {
|
||||
for (int i = 0; i < NUM_LANGUAGES; i++)
|
||||
this.strings[i] = init;
|
||||
}
|
||||
|
||||
public TextStrings(List<String> strings, int key) {
|
||||
// Some hashes don't have strings for some languages :(
|
||||
String nullReplacement = "[N/A] %d".formatted((long) key & 0xFFFFFFFFL);
|
||||
for (int i = 0; i < NUM_LANGUAGES; i++) { // Find first non-null if there is any
|
||||
String s = strings.get(i);
|
||||
if (s != null) {
|
||||
nullReplacement = "[%s] - %s".formatted(ARR_LANGUAGES[i], s);
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < NUM_LANGUAGES; i++) {
|
||||
String s = strings.get(i);
|
||||
if (s != null)
|
||||
this.strings[i] = s;
|
||||
else
|
||||
this.strings[i] = nullReplacement;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Language> getLanguages() {
|
||||
return Arrays.stream(ARR_GC_LANGUAGES).map(Language::getLanguage).toList();
|
||||
}
|
||||
|
||||
public String get(int languageIndex) {
|
||||
return strings[languageIndex];
|
||||
}
|
||||
|
||||
public String get(String languageCode) {
|
||||
return strings[MAP_LANGUAGES.getOrDefault(languageCode, 0)];
|
||||
}
|
||||
|
||||
public String getGC(String languageCode) {
|
||||
return strings[MAP_GC_LANGUAGES.getOrDefault(languageCode, 0)];
|
||||
}
|
||||
|
||||
public boolean set(String languageCode, String string) {
|
||||
int index = MAP_LANGUAGES.getOrDefault(languageCode, -1);
|
||||
if (index < 0) return false;
|
||||
strings[index] = string;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.FALLBACK_LANGUAGE;
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.data.GameData;
|
||||
import emu.grasscutter.data.ResourceLoader;
|
||||
import emu.grasscutter.data.excels.AchievementData;
|
||||
import emu.grasscutter.game.player.Player;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
|
||||
import it.unimi.dsi.fastutil.ints.IntSet;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
public final class Language {
|
||||
private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
|
||||
private static final int TEXTMAP_CACHE_VERSION = 0x9CCACE04;
|
||||
private static final Pattern textMapKeyValueRegex = Pattern.compile("\"(\\d+)\": \"(.+)\"");
|
||||
private static final Path TEXTMAP_CACHE_PATH =
|
||||
Path.of(Utils.toFilePath("cache/TextMapCache.bin"));
|
||||
private static boolean scannedTextmaps =
|
||||
false; // Ensure that we don't infinitely rescan on cache misses that don't exist
|
||||
private static Int2ObjectMap<TextStrings> textMapStrings;
|
||||
private final String languageCode;
|
||||
private final Map<String, String> translations = new ConcurrentHashMap<>();
|
||||
|
||||
/** Reads a file and creates a language instance. */
|
||||
private Language(LanguageStreamDescription description) {
|
||||
languageCode = description.getLanguageCode();
|
||||
|
||||
try {
|
||||
var object =
|
||||
JsonUtils.decode(
|
||||
Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
|
||||
object
|
||||
.entrySet()
|
||||
.forEach(entry -> putFlattenedKey(translations, entry.getKey(), entry.getValue()));
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger()
|
||||
.warn("Failed to load language file: " + description.getLanguageCode(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a language instance from a code.
|
||||
*
|
||||
* @param langCode The language code.
|
||||
* @return A language instance.
|
||||
*/
|
||||
public static Language getLanguage(String langCode) {
|
||||
if (cachedLanguages.containsKey(langCode)) {
|
||||
return cachedLanguages.get(langCode);
|
||||
}
|
||||
|
||||
var fallbackLanguageCode = Utils.getLanguageCode(FALLBACK_LANGUAGE);
|
||||
var description = getLanguageFileDescription(langCode, fallbackLanguageCode);
|
||||
var actualLanguageCode = description.getLanguageCode();
|
||||
|
||||
Language languageInst;
|
||||
if (description.getLanguageFile() != null) {
|
||||
languageInst = new Language(description);
|
||||
cachedLanguages.put(actualLanguageCode, languageInst);
|
||||
} else {
|
||||
languageInst = cachedLanguages.get(actualLanguageCode);
|
||||
cachedLanguages.put(langCode, languageInst);
|
||||
}
|
||||
|
||||
return languageInst;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the translated value from the key while substituting arguments.
|
||||
*
|
||||
* @param key The key of the translated value to return.
|
||||
* @param args The arguments to substitute.
|
||||
* @return A translated value with arguments substituted.
|
||||
*/
|
||||
public static String translate(String key, Object... args) {
|
||||
String translated = Grasscutter.getLanguage().get(key);
|
||||
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] =
|
||||
switch (args[i].getClass().getSimpleName()) {
|
||||
case "String" -> args[i];
|
||||
case "TextStrings" -> ((TextStrings) args[i])
|
||||
.get(0)
|
||||
.replace("\\\\n", "\\n"); // TODO: Change this to server language
|
||||
default -> args[i].toString();
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return translated.formatted(args);
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Failed to format string: " + key, exception);
|
||||
return translated;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the translated value from the key while substituting arguments.
|
||||
*
|
||||
* @param player Target player
|
||||
* @param key The key of the translated value to return.
|
||||
* @param args The arguments to substitute.
|
||||
* @return A translated value with arguments substituted.
|
||||
*/
|
||||
public static String translate(Player player, String key, Object... args) {
|
||||
if (player == null) {
|
||||
return translate(key, args);
|
||||
}
|
||||
|
||||
var langCode = Utils.getLanguageCode(player.getAccount().getLocale());
|
||||
String translated = getLanguage(langCode).get(key);
|
||||
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] =
|
||||
switch (args[i].getClass().getSimpleName()) {
|
||||
case "String" -> args[i];
|
||||
case "TextStrings" -> ((TextStrings) args[i])
|
||||
.getGC(langCode)
|
||||
.replace("\\\\n", "\n"); // Note that we don't unescape \n for server console
|
||||
default -> args[i].toString();
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return translated.formatted(args);
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Failed to format string: " + key, exception);
|
||||
return translated;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive helper function to flatten a Json tree Converts input like {"foo": {"bar": "baz"}} to
|
||||
* {"foo.bar": "baz"}
|
||||
*
|
||||
* @param map The map to insert the keys into
|
||||
* @param key The flattened key of the current element
|
||||
* @param element The current element
|
||||
*/
|
||||
private static void putFlattenedKey(Map<String, String> map, String key, JsonElement element) {
|
||||
if (element.isJsonObject()) {
|
||||
element
|
||||
.getAsJsonObject()
|
||||
.entrySet()
|
||||
.forEach(
|
||||
entry -> {
|
||||
String keyPrefix = key.isEmpty() ? "" : key + ".";
|
||||
putFlattenedKey(map, keyPrefix + entry.getKey(), entry.getValue());
|
||||
});
|
||||
} else {
|
||||
map.put(key, element.getAsString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* create a LanguageStreamDescription
|
||||
*
|
||||
* @param languageCode The name of the language code.
|
||||
* @param fallbackLanguageCode The name of the fallback language code.
|
||||
*/
|
||||
private static LanguageStreamDescription getLanguageFileDescription(
|
||||
String languageCode, String fallbackLanguageCode) {
|
||||
var fileName = languageCode + ".json";
|
||||
var fallback = fallbackLanguageCode + ".json";
|
||||
|
||||
String actualLanguageCode = languageCode;
|
||||
InputStream file = Grasscutter.class.getResourceAsStream("/languages/" + fileName);
|
||||
|
||||
if (file == null) { // Provided fallback language.
|
||||
Grasscutter.getLogger()
|
||||
.warn("Failed to load language file: " + fileName + ", falling back to: " + fallback);
|
||||
actualLanguageCode = fallbackLanguageCode;
|
||||
if (cachedLanguages.containsKey(actualLanguageCode)) {
|
||||
return new LanguageStreamDescription(actualLanguageCode, null);
|
||||
}
|
||||
|
||||
file = Grasscutter.class.getResourceAsStream("/languages/" + fallback);
|
||||
}
|
||||
|
||||
if (file == null) { // Fallback the fallback language.
|
||||
Grasscutter.getLogger()
|
||||
.warn("Failed to load language file: " + fallback + ", falling back to: en-US.json");
|
||||
actualLanguageCode = "en-US";
|
||||
if (cachedLanguages.containsKey(actualLanguageCode)) {
|
||||
return new LanguageStreamDescription(actualLanguageCode, null);
|
||||
}
|
||||
|
||||
file = Grasscutter.class.getResourceAsStream("/languages/en-US.json");
|
||||
}
|
||||
|
||||
if (file == null)
|
||||
throw new RuntimeException(
|
||||
"Unable to load the primary, fallback, and 'en-US' language files.");
|
||||
|
||||
return new LanguageStreamDescription(actualLanguageCode, file);
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<String> loadTextMapFile(String language, IntSet nameHashes) {
|
||||
Int2ObjectMap<String> output = new Int2ObjectOpenHashMap<>();
|
||||
try (BufferedReader file =
|
||||
Files.newBufferedReader(
|
||||
getResourcePath("TextMap/TextMap" + language + ".json"), StandardCharsets.UTF_8)) {
|
||||
Matcher matcher = textMapKeyValueRegex.matcher("");
|
||||
return new Int2ObjectOpenHashMap<>(
|
||||
file.lines()
|
||||
.sequential()
|
||||
.map(matcher::reset) // Side effects, but it's faster than making a new one
|
||||
.filter(Matcher::find)
|
||||
.filter(
|
||||
m ->
|
||||
nameHashes.contains(
|
||||
(int) Long.parseLong(m.group(1)))) // TODO: Cache this parse somehow
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
m -> (int) Long.parseLong(m.group(1)),
|
||||
m -> m.group(2).replace("\\\"", "\""))));
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().error("Error loading textmap: " + language);
|
||||
Grasscutter.getLogger().error(e.toString());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapFiles(IntSet nameHashes) {
|
||||
Map<Integer, Int2ObjectMap<String>>
|
||||
mapLanguageMaps = // Separate step to process the textmaps in parallel
|
||||
TextStrings.LIST_LANGUAGES.parallelStream()
|
||||
.collect(
|
||||
Collectors.toConcurrentMap(
|
||||
s -> TextStrings.MAP_LANGUAGES.getInt(s),
|
||||
s -> loadTextMapFile(s, nameHashes)));
|
||||
List<Int2ObjectMap<String>> languageMaps =
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> mapLanguageMaps.get(i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Map<TextStrings, TextStrings> canonicalTextStrings = new HashMap<>();
|
||||
return new Int2ObjectOpenHashMap<TextStrings>(
|
||||
nameHashes
|
||||
.intStream()
|
||||
.boxed()
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
key -> key,
|
||||
key -> {
|
||||
TextStrings t =
|
||||
new TextStrings(
|
||||
IntStream.range(0, TextStrings.NUM_LANGUAGES)
|
||||
.mapToObj(i -> languageMaps.get(i).get((int) key))
|
||||
.collect(Collectors.toList()),
|
||||
key);
|
||||
return canonicalTextStrings.computeIfAbsent(t, x -> t);
|
||||
})));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Int2ObjectMap<TextStrings> loadTextMapsCache() throws Exception {
|
||||
try (ObjectInputStream file =
|
||||
new ObjectInputStream(
|
||||
new BufferedInputStream(Files.newInputStream(TEXTMAP_CACHE_PATH), 0x100000))) {
|
||||
final int fileVersion = file.readInt();
|
||||
if (fileVersion != TEXTMAP_CACHE_VERSION) throw new Exception("Invalid cache version");
|
||||
return (Int2ObjectMap<TextStrings>) file.readObject();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveTextMapsCache(Int2ObjectMap<TextStrings> input) throws IOException {
|
||||
try {
|
||||
Files.createDirectory(Path.of("cache"));
|
||||
} catch (FileAlreadyExistsException ignored) {
|
||||
}
|
||||
try (ObjectOutputStream file =
|
||||
new ObjectOutputStream(
|
||||
new BufferedOutputStream(
|
||||
Files.newOutputStream(TEXTMAP_CACHE_PATH, StandardOpenOption.CREATE), 0x100000))) {
|
||||
file.writeInt(TEXTMAP_CACHE_VERSION);
|
||||
file.writeObject(input);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
public static Int2ObjectMap<TextStrings> getTextMapStrings() {
|
||||
if (textMapStrings == null) loadTextMaps();
|
||||
return textMapStrings;
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(int key) {
|
||||
if ((textMapStrings == null) || (!scannedTextmaps && !textMapStrings.containsKey(key)))
|
||||
loadTextMaps();
|
||||
return textMapStrings.get(key);
|
||||
}
|
||||
|
||||
public static TextStrings getTextMapKey(long hash) {
|
||||
return getTextMapKey((int) hash);
|
||||
}
|
||||
|
||||
public static void loadTextMaps() {
|
||||
// Check system timestamps on cache and resources
|
||||
try {
|
||||
long cacheModified = Files.getLastModifiedTime(TEXTMAP_CACHE_PATH).toMillis();
|
||||
|
||||
long textmapsModified =
|
||||
Files.list(getResourcePath("TextMap"))
|
||||
.filter(path -> path.toString().endsWith(".json"))
|
||||
.map(
|
||||
path -> {
|
||||
try {
|
||||
return Files.getLastModifiedTime(path).toMillis();
|
||||
} catch (Exception ignored) {
|
||||
Grasscutter.getLogger()
|
||||
.debug("Exception while checking modified time: ", path);
|
||||
return Long.MAX_VALUE; // Don't use cache, something has gone wrong
|
||||
}
|
||||
})
|
||||
.max(Long::compare)
|
||||
.get();
|
||||
|
||||
Grasscutter.getLogger()
|
||||
.debug(
|
||||
"Cache modified %d, textmap modified %d".formatted(cacheModified, textmapsModified));
|
||||
if (textmapsModified < cacheModified) {
|
||||
// Try loading from cache
|
||||
Grasscutter.getLogger().info("Loading cached 'TextMaps'...");
|
||||
textMapStrings = loadTextMapsCache();
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Grasscutter.getLogger().debug("Exception while checking cache: ", e);
|
||||
}
|
||||
|
||||
// Regenerate cache
|
||||
Grasscutter.getLogger().debug("Generating TextMaps cache");
|
||||
ResourceLoader.loadAll();
|
||||
IntSet usedHashes = new IntOpenHashSet();
|
||||
GameData.getAchievementDataMap().values().stream()
|
||||
.filter(AchievementData::isUsed)
|
||||
.forEach(
|
||||
a -> {
|
||||
usedHashes.add((int) a.getTitleTextMapHash());
|
||||
usedHashes.add((int) a.getDescTextMapHash());
|
||||
});
|
||||
GameData.getAvatarDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getAvatarSkillDataMap()
|
||||
.forEach(
|
||||
(k, v) -> {
|
||||
usedHashes.add((int) v.getNameTextMapHash());
|
||||
usedHashes.add((int) v.getDescTextMapHash());
|
||||
});
|
||||
GameData.getItemDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getHomeWorldBgmDataMap()
|
||||
.forEach((k, v) -> usedHashes.add((int) v.getBgmNameTextMapHash()));
|
||||
GameData.getMonsterDataMap().forEach((k, v) -> usedHashes.add((int) v.getNameTextMapHash()));
|
||||
GameData.getMainQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getTitleTextMapHash()));
|
||||
GameData.getQuestDataMap().forEach((k, v) -> usedHashes.add((int) v.getDescTextMapHash()));
|
||||
// Incidental strings
|
||||
usedHashes.add((int) 4233146695L); // Character
|
||||
usedHashes.add((int) 4231343903L); // Weapon
|
||||
usedHashes.add((int) 332935371L); // Standard Wish
|
||||
usedHashes.add((int) 2272170627L); // Character Event Wish
|
||||
usedHashes.add((int) 3352513147L); // Character Event Wish-2
|
||||
usedHashes.add((int) 2864268523L); // Weapon Event Wish
|
||||
|
||||
textMapStrings = loadTextMapFiles(usedHashes);
|
||||
scannedTextmaps = true;
|
||||
try {
|
||||
saveTextMapsCache(textMapStrings);
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to save TextMap cache: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** get language code */
|
||||
public String getLanguageCode() {
|
||||
return languageCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value (as a string) from a nested key.
|
||||
*
|
||||
* @param key The key to look for.
|
||||
* @return The value (as a string) from a nested key.
|
||||
*/
|
||||
public String get(String key) {
|
||||
if (translations.containsKey(key)) return translations.get(key);
|
||||
String valueNotFoundPattern = "This value does not exist. Please report this to the Discord: ";
|
||||
String result = valueNotFoundPattern + key;
|
||||
if (!languageCode.equals("en-US")) {
|
||||
String englishValue = getLanguage("en-US").get(key);
|
||||
if (!englishValue.contains(valueNotFoundPattern)) {
|
||||
result += "\nhere is english version:\n" + englishValue;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static class LanguageStreamDescription {
|
||||
private final String languageCode;
|
||||
private final InputStream languageFile;
|
||||
|
||||
public LanguageStreamDescription(String languageCode, InputStream languageFile) {
|
||||
this.languageCode = languageCode;
|
||||
this.languageFile = languageFile;
|
||||
}
|
||||
|
||||
public String getLanguageCode() {
|
||||
return languageCode;
|
||||
}
|
||||
|
||||
public InputStream getLanguageFile() {
|
||||
return languageFile;
|
||||
}
|
||||
}
|
||||
|
||||
@EqualsAndHashCode
|
||||
public static class TextStrings implements Serializable {
|
||||
public static final String[] ARR_LANGUAGES = {
|
||||
"EN", "CHS", "CHT", "JP", "KR", "DE", "ES", "FR", "ID", "PT", "RU", "TH", "VI"
|
||||
};
|
||||
public static final String[] ARR_GC_LANGUAGES = {
|
||||
"en-US", "zh-CN", "zh-TW", "ja-JP", "ko-KR", "en-US", "es-ES", "fr-FR", "en-US", "en-US",
|
||||
"ru-RU", "en-US", "en-US"
|
||||
}; // TODO: Update the placeholder en-US entries if we ever add GC translations for the missing
|
||||
// client languages
|
||||
public static final int NUM_LANGUAGES = ARR_LANGUAGES.length;
|
||||
public static final List<String> LIST_LANGUAGES = Arrays.asList(ARR_LANGUAGES);
|
||||
public static final Object2IntMap<String>
|
||||
MAP_LANGUAGES = // Map "EN": 0, "CHS": 1, ..., "VI": 12
|
||||
new Object2IntOpenHashMap<>(
|
||||
IntStream.range(0, ARR_LANGUAGES.length)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(i -> ARR_LANGUAGES[i], i -> i)));
|
||||
public static final Object2IntMap<String> MAP_GC_LANGUAGES = // Map "en-US": 0, "zh-CN": 1, ...
|
||||
new Object2IntOpenHashMap<>(
|
||||
IntStream.range(0, ARR_GC_LANGUAGES.length)
|
||||
.boxed()
|
||||
.collect(
|
||||
Collectors.toMap(
|
||||
i -> ARR_GC_LANGUAGES[i],
|
||||
i -> i,
|
||||
(i1, i2) -> i1))); // Have to handle duplicates referring back to the first
|
||||
public String[] strings = new String[ARR_LANGUAGES.length];
|
||||
|
||||
public TextStrings() {}
|
||||
|
||||
public TextStrings(String init) {
|
||||
for (int i = 0; i < NUM_LANGUAGES; i++) this.strings[i] = init;
|
||||
}
|
||||
|
||||
public TextStrings(List<String> strings, int key) {
|
||||
// Some hashes don't have strings for some languages :(
|
||||
String nullReplacement = "[N/A] %d".formatted((long) key & 0xFFFFFFFFL);
|
||||
for (int i = 0; i < NUM_LANGUAGES; i++) { // Find first non-null if there is any
|
||||
String s = strings.get(i);
|
||||
if (s != null) {
|
||||
nullReplacement = "[%s] - %s".formatted(ARR_LANGUAGES[i], s);
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < NUM_LANGUAGES; i++) {
|
||||
String s = strings.get(i);
|
||||
if (s != null) this.strings[i] = s;
|
||||
else this.strings[i] = nullReplacement;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Language> getLanguages() {
|
||||
return Arrays.stream(ARR_GC_LANGUAGES).map(Language::getLanguage).toList();
|
||||
}
|
||||
|
||||
public String get(int languageIndex) {
|
||||
return strings[languageIndex];
|
||||
}
|
||||
|
||||
public String get(String languageCode) {
|
||||
return strings[MAP_LANGUAGES.getOrDefault(languageCode, 0)];
|
||||
}
|
||||
|
||||
public String getGC(String languageCode) {
|
||||
return strings[MAP_GC_LANGUAGES.getOrDefault(languageCode, 0)];
|
||||
}
|
||||
|
||||
public boolean set(String languageCode, String string) {
|
||||
int index = MAP_LANGUAGES.getOrDefault(languageCode, -1);
|
||||
if (index < 0) return false;
|
||||
strings[index] = string;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,43 +1,40 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import dev.morphia.annotations.Entity;
|
||||
import dev.morphia.annotations.Transient;
|
||||
import emu.grasscutter.game.world.Scene;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
public class Location extends Position {
|
||||
@Transient
|
||||
@Getter
|
||||
@Setter
|
||||
private Scene scene;
|
||||
|
||||
public Location(Scene scene, Position position) {
|
||||
this.set(position);
|
||||
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
public Location(Scene scene, float x, float y) {
|
||||
this.set(x, y);
|
||||
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
public Location(Scene scene, float x, float y, float z) {
|
||||
this.set(x, y, z);
|
||||
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location clone() {
|
||||
return new Location(this.scene, super.clone());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s:%s,%s,%s", this.scene.getId(), this.getX(), this.getY(), this.getZ());
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import dev.morphia.annotations.Entity;
|
||||
import dev.morphia.annotations.Transient;
|
||||
import emu.grasscutter.game.world.Scene;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
public class Location extends Position {
|
||||
@Transient @Getter @Setter private Scene scene;
|
||||
|
||||
public Location(Scene scene, Position position) {
|
||||
this.set(position);
|
||||
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
public Location(Scene scene, float x, float y) {
|
||||
this.set(x, y);
|
||||
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
public Location(Scene scene, float x, float y, float z) {
|
||||
this.set(x, y, z);
|
||||
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Location clone() {
|
||||
return new Location(this.scene, super.clone());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s:%s,%s,%s", this.scene.getId(), this.getX(), this.getY(), this.getZ());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
public class MessageHandler {
|
||||
private String message;
|
||||
|
||||
public MessageHandler() {
|
||||
this.message = "";
|
||||
}
|
||||
|
||||
public void append(String message) {
|
||||
this.message += message + "\r\n\r\n";
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
public class MessageHandler {
|
||||
private String message;
|
||||
|
||||
public MessageHandler() {
|
||||
this.message = "";
|
||||
}
|
||||
|
||||
public void append(String message) {
|
||||
this.message += message + "\r\n\r\n";
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,201 +1,196 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.github.davidmoten.rtreemulti.geometry.Point;
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import dev.morphia.annotations.Entity;
|
||||
import emu.grasscutter.net.proto.VectorOuterClass.Vector;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Position implements Serializable {
|
||||
private static final long serialVersionUID = -2001232313615923575L;
|
||||
|
||||
@SerializedName(value = "x", alternate = {"_x", "X"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float x;
|
||||
|
||||
@SerializedName(value = "y", alternate = {"_y", "Y"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float y;
|
||||
|
||||
@SerializedName(value = "z", alternate = {"_z", "Z"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float z;
|
||||
|
||||
public Position() {
|
||||
}
|
||||
|
||||
public Position(float x, float y) {
|
||||
set(x, y);
|
||||
}
|
||||
|
||||
public Position(float x, float y, float z) {
|
||||
set(x, y, z);
|
||||
}
|
||||
|
||||
public Position(List<Float> xyz) {
|
||||
switch (xyz.size()) {
|
||||
default: // Might want to error on excess elements, but maybe we want to extend to 3+3 representation later.
|
||||
case 3:
|
||||
this.z = xyz.get(2); // Fall-through
|
||||
case 2:
|
||||
this.y = xyz.get(1); // Fall-through
|
||||
case 1:
|
||||
this.y = xyz.get(0); // pointless fall-through
|
||||
case 0:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public Position(String p) {
|
||||
String[] split = p.split(",");
|
||||
if (split.length >= 2) {
|
||||
this.x = Float.parseFloat(split[0]);
|
||||
this.y = Float.parseFloat(split[1]);
|
||||
}
|
||||
if (split.length >= 3) {
|
||||
this.z = Float.parseFloat(split[2]);
|
||||
}
|
||||
}
|
||||
|
||||
public Position(Vector vector) {
|
||||
this.set(vector);
|
||||
}
|
||||
|
||||
public Position(Position pos) {
|
||||
this.set(pos);
|
||||
}
|
||||
|
||||
public Position set(float x, float y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Deep copy
|
||||
public Position set(Position pos) {
|
||||
return this.set(pos.getX(), pos.getY(), pos.getZ());
|
||||
}
|
||||
|
||||
public Position set(Vector pos) {
|
||||
return this.set(pos.getX(), pos.getY(), pos.getZ());
|
||||
}
|
||||
|
||||
public Position set(float x, float y, float z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position add(Position add) {
|
||||
this.x += add.getX();
|
||||
this.y += add.getY();
|
||||
this.z += add.getZ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position addX(float d) {
|
||||
this.x += d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position addY(float d) {
|
||||
this.y += d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position addZ(float d) {
|
||||
this.z += d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position subtract(Position sub) {
|
||||
this.x -= sub.getX();
|
||||
this.y -= sub.getY();
|
||||
this.z -= sub.getZ();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* In radians
|
||||
*/
|
||||
public Position translate(float dist, float angle) {
|
||||
this.x += dist * Math.sin(angle);
|
||||
this.y += dist * Math.cos(angle);
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean equal2d(Position other) {
|
||||
// Y is height
|
||||
return getX() == other.getX() && getZ() == other.getZ();
|
||||
}
|
||||
|
||||
public boolean equal3d(Position other) {
|
||||
return getX() == other.getX() && getY() == other.getY() && getZ() == other.getZ();
|
||||
}
|
||||
|
||||
public double computeDistance(Position b) {
|
||||
double detX = getX() - b.getX();
|
||||
double detY = getY() - b.getY();
|
||||
double detZ = getZ() - b.getZ();
|
||||
return Math.sqrt(detX * detX + detY * detY + detZ * detZ);
|
||||
}
|
||||
|
||||
public Position nearby2d(float range) {
|
||||
Position position = clone();
|
||||
position.z += Utils.randomFloatRange(-range, range);
|
||||
position.x += Utils.randomFloatRange(-range, range);
|
||||
return position;
|
||||
}
|
||||
|
||||
public Position translateWithDegrees(float dist, float angle) {
|
||||
angle = (float) Math.toRadians(angle);
|
||||
this.x += dist * Math.sin(angle);
|
||||
this.y += -dist * Math.cos(angle);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Position clone() {
|
||||
return new Position(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "(" + this.getX() + ", " + this.getY() + ", " + this.getZ() + ")";
|
||||
}
|
||||
|
||||
public Vector toProto() {
|
||||
return Vector.newBuilder()
|
||||
.setX(this.getX())
|
||||
.setY(this.getY())
|
||||
.setZ(this.getZ())
|
||||
.build();
|
||||
}
|
||||
|
||||
public Point toPoint() {
|
||||
return Point.create(x, y, z);
|
||||
}
|
||||
|
||||
/**
|
||||
* To XYZ array for Spatial Index
|
||||
*/
|
||||
public double[] toDoubleArray() {
|
||||
return new double[]{x, y, z};
|
||||
}
|
||||
|
||||
/**
|
||||
* To XZ array for Spatial Index (Blocks)
|
||||
*/
|
||||
public double[] toXZDoubleArray() {
|
||||
return new double[]{x, z};
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.github.davidmoten.rtreemulti.geometry.Point;
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import dev.morphia.annotations.Entity;
|
||||
import emu.grasscutter.net.proto.VectorOuterClass.Vector;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
public class Position implements Serializable {
|
||||
private static final long serialVersionUID = -2001232313615923575L;
|
||||
|
||||
@SerializedName(
|
||||
value = "x",
|
||||
alternate = {"_x", "X"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float x;
|
||||
|
||||
@SerializedName(
|
||||
value = "y",
|
||||
alternate = {"_y", "Y"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float y;
|
||||
|
||||
@SerializedName(
|
||||
value = "z",
|
||||
alternate = {"_z", "Z"})
|
||||
@Getter
|
||||
@Setter
|
||||
private float z;
|
||||
|
||||
public Position() {}
|
||||
|
||||
public Position(float x, float y) {
|
||||
set(x, y);
|
||||
}
|
||||
|
||||
public Position(float x, float y, float z) {
|
||||
set(x, y, z);
|
||||
}
|
||||
|
||||
public Position(List<Float> xyz) {
|
||||
switch (xyz.size()) {
|
||||
default: // Might want to error on excess elements, but maybe we want to extend to 3+3
|
||||
// representation later.
|
||||
case 3:
|
||||
this.z = xyz.get(2); // Fall-through
|
||||
case 2:
|
||||
this.y = xyz.get(1); // Fall-through
|
||||
case 1:
|
||||
this.y = xyz.get(0); // pointless fall-through
|
||||
case 0:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public Position(String p) {
|
||||
String[] split = p.split(",");
|
||||
if (split.length >= 2) {
|
||||
this.x = Float.parseFloat(split[0]);
|
||||
this.y = Float.parseFloat(split[1]);
|
||||
}
|
||||
if (split.length >= 3) {
|
||||
this.z = Float.parseFloat(split[2]);
|
||||
}
|
||||
}
|
||||
|
||||
public Position(Vector vector) {
|
||||
this.set(vector);
|
||||
}
|
||||
|
||||
public Position(Position pos) {
|
||||
this.set(pos);
|
||||
}
|
||||
|
||||
public Position set(float x, float y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Deep copy
|
||||
public Position set(Position pos) {
|
||||
return this.set(pos.getX(), pos.getY(), pos.getZ());
|
||||
}
|
||||
|
||||
public Position set(Vector pos) {
|
||||
return this.set(pos.getX(), pos.getY(), pos.getZ());
|
||||
}
|
||||
|
||||
public Position set(float x, float y, float z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position add(Position add) {
|
||||
this.x += add.getX();
|
||||
this.y += add.getY();
|
||||
this.z += add.getZ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position addX(float d) {
|
||||
this.x += d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position addY(float d) {
|
||||
this.y += d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position addZ(float d) {
|
||||
this.z += d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Position subtract(Position sub) {
|
||||
this.x -= sub.getX();
|
||||
this.y -= sub.getY();
|
||||
this.z -= sub.getZ();
|
||||
return this;
|
||||
}
|
||||
|
||||
/** In radians */
|
||||
public Position translate(float dist, float angle) {
|
||||
this.x += dist * Math.sin(angle);
|
||||
this.y += dist * Math.cos(angle);
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean equal2d(Position other) {
|
||||
// Y is height
|
||||
return getX() == other.getX() && getZ() == other.getZ();
|
||||
}
|
||||
|
||||
public boolean equal3d(Position other) {
|
||||
return getX() == other.getX() && getY() == other.getY() && getZ() == other.getZ();
|
||||
}
|
||||
|
||||
public double computeDistance(Position b) {
|
||||
double detX = getX() - b.getX();
|
||||
double detY = getY() - b.getY();
|
||||
double detZ = getZ() - b.getZ();
|
||||
return Math.sqrt(detX * detX + detY * detY + detZ * detZ);
|
||||
}
|
||||
|
||||
public Position nearby2d(float range) {
|
||||
Position position = clone();
|
||||
position.z += Utils.randomFloatRange(-range, range);
|
||||
position.x += Utils.randomFloatRange(-range, range);
|
||||
return position;
|
||||
}
|
||||
|
||||
public Position translateWithDegrees(float dist, float angle) {
|
||||
angle = (float) Math.toRadians(angle);
|
||||
this.x += dist * Math.sin(angle);
|
||||
this.y += -dist * Math.cos(angle);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Position clone() {
|
||||
return new Position(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "(" + this.getX() + ", " + this.getY() + ", " + this.getZ() + ")";
|
||||
}
|
||||
|
||||
public Vector toProto() {
|
||||
return Vector.newBuilder().setX(this.getX()).setY(this.getY()).setZ(this.getZ()).build();
|
||||
}
|
||||
|
||||
public Point toPoint() {
|
||||
return Point.create(x, y, z);
|
||||
}
|
||||
|
||||
/** To XYZ array for Spatial Index */
|
||||
public double[] toDoubleArray() {
|
||||
return new double[] {x, y, z};
|
||||
}
|
||||
|
||||
/** To XZ array for Spatial Index (Blocks) */
|
||||
public double[] toXZDoubleArray() {
|
||||
return new double[] {x, z};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.game.props.PlayerProperty;
|
||||
import emu.grasscutter.net.proto.PropValueOuterClass.PropValue;
|
||||
|
||||
public final class ProtoHelper {
|
||||
public static PropValue newPropValue(PlayerProperty key, int value) {
|
||||
return PropValue.newBuilder().setType(key.getId()).setIval(value).setVal(value).build();
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.game.props.PlayerProperty;
|
||||
import emu.grasscutter.net.proto.PropValueOuterClass.PropValue;
|
||||
|
||||
public final class ProtoHelper {
|
||||
public static PropValue newPropValue(PlayerProperty key, int value) {
|
||||
return PropValue.newBuilder().setType(key.getId()).setIval(value).setVal(value).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
import ch.qos.logback.core.encoder.Encoder;
|
||||
import emu.grasscutter.server.event.internal.ServerLogEvent;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class ServerLogEventAppender<E> extends AppenderBase<E> {
|
||||
protected Encoder<E> encoder;
|
||||
|
||||
@Override
|
||||
protected void append(E event) {
|
||||
byte[] byteArray = this.encoder.encode(event);
|
||||
ServerLogEvent sle = new ServerLogEvent((ILoggingEvent) event, new String(byteArray, StandardCharsets.UTF_8));
|
||||
sle.call();
|
||||
}
|
||||
|
||||
public Encoder<E> getEncoder() {
|
||||
return this.encoder;
|
||||
}
|
||||
|
||||
public void setEncoder(Encoder<E> encoder) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
import ch.qos.logback.core.encoder.Encoder;
|
||||
import emu.grasscutter.server.event.internal.ServerLogEvent;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class ServerLogEventAppender<E> extends AppenderBase<E> {
|
||||
protected Encoder<E> encoder;
|
||||
|
||||
@Override
|
||||
protected void append(E event) {
|
||||
byte[] byteArray = this.encoder.encode(event);
|
||||
ServerLogEvent sle =
|
||||
new ServerLogEvent((ILoggingEvent) event, new String(byteArray, StandardCharsets.UTF_8));
|
||||
sle.call();
|
||||
}
|
||||
|
||||
public Encoder<E> getEncoder() {
|
||||
return this.encoder;
|
||||
}
|
||||
|
||||
public void setEncoder(Encoder<E> encoder) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +1,67 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
public final class SparseSet {
|
||||
private final List<Range> rangeEntries;
|
||||
private final Set<Integer> denseEntries;
|
||||
public SparseSet(String csv) {
|
||||
this.rangeEntries = new ArrayList<>();
|
||||
this.denseEntries = new TreeSet<>();
|
||||
|
||||
for (String token : csv.replace("\n", "").replace(" ", "").split(",")) {
|
||||
String[] tokens = token.split("-");
|
||||
switch (tokens.length) {
|
||||
case 1:
|
||||
this.denseEntries.add(Integer.parseInt(tokens[0]));
|
||||
break;
|
||||
case 2:
|
||||
this.rangeEntries.add(new Range(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])));
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid token passed to SparseSet initializer - " + token + " (split length " + tokens.length + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean contains(int i) {
|
||||
for (Range range : this.rangeEntries) {
|
||||
if (range.check(i)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return this.denseEntries.contains(i);
|
||||
}
|
||||
|
||||
/*
|
||||
* A convenience class for constructing integer sets out of large ranges
|
||||
* Designed to be fed literal strings from this project only -
|
||||
* can and will throw exceptions to tell you to fix your code if you feed it garbage. :)
|
||||
*/
|
||||
private static class Range {
|
||||
private final int min, max;
|
||||
|
||||
public Range(int min, int max) {
|
||||
if (min > max) {
|
||||
throw new IllegalArgumentException("Range passed minimum higher than maximum - " + min + " > " + max);
|
||||
}
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public boolean check(int value) {
|
||||
return value >= this.min && value <= this.max;
|
||||
}
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
public final class SparseSet {
|
||||
private final List<Range> rangeEntries;
|
||||
private final Set<Integer> denseEntries;
|
||||
|
||||
public SparseSet(String csv) {
|
||||
this.rangeEntries = new ArrayList<>();
|
||||
this.denseEntries = new TreeSet<>();
|
||||
|
||||
for (String token : csv.replace("\n", "").replace(" ", "").split(",")) {
|
||||
String[] tokens = token.split("-");
|
||||
switch (tokens.length) {
|
||||
case 1:
|
||||
this.denseEntries.add(Integer.parseInt(tokens[0]));
|
||||
break;
|
||||
case 2:
|
||||
this.rangeEntries.add(
|
||||
new Range(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])));
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid token passed to SparseSet initializer - "
|
||||
+ token
|
||||
+ " (split length "
|
||||
+ tokens.length
|
||||
+ ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean contains(int i) {
|
||||
for (Range range : this.rangeEntries) {
|
||||
if (range.check(i)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return this.denseEntries.contains(i);
|
||||
}
|
||||
|
||||
/*
|
||||
* A convenience class for constructing integer sets out of large ranges
|
||||
* Designed to be fed literal strings from this project only -
|
||||
* can and will throw exceptions to tell you to fix your code if you feed it garbage. :)
|
||||
*/
|
||||
private static class Range {
|
||||
private final int min, max;
|
||||
|
||||
public Range(int min, int max) {
|
||||
if (min > max) {
|
||||
throw new IllegalArgumentException(
|
||||
"Range passed minimum higher than maximum - " + min + " > " + max);
|
||||
}
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public boolean check(int value) {
|
||||
return value >= this.min && value <= this.max;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,131 +1,129 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import emu.grasscutter.BuildConfig;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.Grasscutter.ServerRunMode;
|
||||
import emu.grasscutter.net.packet.PacketOpcodesUtils;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
|
||||
/**
|
||||
* A parser for start-up arguments.
|
||||
*/
|
||||
public final class StartupArguments {
|
||||
/* A map of parameter -> argument handler. */
|
||||
private static final Map<String, Function<String, Boolean>> argumentHandlers = Map.of(
|
||||
"-dumppacketids", parameter -> {
|
||||
PacketOpcodesUtils.dumpPacketIds();
|
||||
return true;
|
||||
},
|
||||
"-version", StartupArguments::printVersion,
|
||||
"-debug", StartupArguments::enableDebug,
|
||||
"-lang", parameter -> {
|
||||
Grasscutter.setPreferredLanguage(parameter);
|
||||
return false;
|
||||
},
|
||||
"-game", parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.GAME_ONLY);
|
||||
return false;
|
||||
},
|
||||
"-dispatch", parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.DISPATCH_ONLY);
|
||||
return false;
|
||||
},
|
||||
"-test", parameter -> {
|
||||
// Disable the console.
|
||||
SERVER.game.enableConsole = false;
|
||||
// Disable HTTP encryption.
|
||||
SERVER.http.encryption.useEncryption = false;
|
||||
return false;
|
||||
},
|
||||
|
||||
// Aliases.
|
||||
"-v", StartupArguments::printVersion,
|
||||
"-debugall", parameter -> {
|
||||
StartupArguments.enableDebug("all");
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
private StartupArguments() {
|
||||
// This class is not meant to be instantiated.
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the provided start-up arguments.
|
||||
*
|
||||
* @param args The application start-up arguments.
|
||||
* @return If the application should exit.
|
||||
*/
|
||||
public static boolean parse(String[] args) {
|
||||
boolean exitEarly = false;
|
||||
|
||||
// Parse the arguments.
|
||||
for (var input : args) {
|
||||
var containsParameter = input.contains("=");
|
||||
|
||||
var argument = containsParameter ? input.split("=")[0] : input;
|
||||
var handler = argumentHandlers.get(argument.toLowerCase());
|
||||
|
||||
if (handler != null) {
|
||||
exitEarly |= handler.apply(containsParameter ? input.split("=")[1] : null);
|
||||
}
|
||||
}
|
||||
|
||||
return exitEarly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the server version.
|
||||
*
|
||||
* @param parameter Additional parameters.
|
||||
* @return True to exit early.
|
||||
*/
|
||||
private static boolean printVersion(String parameter) {
|
||||
System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables debug logging.
|
||||
*
|
||||
* @param parameter Additional parameters.
|
||||
* @return False to continue execution.
|
||||
*/
|
||||
private static boolean enableDebug(String parameter) {
|
||||
if (parameter != null && parameter.equals("all")) {
|
||||
// Override default debug configs
|
||||
GAME_INFO.isShowLoopPackets = DEBUG_MODE_INFO.isShowLoopPackets;
|
||||
GAME_INFO.isShowPacketPayload = DEBUG_MODE_INFO.isShowPacketPayload;
|
||||
GAME_INFO.logPackets = DEBUG_MODE_INFO.logPackets;
|
||||
DISPATCH_INFO.logRequests = DEBUG_MODE_INFO.logRequests;
|
||||
}
|
||||
|
||||
// Set the main logger to debug.
|
||||
Grasscutter.getLogger().setLevel(DEBUG_MODE_INFO.serverLoggerLevel);
|
||||
Grasscutter.getLogger().debug("The logger is now running in debug mode.");
|
||||
|
||||
// Log level to other third-party services
|
||||
Level loggerLevel = DEBUG_MODE_INFO.servicesLoggersLevel;
|
||||
|
||||
// Change loggers to debug.
|
||||
((Logger) LoggerFactory.getLogger("io.javalin"))
|
||||
.setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.quartz"))
|
||||
.setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.reflections"))
|
||||
.setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.eclipse.jetty"))
|
||||
.setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.mongodb.driver"))
|
||||
.setLevel(loggerLevel);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import emu.grasscutter.BuildConfig;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.Grasscutter.ServerRunMode;
|
||||
import emu.grasscutter.net.packet.PacketOpcodesUtils;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** A parser for start-up arguments. */
|
||||
public final class StartupArguments {
|
||||
/* A map of parameter -> argument handler. */
|
||||
private static final Map<String, Function<String, Boolean>> argumentHandlers =
|
||||
Map.of(
|
||||
"-dumppacketids",
|
||||
parameter -> {
|
||||
PacketOpcodesUtils.dumpPacketIds();
|
||||
return true;
|
||||
},
|
||||
"-version", StartupArguments::printVersion,
|
||||
"-debug", StartupArguments::enableDebug,
|
||||
"-lang",
|
||||
parameter -> {
|
||||
Grasscutter.setPreferredLanguage(parameter);
|
||||
return false;
|
||||
},
|
||||
"-game",
|
||||
parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.GAME_ONLY);
|
||||
return false;
|
||||
},
|
||||
"-dispatch",
|
||||
parameter -> {
|
||||
Grasscutter.setRunModeOverride(ServerRunMode.DISPATCH_ONLY);
|
||||
return false;
|
||||
},
|
||||
"-test",
|
||||
parameter -> {
|
||||
// Disable the console.
|
||||
SERVER.game.enableConsole = false;
|
||||
// Disable HTTP encryption.
|
||||
SERVER.http.encryption.useEncryption = false;
|
||||
return false;
|
||||
},
|
||||
|
||||
// Aliases.
|
||||
"-v", StartupArguments::printVersion,
|
||||
"-debugall",
|
||||
parameter -> {
|
||||
StartupArguments.enableDebug("all");
|
||||
return false;
|
||||
});
|
||||
|
||||
private StartupArguments() {
|
||||
// This class is not meant to be instantiated.
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the provided start-up arguments.
|
||||
*
|
||||
* @param args The application start-up arguments.
|
||||
* @return If the application should exit.
|
||||
*/
|
||||
public static boolean parse(String[] args) {
|
||||
boolean exitEarly = false;
|
||||
|
||||
// Parse the arguments.
|
||||
for (var input : args) {
|
||||
var containsParameter = input.contains("=");
|
||||
|
||||
var argument = containsParameter ? input.split("=")[0] : input;
|
||||
var handler = argumentHandlers.get(argument.toLowerCase());
|
||||
|
||||
if (handler != null) {
|
||||
exitEarly |= handler.apply(containsParameter ? input.split("=")[1] : null);
|
||||
}
|
||||
}
|
||||
|
||||
return exitEarly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the server version.
|
||||
*
|
||||
* @param parameter Additional parameters.
|
||||
* @return True to exit early.
|
||||
*/
|
||||
private static boolean printVersion(String parameter) {
|
||||
System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables debug logging.
|
||||
*
|
||||
* @param parameter Additional parameters.
|
||||
* @return False to continue execution.
|
||||
*/
|
||||
private static boolean enableDebug(String parameter) {
|
||||
if (parameter != null && parameter.equals("all")) {
|
||||
// Override default debug configs
|
||||
GAME_INFO.isShowLoopPackets = DEBUG_MODE_INFO.isShowLoopPackets;
|
||||
GAME_INFO.isShowPacketPayload = DEBUG_MODE_INFO.isShowPacketPayload;
|
||||
GAME_INFO.logPackets = DEBUG_MODE_INFO.logPackets;
|
||||
DISPATCH_INFO.logRequests = DEBUG_MODE_INFO.logRequests;
|
||||
}
|
||||
|
||||
// Set the main logger to debug.
|
||||
Grasscutter.getLogger().setLevel(DEBUG_MODE_INFO.serverLoggerLevel);
|
||||
Grasscutter.getLogger().debug("The logger is now running in debug mode.");
|
||||
|
||||
// Log level to other third-party services
|
||||
Level loggerLevel = DEBUG_MODE_INFO.servicesLoggersLevel;
|
||||
|
||||
// Change loggers to debug.
|
||||
((Logger) LoggerFactory.getLogger("io.javalin")).setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.quartz")).setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.reflections")).setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.eclipse.jetty")).setLevel(loggerLevel);
|
||||
((Logger) LoggerFactory.getLogger("org.mongodb.driver")).setLevel(loggerLevel);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,436 +1,449 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.config.ConfigContainer;
|
||||
import emu.grasscutter.data.DataLoader;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.ByteBufUtil;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
@SuppressWarnings({"UnusedReturnValue", "BooleanMethodIsAlwaysInverted"})
|
||||
public final class Utils {
|
||||
public static final Random random = new Random();
|
||||
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
|
||||
|
||||
public static int randomRange(int min, int max) {
|
||||
return random.nextInt(max - min + 1) + min;
|
||||
}
|
||||
|
||||
public static float randomFloatRange(float min, float max) {
|
||||
return random.nextFloat() * (max - min) + min;
|
||||
}
|
||||
|
||||
public static double getDist(Position pos1, Position pos2) {
|
||||
double xs = pos1.getX() - pos2.getX();
|
||||
xs = xs * xs;
|
||||
|
||||
double ys = pos1.getY() - pos2.getY();
|
||||
ys = ys * ys;
|
||||
|
||||
double zs = pos1.getZ() - pos2.getZ();
|
||||
zs = zs * zs;
|
||||
|
||||
return Math.sqrt(xs + zs + ys);
|
||||
}
|
||||
|
||||
public static int getCurrentSeconds() {
|
||||
return (int) (System.currentTimeMillis() / 1000.0);
|
||||
}
|
||||
|
||||
public static String lowerCaseFirstChar(String s) {
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
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()) {
|
||||
buf.write((byte) result);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static void logByteArray(byte[] array) {
|
||||
ByteBuf b = Unpooled.wrappedBuffer(array);
|
||||
Grasscutter.getLogger().info("\n" + ByteBufUtil.prettyHexDump(b));
|
||||
b.release();
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
if (bytes == null) return "";
|
||||
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);
|
||||
}
|
||||
|
||||
public static String bytesToHex(ByteBuf buf) {
|
||||
return bytesToHex(byteBufToArray(buf));
|
||||
}
|
||||
|
||||
public static byte[] byteBufToArray(ByteBuf buf) {
|
||||
byte[] bytes = new byte[buf.capacity()];
|
||||
buf.getBytes(0, bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static int abilityHash(String str) {
|
||||
int v7 = 0;
|
||||
int v8 = 0;
|
||||
while (v8 < str.length()) {
|
||||
v7 = str.charAt(v8++) + 131 * v7;
|
||||
}
|
||||
return v7;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Unable to copy resource " + resource + " to " + destination, exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an object to the console.
|
||||
*
|
||||
* @param object The object to log.
|
||||
*/
|
||||
public static void logObject(Object object) {
|
||||
Grasscutter.getLogger().info(JsonUtils.encode(object));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for required files and folders before startup.
|
||||
*/
|
||||
public static void startupCheck() {
|
||||
ConfigContainer config = Grasscutter.getConfig();
|
||||
Logger logger = Grasscutter.getLogger();
|
||||
boolean exit = false;
|
||||
|
||||
String dataFolder = config.folderStructure.data;
|
||||
|
||||
// Check for resources folder.
|
||||
if (!Files.exists(getResourcePath(""))) {
|
||||
logger.info(translate("messages.status.create_resources"));
|
||||
logger.info(translate("messages.status.resources_error"));
|
||||
createFolder(config.folderStructure.resources);
|
||||
exit = true;
|
||||
}
|
||||
|
||||
// Check for BinOutput + ExcelBinOutput.
|
||||
if (!Files.exists(getResourcePath("BinOutput")) ||
|
||||
!Files.exists(getResourcePath("ExcelBinOutput"))) {
|
||||
logger.info(translate("messages.status.resources_error"));
|
||||
exit = true;
|
||||
}
|
||||
|
||||
// Check for game data.
|
||||
if (!fileExists(dataFolder))
|
||||
createFolder(dataFolder);
|
||||
|
||||
// Make sure the data folder is populated, if there are any missing files copy them from resources
|
||||
DataLoader.checkAllFiles();
|
||||
|
||||
if (exit) System.exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the timestamp of the next hour.
|
||||
*
|
||||
* @return The timestamp in UNIX seconds.
|
||||
*/
|
||||
public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a string from an input stream.
|
||||
*
|
||||
* @param stream The input stream.
|
||||
* @return The string.
|
||||
*/
|
||||
public static String readFromInputStream(@Nullable InputStream stream) {
|
||||
if (stream == null) return "empty";
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
stringBuilder.append(line);
|
||||
}
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read from input stream.");
|
||||
} catch (NullPointerException ignored) {
|
||||
return "empty";
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a linear interpolation using a table of fixed points to create an effective piecewise f(x) = y function.
|
||||
*
|
||||
* @param x The x value.
|
||||
* @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!
|
||||
// Using floats would be slightly cleaner but we can just as easily use ints if we're careful with order of operations.
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the language code from a given locale.
|
||||
*
|
||||
* @param locale A locale.
|
||||
* @return A string in the format of 'XX-XX'.
|
||||
*/
|
||||
public static String getLanguageCode(Locale locale) {
|
||||
return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/***
|
||||
* 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);
|
||||
}
|
||||
|
||||
/***
|
||||
* 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);
|
||||
}
|
||||
|
||||
/***
|
||||
* Splits a string by a character, into a list
|
||||
* @param input The string to split
|
||||
* @param separator The character to use as the split points
|
||||
* @return A list of all the substrings
|
||||
*/
|
||||
public static List<String> nonRegexSplit(String input, int separator) {
|
||||
var output = new ArrayList<String>();
|
||||
int start = 0;
|
||||
for (int next = input.indexOf(separator); next > 0; next = input.indexOf(separator, start)) {
|
||||
output.add(input.substring(start, next));
|
||||
start = next + 1;
|
||||
}
|
||||
if (start < input.length())
|
||||
output.add(input.substring(start));
|
||||
return output;
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.config.ConfigContainer;
|
||||
import emu.grasscutter.data.DataLoader;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.ByteBufUtil;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
@SuppressWarnings({"UnusedReturnValue", "BooleanMethodIsAlwaysInverted"})
|
||||
public final class Utils {
|
||||
public static final Random random = new Random();
|
||||
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
|
||||
|
||||
public static int randomRange(int min, int max) {
|
||||
return random.nextInt(max - min + 1) + min;
|
||||
}
|
||||
|
||||
public static float randomFloatRange(float min, float max) {
|
||||
return random.nextFloat() * (max - min) + min;
|
||||
}
|
||||
|
||||
public static double getDist(Position pos1, Position pos2) {
|
||||
double xs = pos1.getX() - pos2.getX();
|
||||
xs = xs * xs;
|
||||
|
||||
double ys = pos1.getY() - pos2.getY();
|
||||
ys = ys * ys;
|
||||
|
||||
double zs = pos1.getZ() - pos2.getZ();
|
||||
zs = zs * zs;
|
||||
|
||||
return Math.sqrt(xs + zs + ys);
|
||||
}
|
||||
|
||||
public static int getCurrentSeconds() {
|
||||
return (int) (System.currentTimeMillis() / 1000.0);
|
||||
}
|
||||
|
||||
public static String lowerCaseFirstChar(String s) {
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
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()) {
|
||||
buf.write((byte) result);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static void logByteArray(byte[] array) {
|
||||
ByteBuf b = Unpooled.wrappedBuffer(array);
|
||||
Grasscutter.getLogger().info("\n" + ByteBufUtil.prettyHexDump(b));
|
||||
b.release();
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
if (bytes == null) return "";
|
||||
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);
|
||||
}
|
||||
|
||||
public static String bytesToHex(ByteBuf buf) {
|
||||
return bytesToHex(byteBufToArray(buf));
|
||||
}
|
||||
|
||||
public static byte[] byteBufToArray(ByteBuf buf) {
|
||||
byte[] bytes = new byte[buf.capacity()];
|
||||
buf.getBytes(0, bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static int abilityHash(String str) {
|
||||
int v7 = 0;
|
||||
int v8 = 0;
|
||||
while (v8 < str.length()) {
|
||||
v7 = str.charAt(v8++) + 131 * v7;
|
||||
}
|
||||
return v7;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger()
|
||||
.warn("Unable to copy resource " + resource + " to " + destination, exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an object to the console.
|
||||
*
|
||||
* @param object The object to log.
|
||||
*/
|
||||
public static void logObject(Object object) {
|
||||
Grasscutter.getLogger().info(JsonUtils.encode(object));
|
||||
}
|
||||
|
||||
/** Checks for required files and folders before startup. */
|
||||
public static void startupCheck() {
|
||||
ConfigContainer config = Grasscutter.getConfig();
|
||||
Logger logger = Grasscutter.getLogger();
|
||||
boolean exit = false;
|
||||
|
||||
String dataFolder = config.folderStructure.data;
|
||||
|
||||
// Check for resources folder.
|
||||
if (!Files.exists(getResourcePath(""))) {
|
||||
logger.info(translate("messages.status.create_resources"));
|
||||
logger.info(translate("messages.status.resources_error"));
|
||||
createFolder(config.folderStructure.resources);
|
||||
exit = true;
|
||||
}
|
||||
|
||||
// Check for BinOutput + ExcelBinOutput.
|
||||
if (!Files.exists(getResourcePath("BinOutput"))
|
||||
|| !Files.exists(getResourcePath("ExcelBinOutput"))) {
|
||||
logger.info(translate("messages.status.resources_error"));
|
||||
exit = true;
|
||||
}
|
||||
|
||||
// Check for game data.
|
||||
if (!fileExists(dataFolder)) createFolder(dataFolder);
|
||||
|
||||
// Make sure the data folder is populated, if there are any missing files copy them from
|
||||
// resources
|
||||
DataLoader.checkAllFiles();
|
||||
|
||||
if (exit) System.exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the timestamp of the next hour.
|
||||
*
|
||||
* @return The timestamp in UNIX seconds.
|
||||
*/
|
||||
public static int getNextTimestampOfThisHour(int hour, String timeZone, int param) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a string from an input stream.
|
||||
*
|
||||
* @param stream The input stream.
|
||||
* @return The string.
|
||||
*/
|
||||
public static String readFromInputStream(@Nullable InputStream stream) {
|
||||
if (stream == null) return "empty";
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
try (BufferedReader reader =
|
||||
new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
stringBuilder.append(line);
|
||||
}
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read from input stream.");
|
||||
} catch (NullPointerException ignored) {
|
||||
return "empty";
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a linear interpolation using a table of fixed points to create an effective piecewise
|
||||
* f(x) = y function.
|
||||
*
|
||||
* @param x The x value.
|
||||
* @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!
|
||||
// Using floats would be slightly cleaner but we can just as easily use ints if we're
|
||||
// careful with order of operations.
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the language code from a given locale.
|
||||
*
|
||||
* @param locale A locale.
|
||||
* @return A string in the format of 'XX-XX'.
|
||||
*/
|
||||
public static String getLanguageCode(Locale locale) {
|
||||
return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/***
|
||||
* 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);
|
||||
}
|
||||
|
||||
/***
|
||||
* 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);
|
||||
}
|
||||
|
||||
/***
|
||||
* Splits a string by a character, into a list
|
||||
* @param input The string to split
|
||||
* @param separator The character to use as the split points
|
||||
* @return A list of all the substrings
|
||||
*/
|
||||
public static List<String> nonRegexSplit(String input, int separator) {
|
||||
var output = new ArrayList<String>();
|
||||
int start = 0;
|
||||
for (int next = input.indexOf(separator); next > 0; next = input.indexOf(separator, start)) {
|
||||
output.add(input.substring(start, next));
|
||||
start = next + 1;
|
||||
}
|
||||
if (start < input.length()) output.add(input.substring(start));
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +1,28 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.NavigableMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class WeightedList<E> {
|
||||
private final NavigableMap<Double, E> map = new TreeMap<Double, E>();
|
||||
private double total = 0;
|
||||
|
||||
public WeightedList() {
|
||||
|
||||
}
|
||||
|
||||
public WeightedList<E> add(double weight, E result) {
|
||||
if (weight <= 0) return this;
|
||||
total += weight;
|
||||
map.put(total, result);
|
||||
return this;
|
||||
}
|
||||
|
||||
public E next() {
|
||||
double value = ThreadLocalRandom.current().nextDouble() * total;
|
||||
return map.higherEntry(value).getValue();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
}
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.util.NavigableMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class WeightedList<E> {
|
||||
private final NavigableMap<Double, E> map = new TreeMap<Double, E>();
|
||||
private double total = 0;
|
||||
|
||||
public WeightedList() {}
|
||||
|
||||
public WeightedList<E> add(double weight, E result) {
|
||||
if (weight <= 0) return this;
|
||||
total += weight;
|
||||
map.put(total, result);
|
||||
return this;
|
||||
}
|
||||
|
||||
public E next() {
|
||||
double value = ThreadLocalRandom.current().nextDouble() * total;
|
||||
return map.higherEntry(value).getValue();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user