classdef Point < handle
% Operations on points in the plane
properties
% A point has an x and y coordinate
x % the x-coordinate
y % the y-coordinate
end

methods
% Construct a point object...
function P = Point(x,y)
if nargin==2
P.x = x;
P.y = y;
end
end

% Rotation...
function Q = Rotate(ThisPoint,phi)
% Q is a point obtained by rotating ThisPoint by phi degrees
% counterclockwise.
% A call of the form P.Rotate(phi) rotates point P by phi degrees
% counterclockwise
theta = phi*pi/180;
c = cos(theta);
s = sin(theta);
x = ThisPoint.x;
y = ThisPoint.y;
if nargout==1
Q = Point(c*x - s*y, s*x + c*y);
else
ThisPoint.x = c*x - s*y;
ThisPoint.y = s*x + c*y;
end
end

% Translation...
function Q = Translate(ThisPoint,delX,delY)
% Translates ThisPoint by amount delX is the x-direction and delY in
% the y-direction.
% A call of the form P.Translate(delX,delY) translates point P by
% amount delX is the x-direction and delY in the y-direction.
x = ThisPoint.x;
y = ThisPoint.y;
if nargout==1
Q = Point(x+delX,y+delY);
else
ThisPoint.x = x+delX;
ThisPoint.y = y+delY;
end
end

% Distance
function d = Dist(ThisPoint,Q)
% The distance from ThisPoint to object Q.
% Q must be either a Point or a Circle
if strcmp(class(Q),'Point')
d = sqrt((ThisPoint.x-Q.x)^2 + (ThisPoint.y-Q.y)^2);
elseif strcmp(class(Q),'Circle')
d = abs(ThisPoint.Dist(Q.center) - Q.r);
end
end

% Nearest
function P = Nearest(Q,P1,P2)
% Q, P1, and P2 are points.
% P is on the line segment that connects P1 to P2 and is the nearest
% such point to Q.
t = ((Q.x-P1.x)*(P2.x-P1.x)+(Q.y-P1.y)*(P2.y-P1.y))/...
((P2.x-P1.x)^2 + (P2.y-P1.y)^2);
if t<0
P = P1;
elseif t>1
P = P2;
else
P = Point(P1.x+t*(P2.x-P1.x),P1.y+t*(P2.y-P1.y));
end
end

% Separation...
function alfa = DiffSide(ThisPoint,ThatPoint,P1,P2)
% P1 and P2 are distinct points.
% alfa is true if and only if the line through P1 and P2 separates
% ThisPoint and ThatPoint.
p1 = [P1.x P1.y];
p2 = [P2.x P2.y];
q = [ThisPoint.x ThisPoint.y];
r = [ThatPoint.x ThatPoint.y];
f = ((p1(1)-q(1))*(p1(2)-p2(2)) - (p1(2)-q(2))*(p1(1)-p2(1)))/...
((r(1)-q(1)) *(p1(2)-p2(2)) - (r(2)-q(2))* (p1(1)-p2(1)));
alfa = 0<=f && f<=1;
end

% Display
function Show(ThisPoint,color)
% Displays the point ThisPoint.
% The color is specified by the character c.
% Assumes hold is on.
plot(ThisPoint.x,ThisPoint.y,['.' color], 'Markersize',30)
end

end %methods
end %classdef