Run the formatter & Generate protocol definitions

This commit is contained in:
KingRainbow44
2023-08-26 19:51:45 -04:00
Unverified
parent edb00adf61
commit f656143038
101 changed files with 15615 additions and 6636 deletions
@@ -1,5 +1,8 @@
package emu.grasscutter.game.quest;
import static emu.grasscutter.GameConstants.DEBUG;
import static emu.grasscutter.config.Configuration.*;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.binout.*;
@@ -12,16 +15,12 @@ import emu.grasscutter.net.proto.GivingRecordOuterClass.GivingRecord;
import emu.grasscutter.server.packet.send.*;
import io.netty.util.concurrent.FastThreadLocalThread;
import it.unimi.dsi.fastutil.ints.*;
import lombok.*;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static emu.grasscutter.GameConstants.DEBUG;
import static emu.grasscutter.config.Configuration.*;
import javax.annotation.Nonnull;
import lombok.*;
public final class QuestManager extends BasePlayerManager {
@Getter private final Player player;
@@ -32,10 +31,15 @@ public final class QuestManager extends BasePlayerManager {
private long lastHourCheck = 0;
private long lastDayCheck = 0;
public static final ExecutorService eventExecutor
= new ThreadPoolExecutor(4, 4,
60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1000),
FastThreadLocalThread::new, new ThreadPoolExecutor.AbortPolicy());
public static final ExecutorService eventExecutor =
new ThreadPoolExecutor(
4,
4,
60,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(1000),
FastThreadLocalThread::new,
new ThreadPoolExecutor.AbortPolicy());
public static long getQuestKey(int mainQuestId) {
QuestEncryptionKey questEncryptionKey = GameData.getMainQuestEncryptionMap().get(mainQuestId);
@@ -50,37 +54,37 @@ public final class QuestManager extends BasePlayerManager {
this.loggedQuests = new ArrayList<>();
if (DEBUG) {
this.loggedQuests.addAll(List.of(
31101, // Quest which holds talks 30902 and 30904.
35001, // Quest which unlocks world border & starts act 2.
30901, // Quest which is completed upon finishing all 3 initial dungeons.
30903, // Quest which is finished when re-entering scene 3. (home world)
30904, // Quest which unlocks the Adventurers' Guild
this.loggedQuests.addAll(
List.of(
31101, // Quest which holds talks 30902 and 30904.
35001, // Quest which unlocks world border & starts act 2.
30901, // Quest which is completed upon finishing all 3 initial dungeons.
30903, // Quest which is finished when re-entering scene 3. (home world)
30904, // Quest which unlocks the Adventurers' Guild
46904, // Quest which is required to be started, but not completed for 31101's talks
// to begin.
// This quest is related to obtaining your first Anemoculus.
46904, // Quest which is required to be started, but not completed for 31101's talks to begin.
// This quest is related to obtaining your first Anemoculus.
35104, // Quest which is required to be finished for 46904 to begin.
// This quest requires 31101 not be finished.
// This quest should be accepted when the account is created.
35104, // Quest which is required to be finished for 46904 to begin.
// This quest requires 31101 not be finished.
// This quest should be accepted when the account is created.
// These quests currently have bugged triggers.
30700, // Quest which is responsible for unlocking Crash Course.
30800, // Quest which is responsible for unlocking Sparks Amongst the Pages.
47001, 47002, 47003, 47004,
2010103, 2010144, // Prologue Act 2: Chasing Shadows,
2012 // This is the main quest ID for Chapter 2 Act 1.
// Used for debugging giving items.
));
// These quests currently have bugged triggers.
30700, // Quest which is responsible for unlocking Crash Course.
30800, // Quest which is responsible for unlocking Sparks Amongst the Pages.
47001,
47002,
47003,
47004,
2010103,
2010144, // Prologue Act 2: Chasing Shadows,
2012 // This is the main quest ID for Chapter 2 Act 1.
// Used for debugging giving items.
));
}
}
/**
* Checks if questing can be enabled.
*/
/** Checks if questing can be enabled. */
public boolean isQuestingEnabled() {
// Check if scripts are enabled.
if (!SERVER.game.enableScriptInBigWorld) {
@@ -97,8 +101,7 @@ public final class QuestManager extends BasePlayerManager {
* @param givingId The giving action ID.
* @throws IllegalStateException If the giving action is already active.
*/
public void addGiveItemAction(int givingId)
throws IllegalStateException {
public void addGiveItemAction(int givingId) throws IllegalStateException {
var progress = this.player.getPlayerProgress();
var givings = progress.getItemGivings();
@@ -163,10 +166,9 @@ public final class QuestManager extends BasePlayerManager {
* @return Serialized giving records to be used in a packet.
*/
public Collection<GivingRecord> getGivingRecords() {
return this.getPlayer().getPlayerProgress()
.getItemGivings().values().stream()
.map(ItemGiveRecord::toProto)
.toList();
return this.getPlayer().getPlayerProgress().getItemGivings().values().stream()
.map(ItemGiveRecord::toProto)
.toList();
}
/**
@@ -199,7 +201,7 @@ public final class QuestManager extends BasePlayerManager {
* @param bargainId The bargain ID.
*/
public void stopBargain(int bargainId) {
var progress = this.player.getPlayerProgress();
var progress = this.player.getPlayerProgress();
var bargains = progress.getBargains();
// Check if the bargain is already present.
@@ -216,14 +218,10 @@ public final class QuestManager extends BasePlayerManager {
this.player.sendPacket(new PacketBargainTerminateNotify(bargainId));
}
/**
* Sends the giving records to the player.
*/
/** Sends the giving records to the player. */
public void sendGivingRecords() {
// Send the record to the player.
this.player.sendPacket(
new PacketGivingRecordNotify(
this.getGivingRecords()));
this.player.sendPacket(new PacketGivingRecordNotify(this.getGivingRecords()));
}
public void onPlayerBorn() {
@@ -244,9 +242,9 @@ public final class QuestManager extends BasePlayerManager {
getPlayer().getPosition().set(rewindPos.get(0));
getPlayer().getRotation().set(rewindPos.get(1));
}
if(activeQuest!=null && rewindPos!=null){
//activeSubs.add(activeQuest);
//player.sendPacket(new PacketQuestProgressUpdateNotify(activeQuest));
if (activeQuest != null && rewindPos != null) {
// activeSubs.add(activeQuest);
// player.sendPacket(new PacketQuestProgressUpdateNotify(activeQuest));
}
quest.checkProgress();
}
@@ -270,29 +268,32 @@ public final class QuestManager extends BasePlayerManager {
boolean checkDays = currentDays != lastDayCheck;
boolean checkHours = currentHours != lastHourCheck;
if(!checkDays && !checkHours){
if (!checkDays && !checkHours) {
return;
}
this.lastDayCheck = currentDays;
this.lastHourCheck = currentHours;
player.getActiveQuestTimers().forEach(mainQuestId -> {
if (checkHours) {
this.queueEvent(QuestCond.QUEST_COND_TIME_VAR_GT_EQ, mainQuestId);
this.queueEvent(QuestContent.QUEST_CONTENT_TIME_VAR_GT_EQ, mainQuestId);
}
if (checkDays) {
this.queueEvent(QuestCond.QUEST_COND_TIME_VAR_PASS_DAY, mainQuestId);
this.queueEvent(QuestContent.QUEST_CONTENT_TIME_VAR_PASS_DAY, mainQuestId);
}
});
player
.getActiveQuestTimers()
.forEach(
mainQuestId -> {
if (checkHours) {
this.queueEvent(QuestCond.QUEST_COND_TIME_VAR_GT_EQ, mainQuestId);
this.queueEvent(QuestContent.QUEST_CONTENT_TIME_VAR_GT_EQ, mainQuestId);
}
if (checkDays) {
this.queueEvent(QuestCond.QUEST_COND_TIME_VAR_PASS_DAY, mainQuestId);
this.queueEvent(QuestContent.QUEST_CONTENT_TIME_VAR_PASS_DAY, mainQuestId);
}
});
}
private List<GameMainQuest> addMultMainQuests(Set<Integer> mainQuestIds) {
List<GameMainQuest> newQuests = new ArrayList<>();
for (Integer id : mainQuestIds) {
getMainQuests().put(id.intValue(),new GameMainQuest(this.player, id));
getMainQuests().put(id.intValue(), new GameMainQuest(this.player, id));
getMainQuestById(id).save();
newQuests.add(getMainQuestById(id));
}
@@ -319,27 +320,29 @@ public final class QuestManager extends BasePlayerManager {
* Looking through mainQuests 72201-72208 and 72174, we can infer that a questGlobalVar's default value is 0
*/
public Integer getQuestGlobalVarValue(Integer variable) {
return getPlayer().getQuestGlobalVariables()
.computeIfAbsent(variable, k -> this.getGlobalVarDefault(variable));
return getPlayer()
.getQuestGlobalVariables()
.computeIfAbsent(variable, k -> this.getGlobalVarDefault(variable));
}
public void setQuestGlobalVarValue(int variable, int setVal) {
var prevVal = this.getPlayer().getQuestGlobalVariables().put(variable, setVal);
if (prevVal == null){
if (prevVal == null) {
prevVal = this.getGlobalVarDefault(variable);
}
var newVal = this.getQuestGlobalVarValue(variable);
Grasscutter.getLogger().debug("Changed questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
Grasscutter.getLogger()
.debug("Changed questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
this.triggerQuestGlobalVarAction(variable, setVal);
}
public void incQuestGlobalVarValue(int variable, int inc) {
var prevVal = getQuestGlobalVarValue(variable);
var newVal = getPlayer().getQuestGlobalVariables()
.compute(variable, (k, v) -> prevVal + inc);
var newVal = getPlayer().getQuestGlobalVariables().compute(variable, (k, v) -> prevVal + inc);
Grasscutter.getLogger().debug("Incremented questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
Grasscutter.getLogger()
.debug("Incremented questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
this.triggerQuestGlobalVarAction(variable, newVal);
}
@@ -349,7 +352,8 @@ public final class QuestManager extends BasePlayerManager {
this.getPlayer().getQuestGlobalVariables().put(variable, prevVal - dec);
var newVal = getQuestGlobalVarValue(variable);
Grasscutter.getLogger().debug("Decremented questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
Grasscutter.getLogger()
.debug("Decremented questGlobalVar {} value from {} to {}", variable, prevVal, newVal);
this.triggerQuestGlobalVarAction(variable, newVal);
}
@@ -422,7 +426,7 @@ public final class QuestManager extends BasePlayerManager {
return null;
}
return this.addQuest(questConfig);
return this.addQuest(questConfig);
}
public GameQuest addQuest(@Nonnull QuestData questConfig) {
@@ -452,10 +456,10 @@ public final class QuestManager extends BasePlayerManager {
}
Arrays.stream(mainQuestData.getSubQuests())
.min(Comparator.comparingInt(MainQuestData.SubQuestData::getOrder))
.map(MainQuestData.SubQuestData::getSubId)
.ifPresent(this::addQuest);
//TODO find a better way then hardcoding to detect needed required quests
.min(Comparator.comparingInt(MainQuestData.SubQuestData::getOrder))
.map(MainQuestData.SubQuestData::getSubId)
.ifPresent(this::addQuest);
// TODO find a better way then hardcoding to detect needed required quests
// if (mainQuestId == 355){
// startMainQuest(361);
// startMainQuest(418);
@@ -463,9 +467,11 @@ public final class QuestManager extends BasePlayerManager {
// startMainQuest(20509);
// }
}
public void queueEvent(QuestCond condType, int... params) {
queueEvent(condType, "", params);
}
public void queueEvent(QuestContent condType, int... params) {
queueEvent(condType, "", params);
}
@@ -478,57 +484,69 @@ public final class QuestManager extends BasePlayerManager {
eventExecutor.submit(() -> triggerEvent(condType, paramStr, params));
}
//QUEST_EXEC are handled directly by each subQuest
// QUEST_EXEC are handled directly by each subQuest
public void triggerEvent(QuestCond condType, String paramStr, int... params) {
Grasscutter.getLogger().trace("Trigger Event {}, {}, {}", condType, paramStr, params);
var potentialQuests = GameData.getQuestDataByConditions(condType, params[0], paramStr);
if(potentialQuests == null){
if (potentialQuests == null) {
return;
}
var questSystem = getPlayer().getServer().getQuestSystem();
var owner = getPlayer();
potentialQuests.forEach(questData -> {
if(this.wasSubQuestStarted(questData)){
return;
}
val acceptCond = questData.getAcceptCond();
int[] accept = new int[acceptCond.size()];
for (int i = 0; i < acceptCond.size(); i++) {
val condition = acceptCond.get(i);
boolean result = questSystem.triggerCondition(owner, questData, condition, paramStr, params);
accept[i] = result ? 1 : 0;
}
potentialQuests.forEach(
questData -> {
if (this.wasSubQuestStarted(questData)) {
return;
}
val acceptCond = questData.getAcceptCond();
int[] accept = new int[acceptCond.size()];
for (int i = 0; i < acceptCond.size(); i++) {
val condition = acceptCond.get(i);
boolean result =
questSystem.triggerCondition(owner, questData, condition, paramStr, params);
accept[i] = result ? 1 : 0;
}
boolean shouldAccept = LogicType.calculate(questData.getAcceptCondComb(), accept);
if (this.loggedQuests.contains(questData.getId())) {
Grasscutter.getLogger().debug(">>> Quest {} will be {} as a result of event trigger {} ({}, {}).",
questData.getId(), shouldAccept ? "accepted" : "not accepted", condType.name(), paramStr,
Arrays.stream(params).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
for (var i = 0; i < accept.length; i++) {
var condition = acceptCond.get(i);
Grasscutter.getLogger().debug("^ Condition {} has params {} with result {}.",
condition.getType().name(),
Arrays.stream(condition.getParam())
.filter(value -> value > 0)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ")),
accept[i] == 1 ? "success" : "failure");
}
}
boolean shouldAccept = LogicType.calculate(questData.getAcceptCondComb(), accept);
if (this.loggedQuests.contains(questData.getId())) {
Grasscutter.getLogger()
.debug(
">>> Quest {} will be {} as a result of event trigger {} ({}, {}).",
questData.getId(),
shouldAccept ? "accepted" : "not accepted",
condType.name(),
paramStr,
Arrays.stream(params)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ")));
for (var i = 0; i < accept.length; i++) {
var condition = acceptCond.get(i);
Grasscutter.getLogger()
.debug(
"^ Condition {} has params {} with result {}.",
condition.getType().name(),
Arrays.stream(condition.getParam())
.filter(value -> value > 0)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ")),
accept[i] == 1 ? "success" : "failure");
}
}
if (shouldAccept) {
GameQuest quest = owner.getQuestManager().addQuest(questData);
Grasscutter.getLogger().debug("Added quest {} result {}", questData.getSubId(), quest != null);
}
});
if (shouldAccept) {
GameQuest quest = owner.getQuestManager().addQuest(questData);
Grasscutter.getLogger()
.debug("Added quest {} result {}", questData.getSubId(), quest != null);
}
});
}
public boolean wasSubQuestStarted(QuestData questData) {
var quest = getQuestById(questData.getId());
if(quest == null) return false;
if (quest == null) return false;
return quest.state != QuestState.QUEST_STATE_UNSTARTED;
}
@@ -536,9 +554,10 @@ public final class QuestManager extends BasePlayerManager {
public void triggerEvent(QuestContent condType, String paramStr, int... params) {
Grasscutter.getLogger().trace("Trigger Event {}, {}, {}", condType, paramStr, params);
List<GameMainQuest> checkMainQuests = this.getMainQuests().values().stream()
.filter(i -> i.getState() != ParentQuestState.PARENT_QUEST_STATE_FINISHED)
.toList();
List<GameMainQuest> checkMainQuests =
this.getMainQuests().values().stream()
.filter(i -> i.getState() != ParentQuestState.PARENT_QUEST_STATE_FINISHED)
.toList();
for (GameMainQuest mainQuest : checkMainQuests) {
mainQuest.tryFailSubQuests(condType, paramStr, params);
mainQuest.tryFinishSubQuests(condType, paramStr, params);
@@ -546,46 +565,58 @@ public final class QuestManager extends BasePlayerManager {
}
/**
* TODO maybe trigger them delayed to allow basic communication finish first
* TODO move content checks to use static informations where possible to allow direct already fulfilled checking
* TODO maybe trigger them delayed to allow basic communication finish first TODO move content
* checks to use static informations where possible to allow direct already fulfilled checking
*
* @param quest The ID of the quest.
*/
public void checkQuestAlreadyFulfilled(GameQuest quest){
Grasscutter.getThreadPool().submit(() -> {
for (var condition : quest.getQuestData().getFinishCond()){
switch (condition.getType()) {
case QUEST_CONTENT_OBTAIN_ITEM, QUEST_CONTENT_ITEM_LESS_THAN -> {
//check if we already own enough of the item
var item = getPlayer().getInventory().getItemByGuid(condition.getParam()[0]);
queueEvent(condition.getType(), condition.getParam()[0], item != null ? item.getCount() : 0);
}
case QUEST_CONTENT_UNLOCK_TRANS_POINT -> {
var scenePoints = getPlayer().getUnlockedScenePoints().get(condition.getParam()[0]);
if (scenePoints != null && scenePoints.contains(condition.getParam()[1])) {
queueEvent(condition.getType(), condition.getParam()[0], condition.getParam()[1]);
}
}
case QUEST_CONTENT_UNLOCK_AREA -> {
var sceneAreas = getPlayer().getUnlockedSceneAreas().get(condition.getParam()[0]);
if (sceneAreas != null && sceneAreas.contains(condition.getParam()[1])) {
queueEvent(condition.getType(), condition.getParam()[0], condition.getParam()[1]);
}
}
case QUEST_CONTENT_PLAYER_LEVEL_UP -> queueEvent(condition.getType(), player.getLevel());
}
}
});
public void checkQuestAlreadyFulfilled(GameQuest quest) {
Grasscutter.getThreadPool()
.submit(
() -> {
for (var condition : quest.getQuestData().getFinishCond()) {
switch (condition.getType()) {
case QUEST_CONTENT_OBTAIN_ITEM, QUEST_CONTENT_ITEM_LESS_THAN -> {
// check if we already own enough of the item
var item = getPlayer().getInventory().getItemByGuid(condition.getParam()[0]);
queueEvent(
condition.getType(),
condition.getParam()[0],
item != null ? item.getCount() : 0);
}
case QUEST_CONTENT_UNLOCK_TRANS_POINT -> {
var scenePoints =
getPlayer().getUnlockedScenePoints().get(condition.getParam()[0]);
if (scenePoints != null && scenePoints.contains(condition.getParam()[1])) {
queueEvent(
condition.getType(), condition.getParam()[0], condition.getParam()[1]);
}
}
case QUEST_CONTENT_UNLOCK_AREA -> {
var sceneAreas =
getPlayer().getUnlockedSceneAreas().get(condition.getParam()[0]);
if (sceneAreas != null && sceneAreas.contains(condition.getParam()[1])) {
queueEvent(
condition.getType(), condition.getParam()[0], condition.getParam()[1]);
}
}
case QUEST_CONTENT_PLAYER_LEVEL_UP -> queueEvent(
condition.getType(), player.getLevel());
}
}
});
}
public List<QuestGroupSuite> getSceneGroupSuite(int sceneId) {
return getMainQuests().values().stream()
.filter(i -> i.getState() != ParentQuestState.PARENT_QUEST_STATE_FINISHED)
.map(GameMainQuest::getQuestGroupSuites)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(i -> i.getScene() == sceneId)
.toList();
.filter(i -> i.getState() != ParentQuestState.PARENT_QUEST_STATE_FINISHED)
.map(GameMainQuest::getQuestGroupSuites)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(i -> i.getScene() == sceneId)
.toList();
}
public void loadFromDatabase() {
List<GameMainQuest> quests = DatabaseHelper.getAllQuests(getPlayer());
@@ -626,24 +657,30 @@ public final class QuestManager extends BasePlayerManager {
var pointId = point.getPointData().getId();
// Get the active quests.
return this.getActiveMainQuests().stream()
// Get the sub-quests of the main quest.
.map(GameMainQuest::getChildQuests)
// Get the values of the sub-quests map.
.map(Map::values)
.map(quests -> quests.stream()
// Get the dungeon IDs of each quest.
.map(GameQuest::getDungeonIds)
.map(ids -> ids.stream()
// Find entry points which match this dungeon.
.filter(id -> id.rightInt() == pointId)
.toList())
.map(ids -> ids.stream()
// Of the remaining dungeons, find the ID of the quest dungeon.
.map(IntIntImmutablePair::leftInt)
.toList())
// Get the sub-quests of the main quest.
.map(GameMainQuest::getChildQuests)
// Get the values of the sub-quests map.
.map(Map::values)
.map(
quests ->
quests.stream()
// Get the dungeon IDs of each quest.
.map(GameQuest::getDungeonIds)
.map(
ids ->
ids.stream()
// Find entry points which match this dungeon.
.filter(id -> id.rightInt() == pointId)
.toList())
.map(
ids ->
ids.stream()
// Of the remaining dungeons, find the ID of the quest dungeon.
.map(IntIntImmutablePair::leftInt)
.toList())
.flatMap(Collection::stream)
.toList())
.flatMap(Collection::stream)
.toList())
.flatMap(Collection::stream)
.toList();
.toList();
}
}