forces.dart 1.77 KB
Newer Older
Matt Perry's avatar
Matt Perry committed
1 2 3 4 5
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:newton/newton.dart';
6

7 8
export 'package:newton/newton.dart' show SpringDescription;

Florian Loitsch's avatar
Florian Loitsch committed
9
/// A factory for simulations.
Matt Perry's avatar
Matt Perry committed
10
abstract class Force {
11 12
  const Force();

13
  Simulation release(double position, double velocity);
Matt Perry's avatar
Matt Perry committed
14 15
}

Florian Loitsch's avatar
Florian Loitsch committed
16
/// A factory for spring-based physics simulations.
Matt Perry's avatar
Matt Perry committed
17
class SpringForce extends Force {
18
  const SpringForce(this.spring, { this.left: 0.0, this.right: 1.0 });
19

Florian Loitsch's avatar
Florian Loitsch committed
20
  /// The description of the spring to be used in the created simulations.
Matt Perry's avatar
Matt Perry committed
21
  final SpringDescription spring;
22

Florian Loitsch's avatar
Florian Loitsch committed
23
  /// Where to put the spring's resting point when releasing left.
24
  final double left;
25

Florian Loitsch's avatar
Florian Loitsch committed
26
  /// Where to put the spring's resting point when releasing right.
27
  final double right;
Matt Perry's avatar
Matt Perry committed
28

Florian Loitsch's avatar
Florian Loitsch committed
29
  /// How pricely to terminate the simulation.
30 31 32 33
  ///
  /// We overshoot the target by this distance, but stop the simulation when
  /// the spring gets within this distance (regardless of how fast it's moving).
  /// This causes the spring to settle a bit faster than it otherwise would.
34
  static const Tolerance tolerance = const Tolerance(
35 36 37 38
    velocity: double.INFINITY,
    distance: 0.01
  );

39
  Simulation release(double position, double velocity) {
40 41
    double target = velocity < 0.0 ? this.left - tolerance.distance
                                   : this.right + tolerance.distance;
42 43
    return new SpringSimulation(spring, position, target, velocity)
      ..tolerance = tolerance;
Matt Perry's avatar
Matt Perry committed
44 45 46
  }
}

47 48 49 50 51 52
final SpringDescription _kDefaultSpringDesc = new SpringDescription.withDampingRatio(
  mass: 1.0,
  springConstant: 500.0,
  ratio: 1.0
);

Florian Loitsch's avatar
Florian Loitsch committed
53
/// A spring force with reasonable default values.
Matt Perry's avatar
Matt Perry committed
54
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);