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
    /**
     * The main game loop.
     *
     * Heavily inspired by an article by Glenn Fiedler:
     * http://gafferongames.com/game-physics/fix-your-timestep/
     * Design copied (and modified) with permission.
     */
    public void run() {
        display.createBufferStrategy(2);
        BufferStrategy strategy = display.getBufferStrategy();

        long t = 0;
        long dt = UPDATE_RATE_NANOS;
        long currentTime = System.nanoTime();
        long accum = 0;

        while (true) {
            long newTime = System.nanoTime();
            // produced frame time (for consumption)
            long pauseTime = pause();
            long frameTime = newTime - currentTime - pauseTime;
            currentTime = newTime;

            accum += frameTime;

            while (accum >= dt) {
                // consume time
                update(t, dt);  // movement updates are done with an RK4 integrator

                // transfer time from the accumulator
                // to the total (t)
                t += dt;
                accum -= dt;
            }

            double alpha = accum / (double)dt;
            display.setAlpha(alpha);
            // draw the frame
            display.render(strategy);

        }
    }