| OLD | NEW |
| (Empty) |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 import 'dart:async'; | |
| 6 | |
| 7 import '../base/scheduler.dart' as scheduler; | |
| 8 import 'mechanics.dart'; | |
| 9 | |
| 10 abstract class Generator { | |
| 11 Stream<double> get onTick; // TODO(ianh): rename this to tickStream | |
| 12 void cancel(); | |
| 13 } | |
| 14 | |
| 15 class FrameGenerator extends Generator { | |
| 16 Function onDone; | |
| 17 StreamController _controller; | |
| 18 | |
| 19 Stream<double> get onTick => _controller.stream; | |
| 20 | |
| 21 int _animationId = 0; | |
| 22 bool _cancelled = false; | |
| 23 | |
| 24 FrameGenerator({this.onDone}) { | |
| 25 _controller = new StreamController( | |
| 26 sync: true, | |
| 27 onListen: _scheduleTick, | |
| 28 onCancel: cancel); | |
| 29 } | |
| 30 | |
| 31 void cancel() { | |
| 32 if (_cancelled) { | |
| 33 return; | |
| 34 } | |
| 35 if (_animationId != 0) { | |
| 36 scheduler.cancelAnimationFrame(_animationId); | |
| 37 } | |
| 38 _animationId = 0; | |
| 39 _cancelled = true; | |
| 40 if (onDone != null) { | |
| 41 onDone(); | |
| 42 } | |
| 43 } | |
| 44 | |
| 45 void _scheduleTick() { | |
| 46 assert(_animationId == 0); | |
| 47 _animationId = scheduler.requestAnimationFrame(_tick); | |
| 48 } | |
| 49 | |
| 50 void _tick(double timeStamp) { | |
| 51 _animationId = 0; | |
| 52 _controller.add(timeStamp); | |
| 53 if (!_cancelled) { | |
| 54 _scheduleTick(); | |
| 55 } | |
| 56 } | |
| 57 } | |
| 58 | |
| 59 class Simulation extends Generator { | |
| 60 Stream<double> get onTick => _stream; | |
| 61 final System system; | |
| 62 | |
| 63 FrameGenerator _generator; | |
| 64 Stream<double> _stream; | |
| 65 double _previousTime = 0.0; | |
| 66 | |
| 67 Simulation(this.system, {Function terminationCondition, Function onDone}) { | |
| 68 _generator = new FrameGenerator(onDone: onDone); | |
| 69 _stream = _generator.onTick.map(_update); | |
| 70 | |
| 71 if (terminationCondition != null) { | |
| 72 bool done = false; | |
| 73 _stream = _stream.takeWhile((_) { | |
| 74 if (done) | |
| 75 return false; | |
| 76 done = terminationCondition(); | |
| 77 return true; | |
| 78 }); | |
| 79 } | |
| 80 } | |
| 81 | |
| 82 void cancel() { | |
| 83 _generator.cancel(); | |
| 84 } | |
| 85 | |
| 86 double _update(double timeStamp) { | |
| 87 double previousTime = _previousTime; | |
| 88 _previousTime = timeStamp; | |
| 89 if (previousTime == 0.0) | |
| 90 return timeStamp; | |
| 91 double deltaT = timeStamp - previousTime; | |
| 92 system.update(deltaT); | |
| 93 return timeStamp; | |
| 94 } | |
| 95 } | |
| OLD | NEW |