-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
ScriptQueue.java
535 lines (456 loc) · 17.3 KB
/
ScriptQueue.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
package com.denizenscript.denizencore.scripts.queues;
import com.denizenscript.denizencore.objects.*;
import com.denizenscript.denizencore.objects.core.DurationTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.objects.core.ScriptTag;
import com.denizenscript.denizencore.scripts.queues.core.TimedQueue;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.DefinitionProvider;
import com.denizenscript.denizencore.utilities.QueueWordList;
import com.denizenscript.denizencore.utilities.debugging.Debuggable;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.utilities.scheduling.AsyncSchedulable;
import com.denizenscript.denizencore.utilities.scheduling.OneTimeSchedulable;
import com.denizenscript.denizencore.utilities.scheduling.Schedulable;
import com.denizenscript.denizencore.DenizenCore;
import com.denizenscript.denizencore.events.ScriptEvent;
import com.denizenscript.denizencore.scripts.ScriptEntry;
import java.util.*;
import java.util.function.Consumer;
public abstract class ScriptQueue implements Debuggable, DefinitionProvider {
protected static long total_queues = 0;
public static String getStats() {
StringBuilder stats = new StringBuilder();
for (ScriptEvent event : ScriptEvent.events) {
if (event.stats.fires > 0) {
stats.append("Event '" + event.getName() + "' ran "
+ event.stats.fires + " times (" + event.stats.scriptFires + " script fires)"
+ ", totalling " + ((float) event.stats.nanoTimes / 1000000f) + "ms, averaging "
+ ((float) event.stats.nanoTimes / 1000000f / (float) event.stats.fires) + "ms per event or " +
+((float) event.stats.nanoTimes / 1000000f / (float) event.stats.scriptFires) + "ms per script.\n");
}
}
return "Total number of queues created: "
+ total_queues
+ ", currently active queues: "
+ allQueues.size() + ",\n" + stats.toString();
}
public static ScriptQueue getExistingQueue(String id) {
if (!queueExists(id)) {
return null;
}
else {
return allQueues.get(id);
}
}
public static String getNextId(String prefix) {
// DUUIDs v2.1
int size = QueueWordList.FinalWordList.size();
String id = prefix + "_"
+ QueueWordList.FinalWordList.get(CoreUtilities.getRandom().nextInt(size))
+ QueueWordList.FinalWordList.get(CoreUtilities.getRandom().nextInt(size))
+ QueueWordList.FinalWordList.get(CoreUtilities.getRandom().nextInt(size));
// DUUIDs v3.1
/*
String id = prefix.replace(' ', '_')
+ "_"
+ randomEntry(QueueWordList.Pronouns)
+ randomEntry(QueueWordList.Verbs)
+ randomEntry(QueueWordList.Modifiers)
+ randomEntry(QueueWordList.Adjectives)
+ randomEntry(QueueWordList.Nouns);*/
return allQueues.containsKey(id) ? getNextId(prefix) : id;
}
protected static Map<String, ScriptQueue> allQueues = new LinkedHashMap<>();
public static Collection<ScriptQueue> getQueues() {
return allQueues.values();
}
public static boolean queueExists(String id) {
return allQueues.containsKey(id);
}
/////////////////////
// Public instance fields
/////////////////////
public String id;
public String debugId;
public boolean was_cleared = false;
public boolean run_async = false;
/**
* Optional secondary debug output method.
*/
public Consumer<String> debugOutput = null;
/////////////////////
// Private instance fields and constructors
/////////////////////
public final List<ScriptEntry> script_entries = new ArrayList<>();
private ScriptEntry lastEntryExecuted = null;
/**
If this number is larger than DenizenCore.serverTimeMillis, the queue will delay execution of the next ScriptEntry.
*/
private long delay_time = 0;
private final HashMap<String, ObjectTag> definitions = new HashMap<>();
public ListTag determinations = null;
private final HashMap<String, ScriptEntry> held_entries = new HashMap<>();
public ScriptTag script;
protected ScriptQueue(String id) {
this.id = id;
generateId(id);
total_queues++;
}
protected ScriptQueue(String id, boolean async) {
this(id);
this.run_async = async;
}
/////////////////////
// Public instance setters and getters
/////////////////////
public ScriptEntry getHeldScriptEntry(String id) {
return held_entries.get(CoreUtilities.toLowerCase(id));
}
public ScriptQueue holdScriptEntry(String id, ScriptEntry entry) {
held_entries.put(CoreUtilities.toLowerCase(id), entry);
return this;
}
public ObjectTag getContext(String id) {
id = CoreUtilities.toLowerCase(id);
if (contextSource == null) {
return null;
}
ObjectTag obj = cachedContext.get(id);
if (obj != null) {
return obj;
}
obj = contextSource.getContext(id);
if (obj != null && contextSource.getShouldCache()) {
cachedContext.put(id, obj);
}
return obj;
}
public ContextSource contextSource = null;
public HashMap<String, ObjectTag> cachedContext;
public void setContextSource(ContextSource source) {
contextSource = source;
cachedContext = new HashMap<>();
}
@Override
public ObjectTag getDefinitionObject(String definition) {
if (definition == null) {
return null;
}
return definitions.get(CoreUtilities.toLowerCase(definition));
}
@Override
public String getDefinition(String definition) {
if (definition == null) {
return null;
}
return CoreUtilities.stringifyNullPass(definitions.get(CoreUtilities.toLowerCase(definition)));
}
@Override
public boolean hasDefinition(String definition) {
return definitions.containsKey(CoreUtilities.toLowerCase(definition));
}
public void addDefinition(String definition, ObjectTag value) {
definitions.put(CoreUtilities.toLowerCase(definition), value);
}
@Override
public void addDefinition(String definition, String value) {
definitions.put(CoreUtilities.toLowerCase(definition), new ElementTag(value));
}
@Override
public void removeDefinition(String definition) {
definitions.remove(CoreUtilities.toLowerCase(definition));
}
@Override
public Map<String, ObjectTag> getAllDefinitions() {
return definitions;
}
public ScriptEntry getLastEntryExecuted() {
return lastEntryExecuted;
}
public void clear() {
was_cleared = true;
script_entries.clear();
}
public void delayUntil(long delayTime) {
this.delay_time = delayTime;
}
///////////////////
// Public 'functional' methods
//////////////////
public void generateId(String prefix) {
if (prefix.startsWith("FORCE:")) {
id = prefix.substring("FORCE:".length());
debugId = id;
return;
}
// DUUIDs v2.1
int size = QueueWordList.FinalWordList.size();
String wordOne = QueueWordList.FinalWordList.get(CoreUtilities.getRandom().nextInt(size));
String wordTwo = QueueWordList.FinalWordList.get(CoreUtilities.getRandom().nextInt(size));
String wordThree = QueueWordList.FinalWordList.get(CoreUtilities.getRandom().nextInt(size));
id = prefix + "_" + wordOne + wordTwo + wordThree;
if (queueExists(id)) {
generateId(prefix);
return;
}
String colorOne = DenizenCore.getImplementation().getRandomColor();
String colorTwo = DenizenCore.getImplementation().getRandomColor();
String colorThree = DenizenCore.getImplementation().getRandomColor();
debugId = prefix + "_" + colorOne + wordOne + colorTwo + wordTwo + colorThree + wordThree;
}
public ScriptQueue replacementQueue = null;
/**
* Converts any queue type to a timed queue.
*
* @param delay how long to delay initially.
* @return the newly created queue.
*/
public TimedQueue forceToTimed(DurationTag delay) {
Runnable r = callback;
callback = null;
stop();
TimedQueue newQueue = new TimedQueue(id, 0);
replacementQueue = newQueue;
newQueue.id = id;
newQueue.debugId = debugId;
newQueue.run_async = this.run_async;
newQueue.debugOutput = this.debugOutput;
for (ScriptEntry entry : getEntries()) {
entry.setInstant(true);
entry.setSendingQueue(newQueue);
}
newQueue.addEntries(getEntries());
for (Map.Entry<String, ObjectTag> def : getAllDefinitions().entrySet()) {
newQueue.addDefinition(def.getKey(), def.getValue());
}
newQueue.setContextSource(contextSource);
newQueue.cachedContext = cachedContext;
for (Map.Entry<String, ScriptEntry> entry : held_entries.entrySet()) {
newQueue.holdScriptEntry(entry.getKey(), entry.getValue());
}
newQueue.setLastEntryExecuted(getLastEntryExecuted());
clear();
if (delay != null) {
newQueue.delayFor(delay);
}
newQueue.script = script;
newQueue.callBack(r);
newQueue.start();
newQueue.startTime = startTime;
newQueue.startTimeMilli = startTimeMilli;
return newQueue;
}
protected abstract void onStart();
public boolean is_started;
public long startTime = 0;
public long startTimeMilli = 0;
public String getName() {
return "UnidentifiedQueueType";
}
public void runMeNow() {
startTime = System.nanoTime();
startTimeMilli = System.currentTimeMillis();
onStart();
}
public void queueDebug(String message) {
Debug.echoDebug(this, "<O>" + message.replace("<QUEUE>", debugId + "<O>"));
}
public void start() {
if (is_started) {
return;
}
if (script_entries.isEmpty()) {
return;
}
allQueues.put(id, this);
is_started = true;
long delay = delay_time - DenizenCore.serverTimeMillis;
boolean is_delayed = delay > 0;
script = script_entries.get(0).getScript();
String name = getName();
if (is_delayed) {
queueDebug("Delaying " + name + " '<QUEUE>'" + " for '"
+ new DurationTag(((double) delay) / 1000f).identify() + "'...");
}
else {
queueDebug("Starting " + name + " '<QUEUE>'" + DenizenCore.getImplementation().queueHeaderInfo(script_entries.get(0)) + "...");
}
if (is_delayed) {
Schedulable schedulable = new OneTimeSchedulable(new Runnable() {
@Override
public void run() {
runMeNow();
}
}, ((float) delay) / 1000);
if (run_async) {
schedulable = new AsyncSchedulable(schedulable);
}
DenizenCore.schedule(schedulable);
}
else {
if (!run_async) {
runMeNow();
}
else {
AsyncSchedulable.executor.execute(new Runnable() {
@Override
public void run() {
runMeNow();
}
});
}
}
}
/**
* Immediately runs a list of entries within the script queue.
* Primarily used as a simple method of instant command injection.
*
* @param entries the entries to be run.
*/
public String runNow(List<ScriptEntry> entries) {
ScriptEntry nextup = getQueueSize() > 0 ? getEntry(0) : null;
injectEntries(entries, 0);
while (getQueueSize() > 0 && getEntry(0) != nextup && !was_cleared) {
getEntry(0).setInstant(true);
getEntry(0).setFinished(true);
DenizenCore.getScriptEngine().revolveOnceForce(this);
}
return null;
}
private Runnable callback = null;
/**
* Adds a runnable to call back when the queue is completed.
*
* @param r the Runnable to call back
*/
public void callBack(Runnable r) {
callback = r;
}
protected abstract void onStop();
public boolean is_stopping = false;
public void stop() {
if (!is_stopping) {
is_stopping = true;
List<ScriptEntry> entries = (lastEntryExecuted != null && lastEntryExecuted.getScript() != null ?
lastEntryExecuted.getScript().getContainer().getEntries(lastEntryExecuted.entryData.clone(), "on queue completes") : null);
if (entries != null && !entries.isEmpty()) {
script_entries.addAll(entries);
queueDebug("Finishing up queue '<QUEUE>'...");
}
else {
if (allQueues.get(id) == this) {
allQueues.remove(id);
}
queueDebug("Completing queue '<QUEUE>' in " + ((System.nanoTime() - startTime) / 1000000) + "ms.");
if (callback != null) {
callback.run();
}
is_started = false;
onStop();
}
}
else {
if (allQueues.get(id) == this) {
allQueues.remove(id);
queueDebug("Re-completing queue '<QUEUE>' in " + ((System.nanoTime() - startTime) / 1000000) + "ms.");
if (callback != null) {
callback.run();
}
is_started = false;
onStop();
}
}
}
////////////////////
// Internal methods and fields
////////////////////
public void setLastEntryExecuted(ScriptEntry entry) {
lastEntryExecuted = entry;
}
protected abstract boolean shouldRevolve();
protected void revolve() {
if (script_entries.isEmpty()) {
stop();
return;
}
if (!shouldRevolve()) {
return;
}
DenizenCore.getScriptEngine().revolve(this);
if (script_entries.isEmpty()) {
stop();
}
}
public ScriptEntry getNext() {
if (!script_entries.isEmpty()) {
return script_entries.remove(0);
}
else {
return null;
}
}
public ScriptQueue addEntries(List<ScriptEntry> entries) {
script_entries.addAll(entries);
return this;
}
public List<ScriptEntry> getEntries() {
return script_entries;
}
public boolean hasInjectedItems = false;
public ScriptQueue injectEntries(List<ScriptEntry> entries, int position) {
if (position > script_entries.size() || position < 0) {
position = 1;
}
if (script_entries.size() == 0) {
position = 0;
}
script_entries.addAll(position, entries);
hasInjectedItems = true;
return this;
}
public boolean removeEntry(int position) {
if (script_entries.size() < position) {
return false;
}
script_entries.remove(position);
return true;
}
public ScriptEntry getEntry(int position) {
if (script_entries.size() < position) {
return null;
}
return script_entries.get(position);
}
public ScriptQueue injectEntry(ScriptEntry entry, int position) {
if (position > script_entries.size() || position < 0) {
position = 1;
}
if (script_entries.size() == 0) {
position = 0;
}
script_entries.add(position, entry);
hasInjectedItems = true;
return this;
}
public int getQueueSize() {
return script_entries.size();
}
// DEBUGGABLE
//
@Override
public boolean shouldDebug() {
return (lastEntryExecuted != null ? lastEntryExecuted.shouldDebug()
: script_entries.get(0).shouldDebug());
}
@Override
public boolean shouldFilter(String criteria) throws Exception {
return (lastEntryExecuted != null ? lastEntryExecuted.getScript().getName().equalsIgnoreCase(criteria.replace("s@", ""))
: script_entries.get(0).getScript().getName().equalsIgnoreCase(criteria.replace("s@", "")));
}
@Override
public String toString() {
return id;
}
}