MovingBlocks/Terasology — pull request #887 by mkienenb (2014-01-31 15:46:07+00:00)
Title: Major sub systems headless

Here's another step toward headless now that the previous patch was submitted.

I know we want to continue using TimerLwjgl, but I still needed a lwjgl-free version of the code to insure that I hadn't missed any lwjgl dependencies when running in headless mode.

Futhermore, when I looked at the Sys implementation of the two timer methods, I found that what TimerSystem does is identical (minus the * 1000 / 1000) to Sys for both linux and mac. Only windows does it differently.

// Linux/Mac/J2SE
public long getTimerResolution() {
return 1000;
}
public long getTime() {
return System.currentTimeMillis();
}

// Windows
public long getTimerResolution() {
return 1000;
}
public long getTime() {
return nGetTime();
}
private static native long nGetTime();

I traced through the source code here:
http://jiggles.googlecode.com/svn-history/r6/trunk/Jiggles/lib/lwjgl-2.4.2/src/native/windows/org_lwjgl_Sys.c

JNIEXPORT jlong JNICALL Java_org_lwjgl_WindowsSysImplementation_nGetTime(JNIEnv * env, jclass unused) {
DWORD time;

timeBeginPeriod(1);
time = timeGetTime();
timeEndPeriod(1);

return time;

and eventually arrived at this:

http://msdn.microsoft.com/en-us/library/windows/desktop/dd757629%28v=vs.85%29.aspx

Doing a little bit more research turned up this:

http://stackoverflow.com/questions/1245388/timer-accuracy-in-java

nanoTime

public static long nanoTime()

Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

So if we switch over to nanoTime(), we should improve timer performance on linux/mac and continue to have the same high performance that we may-or-may-not have had on windows.

@Override
public long getRawTimeInMs() {
return System.nanoTime() / 1000000L;
}

Here's some tricks to deal with converting from nanos to millis if we think that might be an issue, but I'm guessing it's fine as-is since we were already multiplying then dividing by 1000.

http://stackoverflow.com/questions/1269994/nanoseconds-to-milliseconds-fast-division-by-1000000

But I will test whether we can simply keep using lwjgl's timer in a future revision since that was what was requested previously.