001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.wpilibj.drive;
006
007/** This is a 2D vector struct that supports basic vector operations. */
008public class Vector2d {
009  @SuppressWarnings("MemberName")
010  public double x;
011
012  @SuppressWarnings("MemberName")
013  public double y;
014
015  public Vector2d() {}
016
017  public Vector2d(double x, double y) {
018    this.x = x;
019    this.y = y;
020  }
021
022  /**
023   * Rotate a vector in Cartesian space.
024   *
025   * @param angle angle in degrees by which to rotate vector counter-clockwise.
026   */
027  public void rotate(double angle) {
028    double cosA = Math.cos(angle * (Math.PI / 180.0));
029    double sinA = Math.sin(angle * (Math.PI / 180.0));
030    double[] out = new double[2];
031    out[0] = x * cosA - y * sinA;
032    out[1] = x * sinA + y * cosA;
033    x = out[0];
034    y = out[1];
035  }
036
037  /**
038   * Returns dot product of this vector with argument.
039   *
040   * @param vec Vector with which to perform dot product.
041   * @return Dot product of this vector with argument.
042   */
043  public double dot(Vector2d vec) {
044    return x * vec.x + y * vec.y;
045  }
046
047  /**
048   * Returns magnitude of vector.
049   *
050   * @return Magnitude of vector.
051   */
052  public double magnitude() {
053    return Math.sqrt(x * x + y * y);
054  }
055
056  /**
057   * Returns scalar projection of this vector onto argument.
058   *
059   * @param vec Vector onto which to project this vector.
060   * @return scalar projection of this vector onto argument.
061   */
062  public double scalarProject(Vector2d vec) {
063    return dot(vec) / vec.magnitude();
064  }
065}