-
-
Notifications
You must be signed in to change notification settings - Fork 294
/
GuidedWaypointProvider.java
462 lines (409 loc) · 17.1 KB
/
GuidedWaypointProvider.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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package net.citizensnpcs.trait.waypoint;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import ch.ethz.globis.phtree.PhDistanceL;
import ch.ethz.globis.phtree.PhFilterDistance;
import ch.ethz.globis.phtree.PhTree;
import ch.ethz.globis.phtree.PhTree.PhKnnQuery;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.ai.Goal;
import net.citizensnpcs.api.ai.GoalSelector;
import net.citizensnpcs.api.astar.AStarGoal;
import net.citizensnpcs.api.astar.AStarMachine;
import net.citizensnpcs.api.astar.AStarNode;
import net.citizensnpcs.api.astar.Agent;
import net.citizensnpcs.api.astar.Plan;
import net.citizensnpcs.api.command.CommandContext;
import net.citizensnpcs.api.command.CommandMessages;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.persistence.PersistenceLoader;
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.Messaging;
import net.citizensnpcs.npc.ai.NPCHolder;
import net.citizensnpcs.trait.waypoint.WaypointProvider.EnumerableWaypointProvider;
import net.citizensnpcs.util.Messages;
import net.citizensnpcs.util.Util;
/**
* Stores guided waypoint info. Guided waypoints are a list of {@link Waypoint}s that will be navigated between
* randomly. Helper waypoints can be used to guide navigation between the random waypoints i.e. navigating between guide
* waypoints. For example, you might have a "realistic" NPC that walks between houses using helper waypoints placed
* along the roads.
*/
public class GuidedWaypointProvider implements EnumerableWaypointProvider {
private GuidedAIGoal currentGoal;
private final List<Waypoint> destinations = Lists.newArrayList();
private float distance = -1;
private final List<Waypoint> guides = Lists.newArrayList();
private NPC npc;
private boolean paused;
private final PhTree<Waypoint> tree = PhTree.create(3);
private final PhTree<Waypoint> treePlusDestinations = PhTree.create(3);
public void addDestination(Waypoint waypoint) {
destinations.add(waypoint);
rebuildTree();
}
public void addDestinations(Collection<Waypoint> waypoint) {
destinations.addAll(waypoint);
rebuildTree();
}
public void addGuide(Waypoint helper) {
guides.add(helper);
rebuildTree();
}
public void addGuides(Collection<Waypoint> helper) {
guides.addAll(helper);
rebuildTree();
}
@Override
public WaypointEditor createEditor(final CommandSender sender, CommandContext args) {
if (!(sender instanceof Player)) {
Messaging.sendErrorTr(sender, CommandMessages.MUST_BE_INGAME);
return null;
}
final Player player = (Player) sender;
return new WaypointEditor() {
private final EntityMarkers<Waypoint> markers = new EntityMarkers<Waypoint>();
private boolean showPath = true;
@Override
public void begin() {
if (showPath) {
createWaypointMarkers();
}
Messaging.sendTr(player, Messages.GUIDED_WAYPOINT_EDITOR_BEGIN);
}
private void createWaypointMarkers() {
for (Waypoint waypoint : waypoints()) {
createWaypointMarkerWithData(waypoint);
}
}
private void createWaypointMarkerWithData(Waypoint element) {
Entity entity = markers.createMarker(element, element.getLocation().clone().add(0, 1, 0));
if (entity == null)
return;
((NPCHolder) entity).getNPC().data().setPersistent("waypointhashcode", element.hashCode());
}
@Override
public void end() {
Messaging.sendTr(player, Messages.GUIDED_WAYPOINT_EDITOR_END);
markers.destroyMarkers();
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
if (!event.getPlayer().equals(sender))
return;
if (event.getMessage().equalsIgnoreCase("toggle path")) {
event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), () -> togglePath());
} else if (event.getMessage().equalsIgnoreCase("clear")) {
event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), () -> {
destinations.clear();
guides.clear();
if (showPath) {
markers.destroyMarkers();
}
});
} else if (event.getMessage().startsWith("distance ")) {
event.setCancelled(true);
double d = Double.parseDouble(event.getMessage().replace("distance ", "").trim());
if (d <= 0)
return;
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), () -> {
distance = (float) d;
Messaging.sendTr(sender, Messages.GUIDED_WAYPOINT_EDITOR_DISTANCE_SET, d);
});
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (!event.getPlayer().equals(player) || event.getAction() == Action.PHYSICAL
|| event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK
|| event.getClickedBlock() == null || Util.isOffHand(event))
return;
if (event.getPlayer().getWorld() != npc.getEntity().getWorld())
return;
event.setCancelled(true);
Location at = event.getClickedBlock().getLocation();
for (Waypoint waypoint : waypoints()) {
if (waypoint.getLocation().equals(at)) {
Messaging.sendTr(player, Messages.GUIDED_WAYPOINT_EDITOR_ALREADY_TAKEN);
return;
}
}
Waypoint element = new Waypoint(at);
if (player.isSneaking()) {
destinations.add(element);
Messaging.sendTr(player, Messages.GUIDED_WAYPOINT_EDITOR_ADDED_AVAILABLE);
} else {
guides.add(element);
Messaging.sendTr(player, Messages.GUIDED_WAYPOINT_EDITOR_ADDED_GUIDE);
}
if (showPath) {
createWaypointMarkerWithData(element);
}
rebuildTree();
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
NPC clicked = CitizensAPI.getNPCRegistry().getNPC(event.getRightClicked());
if (clicked == null || Util.isOffHand(event))
return;
Integer hashcode = clicked.data().get("waypointhashcode");
if (hashcode == null)
return;
Iterator<Waypoint> itr = waypoints().iterator();
while (itr.hasNext()) {
Waypoint point = itr.next();
if (point.hashCode() == hashcode) {
markers.removeMarker(point);
itr.remove();
break;
}
}
}
private void togglePath() {
showPath = !showPath;
if (showPath) {
createWaypointMarkers();
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_SHOWING_MARKERS);
} else {
markers.destroyMarkers();
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_NOT_SHOWING_MARKERS);
}
}
};
}
@Override
public boolean isPaused() {
return paused;
}
@Override
public void load(DataKey key) {
DataKey dd = key.keyExists("availablewaypoints") ? key.getRelative("availablewaypoints")
: key.getRelative("destinations");
for (DataKey root : dd.getIntegerSubKeys()) {
Waypoint waypoint = PersistenceLoader.load(Waypoint.class, root);
if (waypoint == null)
continue;
destinations.add(waypoint);
}
DataKey gd = key.keyExists("helperwaypoints") ? key.getRelative("helperwaypoints") : key.getRelative("guides");
for (DataKey root : gd.getIntegerSubKeys()) {
Waypoint waypoint = PersistenceLoader.load(Waypoint.class, root);
if (waypoint == null)
continue;
guides.add(waypoint);
}
if (key.keyExists("distance")) {
distance = (float) key.getDouble("distance");
}
rebuildTree();
}
@Override
public void onRemove() {
if (currentGoal == null)
return;
currentGoal.onProviderChanged();
npc.getDefaultGoalController().removeGoal(currentGoal);
currentGoal = null;
}
@Override
public void onSpawn(NPC npc) {
this.npc = npc;
if (currentGoal == null) {
currentGoal = new GuidedAIGoal();
npc.getDefaultGoalController().addGoal(currentGoal, 1);
}
}
private void rebuildTree() {
tree.clear();
treePlusDestinations.clear();
for (Waypoint waypoint : guides) {
tree.put(new long[] { waypoint.getLocation().getBlockX(), waypoint.getLocation().getBlockY(),
waypoint.getLocation().getBlockZ() }, waypoint);
treePlusDestinations.put(new long[] { waypoint.getLocation().getBlockX(),
waypoint.getLocation().getBlockY(), waypoint.getLocation().getBlockZ() }, waypoint);
}
for (Waypoint waypoint : destinations) {
treePlusDestinations.put(new long[] { waypoint.getLocation().getBlockX(),
waypoint.getLocation().getBlockY(), waypoint.getLocation().getBlockZ() }, waypoint);
}
if (currentGoal != null) {
currentGoal.onProviderChanged();
}
}
@Override
public void save(DataKey key) {
key.removeKey("availablewaypoints");
DataKey root = key.getRelative("destinations");
for (int i = 0; i < destinations.size(); ++i) {
PersistenceLoader.save(destinations.get(i), root.getRelative(i));
}
key.removeKey("helperwaypoints");
root = key.getRelative("guides");
for (int i = 0; i < guides.size(); ++i) {
PersistenceLoader.save(guides.get(i), root.getRelative(i));
}
if (distance != -1) {
key.setDouble("distance", distance);
}
}
@Override
public void setPaused(boolean paused) {
this.paused = paused;
if (currentGoal != null) {
currentGoal.onProviderChanged();
}
}
/**
* Returns destination and guide waypoints.
*/
@Override
public Iterable<Waypoint> waypoints() {
return Iterables.concat(destinations, guides);
}
private class GuidedAIGoal implements Goal {
private GuidedPlan plan;
public void onProviderChanged() {
if (plan == null)
return;
reset();
if (npc.getNavigator().isNavigating()) {
npc.getNavigator().cancelNavigation();
}
}
@Override
public void reset() {
plan = null;
}
@Override
public void run(GoalSelector selector) {
if (plan == null || plan.isComplete()) {
selector.finish();
return;
}
if (npc.getNavigator().isNavigating())
return;
Waypoint current = plan.getCurrentWaypoint();
npc.getNavigator().setTarget(current.getLocation());
npc.getNavigator().getLocalParameters().addSingleUseCallback(cancelReason -> {
if (plan != null) {
plan.update(npc);
}
});
}
@Override
public boolean shouldExecute(GoalSelector selector) {
if (paused || destinations.size() == 0 || !npc.isSpawned() || npc.getNavigator().isNavigating())
return false;
Waypoint target = destinations.get(Util.getFastRandom().nextInt(destinations.size()));
plan = ASTAR.runFully(new GuidedGoal(target), new GuidedNode(null, new Waypoint(npc.getStoredLocation())));
return plan != null;
}
}
private static class GuidedGoal implements AStarGoal<GuidedNode> {
private final Waypoint dest;
public GuidedGoal(Waypoint dest) {
this.dest = dest;
}
@Override
public float g(GuidedNode from, GuidedNode to) {
return (float) from.distance(to.waypoint);
}
@Override
public float getInitialCost(GuidedNode node) {
return h(node);
}
@Override
public float h(GuidedNode from) {
return (float) from.distance(dest);
}
@Override
public boolean isFinished(GuidedNode node) {
return node.waypoint.equals(dest);
}
}
private class GuidedNode extends AStarNode {
private final Waypoint waypoint;
public GuidedNode(GuidedNode parent, Waypoint waypoint) {
super(parent);
this.waypoint = waypoint;
}
@Override
public Plan buildPlan() {
return new GuidedPlan(this.<GuidedNode> getParents());
}
public double distance(Waypoint dest) {
return waypoint.distance(dest);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
GuidedNode other = (GuidedNode) obj;
if (waypoint == null) {
if (other.waypoint != null) {
return false;
}
} else if (!waypoint.equals(other.waypoint)) {
return false;
}
return true;
}
@Override
public Iterable<AStarNode> getNeighbours() {
PhFilterDistance filter = new PhFilterDistance();
filter.set(
new long[] { waypoint.getLocation().getBlockX(), waypoint.getLocation().getBlockY(),
waypoint.getLocation().getBlockZ() },
PhDistanceL.THIS, distance == -1 ? npc.getNavigator().getDefaultParameters().range() : distance);
PhTree<Waypoint> source = getParent() == null ? tree : treePlusDestinations;
PhKnnQuery<Waypoint> res = source.nearestNeighbour(100, PhDistanceL.THIS, filter,
waypoint.getLocation().getBlockX(), waypoint.getLocation().getBlockY(),
waypoint.getLocation().getBlockZ());
List<AStarNode> neighbours = Lists.newArrayList();
res.forEachRemaining(n -> neighbours.add(new GuidedNode(this, n)));
return neighbours;
}
@Override
public int hashCode() {
return 31 + ((waypoint == null) ? 0 : waypoint.hashCode());
}
}
private static class GuidedPlan implements Plan {
private int index = 0;
private final Waypoint[] path;
public GuidedPlan(Iterable<GuidedNode> path) {
this.path = Iterables.toArray(Iterables.transform(path, to -> to.waypoint), Waypoint.class);
}
public Waypoint getCurrentWaypoint() {
return path[index];
}
@Override
public boolean isComplete() {
return index >= path.length;
}
@Override
public void update(Agent agent) {
index++;
}
}
private static final AStarMachine<GuidedNode, GuidedPlan> ASTAR = AStarMachine.createWithDefaultStorage();
}