-
Notifications
You must be signed in to change notification settings - Fork 5
/
DialogueStateMachine.java
239 lines (210 loc) · 10.1 KB
/
DialogueStateMachine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
/*
* Blabber
* Copyright (C) 2022-2024 Ladysnake
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; If not, see <https://www.gnu.org/licenses>.
*/
package org.ladysnake.blabber.impl.common.machine;
import com.google.common.collect.ImmutableList;
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanMaps;
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
import net.minecraft.loot.LootDataType;
import net.minecraft.loot.condition.LootCondition;
import net.minecraft.loot.context.LootContext;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
import org.ladysnake.blabber.Blabber;
import org.ladysnake.blabber.api.DialogueActionV2;
import org.ladysnake.blabber.impl.common.InstancedDialogueAction;
import org.ladysnake.blabber.impl.common.model.ChoiceResult;
import org.ladysnake.blabber.impl.common.model.DialogueChoice;
import org.ladysnake.blabber.impl.common.model.DialogueChoiceCondition;
import org.ladysnake.blabber.impl.common.model.DialogueLayout;
import org.ladysnake.blabber.impl.common.model.DialogueState;
import org.ladysnake.blabber.impl.common.model.DialogueTemplate;
import org.ladysnake.blabber.impl.common.model.UnavailableAction;
import org.ladysnake.blabber.impl.common.model.UnavailableDisplay;
import org.ladysnake.blabber.impl.common.packets.ChoiceAvailabilityPacket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.IntStream;
public final class DialogueStateMachine {
private final Identifier id;
private final DialogueTemplate template;
private final Map<String, Int2BooleanMap> conditionalChoices;
private @Nullable String currentStateKey;
private ImmutableList<AvailableChoice> availableChoices = ImmutableList.of();
public DialogueStateMachine(Identifier id, DialogueTemplate template, @Nullable String start) {
this.template = template;
this.id = id;
this.conditionalChoices = gatherConditionalChoices(template);
this.selectState(start == null ? template.start() : start);
}
private static Map<String, Int2BooleanMap> gatherConditionalChoices(DialogueTemplate template) {
Map<String, Int2BooleanMap> conditionalChoices = new HashMap<>();
for (Map.Entry<String, DialogueState> entry : template.states().entrySet()) {
List<DialogueChoice> choices = entry.getValue().choices();
Int2BooleanMap m = new Int2BooleanOpenHashMap();
for (int i = 0; i < choices.size(); i++) {
DialogueChoice choice = choices.get(i);
if (choice.condition().isPresent()) {
m.put(i, false);
}
}
if (!m.isEmpty()) {
conditionalChoices.put(entry.getKey(), m);
}
}
return conditionalChoices;
}
public static void writeToPacket(PacketByteBuf buf, DialogueStateMachine dialogue) {
buf.writeIdentifier(dialogue.getId());
DialogueTemplate.writeToPacket(buf, dialogue.template);
buf.writeString(dialogue.getCurrentStateKey());
}
public DialogueStateMachine(PacketByteBuf buf) {
this(buf.readIdentifier(), new DialogueTemplate(buf), buf.readString());
}
private Map<String, DialogueState> getStates() {
return this.template.states();
}
private DialogueState getCurrentState() {
return getStates().get(this.getCurrentStateKey());
}
public Identifier getId() {
return this.id;
}
public DialogueLayout getLayout() {
return this.template.layout();
}
public Text getCurrentText() {
return this.getCurrentState().text();
}
public ImmutableList<AvailableChoice> getAvailableChoices() {
return this.availableChoices;
}
public boolean hasConditions() {
return !this.conditionalChoices.isEmpty();
}
public @Nullable ChoiceAvailabilityPacket updateConditions(LootContext context) {
ChoiceAvailabilityPacket ret = null;
for (Map.Entry<String, Int2BooleanMap> conditionalState : this.conditionalChoices.entrySet()) {
List<DialogueChoice> availableChoices = getStates().get(conditionalState.getKey()).choices();
for (Int2BooleanMap.Entry conditionalChoice : conditionalState.getValue().int2BooleanEntrySet()) {
LootCondition condition = context.getWorld().getServer().getLootManager().getElement(
LootDataType.PREDICATES, availableChoices.get(conditionalChoice.getIntKey()).condition().orElseThrow().predicate()
);
boolean testResult = runTest(condition, context);
if (testResult != conditionalChoice.setValue(testResult)) {
if (ret == null) ret = new ChoiceAvailabilityPacket();
ret.markUpdated(conditionalState.getKey(), conditionalChoice.getIntKey(), testResult);
}
}
}
return ret;
}
public ChoiceAvailabilityPacket createFullAvailabilityUpdatePacket() {
return new ChoiceAvailabilityPacket(this.conditionalChoices);
}
private static boolean runTest(LootCondition condition, LootContext context) {
LootContext.Entry<LootCondition> lootEntry = LootContext.predicate(condition);
context.markActive(lootEntry);
boolean testResult = condition.test(context);
context.markInactive(lootEntry);
return testResult;
}
public void applyAvailabilityUpdate(ChoiceAvailabilityPacket payload) {
payload.updatedChoices().forEach((stateKey, choiceIndices) -> {
Int2BooleanMap conditionalState = this.conditionalChoices.get(stateKey);
for (Int2BooleanMap.Entry updatedChoice : choiceIndices.int2BooleanEntrySet()) {
conditionalState.put(updatedChoice.getIntKey(), updatedChoice.getBooleanValue());
}
this.availableChoices = this.rebuildAvailableChoices();
});
}
public boolean isAvailable(int choice) {
return this.conditionalChoices.getOrDefault(this.currentStateKey, Int2BooleanMaps.EMPTY_MAP).getOrDefault(choice, true);
}
/**
* @throws IllegalStateException if making an invalid choice
*/
public ChoiceResult choose(int choice, Consumer<DialogueActionV2> actionRunner) {
if (choice == AvailableChoice.ESCAPE_HATCH.originalChoiceIndex() && IntStream.range(0, this.getCurrentState().choices().size()).noneMatch(this::isAvailable)) {
Blabber.LOGGER.warn("(Blabber) Escape hatch used on {}#{}", this.getId(), this.currentStateKey);
return ChoiceResult.END_DIALOGUE;
}
this.validateChoice(choice);
DialogueState nextState = this.selectState(this.getCurrentState().getNextState(choice));
nextState.action().map(InstancedDialogueAction::action).ifPresent(actionRunner);
return nextState.type();
}
private void validateChoice(int choice) {
if (choice < 0 || choice >= this.getCurrentState().choices().size()) {
throw new IllegalStateException("only choices 0 to %d available".formatted(this.getCurrentState().choices().size() - 1));
} else if (!this.isAvailable(choice)) {
throw new IllegalStateException("condition %s is not fulfilled".formatted(this.getCurrentState().choices().get(choice).condition()));
}
}
public DialogueState selectState(String state) {
if (!this.getStates().containsKey(state)) {
throw new IllegalArgumentException(state + " is not an available dialogue state");
}
this.currentStateKey = state;
DialogueState currentState = this.getStates().get(state);
this.availableChoices = rebuildAvailableChoices();
return currentState;
}
private ImmutableList<AvailableChoice> rebuildAvailableChoices() {
ImmutableList.Builder<AvailableChoice> newChoices = ImmutableList.builder();
List<DialogueChoice> availableChoices = this.getCurrentState().choices();
boolean allUnavailable = true;
for (int i = 0; i < availableChoices.size(); i++) {
DialogueChoice c = availableChoices.get(i);
boolean available = conditionalChoices.getOrDefault(this.currentStateKey, Int2BooleanMaps.EMPTY_MAP).getOrDefault(i, true);
Optional<UnavailableAction> whenUnavailable = c.condition().map(DialogueChoiceCondition::whenUnavailable);
allUnavailable &= !available;
if (available || (whenUnavailable.filter(t -> t.display() == UnavailableDisplay.GRAYED_OUT).isPresent())) {
newChoices.add(new AvailableChoice(
i,
c.text(),
whenUnavailable.filter(t -> !available).flatMap(a -> a.message().or(DialogueStateMachine::defaultLockedMessage))
));
}
}
if (allUnavailable) {
newChoices.add(AvailableChoice.ESCAPE_HATCH);
}
return newChoices.build();
}
private static Optional<Text> defaultLockedMessage() {
return Optional.of(Text.translatable("blabber:dialogue.locked_choice"));
}
public String getCurrentStateKey() {
return Objects.requireNonNull(this.currentStateKey, () -> this + " has not been initialized !");
}
public boolean isUnskippable() {
return this.template.unskippable();
}
@Override
public String toString() {
return "DialogueStateMachine" + this.getStates();
}
}