GameMainQuest.java 15.9 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.game.quest;

Akka's avatar
Akka committed
3
import java.util.*;
Melledy's avatar
Melledy committed
4

akatatsu27's avatar
akatatsu27 committed
5
6
7
8
9
10
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.binout.ScriptSceneData;
import emu.grasscutter.data.excels.QuestData;
import emu.grasscutter.game.quest.enums.LogicType;
import emu.grasscutter.game.quest.enums.QuestTrigger;
import emu.grasscutter.scripts.ScriptLoader;
11
import emu.grasscutter.server.packet.send.PacketCodexDataUpdateNotify;
akatatsu27's avatar
akatatsu27 committed
12
13
import emu.grasscutter.utils.Position;
import lombok.Getter;
Melledy's avatar
Melledy committed
14
15
16
17
18
19
20
import org.bson.types.ObjectId;

import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.Indexed;
import dev.morphia.annotations.Transient;
import emu.grasscutter.data.GameData;
Melledy's avatar
Melledy committed
21
import emu.grasscutter.data.binout.MainQuestData;
akatatsu27's avatar
akatatsu27 committed
22
import emu.grasscutter.data.binout.MainQuestData.*;
Melledy's avatar
Melledy committed
23
import emu.grasscutter.data.excels.RewardData;
Melledy's avatar
Melledy committed
24
25
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.player.Player;
Melledy's avatar
Melledy committed
26
import emu.grasscutter.game.props.ActionReason;
Melledy's avatar
Melledy committed
27
28
29
30
31
32
33
34
import emu.grasscutter.game.quest.enums.ParentQuestState;
import emu.grasscutter.game.quest.enums.QuestState;
import emu.grasscutter.net.proto.ChildQuestOuterClass.ChildQuest;
import emu.grasscutter.net.proto.ParentQuestOuterClass.ParentQuest;
import emu.grasscutter.net.proto.QuestOuterClass.Quest;
import emu.grasscutter.server.packet.send.PacketFinishedParentQuestUpdateNotify;
import emu.grasscutter.server.packet.send.PacketQuestListUpdateNotify;
import emu.grasscutter.server.packet.send.PacketQuestProgressUpdateNotify;
akatatsu27's avatar
akatatsu27 committed
35
36
37
38
39
40

import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptException;

import static emu.grasscutter.config.Configuration.SCRIPT;
Melledy's avatar
Melledy committed
41
42
43
44

@Entity(value = "quests", useDiscriminator = false)
public class GameMainQuest {
	@Id private ObjectId id;
akatatsu27's avatar
akatatsu27 committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
	@Indexed @Getter private int ownerUid;
	@Transient @Getter private Player owner;
    @Transient @Getter private QuestManager questManager;
	@Getter private Map<Integer, GameQuest> childQuests;
	@Getter private int parentQuestId;
	@Getter private int[] questVars;
    //QuestUpdateQuestVarReq is sent in two stages...
    @Getter private List<Integer> questVarsUpdate;
	@Getter private ParentQuestState state;
	@Getter private boolean isFinished;
    @Getter List<QuestGroupSuite> questGroupSuites;

    @Getter int[] suggestTrackMainQuestList;
    @Getter private Map<Integer,TalkData> talks;
    //key is subId
    private Map<Integer,Position> rewindPositions;
    private Map<Integer,Position> rewindRotations;
Akka's avatar
Akka committed
62

Melledy's avatar
Melledy committed
63
64
	@Deprecated // Morphia only. Do not use.
	public GameMainQuest() {}
Akka's avatar
Akka committed
65

Melledy's avatar
Melledy committed
66
67
68
	public GameMainQuest(Player player, int parentQuestId) {
		this.owner = player;
		this.ownerUid = player.getUid();
akatatsu27's avatar
akatatsu27 committed
69
        this.questManager = player.getQuestManager();
Melledy's avatar
Melledy committed
70
71
		this.parentQuestId = parentQuestId;
		this.childQuests = new HashMap<>();
akatatsu27's avatar
akatatsu27 committed
72
73
74
        this.talks = new HashMap<>();
        //official server always has a list of 5 questVars, with default value 0
		this.questVars = new int[] {0,0,0,0,0};
Melledy's avatar
Melledy committed
75
		this.state = ParentQuestState.PARENT_QUEST_STATE_NONE;
Akka's avatar
Akka committed
76
        this.questGroupSuites = new ArrayList<>();
akatatsu27's avatar
akatatsu27 committed
77
78
79
80
        this.rewindPositions = new HashMap<>();
        this.rewindRotations = new HashMap<>();
        addAllChildQuests();
        addRewindPoints();
Melledy's avatar
Melledy committed
81
82
	}

akatatsu27's avatar
akatatsu27 committed
83
84
85
86
87
88
89
    private void addAllChildQuests() {
        List<Integer> subQuestIds = Arrays.stream(GameData.getMainQuestDataMap().get(this.parentQuestId).getSubQuests()).map(SubQuestData::getSubId).toList();
        for (Integer subQuestId : subQuestIds) {
            QuestData questConfig = GameData.getQuestDataMap().get(subQuestId);
            this.childQuests.put(subQuestId, new GameQuest(this, questConfig));
        }
    }
Melledy's avatar
Melledy committed
90
91
92
93
94
95

	public void setOwner(Player player) {
		if (player.getUid() != this.getOwnerUid()) return;
		this.owner = player;
	}

akatatsu27's avatar
akatatsu27 committed
96
97
98
99
100
101
102
103
    public int getQuestVar(int i) {
        return questVars[i];
    }
    public void setQuestVar(int i, int value) {
        int previousValue = this.questVars[i];
        this.questVars[i] = value;
        Grasscutter.getLogger().debug("questVar {} value changed from {} to {}", i, previousValue, value);
    }
Akka's avatar
Akka committed
104

akatatsu27's avatar
akatatsu27 committed
105
106
107
108
109
    public void incQuestVar(int i, int inc) {
        int previousValue = this.questVars[i];
        this.questVars[i] += inc;
        Grasscutter.getLogger().debug("questVar {} value incremented from {} to {}", i, previousValue, previousValue + inc);
    }
Melledy's avatar
Melledy committed
110

akatatsu27's avatar
akatatsu27 committed
111
112
113
114
115
    public void decQuestVar(int i, int dec) {
        int previousValue = this.questVars[i];
        this.questVars[i] -= dec;
        Grasscutter.getLogger().debug("questVar {} value decremented from {} to {}", i, previousValue, previousValue - dec);
    }
Melledy's avatar
Melledy committed
116
117


akatatsu27's avatar
akatatsu27 committed
118
119
	public GameQuest getChildQuestById(int id) {
		return this.getChildQuests().get(id);
Melledy's avatar
Melledy committed
120
	}
akatatsu27's avatar
akatatsu27 committed
121
122
    public GameQuest getChildQuestByOrder(int order) {
        return this.getChildQuests().values().stream().filter(p -> p.getQuestData().getOrder() == order).toList().get(0);
Akka's avatar
Akka committed
123
124
125
    }

    public void finish() {
Melledy's avatar
Melledy committed
126
127
		this.isFinished = true;
		this.state = ParentQuestState.PARENT_QUEST_STATE_FINISHED;
Akka's avatar
Akka committed
128

Melledy's avatar
Melledy committed
129
		this.getOwner().getSession().send(new PacketFinishedParentQuestUpdateNotify(this));
130
		this.getOwner().getSession().send(new PacketCodexDataUpdateNotify(this));
Akka's avatar
Akka committed
131

132
		this.save();
Akka's avatar
Akka committed
133

Melledy's avatar
Melledy committed
134
135
136
137
		// Add rewards
		MainQuestData mainQuestData = GameData.getMainQuestDataMap().get(this.getParentQuestId());
		for (int rewardId : mainQuestData.getRewardIdList()) {
			RewardData rewardData = GameData.getRewardDataMap().get(rewardId);
Akka's avatar
Akka committed
138

Melledy's avatar
Melledy committed
139
140
141
			if (rewardData == null) {
				continue;
			}
Akka's avatar
Akka committed
142

Melledy's avatar
Melledy committed
143
144
			getOwner().getInventory().addItemParamDatas(rewardData.getRewardItemList(), ActionReason.QuestReward);
		}
Akka's avatar
Akka committed
145
146
147
148

        // handoff main quest
        if(mainQuestData.getSuggestTrackMainQuestList() != null){
            Arrays.stream(mainQuestData.getSuggestTrackMainQuestList())
akatatsu27's avatar
akatatsu27 committed
149
                .forEach(getQuestManager()::startMainQuest);
Akka's avatar
Akka committed
150
        }
Melledy's avatar
Melledy committed
151
	}
akatatsu27's avatar
akatatsu27 committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
    //TODO
    public void fail() {}
    public void cancel() {}

