package matrix; import java.lang.Math; // Matrix2D for making transformations // to 2D Vectors (Vector2D) // including rotations and scales. // These transformation can be applied // on other transformation to make composite // transformations. public class Matrix2D extends Matrix { public Matrix2D() { super(2); //{{INIT_CONTROLS //}} } public Matrix2D(Matrix M) throws MatrixDimensionError { super(2); copy(M); } // create a transformation matrix which when applied // to a Vector2D(X, Y) yeilds Vector2D(X*x, Y*y). public static Matrix2D scale(double x, double y) { Matrix2D scale = new Matrix2D(); scale.setCell(0, 0, x); scale.setCell(1, 1, y); return scale; } public static Matrix2D scale(Vector2D v) { return scale(v.x(), v.y()); } // create a transformation matrix which rotates // a Vector2D in a right-handed way // (1, 0) -> (cos, sin) // (0, 1) -> (-sin, cos) public static Matrix2D rotate(double radians) { Matrix2D rot = new Matrix2D(); double cosine = Math.cos(radians); double sine = Math.sin(radians); rot.setCell(0, 0, cosine); rot.setCell(0, 1, sine); rot.setCell(1, 0, -sine); rot.setCell(1, 1, cosine); return rot; } /* scalar multiplication */ public static Matrix2D mult(Matrix2D M, double a) { Matrix2D result = new Matrix2D(); result.copy(M); result.selfMult(a); return result; } public Matrix mult(double a) { return mult(this, a); } /* vector multiplication */ public Vector2D applyOn(Vector2D v2) { // equivalent to Vector2D(Matrix.mult(this, v2)) // but optimized for the 2D case and no conversion needed. return new Vector2D(cell(0, 0) * v2.x() + cell(1, 0) * v2.y(), cell(0, 1) * v2.x() + cell(1, 1) * v2.y()); } /* matrix multiplication */ public Matrix2D applyOn(Matrix2D M2) { // equivalent to Vector2D(Matrix.mult(this, v2) // but optimized for the 2D case and no conversion needed. Matrix2D result = new Matrix2D(); for (int j = 0; j < 2; j++) for (int i = 0; i < 2; i++) result.setCell(i, j, cell(0, j) * M2.cell(i, 0) + cell(1, j) * M2.cell(i, 1)); return result; } public Matrix2Dh applyOn(Matrix2Dh M2) { // equivalent to Matrix2Dh(Matrix.mult(Matrix2Dh(this), M2)) // but optimized for the 2Dh case and no conversion needed. return Matrix2Dh.apply(this, M2); } //{{DECLARE_CONTROLS //}} }