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:
Magix
2023-05-31 20:48:16 -07:00
committed by GitHub
parent f46fd372d2
commit 9e5b57a043
3839 changed files with 1841548 additions and 37533 deletions

View File

@@ -1,9 +1,13 @@
package emu.grasscutter.game.player;
import lombok.NonNull;
import lombok.*;
public abstract class BasePlayerManager {
protected transient final Player player;
protected final transient Player player;
@Getter
@Setter(AccessLevel.PROTECTED)
protected boolean loaded = false;
public BasePlayerManager(@NonNull Player player) {
this.player = player;
@@ -13,9 +17,7 @@ public abstract class BasePlayerManager {
return this.player;
}
/**
* Saves the player to the database
*/
/** Saves the player to the database */
public void save() {
getPlayer().save();
}

View File

@@ -1,60 +1,64 @@
package emu.grasscutter.game.player;
import java.util.ArrayList;
import java.util.List;
import emu.grasscutter.net.packet.BasePacket;
import emu.grasscutter.net.proto.ForwardTypeOuterClass.ForwardType;
import java.util.ArrayList;
import java.util.List;
public class InvokeHandler<T> {
private final List<T> entryListForwardAll;
private final List<T> entryListForwardAllExceptCur;
private final List<T> entryListForwardHost;
private final Class<? extends BasePacket> packetClass;
public InvokeHandler(Class<? extends BasePacket> packetClass) {
this.entryListForwardAll = new ArrayList<>();
this.entryListForwardAllExceptCur = new ArrayList<>();
this.entryListForwardHost = new ArrayList<>();
this.packetClass = packetClass;
}
private final List<T> entryListForwardAll;
private final List<T> entryListForwardAllExceptCur;
private final List<T> entryListForwardHost;
private final Class<? extends BasePacket> packetClass;
public synchronized void addEntry(ForwardType forward, T entry) {
switch (forward) {
case FORWARD_TYPE_TO_ALL -> entryListForwardAll.add(entry);
case FORWARD_TYPE_TO_ALL_EXCEPT_CUR, FORWARD_TYPE_TO_ALL_EXIST_EXCEPT_CUR -> entryListForwardAllExceptCur.add(entry);
case FORWARD_TYPE_TO_HOST -> entryListForwardHost.add(entry);
default -> {
}
}
}
public synchronized void update(Player player) {
if (player.getWorld() == null || player.getScene() == null) {
this.entryListForwardAll.clear();
this.entryListForwardAllExceptCur.clear();
this.entryListForwardHost.clear();
return;
}
try {
if (entryListForwardAll.size() > 0) {
BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardAll);
player.getScene().broadcastPacket(packet);
this.entryListForwardAll.clear();
}
if (entryListForwardAllExceptCur.size() > 0) {
BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardAllExceptCur);
player.getScene().broadcastPacketToOthers(player, packet);
this.entryListForwardAllExceptCur.clear();
}
if (entryListForwardHost.size() > 0) {
BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardHost);
player.getWorld().getHost().sendPacket(packet);
this.entryListForwardHost.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public InvokeHandler(Class<? extends BasePacket> packetClass) {
this.entryListForwardAll = new ArrayList<>();
this.entryListForwardAllExceptCur = new ArrayList<>();
this.entryListForwardHost = new ArrayList<>();
this.packetClass = packetClass;
}
public synchronized void addEntry(ForwardType forward, T entry) {
switch (forward) {
case FORWARD_TYPE_TO_ALL -> entryListForwardAll.add(entry);
case FORWARD_TYPE_TO_ALL_EXCEPT_CUR,
FORWARD_TYPE_TO_ALL_EXIST_EXCEPT_CUR -> entryListForwardAllExceptCur.add(entry);
case FORWARD_TYPE_TO_HOST -> entryListForwardHost.add(entry);
default -> {}
}
}
public synchronized void update(Player player) {
if (player.getWorld() == null || player.getScene() == null) {
this.entryListForwardAll.clear();
this.entryListForwardAllExceptCur.clear();
this.entryListForwardHost.clear();
return;
}
try {
if (entryListForwardAll.size() > 0) {
BasePacket packet =
packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardAll);
player.getScene().broadcastPacket(packet);
this.entryListForwardAll.clear();
}
if (entryListForwardAllExceptCur.size() > 0) {
BasePacket packet =
packetClass
.getDeclaredConstructor(List.class)
.newInstance(this.entryListForwardAllExceptCur);
player.getScene().broadcastPacketToOthers(player, packet);
this.entryListForwardAllExceptCur.clear();
}
if (entryListForwardHost.size() > 0) {
BasePacket packet =
packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardHost);
player.getWorld().getHost().sendPacket(packet);
this.entryListForwardHost.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -5,7 +5,7 @@ import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.PlayerLevelData;
import emu.grasscutter.data.excels.WeatherData;
import emu.grasscutter.data.excels.world.WeatherData;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.game.CoopRequest;
@@ -39,15 +39,15 @@ import emu.grasscutter.game.managers.forging.ForgingManager;
import emu.grasscutter.game.managers.mapmark.MapMark;
import emu.grasscutter.game.managers.mapmark.MapMarksManager;
import emu.grasscutter.game.managers.stamina.StaminaManager;
import emu.grasscutter.game.props.ActionReason;
import emu.grasscutter.game.props.ClimateType;
import emu.grasscutter.game.props.PlayerProperty;
import emu.grasscutter.game.props.WatcherTriggerType;
import emu.grasscutter.game.props.*;
import emu.grasscutter.game.quest.QuestManager;
import emu.grasscutter.game.quest.enums.QuestTrigger;
import emu.grasscutter.game.quest.enums.QuestCond;
import emu.grasscutter.game.quest.enums.QuestContent;
import emu.grasscutter.game.shop.ShopLimit;
import emu.grasscutter.game.talk.TalkManager;
import emu.grasscutter.game.tower.TowerData;
import emu.grasscutter.game.tower.TowerManager;
import emu.grasscutter.game.world.Position;
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.game.world.World;
import emu.grasscutter.net.packet.BasePacket;
@@ -65,17 +65,18 @@ import emu.grasscutter.net.proto.PropChangeReasonOuterClass.PropChangeReason;
import emu.grasscutter.net.proto.ShowAvatarInfoOuterClass;
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
import emu.grasscutter.net.proto.SocialShowAvatarInfoOuterClass;
import emu.grasscutter.plugin.api.PlayerHook;
import emu.grasscutter.scripts.data.SceneRegion;
import emu.grasscutter.server.event.player.PlayerEnterAreaEvent;
import emu.grasscutter.server.event.player.PlayerJoinEvent;
import emu.grasscutter.server.event.player.PlayerQuitEvent;
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.server.game.GameSession.SessionState;
import emu.grasscutter.server.packet.send.*;
import emu.grasscutter.utils.DateHelper;
import emu.grasscutter.utils.MessageHandler;
import emu.grasscutter.utils.Position;
import emu.grasscutter.utils.Utils;
import emu.grasscutter.utils.*;
import emu.grasscutter.utils.helpers.DateHelper;
import emu.grasscutter.utils.objects.FieldFetch;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import lombok.Getter;
@@ -92,11 +93,13 @@ import java.util.concurrent.LinkedBlockingQueue;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
@Entity(value = "players", useDiscriminator = false)
public class Player {
public class Player implements PlayerHook, FieldFetch {
@Id private int id;
@Indexed(options = @IndexOptions(unique = true)) private String accountId;
@Indexed(options = @IndexOptions(unique = true))
@Getter private String accountId;
@Setter private transient Account account;
@Getter @Setter private transient GameSession session;
@Transient private String sessionKey;
@Getter private String nickname;
@Getter private String signature;
@@ -116,12 +119,13 @@ public class Player {
@Getter @Setter private int sceneId;
@Getter @Setter private int regionId;
@Getter private int mainCharacterId;
@Setter private boolean godmode; // Getter is inGodmode
private boolean stamina; // Getter is getUnlimitedStamina, Setter is setUnlimitedStamina
@Getter @Setter private boolean inGodMode;
@Getter @Setter private boolean unlimitedStamina;
@Getter private Set<Integer> nameCardList;
@Getter private Set<Integer> flyCloakList;
@Getter private Set<Integer> costumeList;
@Getter private Set<Integer> personalLineList;
@Getter @Setter private Set<Integer> rewardedLevels;
@Getter @Setter private Set<Integer> homeRewardedLevels;
@Getter @Setter private Set<Integer> realmList;
@@ -146,13 +150,14 @@ public class Player {
@Transient private Scene scene; // Synchronized getter and setter
@Transient @Getter private int weatherId = 0;
@Transient @Getter private ClimateType climate = ClimateType.CLIMATE_SUNNY;
@Transient @Getter private int areaId = 0;
@Transient @Getter private int areaType = 0;
// Player managers go here
@Getter private transient AvatarStorage avatars;
@Getter private transient Inventory inventory;
@Getter private transient FriendsList friendsList;
@Getter private transient MailHandler mailHandler;
@Getter @Setter private transient MessageHandler messageHandler;
@Getter private transient AbilityManager abilityManager;
@Getter @Setter private transient QuestManager questManager;
@Getter private transient TowerManager towerManager;
@@ -171,6 +176,9 @@ public class Player {
@Getter private transient PlayerBuffManager buffManager;
@Getter private transient PlayerProgressManager progressManager;
@Getter private transient SatiationManager satiationManager;
@Getter private transient TalkManager talkManager;
@Getter @Setter private transient Position lastCheckedPosition = null;
// Manager data (Save-able to the database)
@Getter private transient Achievements achievements;
@@ -205,7 +213,13 @@ public class Player {
@Getter @Setter private int nextResinRefresh;
@Getter @Setter private int resinBuyCount;
@Getter @Setter private int lastDailyReset;
@Getter private transient MpSettingType mpSetting = MpSettingType.MP_SETTING_TYPE_ENTER_AFTER_APPLY; // TODO
@Getter private transient MpSettingType mpSetting = MpSettingType.MP_SETTING_TYPE_ENTER_AFTER_APPLY;
@Getter private long playerGameTime = 540000; // 9 in-game hours. Present at the start of the game.
@Getter private PlayerProgress playerProgress;
@Getter private Set<Integer> activeQuestTimers;
@Getter @Setter private ElementType mainCharacterElement = ElementType.None;
@Deprecated
@SuppressWarnings({"rawtypes", "unchecked"}) // Morphia only!
@@ -236,13 +250,14 @@ public class Player {
this.nameCardList = new HashSet<>();
this.flyCloakList = new HashSet<>();
this.costumeList = new HashSet<>();
this.personalLineList = new HashSet<>();
this.towerData = new TowerData();
this.collectionRecordStore = new PlayerCollectionRecords();
this.unlockedForgingBlueprints = new HashSet<>();
this.unlockedCombines = new HashSet<>();
this.unlockedFurniture = new HashSet<>();
this.unlockedFurnitureSuite = new HashSet<>();
this.activeCookCompounds=new HashMap<>();
this.activeCookCompounds = new HashMap<>();
this.activeForges = new ArrayList<>();
this.unlockedRecipies = new HashMap<>();
this.questGlobalVariables = new HashMap<>();
@@ -250,6 +265,8 @@ public class Player {
this.unlockedSceneAreas = new HashMap<>();
this.unlockedScenePoints = new HashMap<>();
this.chatEmojiIdList = new ArrayList<>();
this.playerProgress = new PlayerProgress();
this.activeQuestTimers = new HashSet<>();
this.attackResults = new LinkedBlockingQueue<>();
this.coopRequests = new Int2ObjectOpenHashMap<>();
@@ -266,7 +283,6 @@ public class Player {
this.progressManager = new PlayerProgressManager(this);
this.shopLimit = new ArrayList<>();
this.expeditionInfo = new HashMap<>();
this.messageHandler = null;
this.mapMarksManager = new MapMarksManager(this);
this.staminaManager = new StaminaManager(this);
this.sotsManager = new SotSManager(this);
@@ -276,13 +292,15 @@ public class Player {
this.progressManager = new PlayerProgressManager(this);
this.furnitureManager = new FurnitureManager(this);
this.cookingManager = new CookingManager(this);
this.cookingCompoundManager=new CookingCompoundManager(this);
this.cookingCompoundManager = new CookingCompoundManager(this);
this.satiationManager = new SatiationManager(this);
this.talkManager = new TalkManager(this);
}
// On player creation
public Player(GameSession session) {
this();
this.account = session.getAccount();
this.accountId = this.getAccount().getId();
this.session = session;
@@ -291,17 +309,11 @@ public class Player {
this.teamManager = new TeamManager(this);
this.birthday = new PlayerBirthday();
this.codex = new PlayerCodex(this);
this.setProperty(PlayerProperty.PROP_PLAYER_LEVEL, 1, false);
this.setProperty(PlayerProperty.PROP_IS_SPRING_AUTO_USE, 1, false);
this.setProperty(PlayerProperty.PROP_SPRING_AUTO_USE_PERCENT, 50, false);
this.setProperty(PlayerProperty.PROP_IS_FLYABLE, 1, false);
this.setProperty(PlayerProperty.PROP_IS_TRANSFERABLE, 1, false);
this.setProperty(PlayerProperty.PROP_MAX_STAMINA, 24000, false);
this.setProperty(PlayerProperty.PROP_CUR_PERSIST_STAMINA, 24000, false);
this.setProperty(PlayerProperty.PROP_PLAYER_RESIN, 160, false);
this.applyProperties();
this.getFlyCloakList().add(140001);
this.getNameCardList().add(210001);
this.messageHandler = null;
this.mapMarksManager = new MapMarksManager(this);
this.staminaManager = new StaminaManager(this);
this.sotsManager = new SotSManager(this);
@@ -312,10 +324,40 @@ public class Player {
this.progressManager = new PlayerProgressManager(this);
this.furnitureManager = new FurnitureManager(this);
this.cookingManager = new CookingManager(this);
this.cookingCompoundManager=new CookingCompoundManager(this);
this.cookingCompoundManager = new CookingCompoundManager(this);
this.satiationManager = new SatiationManager(this);
}
@Override
public Player getPlayer() {
return this;
}
/**
* Updates the player's game time if it has changed.
*
* @param gameTime The new game time.
*/
public void updatePlayerGameTime(long gameTime) {
if (this.playerGameTime == gameTime) return;
// Update the game time.
this.playerGameTime = gameTime;
// If the player is the host of the world, update the game time as well.
if (this.getWorld().getHost() == this) {
this.getWorld().changeTime(gameTime);
}
// Trigger the script event for game time update.
var questManager = this.getQuestManager();
questManager.queueEvent(QuestCond.QUEST_COND_IS_DAYTIME);
questManager.queueEvent(QuestCond.QUEST_COND_TIME_VAR_GT_EQ);
questManager.queueEvent(QuestCond.QUEST_COND_TIME_VAR_PASS_DAY);
this.save();
}
public int getUid() {
return id;
}
@@ -335,6 +377,24 @@ public class Player {
return this.account;
}
/**
* @return The player's session key.
*/
public String getSessionKey() {
if (this.sessionKey == null) {
// Check if the account is null.
if (this.account == null) {
this.account = DispatchUtils.getAccountById(this.getAccountId());
}
if (this.account == null) return "";
// Get the session key.
this.sessionKey = this.getAccount().getSessionKey();
}
return this.sessionKey;
}
public boolean isOnline() {
return this.getSession() != null && this.getSession().isActive();
}
@@ -364,11 +424,11 @@ public class Player {
this.session.send(new PacketSceneAreaWeatherNotify(this));
}
synchronized public void setWeather(int weather) {
public synchronized void setWeather(int weather) {
this.setWeather(weather, ClimateType.CLIMATE_NONE);
}
synchronized public void setWeather(int weatherId, ClimateType climate) {
public synchronized void setWeather(int weatherId, ClimateType climate) {
// Lookup default climate for this weather
if (climate == ClimateType.CLIMATE_NONE) {
WeatherData w = GameData.getWeatherDataMap().get(weatherId);
@@ -381,6 +441,21 @@ public class Player {
this.session.send(new PacketSceneAreaWeatherNotify(this));
}
/**
* Sets the player's weather and climate.
*
* @param areaId The area ID.
* @param areaType The area type.
*/
public void setArea(int areaId, int areaType) {
this.areaId = areaId;
this.areaType = areaType;
// Call the event.
var event = new PlayerEnterAreaEvent(this);
event.call();
}
public void setNickname(String nickName) {
this.nickname = nickName;
this.updateProfile();
@@ -456,6 +531,8 @@ public class Player {
// Handle open state unlocks from level-up.
this.getProgressManager().tryUnlockOpenStates();
this.getQuestManager().queueEvent(QuestContent.QUEST_CONTENT_PLAYER_LEVEL_UP, level);
this.getQuestManager().queueEvent(QuestCond.QUEST_COND_PLAYER_LEVEL_EQUAL_GREATER, level);
return true;
}
@@ -492,6 +569,40 @@ public class Player {
return this.setProperty(PlayerProperty.PROP_PLAYER_FORGE_POINT, value);
}
/**
* Applies the properties to the player.
*/
private void applyProperties() {
var withQuesting = GAME_OPTIONS.questing.enabled;
this.setOrFetch(PlayerProperty.PROP_PLAYER_LEVEL, 1);
this.setOrFetch(PlayerProperty.PROP_IS_SPRING_AUTO_USE, 1);
this.setOrFetch(PlayerProperty.PROP_SPRING_AUTO_USE_PERCENT, 50);
this.setOrFetch(PlayerProperty.PROP_IS_FLYABLE,
withQuesting ? 0 : 1);
this.setOrFetch(PlayerProperty.PROP_IS_TRANSFERABLE, 1);
this.setOrFetch(PlayerProperty.PROP_MAX_STAMINA,
withQuesting ? 10000 : 24000);
this.setOrFetch(PlayerProperty.PROP_PLAYER_RESIN, 160);
// The player's current stamina is always their max stamina.
this.setProperty(PlayerProperty.PROP_CUR_PERSIST_STAMINA,
this.getProperty(PlayerProperty.PROP_MAX_STAMINA));
}
/**
* Applies a property to the player if it doesn't exist in the database.
*
* @param property The property to apply.
* @param defaultValue The value to apply if the property doesn't exist.
*/
private void setOrFetch(PlayerProperty property, int defaultValue) {
var exists = this.properties.containsKey(property.getId());
if (exists) exists = this.getProperty(property) != 0;
this.setProperty(property, exists ? this.getProperty(property)
: defaultValue, false);
}
public int getPrimogems() {
return this.getProperty(PlayerProperty.PROP_PLAYER_HCOIN);
}
@@ -523,6 +634,7 @@ public class Player {
public boolean setHomeCoin(int coin) {
return this.setProperty(PlayerProperty.PROP_PLAYER_HOME_COIN, coin);
}
private int getExpRequired(int level) {
PlayerLevelData levelData = GameData.getPlayerLevelDataMap().get(level);
return levelData != null ? levelData.getExp() : 0;
@@ -564,14 +676,14 @@ public class Player {
int newWorldLevel =
(currentLevel >= 55) ? 8 :
(currentLevel >= 50) ? 7 :
(currentLevel >= 45) ? 6 :
(currentLevel >= 40) ? 5 :
(currentLevel >= 35) ? 4 :
(currentLevel >= 30) ? 3 :
(currentLevel >= 25) ? 2 :
(currentLevel >= 20) ? 1 :
0;
(currentLevel >= 50) ? 7 :
(currentLevel >= 45) ? 6 :
(currentLevel >= 40) ? 5 :
(currentLevel >= 35) ? 4 :
(currentLevel >= 30) ? 3 :
(currentLevel >= 25) ? 2 :
(currentLevel >= 20) ? 1 :
0;
if (newWorldLevel != currentWorldLevel) {
this.setWorldLevel(newWorldLevel);
@@ -595,12 +707,14 @@ public class Player {
}
public void onEnterRegion(SceneRegion region) {
getQuestManager().forEachActiveQuest(quest -> {
if (quest.getTriggers().containsKey("ENTER_REGION_"+ region.config_id)) {
this.getQuestManager().forEachActiveQuest(quest -> {
if (quest.getTriggerData() != null &&
quest.getTriggers().containsKey("ENTER_REGION_"+ region.config_id)) {
// If trigger hasn't been fired yet
if (!Boolean.TRUE.equals(quest.getTriggers().put("ENTER_REGION_"+ region.config_id, true))) {
//getSession().send(new PacketServerCondMeetQuestListUpdateNotify());
getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_TRIGGER_FIRE, quest.getTriggerData().get("ENTER_REGION_"+ region.config_id).getId(),0);
if (!Boolean.TRUE.equals(quest.getTriggers().put("ENTER_REGION_" + region.config_id, true))) {
this.getSession().send(new PacketServerCondMeetQuestListUpdateNotify());
this.getQuestManager().queueEvent(QuestContent.QUEST_CONTENT_TRIGGER_FIRE,
quest.getTriggerData().get("ENTER_REGION_" + region.config_id).getId(), 0);
}
}
});
@@ -608,12 +722,13 @@ public class Player {
}
public void onLeaveRegion(SceneRegion region) {
getQuestManager().forEachActiveQuest(quest -> {
if (quest.getTriggers().containsKey("LEAVE_REGION_"+ region.config_id)) {
this.getQuestManager().forEachActiveQuest(quest -> {
if (quest.getTriggers().containsKey("LEAVE_REGION_" + region.config_id)) {
// If trigger hasn't been fired yet
if (!Boolean.TRUE.equals(quest.getTriggers().put("LEAVE_REGION_"+ region.config_id, true))) {
getSession().send(new PacketServerCondMeetQuestListUpdateNotify());
getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_TRIGGER_FIRE, quest.getTriggerData().get("LEAVE_REGION_"+ region.config_id).getId(),0);
if (!Boolean.TRUE.equals(quest.getTriggers().put("LEAVE_REGION_" + region.config_id, true))) {
this.getSession().send(new PacketServerCondMeetQuestListUpdateNotify());
this.getQuestManager().queueEvent(QuestContent.QUEST_CONTENT_TRIGGER_FIRE,
quest.getTriggerData().get("LEAVE_REGION_" + region.config_id).getId(), 0);
}
}
});
@@ -626,6 +741,17 @@ public class Player {
return playerProfile;
}
/**
* Sets a player's property.
*
* @param prop The property.
* @param value The value as a boolean.
* @return True if the property was set.
*/
public boolean setProperty(PlayerProperty prop, boolean value) {
return setPropertyWithSanityCheck(prop, value ? 1 : 0, true);
}
public boolean setProperty(PlayerProperty prop, int value) {
return setPropertyWithSanityCheck(prop, value, true);
}
@@ -663,7 +789,7 @@ public class Player {
}
public void setPaused(boolean newPauseState) {
boolean oldPauseState = this.paused;
var oldPauseState = this.paused;
this.paused = newPauseState;
if (newPauseState && !oldPauseState) {
@@ -705,9 +831,7 @@ public class Player {
} else {
moonCardDuration += 30;
}
if (!moonCardGetTimes.contains(moonCardStartTime)) {
moonCardGetTimes.add(moonCardStartTime);
}
moonCardGetTimes.add(moonCardStartTime);
return true;
}
@@ -776,18 +900,6 @@ public class Player {
this.save();
}
public boolean getUnlimitedStamina() {
return stamina;
}
public void setUnlimitedStamina(boolean stamina) {
this.stamina = stamina;
}
public boolean inGodmode() {
return godmode;
}
public boolean hasSentLoginPackets() {
return hasSentLoginPackets;
}
@@ -819,6 +931,11 @@ public class Player {
addAvatar(avatar, true);
}
public void addAvatar(int avatarId) {
// I dont see why we cant do this lolz
addAvatar(new Avatar(avatarId), true);
}
public void addFlycloak(int flycloakId) {
this.getFlyCloakList().add(flycloakId);
this.sendPacket(new PacketAvatarGainFlycloakNotify(flycloakId));
@@ -829,6 +946,11 @@ public class Player {
this.sendPacket(new PacketAvatarGainCostumeNotify(costumeId));
}
public void addPersonalLine(int personalLineId) {
this.getPersonalLineList().add(personalLineId);
session.getPlayer().getQuestManager().queueEvent(QuestCond.QUEST_COND_PERSONAL_LINE_UNLOCK, personalLineId);
}
public void addNameCard(int nameCardId) {
this.getNameCardList().add(nameCardId);
this.sendPacket(new PacketUnlockNameCardNotify(nameCardId));
@@ -844,12 +966,12 @@ public class Player {
this.sendPacket(new PacketSetNameCardRsp(nameCardId));
}
/**
* Sends a message to this player.
*
* @param message The message to send.
*/
public void dropMessage(Object message) {
if (this.messageHandler != null) {
this.messageHandler.append(message.toString());
return;
}
this.getServer().getChatSystem().sendPrivateMessageFromServer(getUid(), message.toString());
}
@@ -865,7 +987,9 @@ public class Player {
// ---------------------MAIL------------------------
public List<Mail> getAllMail() { return this.getMailHandler().getMail(); }
public List<Mail> getAllMail() {
return this.getMailHandler().getMail();
}
public void sendMail(Mail message) {
this.getMailHandler().sendMail(message);
@@ -875,7 +999,9 @@ public class Player {
return this.getMailHandler().deleteMail(mailId);
}
public Mail getMail(int index) { return this.getMailHandler().getMailById(index); }
public Mail getMail(int index) {
return this.getMailHandler().getMailById(index);
}
public int getMailId(Mail message) {
return this.getMailHandler().getMailIndex(message);
@@ -909,13 +1035,13 @@ public class Player {
public OnlinePlayerInfo getOnlinePlayerInfo() {
OnlinePlayerInfo.Builder onlineInfo = OnlinePlayerInfo.newBuilder()
.setUid(this.getUid())
.setNickname(this.getNickname())
.setPlayerLevel(this.getLevel())
.setMpSettingType(this.getMpSetting())
.setNameCardId(this.getNameCardId())
.setSignature(this.getSignature())
.setProfilePicture(ProfilePicture.newBuilder().setAvatarId(this.getHeadImage()));
.setUid(this.getUid())
.setNickname(this.getNickname())
.setPlayerLevel(this.getLevel())
.setMpSettingType(this.getMpSetting())
.setNameCardId(this.getNameCardId())
.setSignature(this.getSignature())
.setProfilePicture(ProfilePicture.newBuilder().setAvatarId(this.getHeadImage()));
if (this.getWorld() != null) {
onlineInfo.setCurPlayerNumInWorld(getWorld().getPlayerCount());
@@ -941,12 +1067,12 @@ public class Player {
if (this.getShowAvatarList() != null) {
for (int avatarId : this.getShowAvatarList()) {
socialShowAvatarInfoList.add(
socialShowAvatarInfoList.size(),
SocialShowAvatarInfoOuterClass.SocialShowAvatarInfo.newBuilder()
.setAvatarId(avatarId)
.setLevel(getAvatars().getAvatarById(avatarId).getLevel())
.setCostumeId(getAvatars().getAvatarById(avatarId).getCostume())
.build()
socialShowAvatarInfoList.size(),
SocialShowAvatarInfoOuterClass.SocialShowAvatarInfo.newBuilder()
.setAvatarId(avatarId)
.setLevel(getAvatars().getAvatarById(avatarId).getLevel())
.setCostumeId(getAvatars().getAvatarById(avatarId).getCostume())
.build()
);
}
}
@@ -957,32 +1083,31 @@ public class Player {
if (showAvatarList != null) {
for (int avatarId : showAvatarList) {
socialShowAvatarInfoList.add(
socialShowAvatarInfoList.size(),
SocialShowAvatarInfoOuterClass.SocialShowAvatarInfo.newBuilder()
.setAvatarId(avatarId)
.setLevel(avatars.getAvatarById(avatarId).getLevel())
.setCostumeId(avatars.getAvatarById(avatarId).getCostume())
.build()
socialShowAvatarInfoList.size(),
SocialShowAvatarInfoOuterClass.SocialShowAvatarInfo.newBuilder()
.setAvatarId(avatarId)
.setLevel(avatars.getAvatarById(avatarId).getLevel())
.setCostumeId(avatars.getAvatarById(avatarId).getCostume())
.build()
);
}
}
}
SocialDetail.Builder social = SocialDetail.newBuilder()
.setUid(this.getUid())
.setProfilePicture(ProfilePicture.newBuilder().setAvatarId(this.getHeadImage()))
.setNickname(this.getNickname())
.setSignature(this.getSignature())
.setLevel(this.getLevel())
.setBirthday(this.getBirthday().getFilledProtoWhenNotEmpty())
.setWorldLevel(this.getWorldLevel())
.setNameCardId(this.getNameCardId())
.setIsShowAvatar(this.isShowAvatars())
.addAllShowAvatarInfoList(socialShowAvatarInfoList)
.addAllShowNameCardIdList(this.getShowNameCardInfoList())
.setFinishAchievementNum(this.getFinishedAchievementNum())
.setFriendEnterHomeOptionValue(this.getHome() == null ? 0 : this.getHome().getEnterHomeOption());
return social;
return SocialDetail.newBuilder()
.setUid(this.getUid())
.setProfilePicture(ProfilePicture.newBuilder().setAvatarId(this.getHeadImage()))
.setNickname(this.getNickname())
.setSignature(this.getSignature())
.setLevel(this.getLevel())
.setBirthday(this.getBirthday().getFilledProtoWhenNotEmpty())
.setWorldLevel(this.getWorldLevel())
.setNameCardId(this.getNameCardId())
.setIsShowAvatar(this.isShowAvatars())
.addAllShowAvatarInfoList(socialShowAvatarInfoList)
.addAllShowNameCardIdList(this.getShowNameCardInfoList())
.setFinishAchievementNum(this.getFinishedAchievementNum())
.setFriendEnterHomeOptionValue(this.getHome() == null ? 0 : this.getHome().getEnterHomeOption());
}
public int getFinishedAchievementNum() {
@@ -1025,17 +1150,17 @@ public class Player {
public PlayerWorldLocationInfoOuterClass.PlayerWorldLocationInfo getWorldPlayerLocationInfo() {
return PlayerWorldLocationInfoOuterClass.PlayerWorldLocationInfo.newBuilder()
.setSceneId(this.getSceneId())
.setPlayerLoc(this.getPlayerLocationInfo())
.build();
.setSceneId(this.getSceneId())
.setPlayerLoc(this.getPlayerLocationInfo())
.build();
}
public PlayerLocationInfo getPlayerLocationInfo() {
return PlayerLocationInfo.newBuilder()
.setUid(this.getUid())
.setPos(this.getPosition().toProto())
.setRot(this.getRotation().toProto())
.build();
.setUid(this.getUid())
.setPos(this.getPosition().toProto())
.setRot(this.getRotation().toProto())
.build();
}
public void loadBattlePassManager() {
@@ -1045,7 +1170,7 @@ public class Player {
}
public PlayerCollectionRecords getCollectionRecordStore() {
if (this.collectionRecordStore==null) {
if (this.collectionRecordStore == null) {
this.collectionRecordStore = new PlayerCollectionRecords();
}
return collectionRecordStore;
@@ -1121,6 +1246,8 @@ public class Player {
// Home resources
this.getHome().updateHourlyResources(this);
this.getQuestManager().onTick();
}
private synchronized void doDailyReset() {
@@ -1186,15 +1313,32 @@ public class Player {
}
// Load from db
this.achievements = Achievements.getByPlayer(this);
this.getAvatars().loadFromDatabase();
this.getInventory().loadFromDatabase();
this.loadBattlePassManager(); // Call before avatar postLoad to avoid null pointer
this.getAvatars().postLoad(); // Needs to be called after inventory is handled
var runner = Grasscutter.getThreadPool();
runner.submit(() -> this.achievements = Achievements.getByPlayer(this));
this.getFriendsList().loadFromDatabase();
this.getMailHandler().loadFromDatabase();
this.getQuestManager().loadFromDatabase();
runner.submit(this.getAvatars()::loadFromDatabase);
runner.submit(this.getInventory()::loadFromDatabase);
runner.submit(this.getFriendsList()::loadFromDatabase);
runner.submit(this.getMailHandler()::loadFromDatabase);
runner.submit(this.getQuestManager()::loadFromDatabase);
runner.submit(this::loadBattlePassManager);
// Wait for all tasks to finish.
Utils.waitFor(() ->
this.getAvatars().isLoaded() &&
this.getInventory().isLoaded());
this.getPlayerProgress().setPlayer(this); // Add reference to the player.
}
/**
* Invoked when the player selects their avatar.
*/
public void onPlayerBorn() {
Grasscutter.getThreadPool().submit(
this.getQuestManager()::onPlayerBorn);
}
public void onLogin() {
@@ -1237,6 +1381,7 @@ public class Player {
session.send(new PacketFinishedParentQuestNotify(this));
session.send(new PacketBattlePassAllDataNotify(this));
session.send(new PacketQuestListNotify(this));
session.send(new PacketQuestGlobalVarNotify(this));
session.send(new PacketCodexDataFullNotify(this));
session.send(new PacketAllWidgetDataNotify(this));
@@ -1262,7 +1407,7 @@ public class Player {
home = GameHome.getByUid(getUid());
home.onOwnerLogin(this);
// Activity
activityManager = new ActivityManager(this);
this.activityManager = new ActivityManager(this);
session.send(new PacketPlayerEnterSceneNotify(this)); // Enter game world
session.send(new PacketPlayerLevelRewardUpdateNotify(rewardedLevels));
@@ -1274,7 +1419,8 @@ public class Player {
session.setState(SessionState.ACTIVE);
// Call join event.
PlayerJoinEvent event = new PlayerJoinEvent(this); event.call();
PlayerJoinEvent event = new PlayerJoinEvent(this);
event.call();
if (event.isCanceled()) { // If event is not cancelled, continue.
session.close();
return;
@@ -1313,11 +1459,12 @@ public class Player {
this.getFriendsList().save();
// Call quit event.
PlayerQuitEvent event = new PlayerQuitEvent(this); event.call();
}catch (Throwable e) {
PlayerQuitEvent event = new PlayerQuitEvent(this);
event.call();
} catch (Throwable e) {
e.printStackTrace();
Grasscutter.getLogger().warn("Player (UID {}) save failure", getUid());
}finally {
} finally {
removeFromServer();
}
}
@@ -1332,23 +1479,15 @@ public class Player {
public int getLegendaryKey() {
return this.getProperty(PlayerProperty.PROP_PLAYER_LEGENDARY_KEY);
}
public synchronized void addLegendaryKey(int count) {
this.setProperty(PlayerProperty.PROP_PLAYER_LEGENDARY_KEY, getLegendaryKey() + count);
}
public synchronized void useLegendaryKey(int count) {
this.setProperty(PlayerProperty.PROP_PLAYER_LEGENDARY_KEY, getLegendaryKey() - count);
}
public enum SceneLoadState {
NONE(0), LOADING(1), INIT(2), LOADED(3);
@Getter private final int value;
SceneLoadState(int value) {
this.value = value;
}
}
public int getPropertyMin(PlayerProperty prop) {
if (prop.isDynamicRange()) {
return 0;
@@ -1376,14 +1515,21 @@ public class Player {
int currentValue = this.properties.get(prop.getId());
this.properties.put(prop.getId(), value);
if (sendPacket) {
// Update player with packet
// Send property change reasons if needed.
switch (prop) {
case PROP_PLAYER_EXP -> this.sendPacket(new PacketPlayerPropChangeReasonNotify(this, prop, currentValue, value,
PropChangeReason.PROP_CHANGE_REASON_PLAYER_ADD_EXP));
case PROP_PLAYER_LEVEL -> this.sendPacket(new PacketPlayerPropChangeReasonNotify(this, prop, currentValue, value,
PropChangeReason.PROP_CHANGE_REASON_LEVELUP));
// TODO: Handle world level changing.
// case PROP_PLAYER_WORLD_LEVEL -> this.sendPacket(new PacketPlayerPropChangeReasonNotify(this, prop, currentValue, value,
// PropChangeReason.PROP_CHANGE_REASON_MANUAL_ADJUST_WORLD_LEVEL));
}
// Update player with packet.
this.sendPacket(new PacketPlayerPropNotify(this, prop));
this.sendPacket(new PacketPlayerPropChangeNotify(this, prop, value - currentValue));
// Make the Adventure EXP pop-up show on screen.
if (prop == PlayerProperty.PROP_PLAYER_EXP) {
this.sendPacket(new PacketPlayerPropChangeReasonNotify(this, prop, currentValue, value, PropChangeReason.PROP_CHANGE_REASON_PLAYER_ADD_EXP));
}
}
return true;
} else {
@@ -1391,4 +1537,15 @@ public class Player {
}
}
public enum SceneLoadState {
NONE(0), LOADING(1), INIT(2), LOADED(3);
@Getter
private final int value;
SceneLoadState(int value) {
this.value = value;
}
}
}

View File

@@ -8,63 +8,57 @@ public class PlayerBirthday {
private int day;
private int month;
public PlayerBirthday(){
public PlayerBirthday() {
this.day = 0;
this.month = 0;
}
public PlayerBirthday(int day, int month){
public PlayerBirthday(int day, int month) {
this.day = day;
this.month = month;
}
public PlayerBirthday set(PlayerBirthday birth){
public PlayerBirthday set(PlayerBirthday birth) {
this.day = birth.day;
this.month = birth.month;
return this;
}
public PlayerBirthday set(int d, int m){
public PlayerBirthday set(int d, int m) {
this.day = d;
this.month = m;
return this;
}
public PlayerBirthday setDay(int value){
public int getDay() {
return this.day;
}
public PlayerBirthday setDay(int value) {
this.day = value;
return this;
}
public PlayerBirthday setMonth(int value){
public int getMonth() {
return this.month;
}
public PlayerBirthday setMonth(int value) {
this.month = value;
return this;
}
public int getDay(){
return this.day;
public Birthday toProto() {
return Birthday.newBuilder().setDay(this.getDay()).setMonth(this.getMonth()).build();
}
public int getMonth(){
return this.month;
}
public Birthday toProto(){
return Birthday.newBuilder()
.setDay(this.getDay())
.setMonth(this.getMonth())
.build();
}
public Birthday.Builder getFilledProtoWhenNotEmpty(){
if(this.getDay() > 0)
{
return Birthday.newBuilder()
.setDay(this.getDay())
.setMonth(this.getMonth());
public Birthday.Builder getFilledProtoWhenNotEmpty() {
if (this.getDay() > 0) {
return Birthday.newBuilder().setDay(this.getDay()).setMonth(this.getMonth());
}
return Birthday.newBuilder();
}
}
}

View File

@@ -1,11 +1,5 @@
package emu.grasscutter.game.player;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.binout.AbilityModifier.AbilityModifierAction;
import emu.grasscutter.data.excels.BuffData;
@@ -14,26 +8,29 @@ import emu.grasscutter.game.props.FightProperty;
import emu.grasscutter.net.proto.ServerBuffChangeNotifyOuterClass.ServerBuffChangeNotify.ServerBuffChangeType;
import emu.grasscutter.net.proto.ServerBuffOuterClass.ServerBuff;
import emu.grasscutter.server.packet.send.PacketServerBuffChangeNotify;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.Getter;
public class PlayerBuffManager extends BasePlayerManager {
private int nextBuffUid;
public final class PlayerBuffManager extends BasePlayerManager {
private final List<PlayerBuff> pendingBuffs;
private final Int2ObjectMap<PlayerBuff> buffs; // Server buffs
private int nextBuffUid;
public PlayerBuffManager(Player player) {
super(player);
this.buffs = new Int2ObjectOpenHashMap<>();
this.pendingBuffs = new ArrayList<>();
}
/**
* Gets a new uid for a server buff
*
* @return New integer buff uid
*/
private int getNextBuffUid() {
@@ -42,6 +39,7 @@ public class PlayerBuffManager extends BasePlayerManager {
/**
* Returns true if the player has a buff with this group id
*
* @param groupId Buff group id
* @return True if a buff with this group id exists
*/
@@ -49,14 +47,15 @@ public class PlayerBuffManager extends BasePlayerManager {
return this.buffs.containsKey(groupId);
}
/**
* Clears all player buffs
*/
/** Clears all player buffs */
public synchronized void clearBuffs() {
// Remove from player
getPlayer().sendPacket(
new PacketServerBuffChangeNotify(getPlayer(), ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_DEL_SERVER_BUFF, this.buffs.values())
);
getPlayer()
.sendPacket(
new PacketServerBuffChangeNotify(
getPlayer(),
ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_DEL_SERVER_BUFF,
this.buffs.values()));
// Clear
this.buffs.clear();
@@ -64,6 +63,7 @@ public class PlayerBuffManager extends BasePlayerManager {
/**
* Adds a server buff to the player.
*
* @param buffId Server buff id
* @return True if a buff was added
*/
@@ -73,6 +73,7 @@ public class PlayerBuffManager extends BasePlayerManager {
/**
* Adds a server buff to the player.
*
* @param buffId Server buff id
* @param duration Duration of the buff in seconds. Set to 0 for an infinite buff.
* @return True if a buff was added
@@ -83,6 +84,7 @@ public class PlayerBuffManager extends BasePlayerManager {
/**
* Adds a server buff to the player.
*
* @param buffId Server buff id
* @param duration Duration of the buff in seconds. Set to 0 for an infinite buff.
* @param target Target avatar
@@ -90,41 +92,40 @@ public class PlayerBuffManager extends BasePlayerManager {
*/
public synchronized boolean addBuff(int buffId, float duration, Avatar target) {
// Get buff excel data
BuffData buffData = GameData.getBuffDataMap().get(buffId);
var buffData = GameData.getBuffDataMap().get(buffId);
if (buffData == null) return false;
boolean success = false;
// Perform onAdded actions
success |= Optional.ofNullable(GameData.getAbilityData(buffData.getAbilityName()))
.map(data -> data.modifiers.get(buffData.getModifierName()))
.map(modifier -> modifier.onAdded)
.map(onAdded -> {
var success =
Optional.ofNullable(GameData.getAbilityData(buffData.getAbilityName()))
.map(data -> data.modifiers.get(buffData.getModifierName()))
.map(modifier -> modifier.onAdded)
.map(
onAdded -> {
var shouldHeal = false;
for (var ability : onAdded) {
if (Objects.requireNonNull(ability.type) == AbilityModifierAction.Type.HealHP) {
if (target == null) continue;
var s = false;
for (var a: onAdded) {
Grasscutter.getLogger().debug("onAdded exists");
if (Objects.requireNonNull(a.type) == AbilityModifierAction.Type.HealHP) {
Grasscutter.getLogger().debug("Attempting heal");
if (target == null) continue;
var maxHp = target.getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);
var amount = a.amount.get() + a.amountByTargetMaxHPRatio.get() * maxHp;
target.getAsEntity().heal(amount);
s = true;
Grasscutter.getLogger().debug("Healed {}", amount);
}
}
return s;
})
.orElse(false);
Grasscutter.getLogger().debug("Oh no");
var maxHp = target.getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);
var amount =
ability.amount.get() + ability.amountByTargetMaxHPRatio.get() * maxHp;
target.getAsEntity().heal(amount);
shouldHeal = true;
}
}
return shouldHeal;
})
.orElse(false);
// Set duration
if (duration < 0f) {
duration = buffData.getTime();
}
// Dont add buff if duration is equal or less than 0
// Don't add buff if duration is equal or less than 0
if (duration <= 0) {
return success;
}
@@ -137,13 +138,17 @@ public class PlayerBuffManager extends BasePlayerManager {
this.buffs.put(buff.getGroupId(), buff);
// Packet
getPlayer().sendPacket(new PacketServerBuffChangeNotify(getPlayer(), ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_ADD_SERVER_BUFF, buff));
getPlayer()
.sendPacket(
new PacketServerBuffChangeNotify(
getPlayer(), ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_ADD_SERVER_BUFF, buff));
return true;
}
/**
* Removes a buff by its group id
*
* @param buffGroupId Server buff group id
* @return True if a buff was remove
*/
@@ -151,9 +156,10 @@ public class PlayerBuffManager extends BasePlayerManager {
PlayerBuff buff = this.buffs.remove(buffGroupId);
if (buff != null) {
getPlayer().sendPacket(
new PacketServerBuffChangeNotify(getPlayer(), ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_DEL_SERVER_BUFF, buff)
);
getPlayer()
.sendPacket(
new PacketServerBuffChangeNotify(
getPlayer(), ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_DEL_SERVER_BUFF, buff));
return true;
}
@@ -167,18 +173,23 @@ public class PlayerBuffManager extends BasePlayerManager {
long currentTime = System.currentTimeMillis();
// Add to pending buffs to remove if buff has expired
this.buffs.values().removeIf(buff -> {
if (currentTime <= buff.getEndTime())
return false;
this.pendingBuffs.add(buff);
return true;
});
this.buffs
.values()
.removeIf(
buff -> {
if (currentTime <= buff.getEndTime()) return false;
this.pendingBuffs.add(buff);
return true;
});
if (this.pendingBuffs.size() > 0) {
// Send packet
getPlayer().sendPacket(
new PacketServerBuffChangeNotify(getPlayer(), ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_DEL_SERVER_BUFF, this.pendingBuffs)
);
getPlayer()
.sendPacket(
new PacketServerBuffChangeNotify(
getPlayer(),
ServerBuffChangeType.SERVER_BUFF_CHANGE_TYPE_DEL_SERVER_BUFF,
this.pendingBuffs));
this.pendingBuffs.clear();
}
}
@@ -201,11 +212,11 @@ public class PlayerBuffManager extends BasePlayerManager {
public ServerBuff toProto() {
return ServerBuff.newBuilder()
.setServerBuffUid(this.getUid())
.setServerBuffId(this.getBuffData().getId())
.setServerBuffType(this.getBuffData().getServerBuffType().getValue())
.setInstancedModifierId(1)
.build();
.setServerBuffUid(this.getUid())
.setServerBuffId(this.getBuffData().getId())
.setServerBuffType(this.getBuffData().getServerBuffType().getValue())
.setInstancedModifierId(1)
.build();
}
}
}

View File

@@ -3,21 +3,20 @@ package emu.grasscutter.game.player;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Transient;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.excels.CodexAnimalData;
import emu.grasscutter.data.excels.codex.CodexAnimalData;
import emu.grasscutter.game.entity.EntityMonster;
import emu.grasscutter.game.entity.GameEntity;
import emu.grasscutter.game.inventory.GameItem;
import emu.grasscutter.server.packet.send.PacketCodexDataUpdateNotify;
import java.util.*;
import lombok.Getter;
import lombok.val;
import java.util.*;
@Entity
public class PlayerCodex {
@Transient private Player player;
//itemId is not codexId!
// itemId is not codexId!
@Getter private Set<Integer> unlockedWeapon;
@Getter private Map<Integer, Integer> unlockedAnimal;
@Getter private Set<Integer> unlockedMaterial;
@@ -54,32 +53,38 @@ public class PlayerCodex {
switch (itemData.getItemType()) {
case ITEM_WEAPON -> {
Optional.ofNullable(GameData.getCodexWeaponDataIdMap().get(itemId))
.ifPresent(codexData -> {
if (this.getUnlockedWeapon().add(itemId)) {
this.player.save();
this.player.sendPacket(new PacketCodexDataUpdateNotify(2, codexData.getId()));
}
});
.ifPresent(
codexData -> {
if (this.getUnlockedWeapon().add(itemId)) {
this.player.save();
this.player.sendPacket(new PacketCodexDataUpdateNotify(2, codexData.getId()));
}
});
}
case ITEM_MATERIAL -> {
switch (itemData.getMaterialType()) {
// Is this check even needed?
case MATERIAL_FOOD, MATERIAL_WIDGET, MATERIAL_EXCHANGE, MATERIAL_AVATAR_MATERIAL, MATERIAL_NOTICE_ADD_HP -> {
// Is this check even needed?
case MATERIAL_FOOD,
MATERIAL_WIDGET,
MATERIAL_EXCHANGE,
MATERIAL_AVATAR_MATERIAL,
MATERIAL_NOTICE_ADD_HP -> {
Optional.ofNullable(GameData.getCodexMaterialDataIdMap().get(itemId))
.ifPresent(codexData -> {
if (this.getUnlockedMaterial().add(itemId)) {
this.player.save();
this.player.sendPacket(new PacketCodexDataUpdateNotify(4, codexData.getId()));
}
});
.ifPresent(
codexData -> {
if (this.getUnlockedMaterial().add(itemId)) {
this.player.save();
this.player.sendPacket(
new PacketCodexDataUpdateNotify(4, codexData.getId()));
}
});
}
default -> {}
}
}
case ITEM_RELIQUARY -> {
val reliquaryId = (itemId/10) * 10; // Normalize to 0-substat form
if (this.getUnlockedReliquary().add(reliquaryId))
checkUnlockedSuits(reliquaryId);
val reliquaryId = (itemId / 10) * 10; // Normalize to 0-substat form
if (this.getUnlockedReliquary().add(reliquaryId)) checkUnlockedSuits(reliquaryId);
}
default -> {}
}
@@ -103,28 +108,29 @@ public class PlayerCodex {
public void checkUnlockedSuits(int reliquaryId) {
GameData.getCodexReliquaryArrayList().stream()
.filter(x -> !this.getUnlockedReliquarySuitCodex().contains(x.getId()))
.filter(x -> x.containsId(reliquaryId))
.filter(x -> this.getUnlockedReliquary().containsAll(x.getIds()))
.forEach(x -> {
int id = x.getId();
this.getUnlockedReliquarySuitCodex().add(id);
this.player.save();
this.player.sendPacket(new PacketCodexDataUpdateNotify(8, id));
});
.filter(x -> !this.getUnlockedReliquarySuitCodex().contains(x.getId()))
.filter(x -> x.containsId(reliquaryId))
.filter(x -> this.getUnlockedReliquary().containsAll(x.getIds()))
.forEach(
x -> {
int id = x.getId();
this.getUnlockedReliquarySuitCodex().add(id);
this.player.save();
this.player.sendPacket(new PacketCodexDataUpdateNotify(8, id));
});
}
@Deprecated // Maybe remove this if we ever stop caring about older dbs
@Deprecated // Maybe remove this if we ever stop caring about older dbs
private void fixReliquaries() {
// Migrate older database entries which were using non-canonical forms of itemIds
val newReliquaries = new HashSet<Integer>();
this.unlockedReliquary.forEach(i -> newReliquaries.add((i/10)*10));
this.unlockedReliquary.forEach(i -> newReliquaries.add((i / 10) * 10));
this.unlockedReliquary = newReliquaries;
GameData.getCodexReliquaryArrayList().stream()
.filter(x -> !this.getUnlockedReliquarySuitCodex().contains(x.getId()))
.filter(x -> this.getUnlockedReliquary().containsAll(x.getIds()))
.forEach(x -> this.getUnlockedReliquarySuitCodex().add(x.getId()));
.filter(x -> !this.getUnlockedReliquarySuitCodex().contains(x.getId()))
.filter(x -> this.getUnlockedReliquary().containsAll(x.getIds()))
.forEach(x -> this.getUnlockedReliquarySuitCodex().add(x.getId()));
this.player.save();
}
}

View File

@@ -1,10 +1,9 @@
package emu.grasscutter.game.player;
import dev.morphia.annotations.Entity;
import java.util.HashMap;
import java.util.Map;
import dev.morphia.annotations.Entity;
@Entity(useDiscriminator = false)
public class PlayerCollectionRecords {
private Map<Integer, CollectionRecord> records;
@@ -19,7 +18,9 @@ public class PlayerCollectionRecords {
public void addRecord(int configId, long expiredMillisecond) {
Map<Integer, CollectionRecord> records;
synchronized (records = getRecords()) {
records.put(configId, new CollectionRecord(configId, expiredMillisecond + System.currentTimeMillis()));
records.put(
configId,
new CollectionRecord(configId, expiredMillisecond + System.currentTimeMillis()));
}
}

View File

@@ -0,0 +1,100 @@
package emu.grasscutter.game.player;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Transient;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.quest.enums.QuestContent;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import java.util.Map;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.val;
/** Tracks progress the player made in the world, like obtained items, seen characters and more */
@Entity
public class PlayerProgress {
@Getter @Setter @Transient private Player player;
@Getter private Map<Integer, ItemEntry> itemHistory;
/*
* A list of dungeon IDs which have been completed.
* This only applies to one-time dungeons.
*/
@Getter private IntArrayList completedDungeons;
// keep track of EXEC_ADD_QUEST_PROGRESS count, will be used in CONTENT_ADD_QUEST_PROGRESS
// not sure where to put this, this should be saved to DB but not to individual quest, since
// it will be hard to loop and compare
private Map<Integer, Integer> questProgressCountMap;
public PlayerProgress() {
this.questProgressCountMap = new Int2IntOpenHashMap();
this.completedDungeons = new IntArrayList();
this.itemHistory = new Int2ObjectOpenHashMap<>();
}
/**
* Marks a dungeon as completed. Triggers the quest event.
*
* @param dungeonId The dungeon which was completed.
*/
public void markDungeonAsComplete(int dungeonId) {
if (this.getCompletedDungeons().contains(dungeonId)) return;
// Mark the dungeon as completed.
this.getCompletedDungeons().add(dungeonId);
// Trigger the completion event.
if (this.getPlayer() != null) {
this.getPlayer()
.getQuestManager()
.queueEvent(QuestContent.QUEST_CONTENT_FINISH_DUNGEON, dungeonId);
} else {
Grasscutter.getLogger()
.warn("Unable to execute 'QUEST_CONTENT_FINISH_DUNGEON'. The player is null.");
}
Grasscutter.getLogger()
.debug("Dungeon {} has been marked complete for {}.", dungeonId, this.getPlayer().getUid());
}
public boolean hasPlayerObtainedItemHistorically(int itemId) {
return itemHistory.containsKey(itemId);
}
public int addToItemHistory(int itemId, int count) {
val itemEntry = itemHistory.computeIfAbsent(itemId, (key) -> new ItemEntry(itemId));
return itemEntry.addToObtainedCount(count);
}
public int getCurrentProgress(int progressId) {
return questProgressCountMap.getOrDefault(progressId, -1);
}
public int addToCurrentProgress(int progressId, int count) {
return questProgressCountMap.merge(progressId, count, Integer::sum);
}
public int resetCurrentProgress(int progressId) {
return questProgressCountMap.merge(progressId, 0, Integer::min);
}
@Entity
@NoArgsConstructor
public static class ItemEntry {
@Getter private int itemId;
@Getter @Setter private int obtainedCount;
ItemEntry(int itemId) {
this.itemId = itemId;
}
int addToObtainedCount(int amount) {
this.obtainedCount += amount;
return this.obtainedCount;
}
}
}

View File

@@ -1,36 +1,79 @@
package emu.grasscutter.game.player;
import dev.morphia.annotations.Entity;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import static emu.grasscutter.scripts.constants.EventType.EVENT_UNLOCK_TRANS_POINT;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.binout.ScenePointEntry;
import emu.grasscutter.data.excels.OpenStateData;
import emu.grasscutter.data.excels.OpenStateData.OpenStateCondType;
import emu.grasscutter.game.inventory.GameItem;
import emu.grasscutter.game.props.ActionReason;
import emu.grasscutter.game.props.PlayerProperty;
import emu.grasscutter.game.quest.enums.QuestState;
import emu.grasscutter.game.quest.enums.QuestTrigger;
import emu.grasscutter.net.proto.PropChangeReasonOuterClass.PropChangeReason;
import emu.grasscutter.game.quest.enums.*;
import emu.grasscutter.net.proto.RetcodeOuterClass.Retcode;
import emu.grasscutter.server.packet.send.PacketOpenStateChangeNotify;
import emu.grasscutter.server.packet.send.PacketOpenStateUpdateNotify;
import emu.grasscutter.server.packet.send.PacketSceneAreaUnlockNotify;
import emu.grasscutter.server.packet.send.PacketScenePointUnlockNotify;
import emu.grasscutter.server.packet.send.PacketSetOpenStateRsp;
import emu.grasscutter.server.packet.send.PacketUnlockTransPointRsp;
import java.util.*;
import emu.grasscutter.scripts.data.ScriptArgs;
import emu.grasscutter.server.packet.send.*;
import java.util.Set;
import java.util.stream.Collectors;
// @Entity
public class PlayerProgressManager extends BasePlayerDataManager {
public final class PlayerProgressManager extends BasePlayerDataManager {
/******************************************************************************************************************
******************************************************************************************************************
* OPEN STATES
******************************************************************************************************************
*****************************************************************************************************************/
// Set of open states that are never unlocked, whether they fulfill the conditions or not.
public static final Set<Integer> BLACKLIST_OPEN_STATES =
Set.of(
48 // blacklist OPEN_STATE_LIMIT_REGION_GLOBAL to make Meledy happy. =D Remove this as
// soon as quest unlocks are fully implemented.
);
public static final Set<Integer> IGNORED_OPEN_STATES =
Set.of(
1404, // OPEN_STATE_MENGDE_INFUSEDCRYSTAL, causes quest 'Mine Craft' to be given to the
// player at the start of the game.
// This should be removed when city reputation is implemented.
57 // OPEN_STATE_PERSONAL_LINE, causes the prompt for showing character hangout quests to
// be permanently shown.
// This should be removed when character story quests are implemented.
);
// Set of open states that are set per default for all accounts. Can be overwritten by an entry in
// `map`.
public static final Set<Integer> DEFAULT_OPEN_STATES =
GameData.getOpenStateList().stream()
.filter(
s ->
s.isDefaultState() && !s.isAllowClientOpen() // Actual default-opened states.
|| ((s.getCond().size() == 1)
&& (s.getCond().get(0).getCondType()
== OpenStateCondType.OPEN_STATE_COND_PLAYER_LEVEL)
&& (s.getCond().get(0).getParam() == 1))
// All states whose unlock we don't handle correctly yet.
|| (s.getCond().stream()
.anyMatch(
c ->
c.getCondType() == OpenStateCondType.OPEN_STATE_OFFERING_LEVEL
|| c.getCondType()
== OpenStateCondType.OPEN_STATE_CITY_REPUTATION_LEVEL))
// Always unlock OPEN_STATE_PAIMON, otherwise the player will not have a
// working chat.
|| s.getId() == 1)
.map(OpenStateData::getId)
.filter(s -> !BLACKLIST_OPEN_STATES.contains(s)) // Filter out states in the blacklist.
.filter(
s ->
!IGNORED_OPEN_STATES.contains(s)) // Filter out states in the default ignore list.
.collect(Collectors.toSet());
public PlayerProgressManager(Player player) {
super(player);
}
/**********
Handler for player login.
**********/
* Handler for player login.
**********/
public void onPlayerLogin() {
// Try unlocking open states on player login. This handles accounts where unlock conditions were
// already met before certain open state unlocks were implemented.
@@ -42,40 +85,18 @@ public class PlayerProgressManager extends BasePlayerDataManager {
// Add statue quests if necessary.
this.addStatueQuestsOnLogin();
// Auto-unlock the first statue and map area, until we figure out how to make
// that particular statue interactable.
this.player.getUnlockedScenePoints(3).add(7);
this.player.getUnlockedSceneAreas(3).add(1);
if (!GAME_OPTIONS.questing.enabled) {
// Auto-unlock the first statue and map area.
this.player.getUnlockedScenePoints(3).add(7);
this.player.getUnlockedSceneAreas(3).add(1);
// Allow the player to visit all areas.
this.setOpenState(47, 1, true);
}
}
/******************************************************************************************************************
******************************************************************************************************************
* OPEN STATES
******************************************************************************************************************
*****************************************************************************************************************/
// Set of open states that are never unlocked, whether they fulfill the conditions or not.
public static final Set<Integer> BLACKLIST_OPEN_STATES = Set.of(
48 // blacklist OPEN_STATE_LIMIT_REGION_GLOBAL to make Meledy happy. =D Remove this as soon as quest unlocks are fully implemented.
);
// Set of open states that are set per default for all accounts. Can be overwritten by an entry in `map`.
public static final Set<Integer> DEFAULT_OPEN_STATES = GameData.getOpenStateList().stream()
.filter(s ->
s.isDefaultState() // Actual default-opened states.
// All states whose unlock we don't handle correctly yet.
|| (s.getCond().stream().filter(c -> c.getCondType() == OpenStateCondType.OPEN_STATE_COND_PLAYER_LEVEL).count() == 0)
// Always unlock OPEN_STATE_PAIMON, otherwise the player will not have a working chat.
|| s.getId() == 1
)
.filter(s -> !BLACKLIST_OPEN_STATES.contains(s.getId())) // Filter out states in the blacklist.
.map(s -> s.getId())
.collect(Collectors.toSet());
/**********
Direct getters and setters for open states.
**********/
* Direct getters and setters for open states.
**********/
public int getOpenState(int openState) {
return this.player.getOpenStates().getOrDefault(openState, 0);
}
@@ -86,38 +107,51 @@ public class PlayerProgressManager extends BasePlayerDataManager {
if (value != previousValue) {
this.player.getOpenStates().put(openState, value);
this.player
.getQuestManager()
.queueEvent(QuestCond.QUEST_COND_OPEN_STATE_EQUAL, openState, value);
if (sendNotify) {
player.getSession().send(new PacketOpenStateChangeNotify(openState, value));
}
}
}
private void setOpenState(int openState, int value) {
this.setOpenState(openState, value, true);
}
/**********
Condition checking for setting open states.
**********/
* Condition checking for setting open states.
**********/
private boolean areConditionsMet(OpenStateData openState) {
// Check all conditions and test if at least one of them is violated.
for (var condition : openState.getCond()) {
// For level conditions, check if the player has reached the necessary level.
if (condition.getCondType() == OpenStateCondType.OPEN_STATE_COND_PLAYER_LEVEL) {
if (this.player.getLevel() < condition.getParam()) {
return false;
switch (condition.getCondType()) {
// For level conditions, check if the player has reached the necessary level.
case OPEN_STATE_COND_PLAYER_LEVEL -> {
if (this.player.getLevel() < condition.getParam()) {
return false;
}
}
}
else if (condition.getCondType() == OpenStateCondType.OPEN_STATE_COND_QUEST) {
// ToDo: Implement.
}
else if (condition.getCondType() == OpenStateCondType.OPEN_STATE_COND_PARENT_QUEST) {
// ToDo: Implement.
}
else if (condition.getCondType() == OpenStateCondType.OPEN_STATE_OFFERING_LEVEL) {
// ToDo: Implement.
}
else if (condition.getCondType() == OpenStateCondType.OPEN_STATE_CITY_REPUTATION_LEVEL) {
// ToDo: Implement.
case OPEN_STATE_COND_QUEST -> {
// check sub quest id for quest finished met requirements
var quest = this.player.getQuestManager().getQuestById(condition.getParam());
if (quest == null || quest.getState() != QuestState.QUEST_STATE_FINISHED) {
return false;
}
}
case OPEN_STATE_COND_PARENT_QUEST -> {
// check main quest id for quest finished met requirements
// TODO not sure if its having or finished quest
var mainQuest = this.player.getQuestManager().getMainQuestById(condition.getParam());
if (mainQuest == null
|| mainQuest.getState() != ParentQuestState.PARENT_QUEST_STATE_FINISHED) {
return false;
}
}
// ToDo: Implement.
case OPEN_STATE_OFFERING_LEVEL, OPEN_STATE_CITY_REPUTATION_LEVEL -> {}
}
}
@@ -126,8 +160,8 @@ public class PlayerProgressManager extends BasePlayerDataManager {
}
/**********
Setting open states from the client (via `SetOpenStateReq`).
**********/
* Setting open states from the client (via `SetOpenStateReq`).
**********/
public void setOpenStateFromClient(int openState, int value) {
// Get the data for this open state.
OpenStateData data = GameData.getOpenStateDataMap().get(openState);
@@ -148,12 +182,20 @@ public class PlayerProgressManager extends BasePlayerDataManager {
this.player.sendPacket(new PacketSetOpenStateRsp(openState, value));
}
/** This force sets an open state, ignoring all conditions and permissions */
public void forceSetOpenState(int openState, int value) {
this.setOpenState(openState, value);
}
/**********
Triggered unlocking of open states (unlock states whose conditions have been met.)
**********/
* Triggered unlocking of open states (unlock states whose conditions have been met.)
**********/
public void tryUnlockOpenStates(boolean sendNotify) {
// Get list of open states that are not yet unlocked.
var lockedStates = GameData.getOpenStateList().stream().filter(s -> this.player.getOpenStates().getOrDefault(s, 0) == 0).toList();
var lockedStates =
GameData.getOpenStateList().stream()
.filter(s -> this.player.getOpenStates().getOrDefault(s, 0) == 0)
.toList();
// Try unlocking all of them.
for (var state : lockedStates) {
@@ -161,11 +203,15 @@ public class PlayerProgressManager extends BasePlayerDataManager {
// * it can not be a state that is unlocked by the client,
// * it has to meet all its unlock conditions, and
// * it can not be in the blacklist.
if (!state.isAllowClientOpen() && this.areConditionsMet(state) && !BLACKLIST_OPEN_STATES.contains(state.getId())) {
if (!state.isAllowClientOpen()
&& this.areConditionsMet(state)
&& !BLACKLIST_OPEN_STATES.contains(state.getId())
&& !IGNORED_OPEN_STATES.contains(state.getId())) {
this.setOpenState(state.getId(), 1, sendNotify);
}
}
}
public void tryUnlockOpenStates() {
this.tryUnlockOpenStates(true);
}
@@ -211,10 +257,18 @@ public class PlayerProgressManager extends BasePlayerDataManager {
this.player.getInventory().addItem(201, 5, ActionReason.UnlockPointReward);
this.player.getInventory().addItem(102, isStatue ? 50 : 10, ActionReason.UnlockPointReward);
// this.player.sendPacket(new PacketPlayerPropChangeReasonNotify(this.player.getProperty(PlayerProperty.PROP_PLAYER_EXP), PlayerProperty.PROP_PLAYER_EXP, PropChangeReason.PROP_CHANGE_REASON_PLAYER_ADD_EXP));
// this.player.sendPacket(new
// PacketPlayerPropChangeReasonNotify(this.player.getProperty(PlayerProperty.PROP_PLAYER_EXP),
// PlayerProperty.PROP_PLAYER_EXP, PropChangeReason.PROP_CHANGE_REASON_PLAYER_ADD_EXP));
// Fire quest trigger for trans point unlock.
this.player.getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_UNLOCK_TRANS_POINT, sceneId, pointId);
this.player
.getQuestManager()
.queueEvent(QuestContent.QUEST_CONTENT_UNLOCK_TRANS_POINT, sceneId, pointId);
this.player
.getScene()
.getScriptManager()
.callEvent(new ScriptArgs(0, EVENT_UNLOCK_TRANS_POINT, sceneId, pointId));
// Send packet.
this.player.sendPacket(new PacketScenePointUnlockNotify(sceneId, pointId));
@@ -228,4 +282,35 @@ public class PlayerProgressManager extends BasePlayerDataManager {
// Send packet.
this.player.sendPacket(new PacketSceneAreaUnlockNotify(sceneId, areaId));
}
/** Give replace costume to player (Amber, Jean, Mona, Rosaria) */
public void addReplaceCostumes() {
var currentPlayerCostumes = player.getCostumeList();
GameData.getAvatarReplaceCostumeDataMap()
.keySet()
.forEach(
costumeId -> {
if (GameData.getAvatarCostumeDataMap().get(costumeId) == null
|| currentPlayerCostumes.contains(costumeId)) {
return;
}
this.player.addCostume(costumeId);
});
}
/** Quest progress */
public void addQuestProgress(int id, int count) {
var newCount = player.getPlayerProgress().addToCurrentProgress(id, count);
player.save();
player
.getQuestManager()
.queueEvent(QuestContent.QUEST_CONTENT_ADD_QUEST_PROGRESS, id, newCount);
}
/** Item history */
public void addItemObtainedHistory(int id, int count) {
var newCount = player.getPlayerProgress().addToItemHistory(id, count);
player.save();
player.getQuestManager().queueEvent(QuestCond.QUEST_COND_HISTORY_GOT_ANY_ITEM, id, newCount);
}
}

View File

@@ -1,16 +1,15 @@
package emu.grasscutter.game.player;
import static emu.grasscutter.config.Configuration.*;
import java.util.ArrayList;
import java.util.List;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import dev.morphia.annotations.Entity;
import emu.grasscutter.game.avatar.Avatar;
import emu.grasscutter.net.proto.AvatarTeamOuterClass.AvatarTeam;
import java.util.ArrayList;
import java.util.List;
@Entity
public class TeamInfo {
public final class TeamInfo {
private String name;
private List<Integer> avatars;
@@ -84,8 +83,7 @@ public class TeamInfo {
}
public AvatarTeam toProto(Player player) {
AvatarTeam.Builder avatarTeam = AvatarTeam.newBuilder()
.setTeamName(this.getName());
AvatarTeam.Builder avatarTeam = AvatarTeam.newBuilder().setTeamName(this.getName());
for (int i = 0; i < this.getAvatars().size(); i++) {
Avatar avatar = player.getAvatars().getAvatarById(this.getAvatars().get(i));

File diff suppressed because it is too large Load Diff