    // Rewinds to the last finished/unfinished rewind quest, and returns the avatar rewind position (if it exists)
    public List<Position> rewind() {
        if(this.questManager == null) {
            this.questManager = getOwner().getQuestManager();
        }
        List<GameQuest> sortedByOrder = new ArrayList<>(getChildQuests().values().stream().filter(q -> q.getQuestData().isRewind()).toList());
        sortedByOrder.sort((a,b) -> {
            if( a == b){
                return 0;
            }
            return a.getQuestData().getOrder() > b.getQuestData().getOrder() ? 1 : -1;});
        boolean didRewind = false;
        for (GameQuest quest : sortedByOrder) {
            int i = sortedByOrder.indexOf(quest);
            if( i == sortedByOrder.size()) {
                didRewind = quest.rewind(null);
            } else {
                didRewind = quest.rewind(sortedByOrder.get(i+1));
            }
            if(didRewind) {
                break;
            }
        }
        List<GameQuest> rewindQuests = getChildQuests().values().stream()
            .filter(p -> (p.getState() == QuestState.QUEST_STATE_UNFINISHED || p.getState() == QuestState.QUEST_STATE_FINISHED) && p.getQuestData().isRewind()).toList();
        for (GameQuest quest : rewindQuests) {
            if(rewindPositions.containsKey(quest.getSubQuestId())) {
                List<Position> posAndRot = new ArrayList<>();
                posAndRot.add(0,rewindPositions.get(quest.getSubQuestId()));
                posAndRot.add(1,rewindRotations.get(quest.getSubQuestId()));
                  return posAndRot;
            }
        }
        return null;
    }
    public void addRewindPoints() {
        Bindings bindings = ScriptLoader.getEngine().createBindings();

        CompiledScript cs = ScriptLoader.getScriptByPath(
            SCRIPT("Quest/Share/Q" + getParentQuestId() + "ShareConfig." + ScriptLoader.getScriptType()));

        if (cs == null) {
            Grasscutter.getLogger().error("Couldn't find Q" + getParentQuestId() + "ShareConfig." + ScriptLoader.getScriptType());
            return;
        }


        // Eval script
        try {
            cs.eval(bindings);

            var rewindDataMap = ScriptLoader.getSerializer().toMap(RewindData.class, bindings.get("rewind_data"));
            for(String subId : rewindDataMap.keySet()) {
                RewindData questRewind = rewindDataMap.get(subId);
                if(questRewind != null) {
                    RewindData.AvatarData avatarData = questRewind.getAvatar();
                    if(avatarData != null) {
                        String avatarPos = avatarData.getPos();
                        QuestData.Guide guide = GameData.getQuestDataMap().get(Integer.valueOf(subId)).getGuide();
                        if (guide != null) {
                            int sceneId = guide.getGuideScene();
                            ScriptSceneData fullGlobals = GameData.getScriptSceneDataMap().get("flat.luas.scenes.full_globals.lua.json");
                            if(fullGlobals != null) {
                                ScriptSceneData.ScriptObject dummyPointScript = fullGlobals.getScriptObjectList().get(sceneId + "/scene" + sceneId + "_dummy_points.lua");
                                if (dummyPointScript != null) {
                                    Map<String, List<Float>> dummyPointMap = dummyPointScript.getDummyPoints();
                                    if (dummyPointMap != null) {
                                        List<Float> avatarPosPos = dummyPointMap.get(avatarPos + ".pos");
                                        if (avatarPosPos != null) {
                                            Position pos = new Position(avatarPosPos.get(0),avatarPosPos.get(1),avatarPosPos.get(2));
                                            List<Float> avatarPosRot = dummyPointMap.get(avatarPos + ".rot");
                                            Position rot =  new Position(avatarPosRot.get(0),avatarPosRot.get(1),avatarPosRot.get(2));
                                            rewindPositions.put(Integer.valueOf(subId),pos);
                                            rewindRotations.put(Integer.valueOf(subId),rot);
                                            Grasscutter.getLogger().debug("Succesfully loaded rewind position for subQuest {}",subId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        } catch (ScriptException e) {
            Grasscutter.getLogger().error("An error occurred while loading rewind positions");
        }
    }

    public void tryAcceptSubQuests(QuestTrigger condType, String paramStr, int... params) {
        try {
            List<GameQuest> subQuestsWithCond = getChildQuests().values().stream()
                .filter(p -> p.getState() == QuestState.QUEST_STATE_UNSTARTED)
                .filter(p -> p.getQuestData().getAcceptCond().stream().anyMatch(q -> q.getType() == condType))
                .toList();

            for (GameQuest subQuestWithCond : subQuestsWithCond) {
                List<QuestData.QuestCondition> acceptCond = subQuestWithCond.getQuestData().getAcceptCond();
                int[] accept = new int[acceptCond.size()];

                for (int i = 0; i < subQuestWithCond.getQuestData().getAcceptCond().size(); i++) {
                    QuestData.QuestCondition condition = acceptCond.get(i);
                    boolean result = this.getOwner().getServer().getQuestSystem().triggerCondition(subQuestWithCond, condition, paramStr, params);
                    accept[i] = result ? 1 : 0;
                }

                boolean shouldAccept = LogicType.calculate(subQuestWithCond.getQuestData().getAcceptCondComb(), accept);

                if (shouldAccept) {
                    subQuestWithCond.start();
                    getQuestManager().getAddToQuestListUpdateNotify().add(subQuestWithCond);
                }

            }
            this.save();
        } catch (Exception e) {
            Grasscutter.getLogger().error("An error occurred while trying to accept quest.", e);
        }

    }

    public void tryFailSubQuests(QuestTrigger condType, String paramStr, int... params) {
        try {
            List<GameQuest> subQuestsWithCond = getChildQuests().values().stream()
                .filter(p -> p.getState() == QuestState.QUEST_STATE_UNFINISHED)
                .filter(p -> p.getQuestData().getFailCond().stream().anyMatch(q -> q.getType() == condType))
                .toList();

            for (GameQuest subQuestWithCond : subQuestsWithCond) {
                List<QuestData.QuestCondition> failCond = subQuestWithCond.getQuestData().getFailCond();
                int[] fail = new int[failCond.size()];

                for (int i = 0; i < subQuestWithCond.getQuestData().getFailCond().size(); i++) {
                    QuestData.QuestCondition condition = failCond.get(i);
                    boolean result = this.getOwner().getServer().getQuestSystem().triggerContent(subQuestWithCond, condition, paramStr, params);
                    fail[i] = result ? 1 : 0;
                }

                boolean shouldFail = LogicType.calculate(subQuestWithCond.getQuestData().getFailCondComb(), fail);

                if (shouldFail) {
                    subQuestWithCond.fail();
                    getQuestManager().getAddToQuestListUpdateNotify().add(subQuestWithCond);
                }
            }

        } catch (Exception e) {
            Grasscutter.getLogger().error("An error occurred while trying to fail quest.", e);
        }
    }

    public void tryFinishSubQuests(QuestTrigger condType, String paramStr, int... params) {
        try {
            List<GameQuest> subQuestsWithCond = getChildQuests().values().stream()
                //There are subQuests with no acceptCond, but can be finished (example: 35104)
                .filter(p -> p.getState() == QuestState.QUEST_STATE_UNFINISHED && p.getQuestData().getAcceptCond() != null)
                .filter(p -> p.getQuestData().getFinishCond().stream().anyMatch(q -> q.getType() == condType))
                .toList();

            for (GameQuest subQuestWithCond : subQuestsWithCond) {
                List<QuestData.QuestCondition> finishCond = subQuestWithCond.getQuestData().getFinishCond();
                int[] finish = new int[finishCond.size()];

                for (int i = 0; i < subQuestWithCond.getQuestData().getFinishCond().size(); i++) {
                    QuestData.QuestCondition condition = finishCond.get(i);
                    boolean result = this.getOwner().getServer().getQuestSystem().triggerContent(subQuestWithCond, condition, paramStr, params);
                    finish[i] = result ? 1 : 0;
                }

                boolean shouldFinish = LogicType.calculate(subQuestWithCond.getQuestData().getFinishCondComb(), finish);

                if (shouldFinish) {
                    subQuestWithCond.finish();
                    getQuestManager().getAddToQuestListUpdateNotify().add(subQuestWithCond);
                }
            }
        } catch (Exception e) {
            Grasscutter.getLogger().debug("An error occurred while trying to finish quest.", e);
        }
    }
Melledy's avatar
Melledy committed
336
337
338
339
340
341
342
343

	public void save() {
		DatabaseHelper.saveQuest(this);
	}

	public ParentQuest toProto() {
		ParentQuest.Builder proto = ParentQuest.newBuilder()
				.setParentQuestId(getParentQuestId())
akatatsu27's avatar
akatatsu27 committed
344
				.setIsFinished(isFinished());
Akka's avatar
Akka committed
345
346


akatatsu27's avatar
akatatsu27 committed
347
            proto.setParentQuestState(getState().getValue());
348
            .setCutsceneEncryptionKey(QuestManager.getQuestKey(parentQuestId));
akatatsu27's avatar
akatatsu27 committed
349
350
351
352
353
354
355
356
357
358
            for (GameQuest quest : this.getChildQuests().values()) {
                if (quest.getState() != QuestState.QUEST_STATE_UNSTARTED) {
                    ChildQuest childQuest = ChildQuest.newBuilder()
                        .setQuestId(quest.getSubQuestId())
                        .setState(quest.getState().getValue())
                        .build();

                    proto.addChildQuestList(childQuest);
                }
            }
359
        
akatatsu27's avatar
akatatsu27 committed
360
361
362
        for (int i : getQuestVars()) {
            proto.addQuestVar(i);
        }
Melledy's avatar
Melledy committed
363
364
365
366


		return proto.build();
	}
akatatsu27's avatar
akatatsu27 committed
367

Melledy's avatar
Melledy committed
368
}