UNPKG

1.54 kBJavaScriptView Raw
1"use strict";
2
3var timeAccumulator = require("time-accumulator");
4
5module.exports = function(entities, simulation, simulationStepTime, renderer, context) {
6 var run = timeAccumulator(simulationStepTime);
7 var timeDelta = require("./absolute-to-relative")();
8 var running = true;
9
10 // run simulation the first time, because not enough time will have elapsed
11 simulation.run(entities, 0);
12
13 var remainingDebugTime;
14 window.timeSystems = function(total) {
15 simulation.resetTimings();
16 renderer.resetTimings();
17 remainingDebugTime = total;
18 };
19 function trackDebugTiming(elapsed) {
20 if (remainingDebugTime === undefined) {
21 return;
22 }
23 remainingDebugTime -= elapsed;
24 if (remainingDebugTime > 0) {
25 return;
26 }
27 remainingDebugTime = undefined;
28
29 var timings = simulation.timings().concat(renderer.timings());
30 var total = timings.map(function(timing) {
31 return timing.time;
32 }).reduce(function(a, b) {
33 return a + b;
34 });
35 timings.sort(function(a, b) {
36 return b.time - a.time;
37 }).forEach(function(timing) {
38 timing.percent = timing.time / total;
39 });
40 console.table(timings);
41 }
42
43 function render(time) {
44 if (!running) {
45 return;
46 }
47
48 var elapsed = timeDelta(time);
49 run(elapsed, function(elapsed) {
50 simulation.run(entities, elapsed);
51 });
52
53 context.save();
54 renderer.run(entities, context, elapsed);
55 context.restore();
56
57 trackDebugTiming(elapsed);
58
59 if (running) {
60 window.requestAnimationFrame(render);
61 }
62 }
63 window.requestAnimationFrame(render);
64
65 return function() {
66 running = false;
67 };
68};