-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
AbstractNPC.java
436 lines (387 loc) · 13.5 KB
/
AbstractNPC.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
package net.citizensnpcs.api.npc;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.metadata.FixedMetadataValue;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.ai.GoalController;
import net.citizensnpcs.api.ai.SimpleGoalController;
import net.citizensnpcs.api.ai.speech.SimpleSpeechController;
import net.citizensnpcs.api.ai.speech.SpeechController;
import net.citizensnpcs.api.event.DespawnReason;
import net.citizensnpcs.api.event.NPCAddTraitEvent;
import net.citizensnpcs.api.event.NPCRemoveEvent;
import net.citizensnpcs.api.event.NPCRemoveTraitEvent;
import net.citizensnpcs.api.event.NPCTeleportEvent;
import net.citizensnpcs.api.persistence.PersistenceLoader;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.trait.trait.MobType;
import net.citizensnpcs.api.trait.trait.Speech;
import net.citizensnpcs.api.util.Colorizer;
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.MemoryDataKey;
import net.citizensnpcs.api.util.Messaging;
public abstract class AbstractNPC implements NPC {
private final GoalController goalController = new SimpleGoalController();
private final int id;
private final MetadataStore metadata = new SimpleMetadataStore() {
@Override
public void remove(String key) {
super.remove(key);
if (getEntity() != null) {
getEntity().removeMetadata(key, CitizensAPI.getPlugin());
}
}
@Override
public void set(String key, Object data) {
super.set(key, data);
if (getEntity() != null) {
getEntity().setMetadata(key, new FixedMetadataValue(CitizensAPI.getPlugin(), data));
}
}
@Override
public void setPersistent(String key, Object data) {
super.setPersistent(key, data);
if (getEntity() != null) {
getEntity().setMetadata(key, new FixedMetadataValue(CitizensAPI.getPlugin(), data));
}
}
};
private String name;
private final NPCRegistry registry;
private final List<String> removedTraits = Lists.newArrayList();
private final List<Runnable> runnables = Lists.newArrayList();
private final SpeechController speechController = new SimpleSpeechController(this);
protected final Map<Class<? extends Trait>, Trait> traits = Maps.newHashMap();
private final UUID uuid;
protected AbstractNPC(UUID uuid, int id, String name, NPCRegistry registry) {
this.uuid = uuid;
this.id = id;
this.registry = registry;
this.name = name;
CitizensAPI.getTraitFactory().addDefaultTraits(this);
}
@Override
public void addTrait(Class<? extends Trait> clazz) {
addTrait(getTraitFor(clazz));
}
@Override
public void addTrait(Trait trait) {
if (trait == null) {
Messaging.severe("Cannot register a null trait. Was it registered properly?");
return;
}
if (trait.getNPC() == null) {
trait.linkToNPC(this);
}
// if an existing trait is being replaced, we need to remove the
// currently registered runnable to avoid conflicts
Trait replaced = traits.get(trait.getClass());
Bukkit.getPluginManager().registerEvents(trait, CitizensAPI.getPlugin());
traits.put(trait.getClass(), trait);
if (isSpawned())
trait.onSpawn();
if (trait.isRunImplemented()) {
if (replaced != null)
runnables.remove(replaced);
runnables.add(trait);
}
Bukkit.getPluginManager().callEvent(new NPCAddTraitEvent(this, trait));
}
@Override
public NPC clone() {
NPC copy = registry.createNPC(getTrait(MobType.class).getType(), getFullName());
DataKey key = new MemoryDataKey();
save(key);
copy.load(key);
for (Trait trait : copy.getTraits()) {
trait.onCopy();
}
return copy;
}
@Override
public MetadataStore data() {
return this.metadata;
}
@Override
public boolean despawn() {
return despawn(DespawnReason.PLUGIN);
}
@Override
public void destroy() {
Bukkit.getPluginManager().callEvent(new NPCRemoveEvent(this));
runnables.clear();
for (Trait trait : traits.values()) {
HandlerList.unregisterAll(trait);
trait.onRemove();
}
traits.clear();
registry.deregister(this);
goalController.clear();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractNPC other = (AbstractNPC) obj;
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return registry.equals(other.registry);
}
@Override
public GoalController getDefaultGoalController() {
return goalController;
}
@Override
public SpeechController getDefaultSpeechController() {
// TODO: Remove in future versions.
// This is here to add the Speech trait to any existing NPCs
// that were created pre-SpeechController, if invoked.
if (!hasTrait(Speech.class)) {
addTrait(Speech.class);
}
return speechController;
}
@Override
public String getFullName() {
int nameLength = getTrait(MobType.class).getType() == EntityType.PLAYER ? 46 : 64;
if (name.length() > nameLength) {
Messaging.severe("ID", id, "created with name length greater than " + nameLength + ", truncating", name,
"to", name.substring(0, nameLength));
name = name.substring(0, nameLength);
}
return name;
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return Colorizer.stripColors(getFullName());
}
@Override
public NPCRegistry getOwningRegistry() {
return registry;
}
@Override
public <T extends Trait> T getTrait(Class<T> clazz) {
Trait trait = traits.get(clazz);
if (trait == null) {
trait = getTraitFor(clazz);
addTrait(trait);
}
return trait != null ? clazz.cast(trait) : null;
}
protected Trait getTraitFor(Class<? extends Trait> clazz) {
return CitizensAPI.getTraitFactory().getTrait(clazz);
}
@Override
public Iterable<Trait> getTraits() {
return traits.values();
}
@Override
public UUID getUniqueId() {
return uuid;
}
@Override
public int hashCode() {
final int prime = 31;
return prime * (prime + id) + ((name == null) ? 0 : name.hashCode());
}
@Override
public boolean hasTrait(Class<? extends Trait> trait) {
return traits.containsKey(trait);
}
@Override
public boolean isFlyable() {
return data().get(NPC.FLYABLE_METADATA, false);
}
@Override
public boolean isProtected() {
return data().get(NPC.DEFAULT_PROTECTED_METADATA, true);
}
@Override
public boolean isSpawned() {
return getEntity() != null && getEntity().isValid();
}
@Override
public void load(final DataKey root) {
name = root.getString("name");
metadata.loadFrom(root.getRelative("metadata"));
String traitNames = root.getString("traitnames");
Set<DataKey> keys = Sets.newHashSet(root.getRelative("traits").getSubKeys());
Iterables.addAll(keys, Iterables.transform(Splitter.on(',').split(traitNames), new Function<String, DataKey>() {
@Override
public DataKey apply(String input) {
return root.getRelative("traits." + input);
}
}));
for (DataKey traitKey : keys) {
if (traitKey.keyExists("enabled") && !traitKey.getBoolean("enabled")
&& traitKey.getRaw("enabled") instanceof Boolean) {
// avoid YAML coercing map existence to boolean
continue;
}
Class<? extends Trait> clazz = CitizensAPI.getTraitFactory().getTraitClass(traitKey.name());
Trait trait;
if (hasTrait(clazz)) {
trait = getTrait(clazz);
} else {
trait = CitizensAPI.getTraitFactory().getTrait(clazz);
if (trait == null) {
Messaging.severeTr("citizens.notifications.trait-load-failed", traitKey.name(), getId());
continue;
}
addTrait(trait);
}
loadTrait(trait, traitKey);
}
}
private void loadTrait(Trait trait, DataKey traitKey) {
try {
trait.load(traitKey);
PersistenceLoader.load(trait, traitKey);
} catch (Throwable ex) {
Messaging.logTr("citizens.notifications.trait-load-failed", traitKey.name(), getId());
}
}
@Override
public void removeTrait(Class<? extends Trait> traitClass) {
Trait trait = traits.remove(traitClass);
if (trait != null) {
Bukkit.getPluginManager().callEvent(new NPCRemoveTraitEvent(this, trait));
removedTraits.add(trait.getName());
if (trait.isRunImplemented()) {
runnables.remove(trait);
}
HandlerList.unregisterAll(trait);
trait.onRemove();
}
}
@Override
public void save(DataKey root) {
if (!metadata.get(NPC.SHOULD_SAVE_METADATA, true))
return;
metadata.saveTo(root.getRelative("metadata"));
root.setString("name", getFullName());
root.setString("uuid", uuid.toString());
// Save all existing traits
StringBuilder traitNames = new StringBuilder();
for (Trait trait : traits.values()) {
DataKey traitKey = root.getRelative("traits." + trait.getName());
trait.save(traitKey);
PersistenceLoader.save(trait, traitKey);
removedTraits.remove(trait.getName());
traitNames.append(trait.getName() + ",");
}
if (traitNames.length() > 0) {
root.setString("traitnames", traitNames.substring(0, traitNames.length() - 1));
} else {
root.setString("traitnames", "");
}
for (String name : removedTraits) {
root.removeKey("traits." + name);
}
removedTraits.clear();
}
@Override
public void setFlyable(boolean flyable) {
data().setPersistent(NPC.FLYABLE_METADATA, flyable);
}
@Override
public void setName(String name) {
this.name = name;
if (!isSpawned())
return;
Entity bukkitEntity = getEntity();
if (bukkitEntity instanceof LivingEntity) {
((LivingEntity) bukkitEntity).setCustomName(getFullName());
}
if (bukkitEntity.getType() == EntityType.PLAYER) {
Location old = bukkitEntity.getLocation();
despawn(DespawnReason.PENDING_RESPAWN);
spawn(old);
}
}
@Override
public void setProtected(boolean isProtected) {
data().setPersistent(NPC.DEFAULT_PROTECTED_METADATA, isProtected);
}
private void teleport(final Entity entity, Location location, int delay) {
final Entity passenger = entity.getPassenger();
entity.eject();
entity.teleport(location);
if (passenger == null)
return;
teleport(passenger, location, delay++);
Runnable task = new Runnable() {
@Override
public void run() {
entity.setPassenger(passenger);
}
};
if (!location.getWorld().equals(entity.getWorld())) {
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), task, delay);
} else {
task.run();
}
}
@Override
public void teleport(Location location, TeleportCause cause) {
if (!isSpawned())
return;
NPCTeleportEvent event = new NPCTeleportEvent(this, location);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled())
return;
Entity entity = getEntity();
while (entity.getVehicle() != null) {
entity = entity.getVehicle();
}
location.getBlock().getChunk();
teleport(entity, location, 5);
}
protected void unloadEvents() {
runnables.clear();
for (Trait trait : traits.values()) {
HandlerList.unregisterAll(trait);
}
traits.clear();
goalController.clear();
}
public void update() {
for (int i = 0; i < runnables.size(); ++i) {
runnables.get(i).run();
}
if (isSpawned()) {
goalController.run();
}
}
}