1 31 32 package org.antlr.xjlib.appkit.gview.base; 33 34 import org.antlr.xjlib.foundation.XJXMLSerializable; 35 36 import java.awt.*; 37 import java.awt.geom.Point2D ; 38 39 public class Vector2D implements XJXMLSerializable { 40 41 public double x = 0; 42 public double y = 0; 43 44 public static Vector2D vector(Point p) { 45 return new Vector2D(p.x, p.y); 46 } 47 48 public static Vector2D vector(Point2D p) { 49 return new Vector2D(p.getX(), p.getY()); 50 } 51 52 public Vector2D() { 53 } 54 55 public Vector2D(double x, double y) { 56 this.x = x; 57 this.y = y; 58 } 59 60 public void setX(double x) { 61 this.x = x; 62 } 63 64 public double getX() { 65 return x; 66 } 67 68 public void setY(double y) { 69 this.y = y; 70 } 71 72 public double getY() { 73 return y; 74 } 75 76 public Vector2D setLength(double l) { 77 double ol = length(); 78 if(ol == 0) { 79 x = 0; 80 y = 0; 81 } else { 82 x = x/ol*l; 83 y = y/ol*l; 84 } 85 return this; 86 } 87 88 public double length() { 89 return Math.sqrt(x*x+y*y); 90 } 91 92 public Vector2D stretch(double f) { 93 x *= f; 94 y *= f; 95 return this; 96 } 97 98 public Vector2D shift(double dx, double dy) { 99 x += dx; 100 y += dy; 101 return this; 102 } 103 104 public Vector2D vectorLength(double l) { 105 Vector2D v = this.copy(); 106 v.setLength(l); 107 return v; 108 } 109 110 public Vector2D rotate(double degree) { 111 if(Math.abs(degree) == 90) { 112 double temp = x; 113 x = y; 114 y = temp; 115 if(degree < 0) y = -y; else x = -x; 117 } else { 118 double angle = Math.toRadians(degree); 119 120 double rx = Math.cos(angle)*x-Math.sin(angle)*y; 121 double ry = Math.sin(angle)*x+Math.cos(angle)*y; 122 123 x = rx; 124 y = ry; 125 } 126 return this; 127 } 128 129 public Vector2D normalize() { 130 double r = length(); 131 if(r == 0) 132 return new Vector2D(); 133 else 134 return new Vector2D(x/r, y/r); 135 } 136 137 public Vector2D add(Vector2D v2) { 138 return new Vector2D(x+v2.x, y+v2.y); 139 } 140 141 public Vector2D sub(Vector2D v2) { 142 return new Vector2D(x-v2.x, y-v2.y); 143 } 144 145 public double dot(Vector2D v2) { 146 return x*v2.x+y*v2.y; 147 } 148 149 public double cross(Vector2D v2) { 150 return x*v2.y-y*v2.x; 151 } 152 153 public int crossSign(Vector2D v2) { 154 double cross = cross(v2); 155 if(cross == 0) 156 return 0; 157 else 158 return cross<0?-1:1; 159 } 160 161 public Point toPoint() { 162 return new Point((int)x, (int)y); 163 } 164 165 public boolean equals(Object other) { 166 if(other instanceof Vector2D) { 167 Vector2D otherVector = (Vector2D) other; 168 return otherVector.x == x && otherVector.y == y; 169 } else { 170 return false; 171 } 172 } 173 174 public String toString() { 175 return "<Vector2D: "+x+", "+y+" >"; 176 } 177 178 180 public Vector2D copy() { 181 return new Vector2D(x, y); 182 } 183 184 } 185 | Popular Tags |