mirror of
https://github.com/Grasscutters/Grasscutter.git
synced 2026-03-28 02:23:31 +01:00
Merge unstable into development (#2173)
* Remove more scene synchronized
* Fix worktop options not appearing
* Format code [skip actions]
* Fix delay with server tasks
* Format code [skip actions]
* Fully fix fairy clock (#2146)
* Fix scene transition
* fully fix fairy clock
* Re-add call to `Player#updatePlayerGameTime`
* Format code [skip actions]
* Initialize the script loader in `ResourceLoader#loadAll`
* Fix region removal checking
* Format code [skip actions]
* Use Lombok's `EqualsAndHashCode` for comparing scene regions
* Format code [skip actions]
* Move 'invalid gather object' to `trace`
* Add more information to the 'unknown condition handler' message
* Move invalid ability action to trace
* Make `KcpTunnel` public
* Validate the NPC being talked to
* Format code [skip actions]
* NPCs are not spawned server side; change logic to handle it
* Format code [skip actions]
* unload scene when there are no players (#2147)
* unload scene when there are no players
* Update src/main/java/emu/grasscutter/game/world/Scene.java
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
---------
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
* Check if a command should be copied or HTTP should be used
* Lint Code [skip actions]
* Fix character names rendering incorrectly
* Add basic troubleshooting command
* Implement handbook teleporting
also a few formatting changes and sort data by logical sense
* Fix listener `ConcurrentModificationException` issue
* Add color change to `Join the Community!`
* Lint Code [skip actions]
* Make clickable buttons appear clickable
* Remove 'Mechanicus' entities from the list of entities
* Format code [skip actions]
* Fix going back returning a blank screen
* Implement entity spawning
* Add setting level to entity card
* Add support for 'plain text' mode
* Make descriptions of objects scrollable
* Lint Code [skip actions]
* Format code [skip actions]
* Change the way existing hooks work
* Format code [skip actions]
* Upgrade Javalin to 5.5.0 & Fix project warnings
* Upgrade logging libraries
* Fix gacha mappings static file issue
* Add temporary backwards compatability for `ServerHelper`
* Format code [skip actions]
* Remove artifact signatures from VCS
* Fix forge queue data protocol definition
* Run `spotlessApply`
* Format code [skip actions]
* Download data required for building artifacts
* Add call for Facebook logins
* Add the wiki page as a submodule
* Format code [skip actions]
* Update translation (#2150)
* Update translation
* Update translation
* Separate the dispatch and game servers (pt. 1)
gacha is still broken, handbook still needs to be done
* Format code [skip actions]
* Separate the dispatch and game servers (pt. 2)
this commit fixes the gacha page
* Add description for '/troubleshoot'
* Set default avatar talent level to 10
* Separate the dispatch and game servers (pt. 3)
implement handbook across servers!
* Format code [skip actions]
* Update GitHub Actions to use 'download-file' over 'wget'
* Gm handbook lmao (#2149)
* Fix font issue
* Fix avatars
* Fix text overflow in commands
* Fix virtualized lists and items page 😭😭
* magix why 💀
* use hover style in all minicards
* button
* remove console.log
* lint
* Add icons
* magix asked
* Fix overflow padding issue
* Fix achievement text overflow
* remove icons from repo
* Change command icon
* Add the wiki page as a submodule
* total magix moment
* fix text overflow in commands
* Fix discord button
* Make text scale on Minicard
* import icons and font from another source
* Add hover effects to siebar buttons
* move font and readme to submodule repo
* Make data folder a submodule
* import icons and font from data submodule
* Update README.md
* total magix moment
* magix moment v2
* submodule change
* Import `.webp` files
* Resize `HomeButton`
* Fix 'Copy Command' reappearing after changing pages
---------
Co-authored-by: KingRainbow44 <kobedo11@gmail.com>
* Lint Code [skip actions]
* Download data for the build, not for the lint
* format imports
this is really just to see if build handbook works kek
* Implement proper handbook authentication (pt. 1)
* Implement proper handbook authentication (pt. 2)
* Format code [skip actions]
* Add quest data dumping for the handbook
* Change colors to fit _something suitable_
* Format code [skip actions]
* Fix force pushing to branches after linting
* Fix logic of `SetPlayerPropReq`
* Move more group loading to `trace`
* Add handbook IP authentication in hybrid mode
* Fix player level up not displaying on the client properly
* Format code [skip actions]
* Fix game time locking
* Format code [skip actions]
* Update player properties
* Format code [skip actions]
* Move `warn`s for groups to `debug`
* Fix player pausing
* Move more logs to `trace`
* Use `removeItemById` for deleting items via quests
* Clean up logger more
* Pause in-game time when the world is paused
* Format code [skip actions]
* More player property documentation
* Multi-threaded resource loading
* Format code [skip actions]
* Add quest widgets
* Add quests page (basic impl.)
* Add/fix colors
also fix tailwind
* Remove banned packets
client modifications already perform the job of blocking malicious packets from being executed, no point in having this if self-windy is wanted
* Re-add `BeginCameraSceneLookNotify`
* Fix being unable to attack (#2157)
* Add `PlayerOpenChestEvent`
* Add methods to get players from the server
* Add static methods to register an event handler
* Add `PlayerEnterDungeonEvent`
* Remove legacy documentation from `PlayerMoveEvent`
* Add `PlayerChatEvent`
* Add defaults to `Position`
* Clean up `.utils`
* Revert `Multi-threaded resource loading`
* Fix changing target UID when talking to the server
* Lint Code [skip actions]
* Format code [skip actions]
* fix NPC talk triggering main quest in 46101 (#2158)
Make it so that only talks where the param matches the talkId are checked.
* Format code [skip actions]
* Partially fix Chasing Shadows (#2159)
* Partially fix Chasing Shadows
* Go ahead and move it before the return before Magix tells me to.
* Format code [skip actions]
* Bring back period lol (#2160)
* Disable SNI for the HTTPS server
* Add `EntityCreationEvent`
* Add initial startup message
this is so the server appears like its preparing to start
* Format code [skip actions]
* Enable debug mode for plugin loggers if enabled for the primary logger
* Add documentation about `WorldAreaConfigData`
* Make more fields in excels accessible
* Remove deprecated fields from `GetShopRsp`
* Run `spotlessApply` on definitions
* Add `PlayerEnterAreaEvent`
* Optimize event calls
* Fix event invokes
* Format code [skip actions]
* Remove manual autofinish for main quests. (#2162)
* Add world areas to the textmap cache
* Format code [skip actions]
* Don't overdefine variables in extended classes (#2163)
* Add dumper for world areas
* Format code [skip actions]
* instantiate personalLineList (#2165)
* Fix protocol definitions
thank you Nazrin! (+ hiro for raw definitions)
* Fix the background color leaking from the character widget
* Change HTML spacing to 2 spaces
* Implement hiding widgets
* Change scrollbar to a vibrant color
* Add _some_ scaling to the home buttons and its text
* Build the handbook with Gradle
* Fix the 'finer details' with the handbook UI
* Lint Code [skip actions]
* Fix target destination for the Gradle-built handbook
* Implement fetching a player across servers & Add a chainable JsonObject
useful for plugins! might be used in grasscutter eventually
* Fix GitHub actions
* Fix event calling & canceling
* Run `spotlessApply`
* Rename fields (might be wrong)
* Add/update all/more protocol definitions
* Add/update all/more protocol definitions
* Remove outdated packet
* Fix protocol definitions
* Format code [skip actions]
* Implement some lua variables for less console spam (#2172)
* Implement some lua variables for less console spam
* Add GetHostQuestState
This fixes some chapter 3 stuff.
* Format code [skip actions]
* Fix merge import
* Format code [skip actions]
* Fully fix fairy clock for real this time (#2167)
* Fully fix fairy clock For real this time
* Make it so relogging keeps the time lock state.
* Refactor out questLockTime
* Per Hartie, the client packet needs to be changed too
* Update src/main/java/emu/grasscutter/game/world/World.java
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
* Update src/main/java/emu/grasscutter/server/packet/recv/HandlerClientLockGameTimeNotify.java
* Remove all code not needed to get clock working
---------
Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>
* Implement a proper ability system (#2166)
* Apply fix `21dec2fe`
* Apply fix `89d01d5f`
* Apply fix `d900f154`
this one was already implemented; updated to use call from previous commit
* Ability changing commit
TODO: change info to debug
* Remove use of deprecated methods/fields
* Temp commit v2
(Adding LoseHP and some fixes)
* Oopsie
* Probably fix monster battle
* Fix issue with reflecting into fields
* Fix some things
* Fix ability names for 3.6 resources
* Improve logging
---------
Co-authored-by: StartForKiller <jesussanz2003@gmail.com>
* Format code [skip actions]
* Add system for sending messages between servers
* Format some code
* Remove protocol definitions from Spotless
* Default debug to false; enable with `-debug`
* Implement completely useless global value copying
* HACK: Return the avatar which holds the weapon when the weapon is referred to by ID
* Add properties to `AbilityModifier`
* Change the way HTML is served after authentication
* Use thread executors to speed up the database loading process
* Format code [skip actions]
* Add system for setting handbook address and port
* Lint Code [skip actions]
* Format code [skip actions]
* Fix game-related data not saving
* Format code [skip actions]
* Fix handbook server details
* Lint Code [skip actions]
* Format code [skip actions]
* Use the headers provided by a context to get the IP address
should acknowledge #1975
* Format code [skip actions]
* Move more logs to `trace`
* Format code [skip actions]
* more trace
* Fix something and implement weapon entities
* Format code [skip actions]
* Fix `EntityWeapon`
* Remove deprecated API & Fix resource checking
* Fix unnecessary warning for first-time setup
* Implement handbook request limiting
* Format code [skip actions]
* Fix new avatar weapons being null
* Format code [skip actions]
* Fix issue with 35303 being un-completable & Try to fix fulfilled quest conditions being met
* Load activity config on server startup
* Require plugins to specify an API version and match with the server
* Add default open state ignore list
* Format code [skip actions]
* Quick fix for questing, needs more investigation
This would make the questing work again
* Remove existing hack for 35303
* Fix ignored open states from being set
* Format code [skip actions]
* fix the stupidest bug ive ever seen
* Optimize player kicking on server close
* Format code [skip actions]
* Re-add hack to fix 35303
* Update GitHub actions
* Format code [skip actions]
* Potentially fix issues with regions
* Download additional handbook data
* Revert "Potentially fix issues with regions"
This reverts commit 84e3823695.
---------
Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: scooterboo <lewasite@yahoo.com>
Co-authored-by: Tesutarin <105267106+Tesutarin@users.noreply.github.com>
Co-authored-by: Scald <104459145+Arikatsu@users.noreply.github.com>
Co-authored-by: StartForKiller <jesussanz2003@gmail.com>
This commit is contained in:
24
src/main/java/emu/grasscutter/utils/ConversionUtils.java
Normal file
24
src/main/java/emu/grasscutter/utils/ConversionUtils.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
/* Various methods to convert from A -> B. */
|
||||
public interface ConversionUtils {
|
||||
/**
|
||||
* Converts in-game minutes to days.
|
||||
*
|
||||
* @param minutes The elapsed in-game minutes.
|
||||
* @return The elapsed in-game days.
|
||||
*/
|
||||
static long gameTimeToDays(long minutes) {
|
||||
return minutes / 1440;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts in-game minutes to hours.
|
||||
*
|
||||
* @param minutes The elapsed in-game minutes.
|
||||
* @return The elapsed in-game hours.
|
||||
*/
|
||||
static long gameTimeToHours(long minutes) {
|
||||
return minutes / 60;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.server.http.objects.QueryCurRegionRspJson;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
@@ -12,11 +12,9 @@ import java.security.Signature;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import javax.crypto.Cipher;
|
||||
|
||||
public final class Crypto {
|
||||
@@ -42,8 +40,10 @@ public final class Crypto {
|
||||
ENCRYPT_SEED_BUFFER = FileUtils.readResource("/keys/secretKeyBuffer.bin");
|
||||
|
||||
try {
|
||||
CUR_SIGNING_KEY = KeyFactory.getInstance("RSA")
|
||||
.generatePrivate(new PKCS8EncodedKeySpec(FileUtils.readResource("/keys/SigningKey.der")));
|
||||
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")) {
|
||||
@@ -52,8 +52,9 @@ public final class Crypto {
|
||||
var m = pattern.matcher(path.getFileName().toString());
|
||||
|
||||
if (m.matches()) {
|
||||
var key = KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(FileUtils.read(path)));
|
||||
var key =
|
||||
KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(FileUtils.read(path)));
|
||||
|
||||
EncryptionKeys.put(Integer.valueOf(m.group(1)), key);
|
||||
}
|
||||
@@ -80,7 +81,8 @@ public final class Crypto {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static QueryCurRegionRspJson encryptAndSignRegionData(byte[] regionInfo, String key_id) throws Exception {
|
||||
public static QueryCurRegionRspJson encryptAndSignRegionData(byte[] regionInfo, String key_id)
|
||||
throws Exception {
|
||||
if (key_id == null) {
|
||||
throw new Exception("Key ID was not set");
|
||||
}
|
||||
@@ -88,17 +90,18 @@ public final class Crypto {
|
||||
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, EncryptionKeys.get(Integer.valueOf(key_id)));
|
||||
|
||||
//Encrypt regionInfo in chunks
|
||||
// Encrypt regionInfo in chunks
|
||||
ByteArrayOutputStream encryptedRegionInfoStream = new ByteArrayOutputStream();
|
||||
|
||||
//Thank you so much GH Copilot
|
||||
// Thank you so much GH Copilot
|
||||
int chunkSize = 256 - 11;
|
||||
int regionInfoLength = regionInfo.length;
|
||||
int numChunks = (int) Math.ceil(regionInfoLength / (double) chunkSize);
|
||||
|
||||
for (int i = 0; i < numChunks; i++) {
|
||||
byte[] chunk = Arrays.copyOfRange(regionInfo, i * chunkSize,
|
||||
Math.min((i + 1) * chunkSize, regionInfoLength));
|
||||
byte[] chunk =
|
||||
Arrays.copyOfRange(
|
||||
regionInfo, i * chunkSize, Math.min((i + 1) * chunkSize, regionInfoLength));
|
||||
byte[] encryptedChunk = cipher.doFinal(chunk);
|
||||
encryptedRegionInfoStream.write(encryptedChunk);
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
296
src/main/java/emu/grasscutter/utils/DispatchUtils.java
Normal file
296
src/main/java/emu/grasscutter/utils/DispatchUtils.java
Normal file
@@ -0,0 +1,296 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.DISPATCH_INFO;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.auth.AuthenticationSystem.AuthenticationRequest;
|
||||
import emu.grasscutter.database.DatabaseHelper;
|
||||
import emu.grasscutter.game.Account;
|
||||
import emu.grasscutter.game.HandbookActions;
|
||||
import emu.grasscutter.server.dispatch.IDispatcher;
|
||||
import emu.grasscutter.server.dispatch.PacketIds;
|
||||
import emu.grasscutter.server.http.handlers.GachaHandler;
|
||||
import emu.grasscutter.server.http.objects.LoginTokenRequestJson;
|
||||
import emu.grasscutter.utils.objects.HandbookBody;
|
||||
import emu.grasscutter.utils.objects.HandbookBody.*;
|
||||
import emu.grasscutter.utils.objects.JObject;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public interface DispatchUtils {
|
||||
/**
|
||||
* @return The dispatch URL.
|
||||
*/
|
||||
static String getDispatchUrl() {
|
||||
return DISPATCH_INFO.dispatchUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an authentication request.
|
||||
*
|
||||
* @param accountId The account ID.
|
||||
* @param token The token.
|
||||
* @return {@code true} if the authentication request is valid, otherwise {@code false}.
|
||||
*/
|
||||
@Nullable static Account authenticate(String accountId, String token) {
|
||||
return switch (Grasscutter.getRunMode()) {
|
||||
case GAME_ONLY ->
|
||||
// Use the authentication system to validate the token.
|
||||
Grasscutter.getAuthenticationSystem()
|
||||
.getSessionTokenValidator()
|
||||
.authenticate(
|
||||
AuthenticationRequest.builder()
|
||||
.tokenRequest(LoginTokenRequestJson.builder().uid(accountId).token(token).build())
|
||||
.build());
|
||||
case HYBRID, DISPATCH_ONLY -> {
|
||||
// Fetch the account from the database.
|
||||
var account = DatabaseHelper.getAccountById(accountId);
|
||||
if (account == null) yield null;
|
||||
|
||||
// Check if the token is valid.
|
||||
yield account.getToken().equals(token) ? account : null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the session key for the specified player ID.
|
||||
*
|
||||
* @param playerId The player ID.
|
||||
* @return The session key.
|
||||
*/
|
||||
@Nullable static String fetchSessionKey(int playerId) {
|
||||
return switch (Grasscutter.getRunMode()) {
|
||||
case GAME_ONLY -> {
|
||||
// Fetch the player from the game server.
|
||||
var player = DatabaseHelper.getPlayerByUid(playerId);
|
||||
if (player == null) yield null;
|
||||
|
||||
// Fetch the account from the dispatch server.
|
||||
var accountId = player.getAccountId();
|
||||
var account = DispatchUtils.getAccountById(accountId);
|
||||
|
||||
// Return the session key.
|
||||
yield account == null ? null : account.getSessionKey();
|
||||
}
|
||||
case DISPATCH_ONLY -> {
|
||||
// Fetch the player's account ID from the game server.
|
||||
var playerFields = DispatchUtils.getPlayerFields(playerId, "accountId");
|
||||
if (playerFields == null) yield null;
|
||||
|
||||
// Get the account ID.
|
||||
var accountId = playerFields.get("accountId").getAsString();
|
||||
if (accountId == null) yield null;
|
||||
|
||||
// Fetch the account from the dispatch server.
|
||||
var account = DatabaseHelper.getAccountById(accountId);
|
||||
// Return the session key.
|
||||
yield account == null ? null : account.getSessionKey();
|
||||
}
|
||||
case HYBRID -> {
|
||||
// Fetch the player from the game server.
|
||||
var player = DatabaseHelper.getPlayerByUid(playerId);
|
||||
if (player == null) yield null;
|
||||
|
||||
// Fetch the account from the database.
|
||||
var account = player.getAccount();
|
||||
// Return the session key.
|
||||
yield account == null ? null : account.getSessionKey();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches an account by its ID.
|
||||
*
|
||||
* @param accountId The account ID.
|
||||
* @return The account.
|
||||
*/
|
||||
@Nullable static Account getAccountById(String accountId) {
|
||||
return switch (Grasscutter.getRunMode()) {
|
||||
case GAME_ONLY -> {
|
||||
// Create a request for account information.
|
||||
var request = new JsonObject();
|
||||
request.addProperty("accountId", accountId);
|
||||
|
||||
// Wait for the request to complete.
|
||||
yield Grasscutter.getGameServer()
|
||||
.getDispatchClient()
|
||||
.await(
|
||||
request,
|
||||
PacketIds.GetAccountReq,
|
||||
PacketIds.GetAccountRsp,
|
||||
packet -> IDispatcher.decode(packet, Account.class));
|
||||
}
|
||||
case HYBRID, DISPATCH_ONLY -> DatabaseHelper.getAccountById(accountId);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the values of fields for a player.
|
||||
*
|
||||
* @param playerId The player's ID.
|
||||
* @param fields The fields to fetch.
|
||||
* @return An object holding the field values.
|
||||
*/
|
||||
@Nullable static JsonObject getPlayerFields(int playerId, String... fields) {
|
||||
return switch (Grasscutter.getRunMode()) {
|
||||
case DISPATCH_ONLY -> {
|
||||
// Create a request for player fields.
|
||||
var request = new JsonObject();
|
||||
request.addProperty("playerId", playerId);
|
||||
request.add("fields", IDispatcher.JSON.toJsonTree(fields));
|
||||
|
||||
// Wait for the request to complete.
|
||||
yield Grasscutter.getDispatchServer()
|
||||
.await(
|
||||
request,
|
||||
PacketIds.GetPlayerFieldsReq,
|
||||
PacketIds.GetPlayerFieldsRsp,
|
||||
IDispatcher.DEFAULT_PARSER);
|
||||
}
|
||||
case HYBRID, GAME_ONLY -> {
|
||||
// Get the player by ID.
|
||||
var player = Grasscutter.getGameServer().getPlayerByUid(playerId, true);
|
||||
if (player == null) yield null;
|
||||
|
||||
// Return the values.
|
||||
yield player.fetchFields(fields);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the values of fields for a player. Uses an account to find the player. Similar to
|
||||
* {@link DispatchUtils#getPlayerFields(int, String...)}
|
||||
*
|
||||
* @param accountId The account ID.
|
||||
* @param fields The fields to fetch.
|
||||
* @return An object holding the field values.
|
||||
*/
|
||||
@Nullable static JsonObject getPlayerByAccount(String accountId, String... fields) {
|
||||
return switch (Grasscutter.getRunMode()) {
|
||||
case DISPATCH_ONLY -> {
|
||||
// Create a request for player fields.
|
||||
var request = JObject.c().add("accountId", accountId).add("fields", fields);
|
||||
|
||||
// Wait for the request to complete.
|
||||
yield Grasscutter.getDispatchServer()
|
||||
.await(
|
||||
request.gson(),
|
||||
PacketIds.GetPlayerByAccountReq,
|
||||
PacketIds.GetPlayerByAccountRsp,
|
||||
IDispatcher.DEFAULT_PARSER);
|
||||
}
|
||||
case HYBRID, GAME_ONLY -> {
|
||||
// Get the player by the account.
|
||||
var player = Grasscutter.getGameServer().getPlayerByAccountId(accountId);
|
||||
if (player == null) yield null;
|
||||
|
||||
// Return the values.
|
||||
yield player.fetchFields(fields);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the gacha history for the specified account.
|
||||
*
|
||||
* @param accountId The account ID.
|
||||
* @param page The page.
|
||||
* @param gachaType The gacha type.
|
||||
* @return The gacha history.
|
||||
*/
|
||||
static JsonObject fetchGachaRecords(String accountId, int page, int gachaType) {
|
||||
return switch (Grasscutter.getRunMode()) {
|
||||
case DISPATCH_ONLY -> {
|
||||
// Create a request for gacha records.
|
||||
var request = new JsonObject();
|
||||
request.addProperty("accountId", accountId);
|
||||
request.addProperty("page", page);
|
||||
request.addProperty("gachaType", gachaType);
|
||||
|
||||
// Create a future for the response.
|
||||
var future = new CompletableFuture<JsonObject>();
|
||||
// Listen for the response.
|
||||
var server = Grasscutter.getDispatchServer();
|
||||
server.registerCallback(
|
||||
PacketIds.GachaHistoryRsp,
|
||||
packet -> future.complete(IDispatcher.decode(packet, JsonObject.class)));
|
||||
|
||||
// Broadcast the request.
|
||||
server.sendMessage(PacketIds.GachaHistoryReq, request);
|
||||
|
||||
try {
|
||||
// Wait for the response.
|
||||
yield future.get(5L, TimeUnit.SECONDS);
|
||||
} catch (Exception ignored) {
|
||||
yield null;
|
||||
}
|
||||
}
|
||||
case HYBRID, GAME_ONLY -> {
|
||||
// Create a response object.
|
||||
var response = new JsonObject();
|
||||
|
||||
// Get the player's ID from the account.
|
||||
var player = Grasscutter.getGameServer().getPlayerByAccountId(accountId);
|
||||
if (player == null) {
|
||||
response.addProperty("retcode", 1);
|
||||
yield response;
|
||||
}
|
||||
|
||||
// Fetch the gacha records.
|
||||
GachaHandler.fetchGachaRecords(player, response, page, gachaType);
|
||||
|
||||
yield response;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a handbook action.
|
||||
*
|
||||
* @param action The action.
|
||||
* @param data The data.
|
||||
* @return The response.
|
||||
*/
|
||||
static Response performHandbookAction(HandbookBody.Action action, Object data) {
|
||||
return switch (Grasscutter.getRunMode()) {
|
||||
case DISPATCH_ONLY -> {
|
||||
// Create a request for the 'GM Talk' action.
|
||||
var request = new JsonObject();
|
||||
request.addProperty("action", action.name());
|
||||
request.add("data", JsonUtils.toJson(data));
|
||||
|
||||
// Create a future for the response.
|
||||
var future = new CompletableFuture<Response>();
|
||||
// Listen for the response.
|
||||
var server = Grasscutter.getDispatchServer();
|
||||
server.registerCallback(
|
||||
PacketIds.GmTalkRsp,
|
||||
packet -> future.complete(IDispatcher.decode(packet, Response.class)));
|
||||
|
||||
// Broadcast the request.
|
||||
server.sendMessage(PacketIds.GmTalkReq, request);
|
||||
|
||||
try {
|
||||
// Wait for the response.
|
||||
yield future.get(5L, TimeUnit.SECONDS);
|
||||
} catch (Exception ignored) {
|
||||
yield Response.builder()
|
||||
.status(400)
|
||||
.message("No response received from any server.")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
case HYBRID, GAME_ONLY -> switch (action) {
|
||||
case GRANT_AVATAR -> HandbookActions.grantAvatar((GrantAvatar) data);
|
||||
case GIVE_ITEM -> HandbookActions.giveItem((GiveItem) data);
|
||||
case TELEPORT_TO -> HandbookActions.teleportTo((TeleportTo) data);
|
||||
case SPAWN_ENTITY -> HandbookActions.spawnEntity((SpawnEntity) data);
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,31 @@
|
||||
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.*;
|
||||
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 CACHE_PATH = Path.of(Grasscutter.config.folderStructure.cache);
|
||||
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;
|
||||
@@ -28,15 +33,21 @@ public final class FileUtils {
|
||||
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.
|
||||
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
|
||||
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());
|
||||
Grasscutter.getLogger()
|
||||
.error("Invalid URI scheme for class resources: " + uri.getScheme());
|
||||
break;
|
||||
}
|
||||
} catch (URISyntaxException | IOException e) {
|
||||
@@ -44,14 +55,16 @@ public final class FileUtils {
|
||||
Grasscutter.getLogger().error("Failed to load jar?!");
|
||||
} finally {
|
||||
DATA_DEFAULT_PATH = path;
|
||||
Grasscutter.getLogger().debug("Setting path for default data: "+path.toAbsolutePath());
|
||||
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
|
||||
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) {
|
||||
@@ -61,19 +74,24 @@ public final class FileUtils {
|
||||
|
||||
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");
|
||||
})) {
|
||||
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.toString() + "\"");
|
||||
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 + "\"");
|
||||
Grasscutter.getLogger()
|
||||
.error("Failed to find ExcelBinOutput in resources zip \"" + resources + "\"");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().error("Failed to scan resources zip \"" + resources + "\"");
|
||||
@@ -83,16 +101,19 @@ public final class FileUtils {
|
||||
|
||||
// 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);
|
||||
};
|
||||
SCRIPTS_PATH =
|
||||
(scripts.startsWith("resources:"))
|
||||
? RESOURCES_PATH.resolve(scripts.substring("resources:".length()))
|
||||
: Path.of(scripts);
|
||||
}
|
||||
|
||||
private static final String[] TSJ_JSON_TSV = {"tsj", "json", "tsv"};
|
||||
/* 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) {
|
||||
@@ -101,7 +122,9 @@ public final class FileUtils {
|
||||
if (Files.exists(path)) return path;
|
||||
}
|
||||
}
|
||||
return fallback ? DATA_USER_PATH.resolve(name + ".tsj") : null; // Maybe they want to write to a new file
|
||||
return fallback
|
||||
? DATA_USER_PATH.resolve(name + ".tsj")
|
||||
: null; // Maybe they want to write to a new file
|
||||
}
|
||||
|
||||
public static Path getDataPath(String path) {
|
||||
@@ -109,13 +132,17 @@ public final class FileUtils {
|
||||
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
|
||||
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 getCachePath(String path) {
|
||||
return CACHE_PATH.resolve(path);
|
||||
}
|
||||
|
||||
public static Path getPacketPath(String path) {
|
||||
return PACKETS_PATH.resolve(path);
|
||||
}
|
||||
@@ -129,7 +156,8 @@ public final class FileUtils {
|
||||
}
|
||||
|
||||
public static Path getExcelPath(String filename) {
|
||||
return getTsjJsonTsv(RESOURCES_PATH.resolve("ExcelBinOutput"), filename);
|
||||
Path p = getTsjJsonTsv(RESOURCES_PATH.resolve("Server"), filename);
|
||||
return Files.exists(p) ? p : getTsjJsonTsv(RESOURCES_PATH.resolve("ExcelBinOutput"), filename);
|
||||
}
|
||||
|
||||
// Gets path of a resource.
|
||||
@@ -181,7 +209,7 @@ public final class FileUtils {
|
||||
return is.readAllBytes();
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().warn("Failed to read resource: " + resourcePath);
|
||||
exception.printStackTrace();
|
||||
Grasscutter.getLogger().debug("Failed to load resource: " + resourcePath, exception);
|
||||
}
|
||||
|
||||
return new byte[0];
|
||||
@@ -200,10 +228,11 @@ public final class FileUtils {
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated // Misnamed legacy function
|
||||
@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);
|
||||
@@ -212,7 +241,7 @@ public final class FileUtils {
|
||||
public static String getFileExtension(Path path) {
|
||||
val filename = path.toString();
|
||||
int i = filename.lastIndexOf(".");
|
||||
return (i < 0) ? "" : filename.substring(i+1);
|
||||
return (i < 0) ? "" : filename.substring(i + 1);
|
||||
}
|
||||
|
||||
public static List<Path> getPathsFromResource(String folder) throws URISyntaxException {
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.ConsoleAppender;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import org.jline.reader.LineReader;
|
||||
|
||||
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,10 +1,5 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.TypeAdapterFactory;
|
||||
@@ -12,88 +7,130 @@ 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 emu.grasscutter.game.world.GridPosition;
|
||||
import emu.grasscutter.game.world.Position;
|
||||
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;
|
||||
|
||||
import static com.google.gson.stream.JsonToken.BEGIN_ARRAY;
|
||||
import static com.google.gson.stream.JsonToken.BEGIN_OBJECT;
|
||||
import static emu.grasscutter.utils.JsonUtils.gson;
|
||||
|
||||
public class JsonAdapters {
|
||||
static class DynamicFloatAdapter extends TypeAdapter<DynamicFloat> {
|
||||
public interface JsonAdapters {
|
||||
class DynamicFloatAdapter extends TypeAdapter<DynamicFloat> {
|
||||
@Override
|
||||
public DynamicFloat read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case STRING:
|
||||
case STRING -> {
|
||||
return new DynamicFloat(reader.nextString());
|
||||
case NUMBER:
|
||||
}
|
||||
case NUMBER -> {
|
||||
return new DynamicFloat((float) reader.nextDouble());
|
||||
case BOOLEAN:
|
||||
}
|
||||
case BOOLEAN -> {
|
||||
return new DynamicFloat(reader.nextBoolean());
|
||||
case BEGIN_ARRAY:
|
||||
}
|
||||
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());
|
||||
});
|
||||
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());
|
||||
}
|
||||
default -> throw new IOException(
|
||||
"Invalid DynamicFloat definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, DynamicFloat f) {};
|
||||
public void write(JsonWriter writer, DynamicFloat f) {}
|
||||
}
|
||||
|
||||
static class IntListAdapter extends TypeAdapter<IntList> {
|
||||
class IntListAdapter extends TypeAdapter<IntList> {
|
||||
@Override
|
||||
public IntList read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case 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;
|
||||
default:
|
||||
throw new IOException("Invalid IntList definition - " + reader.peek().name());
|
||||
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);
|
||||
for (val i : l) // .forEach() doesn't appreciate exceptions
|
||||
writer.value(i);
|
||||
writer.endArray();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
static class PositionAdapter extends TypeAdapter<Position> {
|
||||
public class ByteArrayAdapter extends TypeAdapter<byte[]> {
|
||||
@Override
|
||||
public void write(JsonWriter out, byte[] value) throws IOException {
|
||||
out.value(Utils.base64Encode(value));
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] read(JsonReader in) throws IOException {
|
||||
return Utils.base64Decode(in.nextString());
|
||||
}
|
||||
}
|
||||
|
||||
class GridPositionAdapter extends TypeAdapter<GridPosition> {
|
||||
@Override
|
||||
public void write(JsonWriter out, GridPosition value) throws IOException {
|
||||
out.value("(" + value.getX() + ", " + value.getZ() + ", " + value.getWidth() + ")");
|
||||
}
|
||||
|
||||
@Override
|
||||
public GridPosition read(JsonReader in) throws IOException {
|
||||
if (in.peek() != JsonToken.STRING)
|
||||
throw new IOException("Invalid GridPosition definition - " + in.peek().name());
|
||||
|
||||
// GridPosition follows the format of: (x, y, z).
|
||||
// Flatten to (x,y,z) for easier parsing.
|
||||
var str = in.nextString().replace("(", "").replace(")", "").replace(" ", "");
|
||||
var split = str.split(",");
|
||||
|
||||
if (split.length != 3)
|
||||
throw new IOException("Invalid GridPosition definition - " + in.peek().name());
|
||||
|
||||
return new GridPosition(
|
||||
Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
|
||||
}
|
||||
}
|
||||
|
||||
class PositionAdapter extends TypeAdapter<Position> {
|
||||
@Override
|
||||
public Position read(JsonReader reader) throws IOException {
|
||||
switch (reader.peek()) {
|
||||
case BEGIN_ARRAY: // "pos": [x,y,z]
|
||||
case BEGIN_ARRAY -> { // "pos": [x,y,z]
|
||||
reader.beginArray();
|
||||
val array = new FloatArrayList(3);
|
||||
while (reader.hasNext())
|
||||
array.add(reader.nextInt());
|
||||
while (reader.hasNext()) array.add(reader.nextInt());
|
||||
reader.endArray();
|
||||
return new Position(array);
|
||||
case BEGIN_OBJECT: // "pos": {"x": x, "y": y, "z": z}
|
||||
}
|
||||
case BEGIN_OBJECT -> { // "pos": {"x": x, "y": y, "z": z}
|
||||
float x = 0f;
|
||||
float y = 0f;
|
||||
float z = 0f;
|
||||
@@ -109,8 +146,8 @@ public class JsonAdapters {
|
||||
}
|
||||
reader.endObject();
|
||||
return new Position(x, y, z);
|
||||
default:
|
||||
throw new IOException("Invalid Position definition - " + reader.peek().name());
|
||||
}
|
||||
default -> throw new IOException("Invalid Position definition - " + reader.peek().name());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,10 +158,10 @@ public class JsonAdapters {
|
||||
writer.value(i.getY());
|
||||
writer.value(i.getZ());
|
||||
writer.endArray();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
static class EnumTypeAdapterFactory implements TypeAdapterFactory {
|
||||
class EnumTypeAdapterFactory implements TypeAdapterFactory {
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
|
||||
Class<T> enumClass = (Class<T>) type.getRawType();
|
||||
@@ -133,38 +170,39 @@ public class JsonAdapters {
|
||||
// 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);
|
||||
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;}) {
|
||||
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)
|
||||
for (var constant : enumConstants) {
|
||||
var accessible = f.canAccess(constant);
|
||||
f.setAccessible(true);
|
||||
map.put(String.valueOf(f.getInt(constant)), constant);
|
||||
f.setAccessible(accessible);
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
// System.out.println("Failed to access enum id field.");
|
||||
}
|
||||
f.setAccessible(acc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new TypeAdapter<T>() {
|
||||
return new TypeAdapter<>() {
|
||||
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());
|
||||
}
|
||||
return switch (reader.peek()) {
|
||||
case STRING -> map.get(reader.nextString());
|
||||
case NUMBER -> 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,5 +1,13 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import emu.grasscutter.data.common.DynamicFloat;
|
||||
import emu.grasscutter.game.world.GridPosition;
|
||||
import emu.grasscutter.game.world.Position;
|
||||
import emu.grasscutter.utils.JsonAdapters.*;
|
||||
import emu.grasscutter.utils.objects.JObject;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
@@ -11,25 +19,29 @@ import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.*;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
|
||||
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();
|
||||
static final Gson gson =
|
||||
new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.registerTypeAdapter(DynamicFloat.class, new DynamicFloatAdapter())
|
||||
.registerTypeAdapter(IntList.class, new IntListAdapter())
|
||||
.registerTypeAdapter(Position.class, new PositionAdapter())
|
||||
.registerTypeAdapter(GridPosition.class, new GridPositionAdapter())
|
||||
.registerTypeAdapter(byte[].class, new ByteArrayAdapter())
|
||||
.registerTypeAdapter(JObject.class, new JObject.Adapter())
|
||||
.registerTypeAdapterFactory(new EnumTypeAdapterFactory())
|
||||
.disableHtmlEscaping()
|
||||
.create();
|
||||
|
||||
/**
|
||||
* Converts the given object to a JsonElement.
|
||||
*
|
||||
* @param object The object to convert.
|
||||
* @return The JsonElement.
|
||||
*/
|
||||
public static JsonElement toJson(Object object) {
|
||||
return gson.toJsonTree(object);
|
||||
}
|
||||
|
||||
/*
|
||||
* Encode an object to a JSON string
|
||||
@@ -38,7 +50,8 @@ public final class JsonUtils {
|
||||
return gson.toJson(object);
|
||||
}
|
||||
|
||||
public static <T> T decode(JsonElement jsonElement, Class<T> classType) throws JsonSyntaxException {
|
||||
public static <T> T decode(JsonElement jsonElement, Class<T> classType)
|
||||
throws JsonSyntaxException {
|
||||
return gson.fromJson(jsonElement, classType);
|
||||
}
|
||||
|
||||
@@ -48,7 +61,9 @@ public final class JsonUtils {
|
||||
|
||||
@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)) {
|
||||
try (InputStreamReader fileReader =
|
||||
new InputStreamReader(
|
||||
new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToClass(fileReader, classType);
|
||||
}
|
||||
}
|
||||
@@ -65,7 +80,9 @@ public final class JsonUtils {
|
||||
|
||||
@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)) {
|
||||
try (InputStreamReader fileReader =
|
||||
new InputStreamReader(
|
||||
new FileInputStream(Utils.toFilePath(filename)), StandardCharsets.UTF_8)) {
|
||||
return loadToList(fileReader, classType);
|
||||
}
|
||||
}
|
||||
@@ -76,25 +93,40 @@ public final class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
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)) {
|
||||
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 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T1, T2> Map<T1, T2> loadToMap(Path filename, Class<T1> keyType, Type valueType)
|
||||
throws IOException {
|
||||
try (var fileReader = Files.newBufferedReader(filename, StandardCharsets.UTF_8)) {
|
||||
return gson.fromJson(
|
||||
fileReader, TypeToken.getParameterized(Map.class, keyType, valueType).getType());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely JSON decodes a given string.
|
||||
*
|
||||
* @param jsonData The JSON-encoded data.
|
||||
* @return JSON decoded data, or null if an exception occurred.
|
||||
*/
|
||||
|
||||
@@ -1,465 +0,0 @@
|
||||
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 static emu.grasscutter.config.Configuration.*;
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
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.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class Language {
|
||||
private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
|
||||
|
||||
private final String languageCode;
|
||||
private final Map<String, String> translations = new ConcurrentHashMap<>();
|
||||
private static boolean scannedTextmaps = false; // Ensure that we don't infinitely rescan on cache misses that don't exist
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get language code
|
||||
*/
|
||||
public String getLanguageCode() {
|
||||
return languageCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
private static final int TEXTMAP_CACHE_VERSION = 0x9CCACE04;
|
||||
@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;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Pattern textMapKeyValueRegex = Pattern.compile("\"(\\d+)\": \"(.+)\"");
|
||||
|
||||
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()), (int) 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);
|
||||
}
|
||||
}
|
||||
|
||||
private static Int2ObjectMap<TextStrings> textMapStrings;
|
||||
private static final Path TEXTMAP_CACHE_PATH = Path.of(Utils.toFilePath("cache/TextMapCache.bin"));
|
||||
|
||||
@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);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
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 +0,0 @@
|
||||
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,190 +0,0 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import com.github.davidmoten.rtreemulti.geometry.Point;
|
||||
import dev.morphia.annotations.Entity;
|
||||
import emu.grasscutter.net.proto.VectorOuterClass.Vector;
|
||||
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 +0,0 @@
|
||||
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,54 +1,87 @@
|
||||
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.GameConstants;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.Grasscutter.ServerRunMode;
|
||||
import emu.grasscutter.net.packet.PacketOpcodesUtils;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import emu.grasscutter.tools.Dumpers;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.*;
|
||||
|
||||
/**
|
||||
* A parser for start-up arguments.
|
||||
*/
|
||||
public final class StartupArguments {
|
||||
private StartupArguments() {
|
||||
// This class is not meant to be instantiated.
|
||||
}
|
||||
|
||||
/** A parser for start-up arguments. */
|
||||
public interface 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;
|
||||
},
|
||||
Map<String, Function<String, Boolean>> argumentHandlers =
|
||||
new HashMap<>() {
|
||||
{
|
||||
putAll(
|
||||
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(Grasscutter.ServerRunMode.GAME_ONLY);
|
||||
return false;
|
||||
},
|
||||
"-dispatch",
|
||||
parameter -> {
|
||||
Grasscutter.setRunModeOverride(Grasscutter.ServerRunMode.DISPATCH_ONLY);
|
||||
return false;
|
||||
},
|
||||
"-noconsole",
|
||||
parameter -> {
|
||||
Grasscutter.setNoConsole(true);
|
||||
return false;
|
||||
},
|
||||
"-test",
|
||||
parameter -> {
|
||||
// Disable the console.
|
||||
SERVER.game.enableConsole = false;
|
||||
// Disable HTTP encryption.
|
||||
SERVER.http.encryption.useEncryption = false;
|
||||
return false;
|
||||
},
|
||||
"-dump",
|
||||
StartupArguments::dump,
|
||||
|
||||
// Aliases.
|
||||
"-v", StartupArguments::printVersion,
|
||||
"-debugall", parameter -> {
|
||||
StartupArguments.enableDebug("all"); return false;
|
||||
}
|
||||
);
|
||||
// Aliases.
|
||||
"-v",
|
||||
StartupArguments::printVersion));
|
||||
putAll(
|
||||
Map.of(
|
||||
"-debugall",
|
||||
parameter -> {
|
||||
StartupArguments.enableDebug("all");
|
||||
return false;
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
static boolean parse(String[] args) {
|
||||
boolean exitEarly = false;
|
||||
|
||||
// Parse the arguments.
|
||||
@@ -68,15 +101,18 @@ public final class StartupArguments {
|
||||
|
||||
/**
|
||||
* 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;
|
||||
System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables debug logging.
|
||||
*
|
||||
* @param parameter Additional parameters.
|
||||
* @return False to continue execution.
|
||||
*/
|
||||
@@ -87,27 +123,58 @@ public final class StartupArguments {
|
||||
GAME_INFO.isShowPacketPayload = DEBUG_MODE_INFO.isShowPacketPayload;
|
||||
GAME_INFO.logPackets = DEBUG_MODE_INFO.logPackets;
|
||||
DISPATCH_INFO.logRequests = DEBUG_MODE_INFO.logRequests;
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
// Set the server to debug.
|
||||
GameConstants.DEBUG = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dumps the specified information.
|
||||
*
|
||||
* @param parameter The parameter to dump.
|
||||
* @return True to exit early.
|
||||
*/
|
||||
private static boolean dump(String parameter) {
|
||||
// Parse the parameter.
|
||||
if (!parameter.contains(",")) {
|
||||
Grasscutter.getLogger().error("Dumper usage: -dump=<content>,<language>");
|
||||
return true;
|
||||
}
|
||||
|
||||
var split = parameter.split(",");
|
||||
var content = split[0];
|
||||
var language = split[1];
|
||||
|
||||
try {
|
||||
switch (content.toLowerCase()) {
|
||||
case "commands" -> Dumpers.dumpCommands(language);
|
||||
case "avatars" -> Dumpers.dumpAvatars(language);
|
||||
case "items" -> Dumpers.dumpItems(language);
|
||||
case "scenes" -> Dumpers.dumpScenes();
|
||||
case "entities" -> Dumpers.dumpEntities(language);
|
||||
case "quests" -> Dumpers.dumpQuests(language);
|
||||
case "areas" -> Dumpers.dumpAreas(language);
|
||||
}
|
||||
|
||||
Grasscutter.getLogger().info("Finished dumping.");
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Unable to complete dump.", exception);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,39 +1,30 @@
|
||||
package emu.grasscutter.utils;
|
||||
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
import static emu.grasscutter.utils.lang.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 org.slf4j.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import emu.grasscutter.game.world.Position;
|
||||
import emu.grasscutter.utils.objects.Returnable;
|
||||
import io.javalin.http.Context;
|
||||
import io.netty.buffer.*;
|
||||
import it.unimi.dsi.fastutil.ints.*;
|
||||
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.nio.file.*;
|
||||
import java.time.*;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static emu.grasscutter.utils.FileUtils.getResourcePath;
|
||||
import static emu.grasscutter.utils.Language.translate;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
@SuppressWarnings({"UnusedReturnValue", "BooleanMethodIsAlwaysInverted"})
|
||||
public final class Utils {
|
||||
public static final Random random = new Random();
|
||||
|
||||
public static <T> T make(Supplier<T> factory) {
|
||||
return factory.get();
|
||||
}
|
||||
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
|
||||
|
||||
public static int randomRange(int min, int max) {
|
||||
return random.nextInt(max - min + 1) + min;
|
||||
@@ -81,7 +72,6 @@ public final class Utils {
|
||||
b.release();
|
||||
}
|
||||
|
||||
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
if (bytes == null) return "";
|
||||
char[] hexChars = new char[bytes.length * 2];
|
||||
@@ -114,6 +104,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@@ -123,6 +114,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Checks if a file exists on the file system.
|
||||
*
|
||||
* @param path The path to the file.
|
||||
* @return True if the file exists, false otherwise.
|
||||
*/
|
||||
@@ -132,6 +124,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Creates a folder on the file system.
|
||||
*
|
||||
* @param path The path to the folder.
|
||||
* @return True if the folder was created, false otherwise.
|
||||
*/
|
||||
@@ -141,6 +134,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -155,26 +149,26 @@ public final class Utils {
|
||||
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);
|
||||
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.
|
||||
*/
|
||||
/** Checks for required files and folders before startup. */
|
||||
public static void startupCheck() {
|
||||
ConfigContainer config = Grasscutter.getConfig();
|
||||
Logger logger = Grasscutter.getLogger();
|
||||
boolean exit = false;
|
||||
boolean exit = false, custom = false;
|
||||
|
||||
String dataFolder = config.folderStructure.data;
|
||||
|
||||
@@ -182,33 +176,50 @@ public final class Utils {
|
||||
if (!Files.exists(getResourcePath(""))) {
|
||||
logger.info(translate("messages.status.create_resources"));
|
||||
logger.info(translate("messages.status.resources_error"));
|
||||
createFolder(config.folderStructure.resources); exit = true;
|
||||
createFolder(config.folderStructure.resources);
|
||||
exit = true;
|
||||
}
|
||||
|
||||
// Check for BinOutput + ExcelBinOutput.
|
||||
if (!Files.exists(getResourcePath("BinOutput")) ||
|
||||
!Files.exists(getResourcePath("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);
|
||||
if (!fileExists(dataFolder)) createFolder(dataFolder);
|
||||
|
||||
// Make sure the data folder is populated, if there are any missing files copy them from resources
|
||||
DataLoader.checkAllFiles();
|
||||
// Check for Server resources.
|
||||
if (!Files.exists(getResourcePath("Server"))) {
|
||||
logger.info(translate("messages.status.resources.missing_server"));
|
||||
custom = true;
|
||||
}
|
||||
|
||||
// Check for ScriptSceneData.
|
||||
if (!Files.exists(getResourcePath("ScriptSceneData"))) {
|
||||
logger.info(translate("messages.status.resources.missing_scenes"));
|
||||
custom = true;
|
||||
}
|
||||
|
||||
// Log message if custom resources are missing.
|
||||
if (custom) logger.info(translate("messages.status.resources.custom"));
|
||||
|
||||
// Exit if there are any missing files.
|
||||
if (exit) System.exit(1);
|
||||
|
||||
// Validate the data directory.
|
||||
DataLoader.checkAllFiles();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ++) {
|
||||
for (int i = 0; i < param; i++) {
|
||||
if (zonedDateTime.getHour() < hour) {
|
||||
zonedDateTime = zonedDateTime.withHour(hour).withMinute(0).withSecond(0);
|
||||
} else {
|
||||
@@ -220,15 +231,22 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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);
|
||||
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);
|
||||
zonedDateTime =
|
||||
zonedDateTime
|
||||
.with(TemporalAdjusters.next(DayOfWeek.MONDAY))
|
||||
.withHour(hour)
|
||||
.withMinute(0)
|
||||
.withSecond(0);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
@@ -236,15 +254,22 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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);
|
||||
zonedDateTime =
|
||||
ZonedDateTime.now(ZoneId.of(timeZone)).withHour(hour).withMinute(0).withSecond(0);
|
||||
} else {
|
||||
zonedDateTime = zonedDateTime.with(TemporalAdjusters.firstDayOfNextMonth()).withHour(hour).withMinute(0).withSecond(0);
|
||||
zonedDateTime =
|
||||
zonedDateTime
|
||||
.with(TemporalAdjusters.firstDayOfNextMonth())
|
||||
.withHour(hour)
|
||||
.withMinute(0)
|
||||
.withSecond(0);
|
||||
}
|
||||
}
|
||||
return (int) zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();
|
||||
@@ -252,6 +277,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Retrieves a string from an input stream.
|
||||
*
|
||||
* @param stream The input stream.
|
||||
* @return The string.
|
||||
*/
|
||||
@@ -259,53 +285,62 @@ public final class Utils {
|
||||
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) {
|
||||
try (BufferedReader reader =
|
||||
new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
stringBuilder.append(line);
|
||||
} stream.close();
|
||||
}
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
Grasscutter.getLogger().warn("Failed to read from input stream.");
|
||||
} catch (NullPointerException ignored) {
|
||||
return "empty";
|
||||
} return stringBuilder.toString();
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a linear interpolation using a table of fixed points to create an effective piecewise f(x) = y function.
|
||||
* 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
|
||||
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];
|
||||
} 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];
|
||||
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]) {
|
||||
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.
|
||||
// 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 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 );
|
||||
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]].");
|
||||
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
|
||||
@@ -321,6 +356,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -337,6 +373,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Gets the language code from a given locale.
|
||||
*
|
||||
* @param locale A locale.
|
||||
* @return A string in the format of 'XX-XX'.
|
||||
*/
|
||||
@@ -346,6 +383,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Base64 encodes a given byte array.
|
||||
*
|
||||
* @param toEncode An array of bytes.
|
||||
* @return A base64 encoded string.
|
||||
*/
|
||||
@@ -355,6 +393,7 @@ public final class Utils {
|
||||
|
||||
/**
|
||||
* Base64 decodes a given string.
|
||||
*
|
||||
* @param toDecode A base64 encoded string.
|
||||
* @return An array of bytes.
|
||||
*/
|
||||
@@ -415,8 +454,43 @@ public final class Utils {
|
||||
output.add(input.substring(start, next));
|
||||
start = next + 1;
|
||||
}
|
||||
if (start < input.length())
|
||||
output.add(input.substring(start));
|
||||
if (start < input.length()) output.add(input.substring(start));
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the IP address of a web request.
|
||||
*
|
||||
* @param ctx The context of the request.
|
||||
* @return The IP address of the request.
|
||||
*/
|
||||
public static String address(Context ctx) {
|
||||
// Check headers.
|
||||
var address = ctx.header("CF-Connecting-IP");
|
||||
if (address != null) return address;
|
||||
|
||||
address = ctx.header("X-Forwarded-For");
|
||||
if (address != null) return address;
|
||||
|
||||
address = ctx.header("X-Real-IP");
|
||||
if (address != null) return address;
|
||||
|
||||
// Return the request IP.
|
||||
return ctx.ip();
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for the task to return true. This will halt the thread until the task returns true.
|
||||
*
|
||||
* @param runnable The task to run.
|
||||
*/
|
||||
public static void waitFor(Returnable<Boolean> runnable) {
|
||||
while (!runnable.invoke()) {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
package emu.grasscutter.utils;
|
||||
package emu.grasscutter.utils.helpers;
|
||||
|
||||
public class ByteHelper {
|
||||
public static byte[] changeBytes(byte[] a) {
|
||||
byte[] b = new byte[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
public interface ByteHelper {
|
||||
static byte[] changeBytes(byte[] a) {
|
||||
var b = new byte[a.length];
|
||||
for (var i = 0; i < a.length; i++) {
|
||||
b[i] = a[a.length - i - 1];
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
public static byte[] longToBytes(long x) {
|
||||
byte[] bytes = new byte[8];
|
||||
static byte[] longToBytes(long x) {
|
||||
var bytes = new byte[8];
|
||||
bytes[0] = (byte) (x >> 56);
|
||||
bytes[1] = (byte) (x >> 48);
|
||||
bytes[2] = (byte) (x >> 40);
|
||||
20
src/main/java/emu/grasscutter/utils/helpers/DateHelper.java
Normal file
20
src/main/java/emu/grasscutter/utils/helpers/DateHelper.java
Normal file
@@ -0,0 +1,20 @@
|
||||
package emu.grasscutter.utils.helpers;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public interface DateHelper {
|
||||
static Date onlyYearMonthDay(Date now) {
|
||||
var 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();
|
||||
}
|
||||
|
||||
static int getUnixTime(Date localDateTime) {
|
||||
return (int) (localDateTime.getTime() / 1000L);
|
||||
}
|
||||
}
|
||||
10
src/main/java/emu/grasscutter/utils/helpers/ProtoHelper.java
Normal file
10
src/main/java/emu/grasscutter/utils/helpers/ProtoHelper.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package emu.grasscutter.utils.helpers;
|
||||
|
||||
import emu.grasscutter.game.props.PlayerProperty;
|
||||
import emu.grasscutter.net.proto.PropValueOuterClass.PropValue;
|
||||
|
||||
public interface ProtoHelper {
|
||||
static PropValue newPropValue(PlayerProperty key, int value) {
|
||||
return PropValue.newBuilder().setType(key.getId()).setIval(value).setVal(value).build();
|
||||
}
|
||||
}
|
||||
526
src/main/java/emu/grasscutter/utils/lang/Language.java
Normal file
526
src/main/java/emu/grasscutter/utils/lang/Language.java
Normal file
@@ -0,0 +1,526 @@
|
||||
package emu.grasscutter.utils.lang;
|
||||
|
||||
import static emu.grasscutter.config.Configuration.FALLBACK_LANGUAGE;
|
||||
import static emu.grasscutter.utils.FileUtils.*;
|
||||
|
||||
import com.google.gson.*;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import emu.grasscutter.data.*;
|
||||
import emu.grasscutter.data.excels.achievement.AchievementData;
|
||||
import emu.grasscutter.game.player.Player;
|
||||
import emu.grasscutter.utils.*;
|
||||
import it.unimi.dsi.fastutil.ints.*;
|
||||
import it.unimi.dsi.fastutil.objects.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.*;
|
||||
import java.util.stream.*;
|
||||
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 = getCachePath("TextMap/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 locale The locale to use.
|
||||
* @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(Locale locale, String key, Object... args) {
|
||||
if (locale == null) {
|
||||
return translate(key, args);
|
||||
}
|
||||
|
||||
var langCode = Utils.getLanguageCode(locale);
|
||||
var translated = getLanguage(langCode).get(key);
|
||||
|
||||
for (var 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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
return translate(player.getAccount().getLocale(), key, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
Files.createDirectories(TEXTMAP_CACHE_PATH.getParent());
|
||||
try (var 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);
|
||||
}
|
||||
|
||||
/** Loads game text maps with caching. */
|
||||
public static void loadTextMaps() {
|
||||
Language.loadTextMaps(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads game language data (text maps).
|
||||
*
|
||||
* @param bypassCache Should the cache be bypassed?
|
||||
*/
|
||||
public static void loadTextMaps(boolean bypassCache) {
|
||||
// Check system timestamps on cache and resources
|
||||
if (!bypassCache)
|
||||
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().debug("Loading cached 'TextMaps'...");
|
||||
textMapStrings = loadTextMapsCache();
|
||||
return;
|
||||
}
|
||||
} catch (NoSuchFileException ignored) {
|
||||
// Cache doesn't exist, generate it.
|
||||
} catch (Exception exception) {
|
||||
Grasscutter.getLogger().error("Error loading textmaps cache: " + exception.toString());
|
||||
}
|
||||
|
||||
// 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()));
|
||||
GameData.getWorldAreaDataMap().forEach((k, v) -> usedHashes.add((int) v.getTextMapHash()));
|
||||
// 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,4 +1,4 @@
|
||||
package emu.grasscutter.utils;
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import emu.grasscutter.server.event.Event;
|
||||
|
||||
42
src/main/java/emu/grasscutter/utils/objects/FieldFetch.java
Normal file
42
src/main/java/emu/grasscutter/utils/objects/FieldFetch.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonObject;
|
||||
import emu.grasscutter.server.dispatch.IDispatcher;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
|
||||
public interface FieldFetch {
|
||||
/**
|
||||
* Fetches the specified fields. Serializes them into a JSON object.
|
||||
*
|
||||
* @param fields The fields to fetch.
|
||||
* @return The JSON object containing the fields.
|
||||
*/
|
||||
default JsonObject fetchFields(String... fields) {
|
||||
// Prepare field properties.
|
||||
var fieldValues = new JsonObject();
|
||||
var fieldMap = new HashMap<String, Field>();
|
||||
Arrays.stream(this.getClass().getDeclaredFields())
|
||||
.forEach(field -> fieldMap.put(field.getName(), field));
|
||||
|
||||
// Find the values of all requested fields.
|
||||
for (var fieldName : fields) {
|
||||
try {
|
||||
var field = fieldMap.get(fieldName);
|
||||
if (field == null) fieldValues.add(fieldName, JsonNull.INSTANCE);
|
||||
else {
|
||||
var wasAccessible = field.canAccess(this);
|
||||
field.setAccessible(true);
|
||||
fieldValues.add(fieldName, IDispatcher.JSON.toJsonTree(field.get(this)));
|
||||
field.setAccessible(wasAccessible);
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
return fieldValues;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
/** HTTP request object for handbook controls. */
|
||||
@SuppressWarnings("FieldMayBeFinal")
|
||||
public interface HandbookBody {
|
||||
@Builder
|
||||
@Getter
|
||||
class Response {
|
||||
private int status;
|
||||
private String message;
|
||||
}
|
||||
|
||||
enum Action {
|
||||
GRANT_AVATAR,
|
||||
GIVE_ITEM,
|
||||
TELEPORT_TO,
|
||||
SPAWN_ENTITY
|
||||
}
|
||||
|
||||
@Getter
|
||||
class GrantAvatar {
|
||||
private String player; // Parse into online player ID.
|
||||
private String playerToken; // Parse into session token.
|
||||
private String avatar; // Parse into avatar ID.
|
||||
|
||||
private int level = 90; // Range between 1 - 90.
|
||||
private int constellations = 6; // Range between 0 - 6.
|
||||
private int talentLevels = 10; // Range between 1 - 15.
|
||||
}
|
||||
|
||||
@Getter
|
||||
class GiveItem {
|
||||
private String player; // Parse into online player ID.
|
||||
private String playerToken; // Parse into session token.
|
||||
private String item; // Parse into item ID.
|
||||
|
||||
private long amount = 1; // Range between 1 - Long.MAX_VALUE.
|
||||
}
|
||||
|
||||
@Getter
|
||||
class TeleportTo {
|
||||
private String player; // Parse into online player ID.
|
||||
private String playerToken; // Parse into session token.
|
||||
private String scene; // Parse into a scene ID.
|
||||
}
|
||||
|
||||
@Getter
|
||||
class SpawnEntity {
|
||||
private String player; // Parse into online player ID.
|
||||
private String playerToken; // Parse into session token.
|
||||
private String entity; // Parse into entity ID.
|
||||
|
||||
private long amount = 1; // Range between 1 - Long.MAX_VALUE.
|
||||
private int level = 1; // Range between 1 - 200.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.ConsoleAppender;
|
||||
import emu.grasscutter.Grasscutter;
|
||||
import java.util.Arrays;
|
||||
|
||||
public final class JLineLogbackAppender extends ConsoleAppender<ILoggingEvent> {
|
||||
@Override
|
||||
protected void append(ILoggingEvent eventObject) {
|
||||
if (!this.started) return;
|
||||
|
||||
Arrays.stream(new String(encoder.encode(eventObject)).split("\n\r"))
|
||||
.forEach(Grasscutter.getConsole()::printAbove);
|
||||
}
|
||||
}
|
||||
139
src/main/java/emu/grasscutter/utils/objects/JObject.java
Normal file
139
src/main/java/emu/grasscutter/utils/objects/JObject.java
Normal file
@@ -0,0 +1,139 @@
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.internal.LinkedTreeMap;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import emu.grasscutter.utils.JsonUtils;
|
||||
import java.io.IOException;
|
||||
|
||||
/* Replica of JsonObject. Includes chaining. */
|
||||
public final class JObject {
|
||||
/* Type adapter for gson. */
|
||||
public static class Adapter extends TypeAdapter<JObject> {
|
||||
@Override
|
||||
public void write(JsonWriter out, JObject value) throws IOException {
|
||||
out.beginObject();
|
||||
for (var entry : value.members.entrySet()) {
|
||||
out.name(entry.getKey());
|
||||
out.jsonValue(entry.getValue().toString());
|
||||
}
|
||||
out.endObject();
|
||||
}
|
||||
|
||||
@Override
|
||||
public JObject read(JsonReader in) throws IOException {
|
||||
var object = JObject.c();
|
||||
in.beginObject();
|
||||
while (in.hasNext()) {
|
||||
object.add(in.nextName(), JsonParser.parseReader(in));
|
||||
}
|
||||
in.endObject();
|
||||
return object;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new empty object.
|
||||
*
|
||||
* @return The new object.
|
||||
*/
|
||||
public static JObject c() {
|
||||
return new JObject();
|
||||
}
|
||||
|
||||
private final LinkedTreeMap<String, JsonElement> members = new LinkedTreeMap<>();
|
||||
|
||||
/**
|
||||
* Adds a member to this object.
|
||||
*
|
||||
* @param name The name of the member.
|
||||
* @param value The value of the member.
|
||||
* @return This object.
|
||||
*/
|
||||
public JObject add(String name, JsonElement value) {
|
||||
this.members.put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a member to this object.
|
||||
*
|
||||
* @param name The name of the member.
|
||||
* @param value The value of the member.
|
||||
* @return This object.
|
||||
*/
|
||||
public JObject add(String name, String value) {
|
||||
return this.add(name, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a member to this object.
|
||||
*
|
||||
* @param name The name of the member.
|
||||
* @param value The value of the member.
|
||||
* @return This object.
|
||||
*/
|
||||
public JObject add(String name, Number value) {
|
||||
return this.add(name, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a member to this object.
|
||||
*
|
||||
* @param name The name of the member.
|
||||
* @param value The value of the member.
|
||||
* @return This object.
|
||||
*/
|
||||
public JObject add(String name, Boolean value) {
|
||||
return this.add(name, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a member to this object.
|
||||
*
|
||||
* @param name The name of the member.
|
||||
* @param value The value of the member.
|
||||
* @return This object.
|
||||
*/
|
||||
public JObject add(String name, Character value) {
|
||||
return this.add(name, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a member to this object.
|
||||
*
|
||||
* @param name The name of the member.
|
||||
* @param value The value of the member.
|
||||
* @return This object.
|
||||
*/
|
||||
public JObject add(String name, Object[] value) {
|
||||
return this.add(name, value == null ? JsonNull.INSTANCE : JsonUtils.toJson(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A {@link JsonObject} representation of this object.
|
||||
*/
|
||||
public JsonObject gson() {
|
||||
var object = new JsonObject();
|
||||
for (var entry : this.members.entrySet()) {
|
||||
object.add(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The property holder.
|
||||
*/
|
||||
public Object json() {
|
||||
return this.members;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A string representation of this object.
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonUtils.encode(this.gson());
|
||||
}
|
||||
}
|
||||
68
src/main/java/emu/grasscutter/utils/objects/KahnsSort.java
Normal file
68
src/main/java/emu/grasscutter/utils/objects/KahnsSort.java
Normal file
@@ -0,0 +1,68 @@
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Stack;
|
||||
|
||||
public class KahnsSort {
|
||||
public static class Node {
|
||||
int source, dest; // Dest is a value, and source too
|
||||
|
||||
public Node(int source, int dest) {
|
||||
this.source = source;
|
||||
this.dest = dest;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Graph {
|
||||
Map<Integer, List<Integer>> mainList;
|
||||
Map<Integer, Integer> degreeList;
|
||||
|
||||
List<Integer> nodeList;
|
||||
|
||||
public Graph(List<Node> nodes, List<Integer> nodeList) {
|
||||
mainList = new HashMap<>();
|
||||
this.nodeList = nodeList;
|
||||
|
||||
for (int i = 0; i < nodeList.size(); i++) mainList.put(nodeList.get(i), new ArrayList<>());
|
||||
|
||||
degreeList = new HashMap<>();
|
||||
for (int i = 0; i < nodeList.size(); i++) degreeList.put(nodeList.get(i), 0);
|
||||
|
||||
for (Node node : nodes) {
|
||||
mainList.get(node.source).add(node.dest);
|
||||
degreeList.replace(node.dest, degreeList.get(node.dest) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Integer> doSort(Graph graph) {
|
||||
List<Integer> orderedList = new ArrayList<>();
|
||||
Map<Integer, Integer> degreeList = graph.degreeList;
|
||||
|
||||
Stack<Integer> zeroStack = new Stack<>();
|
||||
degreeList.forEach(
|
||||
(key, value) -> {
|
||||
if (value == 0) zeroStack.add(key);
|
||||
});
|
||||
|
||||
while (!zeroStack.isEmpty()) {
|
||||
int element = zeroStack.pop();
|
||||
|
||||
// If the list is empty then this node
|
||||
if (!graph.mainList.get(element).isEmpty()) orderedList.add(element);
|
||||
for (int topElement : graph.mainList.get(element)) {
|
||||
degreeList.replace(topElement, degreeList.get(topElement) - 1);
|
||||
|
||||
if (degreeList.get(topElement) == 0) zeroStack.add(topElement);
|
||||
}
|
||||
}
|
||||
|
||||
if (degreeList.values().stream().filter(value -> value != 0).count() != 0)
|
||||
return null; // Loop found
|
||||
|
||||
return orderedList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
public interface Returnable<T> {
|
||||
/**
|
||||
* @return The value.
|
||||
*/
|
||||
T invoke();
|
||||
}
|
||||
@@ -1,23 +1,19 @@
|
||||
package emu.grasscutter.utils;
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
import ch.qos.logback.core.encoder.Encoder;
|
||||
import ch.qos.logback.core.spi.DeferredProcessingAware;
|
||||
import ch.qos.logback.core.status.ErrorStatus;
|
||||
import emu.grasscutter.server.event.internal.ServerLogEvent;
|
||||
import emu.grasscutter.server.event.types.ServerEvent;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class ServerLogEventAppender<E> extends AppenderBase<E> {
|
||||
public final 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));
|
||||
ServerLogEvent sle =
|
||||
new ServerLogEvent((ILoggingEvent) event, new String(byteArray, StandardCharsets.UTF_8));
|
||||
sle.call();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package emu.grasscutter.utils;
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -6,27 +6,6 @@ import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
public final class SparseSet {
|
||||
/*
|
||||
* 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 - " + Integer.toString(min) + " > " + Integer.toString(max));
|
||||
}
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public boolean check(int value) {
|
||||
return value >= this.min && value <= this.max;
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Range> rangeEntries;
|
||||
private final Set<Integer> denseEntries;
|
||||
|
||||
@@ -41,10 +20,16 @@ public final class SparseSet {
|
||||
this.denseEntries.add(Integer.parseInt(tokens[0]));
|
||||
break;
|
||||
case 2:
|
||||
this.rangeEntries.add(new Range(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])));
|
||||
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 " + Integer.toString(tokens.length) + ")");
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid token passed to SparseSet initializer - "
|
||||
+ token
|
||||
+ " (split length "
|
||||
+ tokens.length
|
||||
+ ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,4 +42,26 @@ public final class SparseSet {
|
||||
}
|
||||
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,4 +1,4 @@
|
||||
package emu.grasscutter.utils;
|
||||
package emu.grasscutter.utils.objects;
|
||||
|
||||
import java.util.NavigableMap;
|
||||
import java.util.TreeMap;
|
||||
@@ -8,9 +8,7 @@ public class WeightedList<E> {
|
||||
private final NavigableMap<Double, E> map = new TreeMap<Double, E>();
|
||||
private double total = 0;
|
||||
|
||||
public WeightedList() {
|
||||
|
||||
}
|
||||
public WeightedList() {}
|
||||
|
||||
public WeightedList<E> add(double weight, E result) {
|
||||
if (weight <= 0) return this;
|
||||
@@ -24,7 +22,7 @@ public class WeightedList<E> {
|
||||
return map.higherEntry(value).getValue();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
}
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
}
|
||||
234
src/main/java/emu/grasscutter/utils/objects/text/Style.java
Normal file
234
src/main/java/emu/grasscutter/utils/objects/text/Style.java
Normal file
@@ -0,0 +1,234 @@
|
||||
package emu.grasscutter.utils.objects.text;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/* Text style container. */
|
||||
@Builder
|
||||
@Data
|
||||
public final class Style {
|
||||
private static final Map<Character, String> unity = new HashMap<>();
|
||||
private static final Map<Character, String> ansi = new HashMap<>();
|
||||
|
||||
static {
|
||||
// Add the Minecraft color codes to the color map.
|
||||
unity.put('0', "#000000"); // Black
|
||||
unity.put('1', "#0000AA"); // Dark Blue
|
||||
unity.put('2', "#00AA00"); // Dark Green
|
||||
unity.put('3', "#00AAAA"); // Dark Aqua
|
||||
unity.put('4', "#AA0000"); // Dark Red
|
||||
unity.put('5', "#AA00AA"); // Dark Purple
|
||||
unity.put('6', "#FFAA00"); // Gold
|
||||
unity.put('7', "#AAAAAA"); // Gray
|
||||
unity.put('8', "#555555"); // Dark Gray
|
||||
unity.put('9', "#5555FF"); // Blue
|
||||
unity.put('a', "#55FF55"); // Green
|
||||
unity.put('b', "#55FFFF"); // Aqua
|
||||
unity.put('c', "#FF5555"); // Red
|
||||
unity.put('d', "#FF55FF"); // Light Purple
|
||||
unity.put('e', "#FFFF55"); // Yellow
|
||||
unity.put('f', "#FFFFFF"); // White
|
||||
|
||||
ansi.put('0', "\u001B[30m"); // Black
|
||||
ansi.put('1', "\u001B[34m"); // Dark Blue
|
||||
ansi.put('2', "\u001B[32m"); // Dark Green
|
||||
ansi.put('3', "\u001B[36m"); // Dark Aqua
|
||||
ansi.put('4', "\u001B[31m"); // Dark Red
|
||||
ansi.put('5', "\u001B[35m"); // Dark Purple
|
||||
ansi.put('6', "\u001B[33m"); // Gold
|
||||
ansi.put('7', "\u001B[37m"); // Gray
|
||||
ansi.put('8', "\u001B[90m"); // Dark Gray
|
||||
ansi.put('9', "\u001B[94m"); // Blue
|
||||
ansi.put('a', "\u001B[92m"); // Green
|
||||
ansi.put('b', "\u001B[96m"); // Aqua
|
||||
ansi.put('c', "\u001B[91m"); // Red
|
||||
ansi.put('d', "\u001B[95m"); // Light Purple
|
||||
ansi.put('e', "\u001B[93m"); // Yellow
|
||||
ansi.put('f', "\u001B[97m"); // White
|
||||
}
|
||||
|
||||
@Builder.Default private int size = -1; // Unity only.
|
||||
@Builder.Default private boolean bold = false; // Unity only.
|
||||
@Builder.Default private boolean italic = false; // Unity only.
|
||||
|
||||
@Builder.Default private Color color = null;
|
||||
|
||||
/**
|
||||
* Replaces detected sequences of &color with the specified text.
|
||||
*
|
||||
* @param input The input text.
|
||||
* @return The replaced text.
|
||||
*/
|
||||
private String replaceUnity(String input) {
|
||||
// Thanks ChatGPT! (from ChatGPT)
|
||||
// Check if the input string is null or empty
|
||||
if (input == null || input.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
var output = new StringBuilder();
|
||||
var i = 0;
|
||||
while (i < input.length()) {
|
||||
var c = input.charAt(i);
|
||||
if (c == '&') {
|
||||
// Check if the Minecraft color code is valid
|
||||
if (i + 1 < input.length() && unity.containsKey(input.charAt(i + 1))) {
|
||||
// Append the Unity color code
|
||||
output.append("<color=").append(unity.get(input.charAt(i + 1))).append(">");
|
||||
|
||||
// Move the index past the Minecraft color code
|
||||
i += 2;
|
||||
|
||||
// Find the end of the color code span
|
||||
var end = input.indexOf('&', i);
|
||||
if (end == -1) {
|
||||
end = input.length();
|
||||
}
|
||||
|
||||
// Append the text within the color code span
|
||||
output.append(input, i, end);
|
||||
|
||||
// Append the closing tag for the Unity color code
|
||||
output.append("</color>");
|
||||
|
||||
// Move the index to the end of the color code span
|
||||
i = end;
|
||||
} else {
|
||||
// Invalid Minecraft color code, treat it as regular text
|
||||
output.append(c);
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
// Append regular text
|
||||
output.append(c);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces detected sequences of &color with the specified text.
|
||||
*
|
||||
* @param input The input text.
|
||||
* @return The replaced text.
|
||||
*/
|
||||
private String replaceTerminal(String input) {
|
||||
// Check if the input string is null or empty
|
||||
if (input == null || input.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
var output = new StringBuilder();
|
||||
var i = 0;
|
||||
while (i < input.length()) {
|
||||
var c = input.charAt(i);
|
||||
if (c == '&') {
|
||||
// Check if the Minecraft color code is valid
|
||||
if (i + 1 < input.length() && ansi.containsKey(input.charAt(i + 1))) {
|
||||
// Append the ANSI escape code
|
||||
output.append(ansi.get(input.charAt(i + 1)));
|
||||
|
||||
// Move the index past the Minecraft color code
|
||||
i += 2;
|
||||
|
||||
// Find the end of the color code span
|
||||
var end = input.indexOf('&', i);
|
||||
if (end == -1) {
|
||||
end = input.length();
|
||||
}
|
||||
|
||||
// Append the text within the color code span
|
||||
output.append(input, i, end);
|
||||
|
||||
// Reset the color back to default
|
||||
output.append("\u001B[0m");
|
||||
|
||||
// Move the index to the end of the color code span
|
||||
i = end;
|
||||
} else {
|
||||
// Invalid Minecraft color code, treat it as regular text
|
||||
output.append(c);
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
// Append regular text
|
||||
output.append(c);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the text in the style. Formatted for Unity clients.
|
||||
*
|
||||
* @param text The text to wrap.
|
||||
* @return The wrapped text.
|
||||
*/
|
||||
public String toUnity(String text) {
|
||||
var builder = new StringBuilder();
|
||||
|
||||
// Set the size.
|
||||
if (this.size != -1) {
|
||||
builder.append("<size=").append(this.size).append(">");
|
||||
}
|
||||
|
||||
// Set the color.
|
||||
if (this.color != null) {
|
||||
builder
|
||||
.append("<color=")
|
||||
.append(
|
||||
String.format(
|
||||
"#%02x%02x%02x",
|
||||
this.color.getRed(), this.color.getGreen(), this.color.getBlue()))
|
||||
.append(">");
|
||||
}
|
||||
|
||||
// Set the boldness.
|
||||
if (this.bold) builder.append("<b>");
|
||||
// Set the italicness.
|
||||
if (this.italic) builder.append("<i>");
|
||||
|
||||
// Append the text.
|
||||
builder.append(this.replaceUnity(text));
|
||||
|
||||
// Close the tags.
|
||||
if (this.italic) builder.append("</i>");
|
||||
if (this.bold) builder.append("</b>");
|
||||
if (this.color != null) builder.append("</color>");
|
||||
if (this.size != -1) builder.append("</size>");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the text in the style. Formatted for terminal clients.
|
||||
*
|
||||
* @param text The text to wrap.
|
||||
* @return The wrapped text.
|
||||
*/
|
||||
public String toTerminal(String text) {
|
||||
// Check for color.
|
||||
if (this.color == null) return this.replaceTerminal(text);
|
||||
|
||||
// Convert the color to an ANSI color.
|
||||
var ansiColor =
|
||||
this.color.getRed() > 127
|
||||
? this.color.getGreen() > 127
|
||||
? this.color.getBlue() > 127 ? 15 : 11
|
||||
: this.color.getBlue() > 127 ? 13 : 9
|
||||
: this.color.getGreen() > 127
|
||||
? this.color.getBlue() > 127 ? 14 : 10
|
||||
: this.color.getBlue() > 127 ? 12 : 8;
|
||||
|
||||
// Return the text with the ANSI color.
|
||||
// Reset the color at the end.
|
||||
return "\u001B[38;5;" + ansiColor + "m" + this.replaceTerminal(text) + "\u001B[0m";
|
||||
}
|
||||
}
|
||||
102
src/main/java/emu/grasscutter/utils/objects/text/Text.java
Normal file
102
src/main/java/emu/grasscutter/utils/objects/text/Text.java
Normal file
@@ -0,0 +1,102 @@
|
||||
package emu.grasscutter.utils.objects.text;
|
||||
|
||||
import java.awt.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/* An instance of text. */
|
||||
public final class Text {
|
||||
/**
|
||||
* Creates a new rich instance of text.
|
||||
*
|
||||
* @param text The text to use.
|
||||
* @return The new instance of text.
|
||||
*/
|
||||
public static Text of(String text) {
|
||||
return new Text(text, false);
|
||||
}
|
||||
|
||||
@Getter private final boolean raw;
|
||||
private final Style.StyleBuilder style = Style.builder();
|
||||
|
||||
@Setter private String text;
|
||||
|
||||
/**
|
||||
* Creates a new rich instance of text.
|
||||
*
|
||||
* @param text The text to use.
|
||||
*/
|
||||
public Text(String text) {
|
||||
this.raw = false;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance of text.
|
||||
*
|
||||
* @param text The text to use.
|
||||
* @param raw Whether the text is raw.
|
||||
*/
|
||||
public Text(String text, boolean raw) {
|
||||
this.raw = raw;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the size of the text.
|
||||
*
|
||||
* @param size The size of the text.
|
||||
* @return This object.
|
||||
*/
|
||||
public Text size(int size) {
|
||||
this.style.size(size);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the color of the text.
|
||||
*
|
||||
* @param color The color of the text.
|
||||
* @return This object.
|
||||
*/
|
||||
public Text color(Color color) {
|
||||
this.style.color(color);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the boldness of the text.
|
||||
*
|
||||
* @param bold Whether the text is bold.
|
||||
* @return This object.
|
||||
*/
|
||||
public Text bold(boolean bold) {
|
||||
this.style.bold(bold);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the italicness of the text.
|
||||
*
|
||||
* @param italic Whether the text is italic.
|
||||
* @return This object.
|
||||
*/
|
||||
public Text italic(boolean italic) {
|
||||
this.style.italic(italic);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts this object to a string. Converts to a console or Unity format.
|
||||
*
|
||||
* @param console Whether to convert the text for the console.
|
||||
* @return The converted string.
|
||||
*/
|
||||
public String toString(boolean console) {
|
||||
// Pull instances of style and text.
|
||||
var style = this.style.build();
|
||||
var text = this.text;
|
||||
|
||||
return console ? style.toTerminal(text) : style.toUnity(text);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user