1 /**
  2  * Constructs a new bound constraint. Before the constraint can be used, the
  3  * {@link #x} and {@link #y} methods must be call to specify the bounds.
  4  *
  5  * @class Constrains particles to within fixed rectangular bounds. For example,
  6  * this constraint can be used to constrain particles in a physics simulation
  7  * within the bounds of an enclosing panel.
  8  *
  9  * <p>Note that the current implementation treats particles as points, with no
 10  * area. If the particles are rendered as dots, be sure to include some
 11  * additional padding to inset the bounds such that the edges of the dots do not
 12  * get clipped by the panel bounds. If the particles have different radii, this
 13  * constraint would need to be extended using a radius function, similar to
 14  * {@link pv.Constraint.collision}.
 15  *
 16  * @see pv.Layout.Force
 17  * @extends pv.Constraint
 18  */
 19 pv.Constraint.bound = function() {
 20   var constraint = {},
 21       x,
 22       y;
 23 
 24   /**
 25    * Sets or gets the bounds on the x-coordinate.
 26    *
 27    * @function
 28    * @name pv.Constraint.bound.prototype.x
 29    * @param {number} min the minimum allowed x-coordinate.
 30    * @param {number} max the maximum allowed x-coordinate.
 31    * @returns {pv.Constraint.bound} this.
 32    */
 33   constraint.x = function(min, max) {
 34     if (arguments.length) {
 35       x = {min: Math.min(min, max), max: Math.max(min, max)};
 36       return this;
 37     }
 38     return x;
 39   };
 40 
 41   /**
 42    * Sets or gets the bounds on the y-coordinate.
 43    *
 44    * @function
 45    * @name pv.Constraint.bound.prototype.y
 46    * @param {number} min the minimum allowed y-coordinate.
 47    * @param {number} max the maximum allowed y-coordinate.
 48    * @returns {pv.Constraint.bound} this.
 49    */
 50   constraint.y = function(min, max) {
 51     if (arguments.length) {
 52       y = {min: Math.min(min, max), max: Math.max(min, max)};
 53       return this;
 54     }
 55     return y;
 56   };
 57 
 58   /**
 59    * Applies this constraint to the specified particles.
 60    *
 61    * @function
 62    * @name pv.Constraint.bound.prototype.apply
 63    * @param {pv.Particle} particles particles to which to apply this constraint.
 64    */
 65   constraint.apply = function(particles) {
 66     if (x) for (var p = particles; p; p = p.next) {
 67       p.x = p.x < x.min ? x.min : (p.x > x.max ? x.max : p.x);
 68     }
 69     if (y) for (var p = particles; p; p = p.next) {
 70       p.y = p.y < y.min ? y.min : (p.y > y.max ? y.max : p.y);
 71     }
 72   };
 73 
 74   return constraint;
 75 };
 76