-
-
Notifications
You must be signed in to change notification settings - Fork 294
/
Citizens.java
471 lines (419 loc) · 16.1 KB
/
Citizens.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
463
464
465
466
467
468
469
470
471
package net.citizensnpcs;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import net.citizensnpcs.Settings.Setting;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.CitizensPlugin;
import net.citizensnpcs.api.ai.speech.SpeechFactory;
import net.citizensnpcs.api.command.CommandContext;
import net.citizensnpcs.api.command.CommandManager;
import net.citizensnpcs.api.command.CommandManager.CommandInfo;
import net.citizensnpcs.api.command.Injector;
import net.citizensnpcs.api.event.CitizensDisableEvent;
import net.citizensnpcs.api.event.CitizensEnableEvent;
import net.citizensnpcs.api.event.CitizensPreReloadEvent;
import net.citizensnpcs.api.event.CitizensReloadEvent;
import net.citizensnpcs.api.event.DespawnReason;
import net.citizensnpcs.api.exception.NPCLoadException;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.npc.NPCDataStore;
import net.citizensnpcs.api.npc.NPCRegistry;
import net.citizensnpcs.api.npc.SimpleNPCDataStore;
import net.citizensnpcs.api.scripting.EventRegistrar;
import net.citizensnpcs.api.scripting.ObjectProvider;
import net.citizensnpcs.api.scripting.ScriptCompiler;
import net.citizensnpcs.api.trait.TraitFactory;
import net.citizensnpcs.api.util.Messaging;
import net.citizensnpcs.api.util.NBTStorage;
import net.citizensnpcs.api.util.Storage;
import net.citizensnpcs.api.util.Translator;
import net.citizensnpcs.api.util.YamlStorage;
import net.citizensnpcs.commands.AdminCommands;
import net.citizensnpcs.commands.EditorCommands;
import net.citizensnpcs.commands.NPCCommands;
import net.citizensnpcs.commands.TemplateCommands;
import net.citizensnpcs.commands.TraitCommands;
import net.citizensnpcs.commands.WaypointCommands;
import net.citizensnpcs.editor.Editor;
import net.citizensnpcs.npc.CitizensNPCRegistry;
import net.citizensnpcs.npc.CitizensTraitFactory;
import net.citizensnpcs.npc.NPCSelector;
import net.citizensnpcs.npc.ai.speech.Chat;
import net.citizensnpcs.npc.ai.speech.CitizensSpeechFactory;
import net.citizensnpcs.npc.profile.ProfileFetcher;
import net.citizensnpcs.npc.skin.Skin;
import net.citizensnpcs.util.Messages;
import net.citizensnpcs.util.NMS;
import net.citizensnpcs.util.PlayerUpdateTask;
import net.citizensnpcs.util.StringHelper;
import net.citizensnpcs.util.Util;
import net.milkbowl.vault.economy.Economy;
public class Citizens extends JavaPlugin implements CitizensPlugin {
private final CommandManager commands = new CommandManager();
private boolean compatible;
private Settings config;
private CitizensNPCRegistry npcRegistry;
private NPCDataStore saves;
private NPCSelector selector;
private CitizensSpeechFactory speechFactory;
private final Map<String, NPCRegistry> storedRegistries = Maps.newHashMap();
private CitizensTraitFactory traitFactory;
@Override
public NPCRegistry createAnonymousNPCRegistry(NPCDataStore store) {
return new CitizensNPCRegistry(store);
}
@Override
public NPCRegistry createNamedNPCRegistry(String name, NPCDataStore store) {
NPCRegistry created = new CitizensNPCRegistry(store);
storedRegistries.put(name, created);
return created;
}
private NPCDataStore createStorage(File folder) {
Storage saves = null;
String type = Setting.STORAGE_TYPE.asString();
if (type.equalsIgnoreCase("nbt")) {
saves = new NBTStorage(new File(folder + File.separator + Setting.STORAGE_FILE.asString()),
"Citizens NPC Storage");
}
if (saves == null) {
saves = new YamlStorage(new File(folder, Setting.STORAGE_FILE.asString()), "Citizens NPC Storage");
}
if (!saves.load())
return null;
return SimpleNPCDataStore.create(saves);
}
private void despawnNPCs() {
Iterator<NPC> itr = npcRegistry.iterator();
while (itr.hasNext()) {
NPC npc = itr.next();
try {
npc.despawn(DespawnReason.RELOAD);
} catch (Throwable e) {
e.printStackTrace();
// ensure that all entities are despawned
}
itr.remove();
}
}
private void enableSubPlugins() {
File root = new File(getDataFolder(), Setting.SUBPLUGIN_FOLDER.asString());
if (!root.exists() || !root.isDirectory())
return;
File[] files = root.listFiles();
for (File file : files) {
Plugin plugin;
try {
plugin = Bukkit.getPluginManager().loadPlugin(file);
} catch (Exception e) {
continue;
}
if (plugin == null)
continue;
// code beneath modified from CraftServer
try {
Messaging.logTr(Messages.LOADING_SUB_PLUGIN, plugin.getDescription().getFullName());
plugin.onLoad();
} catch (Throwable ex) {
Messaging.severeTr(Messages.ERROR_INITALISING_SUB_PLUGIN, ex.getMessage(),
plugin.getDescription().getFullName());
ex.printStackTrace();
}
}
NMS.loadPlugins();
}
public CommandInfo getCommandInfo(String rootCommand, String modifier) {
return commands.getCommand(rootCommand, modifier);
}
public Iterable<CommandInfo> getCommands(String base) {
return commands.getCommands(base);
}
@Override
public net.citizensnpcs.api.npc.NPCSelector getDefaultNPCSelector() {
return selector;
}
@Override
public NPCRegistry getNamedNPCRegistry(String name) {
return storedRegistries.get(name);
}
@Override
public Iterable<NPCRegistry> getNPCRegistries() {
return new Iterable<NPCRegistry>() {
@Override
public Iterator<NPCRegistry> iterator() {
return new Iterator<NPCRegistry>() {
Iterator<NPCRegistry> stored;
@Override
public boolean hasNext() {
return stored == null ? true : stored.hasNext();
}
@Override
public NPCRegistry next() {
if (stored == null) {
stored = storedRegistries.values().iterator();
return npcRegistry;
}
return stored.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
@Override
public NPCRegistry getNPCRegistry() {
return npcRegistry;
}
public NPCSelector getNPCSelector() {
return selector;
}
@Override
public ClassLoader getOwningClassLoader() {
return getClassLoader();
}
@Override
public File getScriptFolder() {
return new File(getDataFolder(), "scripts");
}
@Override
public SpeechFactory getSpeechFactory() {
return speechFactory;
}
@Override
public TraitFactory getTraitFactory() {
return traitFactory;
}
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String cmdName, String[] args) {
String modifier = args.length > 0 ? args[0] : "";
if (!commands.hasCommand(command, modifier) && !modifier.isEmpty()) {
return suggestClosestModifier(sender, command.getName(), modifier);
}
NPC npc = selector == null ? null : selector.getSelected(sender);
// TODO: change the args supplied to a context style system for
// flexibility (ie. adding more context in the future without
// changing everything)
Object[] methodArgs = { sender, npc };
return commands.executeSafe(command, args, sender, methodArgs);
}
@Override
public void onDisable() {
Bukkit.getPluginManager().callEvent(new CitizensDisableEvent());
Editor.leaveAll();
if (compatible) {
saves.storeAll(npcRegistry);
saves.saveToDiskImmediate();
despawnNPCs();
npcRegistry = null;
NMS.shutdown();
}
CitizensAPI.shutdown();
}
@Override
public void onEnable() {
setupTranslator();
CitizensAPI.setImplementation(this);
config = new Settings(getDataFolder());
// Disable if the server is not using the compatible Minecraft version
String mcVersion = Util.getMinecraftRevision();
compatible = true;
try {
NMS.loadBridge(mcVersion);
} catch (Exception e) {
compatible = false;
if (Messaging.isDebugging()) {
e.printStackTrace();
}
Messaging.severeTr(Messages.CITIZENS_INCOMPATIBLE, getDescription().getVersion(), mcVersion);
getServer().getPluginManager().disablePlugin(this);
return;
}
registerScriptHelpers();
saves = createStorage(getDataFolder());
if (saves == null) {
Messaging.severeTr(Messages.FAILED_LOAD_SAVES);
getServer().getPluginManager().disablePlugin(this);
return;
}
npcRegistry = new CitizensNPCRegistry(saves);
traitFactory = new CitizensTraitFactory();
selector = new NPCSelector(this);
speechFactory = new CitizensSpeechFactory();
speechFactory.register(Chat.class, "chat");
getServer().getPluginManager().registerEvents(new EventListen(storedRegistries), this);
if (Setting.NPC_COST.asDouble() > 0) {
setupEconomy();
}
registerCommands();
enableSubPlugins();
// Setup NPCs after all plugins have been enabled (allows for multiworld
// support and for NPCs to properly register external settings)
if (getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
saves.loadInto(npcRegistry);
Messaging.logTr(Messages.NUM_LOADED_NOTIFICATION, Iterables.size(npcRegistry), "?");
startMetrics();
scheduleSaveTask(Setting.SAVE_TASK_DELAY.asInt());
Bukkit.getPluginManager().callEvent(new CitizensEnableEvent());
new PlayerUpdateTask().runTaskTimer(Citizens.this, 0, 1);
}
}, 1) == -1) {
Messaging.severeTr(Messages.LOAD_TASK_NOT_SCHEDULED);
getServer().getPluginManager().disablePlugin(this);
}
}
@Override
public void onImplementationChanged() {
Messaging.severeTr(Messages.CITIZENS_IMPLEMENTATION_DISABLED);
Bukkit.getPluginManager().disablePlugin(this);
}
public void registerCommandClass(Class<?> clazz) {
try {
commands.register(clazz);
} catch (Throwable ex) {
Messaging.logTr(Messages.CITIZENS_INVALID_COMMAND_CLASS);
ex.printStackTrace();
}
}
private void registerCommands() {
commands.setInjector(new Injector(this));
// Register command classes
commands.register(AdminCommands.class);
commands.register(EditorCommands.class);
commands.register(NPCCommands.class);
commands.register(TemplateCommands.class);
commands.register(TraitCommands.class);
commands.register(WaypointCommands.class);
}
private void registerScriptHelpers() {
ScriptCompiler compiler = CitizensAPI.getScriptCompiler();
compiler.registerGlobalContextProvider(new EventRegistrar(this));
compiler.registerGlobalContextProvider(new ObjectProvider("plugin", this));
}
public void reload() throws NPCLoadException {
Editor.leaveAll();
config.reload();
despawnNPCs();
ProfileFetcher.reset();
Skin.clearCache();
getServer().getPluginManager().callEvent(new CitizensPreReloadEvent());
saves = createStorage(getDataFolder());
saves.loadInto(npcRegistry);
getServer().getPluginManager().callEvent(new CitizensReloadEvent());
}
@Override
public void removeNamedNPCRegistry(String name) {
storedRegistries.remove(name);
}
private void scheduleSaveTask(int delay) {
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
storeNPCs();
saves.saveToDisk();
}
}, delay, delay);
}
private void setupEconomy() {
try {
RegisteredServiceProvider<Economy> provider = Bukkit.getServicesManager().getRegistration(Economy.class);
if (provider != null && provider.getProvider() != null) {
Economy economy = provider.getProvider();
Bukkit.getPluginManager().registerEvents(new PaymentListener(economy), this);
}
} catch (NoClassDefFoundError e) {
Messaging.logTr(Messages.ERROR_LOADING_ECONOMY);
}
}
private void setupTranslator() {
Locale locale = Locale.getDefault();
String setting = Setting.LOCALE.asString();
if (!setting.isEmpty()) {
String[] parts = setting.split("[\\._]");
switch (parts.length) {
case 1:
locale = new Locale(parts[0]);
break;
case 2:
locale = new Locale(parts[0], parts[1]);
break;
case 3:
locale = new Locale(parts[0], parts[1], parts[2]);
break;
default:
break;
}
}
Translator.setInstance(new File(getDataFolder(), "lang"), locale);
}
private void startMetrics() {
try {
Metrics metrics = new Metrics(Citizens.this);
if (metrics.isOptOut())
return;
metrics.addCustomData(new Metrics.Plotter("Total NPCs") {
@Override
public int getValue() {
if (npcRegistry == null)
return 0;
return Iterables.size(npcRegistry);
}
});
metrics.addCustomData(new Metrics.Plotter("Total goals") {
@Override
public int getValue() {
if (npcRegistry == null)
return 0;
int goalCount = 0;
for (NPC npc : npcRegistry) {
goalCount += Iterables.size(npc.getDefaultGoalController());
}
return goalCount;
}
});
traitFactory.addPlotters(metrics.createGraph("traits"));
metrics.start();
} catch (IOException e) {
Messaging.logTr(Messages.METRICS_ERROR_NOTIFICATION, e.getMessage());
}
}
public void storeNPCs() {
if (saves == null)
return;
for (NPC npc : npcRegistry) {
saves.store(npc);
}
}
public void storeNPCs(CommandContext args) {
storeNPCs();
boolean async = args.hasFlag('a');
if (async) {
saves.saveToDisk();
} else {
saves.saveToDiskImmediate();
}
}
private boolean suggestClosestModifier(CommandSender sender, String command, String modifier) {
String closest = commands.getClosestCommandModifier(command, modifier);
if (!closest.isEmpty()) {
sender.sendMessage(ChatColor.GRAY + Messaging.tr(Messages.UNKNOWN_COMMAND));
sender.sendMessage(StringHelper.wrap(" /") + command + " " + StringHelper.wrap(closest));
return true;
}
return false;
}
}