Refactor Engine Methods
Extract method checking for update necessity.
This commit is contained in:
parent
2993b33d9e
commit
e8c1e6ed8b
2 changed files with 112 additions and 16 deletions
|
|
@ -1,5 +1,4 @@
|
|||
import 'dart:html' as html;
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:rules_of_living/src/Simulation.dart';
|
||||
|
||||
|
|
@ -47,31 +46,37 @@ class Engine {
|
|||
}
|
||||
|
||||
void animFrame(num now) {
|
||||
process(now);
|
||||
int elapsed = _elapsed.elapsedMilliseconds;
|
||||
_elapsed.reset();
|
||||
process(elapsed, SAFETY_TIMEOUT, update: this.update, render: this.render);
|
||||
html.window.animationFrame.then(animFrame);
|
||||
}
|
||||
|
||||
void process(num now) {
|
||||
_drawLag += _elapsed.elapsedMilliseconds;
|
||||
_updateLag += _elapsed.elapsedMilliseconds;
|
||||
_elapsed.reset();
|
||||
void process(int elapsed, int timeOut, {Function update, Function render}) {
|
||||
_drawLag += elapsed;
|
||||
_updateLag += elapsed;
|
||||
|
||||
while (_updateLag >= _MS_PER_STEP) {
|
||||
if (_elapsed.elapsedMilliseconds > SAFETY_TIMEOUT) {
|
||||
// TODO stub - give warning etc when this occurs
|
||||
print("ERROR STUCK IN UPDATE LOOP");
|
||||
break;
|
||||
}
|
||||
if (running == true) update();
|
||||
while (running == true &&
|
||||
_shouldUpdate(_updateLag, elapsed, timeOut) == true) {
|
||||
_updateLag -= _MS_PER_STEP;
|
||||
if (update == null) break;
|
||||
update();
|
||||
}
|
||||
|
||||
if (_drawLag >= _MS_PER_FRAME) {
|
||||
render(_updateLag / _MS_PER_STEP);
|
||||
_drawLag = 0;
|
||||
if (render == null) return;
|
||||
render(_updateLag / _MS_PER_STEP);
|
||||
}
|
||||
}
|
||||
|
||||
bool _shouldUpdate(int updateLag, int elapsed, int timeOut) {
|
||||
if (updateLag < _MS_PER_STEP) return false;
|
||||
if (elapsed > timeOut) throw StackOverflowError;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Update Engine Logic
|
||||
///
|
||||
/// Updates the logic of the engine by one tick. Should usually not be called
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue