-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
DenizenCore.java
327 lines (295 loc) · 11.7 KB
/
DenizenCore.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
package com.denizenscript.denizencore;
import com.denizenscript.denizencore.events.ScriptEvent;
import com.denizenscript.denizencore.events.core.*;
import com.denizenscript.denizencore.flags.SavableMapFlagTracker;
import com.denizenscript.denizencore.objects.ObjectFetcher;
import com.denizenscript.denizencore.objects.core.SecretTag;
import com.denizenscript.denizencore.objects.notable.NoteManager;
import com.denizenscript.denizencore.scripts.ScriptHelper;
import com.denizenscript.denizencore.scripts.ScriptRegistry;
import com.denizenscript.denizencore.scripts.commands.CommandRegistry;
import com.denizenscript.denizencore.scripts.commands.queue.RunLaterCommand;
import com.denizenscript.denizencore.scripts.containers.ScriptContainer;
import com.denizenscript.denizencore.scripts.queues.core.TimedQueue;
import com.denizenscript.denizencore.tags.Attribute;
import com.denizenscript.denizencore.tags.ReplaceableTagEvent;
import com.denizenscript.denizencore.tags.TagManager;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.ReflectionHelper;
import com.denizenscript.denizencore.utilities.debugging.*;
import com.denizenscript.denizencore.utilities.scheduling.AsyncSchedulable;
import com.denizenscript.denizencore.utilities.scheduling.OneTimeSchedulable;
import com.denizenscript.denizencore.utilities.scheduling.Schedulable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
/**
* The entry point of the core Denizen engine.
*/
public class DenizenCore {
/**
* (Automatically populated) current core version.
*/
public final static String VERSION;
/**
* All commands known to the system are registered here.
*/
public static CommandRegistry commandRegistry = new CommandRegistry();
/**
* Monotonic time (CoreUtilities.monotonicMillis) that the engine first loaded.
*/
public final static long startTime = CoreUtilities.monotonicMillis();
/**
* Server flags, for the 'flag' command and 'server.flag[...]' tags.
*/
public static SavableMapFlagTracker serverFlagMap;
/**
* Last monotonic time (CoreUtilities.monotonicMillis) that scripts wre reloaded.
*/
public static long lastReloadTime;
/**
* How many times scripts have been reloaded.
*/
public static int reloads = 0;
/**
* Helper to intercept System.out for the redirect_logging mechanism.
*/
public static LogInterceptor logInterceptor = new LogInterceptor();
/**
* Known main thread reference, for async scheduler usage.
*/
public static Thread MAIN_THREAD;
/**
* Current system time (System.currentTimeMillis), updated per-tick.
* Used to avoid multiple checks in the same tick having different time values.
*/
public static long currentTimeMillis = System.currentTimeMillis();
/**
* Current monotonic time (System.nanoTime), updated per-tick.
* Used to avoid multiple checks in the same tick having different time values.
*/
public static long currentTimeMonotonicMillis = CoreUtilities.monotonicMillis();
/**
* Duration of time, in milliseconds, since the server started.
*/
public static long serverTimeMillis = 1;
/**
* All current scheduled tasks.
*/
public static final ArrayList<Schedulable> scheduled = new ArrayList<>();
/**
* All current delayed queues.
*/
public static final ArrayList<TimedQueue> timedQueues = new ArrayList<>();
/**
* Implementation helper class, must be implemented for Denizen to function.
*/
public static DenizenImplementation implementation;
static {
String version = "UNKNOWN";
try {
InputStream is = DenizenCore.class.getClassLoader().getResourceAsStream("denizencore.properties");
if (is == null) {
throw new FileNotFoundException("denizencore.properties not found in jar file");
}
else {
Properties properties = new Properties();
properties.load(is);
version = properties.getProperty("version") + " (Build " + properties.getProperty("build") + ")";
is.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
VERSION = version;
}
/**
* Must be called first: prepares the engine!
*
* @param implementation your Denizen implementation.
*/
public static void init(DenizenImplementation implementation) {
currentTimeMillis = System.currentTimeMillis();
currentTimeMonotonicMillis = CoreUtilities.monotonicMillis();
DenizenCore.implementation = implementation;
MAIN_THREAD = Thread.currentThread();
Debug.log("Initializing Denizen Core v" + VERSION + ", impl for " + implementation.getImplementationName() + " v" + implementation.getImplementationVersion());
ScriptRegistry._registerCoreTypes();
ScriptEvent.registerCoreEvents();
ObjectFetcher.registerCoreObjects();
TagManager.registerCoreTags();
commandRegistry.registerCoreCommands();
DebugSubmitter.init();
ReflectionHelper.hasInitialized = true;
}
/**
* Call to reload anything that was saved, especially after init.
*/
public static void reloadSaves() {
serverFlagMap = SavableMapFlagTracker.loadFlagFile(new File(implementation.getDataFolder(), "server_flags").getPath(), true);
SecretTag.load();
}
/**
* Call to save anything that needs to be saved, especially before shutdown.
*/
public static void saveAll(boolean lockUntilDone) {
NoteManager.save(lockUntilDone);
serverFlagMap.saveToFile(new File(implementation.getDataFolder(), "server_flags").getPath(), lockUntilDone);
}
/**
* Must be called last: performs final shutdowns / saves / etc.
*/
public static void shutdown() {
ShutdownScriptEvent.instance.fire();
saveAll(true);
logInterceptor.standardOutput();
commandRegistry.disableCoreMembers();
}
/**
* Call postLoadScripts after.
*/
public static void preloadScripts(boolean delayable, Runnable onFinished) {
try {
reloads++;
final long start = CoreUtilities.monotonicMillis();
ScriptHelper.resetError();
ScriptHelper.reloadScripts(delayable, () -> {
PreScriptReloadScriptEvent.instance.fire();
ScriptEvent.worldContainers.clear();
implementation.preScriptReload();
}, (midpoint) -> {
long completion = CoreUtilities.monotonicMillis();
Debug.log("Scripts loaded! File load took <A>" + (midpoint - start) + "<W>ms, processing <A>" + (completion - midpoint) + "<W>ms.");
if (onFinished != null) {
onFinished.run();
}
});
}
catch (Exception ex) {
Debug.echoError("Error loading scripts:");
Debug.echoError(ex);
}
}
/**
* Called last in the init sequence, loads all scripts and starts the Denizen engine.
* Call preloadScripts first.
*/
public static void postLoadScripts() {
try {
TagManager.preCalced.clear();
Attribute.attribsLookup.clear();
ReplaceableTagEvent.refs.clear();
ScriptRegistry.postLoadScripts();
for (ScriptContainer container : ScriptRegistry.scriptContainers.values()) {
container.postCheck();
}
ScriptEvent.reload();
implementation.onScriptReload();
lastReloadTime = CoreUtilities.monotonicMillis();
ScriptsLoadedScriptEvent.instance.hadError = ScriptHelper.hadError();
ScriptsLoadedScriptEvent.instance.fire();
}
catch (Exception ex) {
Debug.echoError("Error loading scripts:");
Debug.echoError(ex);
}
}
/**
* Call when a script reload is required (EG, requested by user command).
*/
public static void reloadScripts(boolean delayable, Runnable onFinished) {
preloadScripts(delayable, () -> {
postLoadScripts();
ReloadScriptsScriptEvent.instance.hadError = ScriptHelper.hadError();
ReloadScriptsScriptEvent.instance.fire();
if (onFinished != null) {
onFinished.run();
}
});
}
/**
* Schedule an item to be run automatically after a given period of time, optionally repeating.
*/
public static void schedule(Schedulable sched) {
synchronized (scheduled) {
scheduled.add(sched);
}
}
/** Returns true if called from the thread that DenizenCore understands to be the main thread, or false if on a different thread. */
public static boolean isMainThread() {
Thread curThread = Thread.currentThread();
return curThread.equals(MAIN_THREAD) || curThread.equals(TagManager.tagThread);
}
/** Runs the task immediately if called on main thread, or later if called off-thread. */
public static void runOnMainThread(Runnable run) {
if (isMainThread()) {
run.run();
}
else {
schedule(new OneTimeSchedulable(run, 0));
}
}
/** Runs the task on a separate thread. */
public static void runAsync(Runnable run) {
AsyncSchedulable.executor.execute(run);
}
/**
* Ran by 'tick' once per second.
*/
static void oncePerSecond() {
SystemTimeScriptEvent.instance.checkTime();
DeltaTimeScriptEvent.instance.checkTime();
}
/**
* Counter for 'oncePerSecond'.
*/
static int tMS = 0;
/**
* Call every 'tick' in the engine. (1/20th of a second on a standard engine.)
*
* @param ms_elapsed how many MS have actually elapsed. (50 on a standard engine).
*/
public static void tick(int ms_elapsed) {
DebugInternals.onTick();
serverTimeMillis += ms_elapsed;
currentTimeMillis = System.currentTimeMillis();
currentTimeMonotonicMillis = CoreUtilities.monotonicMillis();
TickScriptEvent.instance.ticks++;
if (TickScriptEvent.instance.eventData.isEnabled) {
TickScriptEvent.instance.fire();
}
RunLaterCommand.tickFutureRuns();
tMS += ms_elapsed;
while (tMS > 1000) {
tMS -= 1000;
oncePerSecond();
}
synchronized (scheduled) {
for (int i = 0; i < scheduled.size(); i++) {
Schedulable current = scheduled.get(i);
try {
if (!current.tick((float) ms_elapsed / 1000)) {
scheduled.remove(i--);
}
}
catch (Throwable ex) {
Debug.echoError("DenizenCore - Scheduler item failed");
Debug.echoError(ex);
if (current instanceof OneTimeSchedulable) {
scheduled.remove(i--);
}
}
}
}
for (int i = 0; i < timedQueues.size(); i++) {
TimedQueue queue = timedQueues.get(i);
queue.tryRevolveOnce();
if (queue.isStopped) {
timedQueues.remove(i--);
}
}
}
}