Homework 5, due Wednesday, March 10.

When you have finished the assignment below, email your source code to the grader, and post the working applet onto the web. Make sure the grader knows the URL of your web site (it should match the one on the class page - if it doesn't, then tell him so).

For next week I'd like you to put together a simple interactive polygon editor, along the lines of what we discussed in class this week. It should respond to mouse down events by going into one of three modes:

  1. If the user clicks the mouse very close to the vertex of any polygon (s)he has made, then your system should go into a mode in which dragging the mouse drags the location of that vertex (thereby modifying the shape of the polygon).
  2. Otherwise, if the user clicks the mouse down outside of any existing polygon, then the system should begin a new polygon. In this mode, allow the user to left click at successive locations to build up a polygon one vertex at a time.

    The user finishes this mode, indicating that the polygon is complete, by clicking very near to the first vertex. When that happens your system should close the polygon.

    It's ok if you implement your system so that it only works properly with convex polygons.

  3. Otherwise, the user has clicked the mouse inside of some finished polygon. In this mode, the user translates that polygon by dragging the mouse.
Note that you need to be able to detect when a mouse click is very near a vertex, and also when a mouse click is inside of a polygon. As you recall from the last class, detecting when a mouse click is within five pixels of a vertex is done by the following algorithm:
   idNear = -1;
   dsNear = 10000.0;
   for (id = 0 ; id < nVertices ; id++) {
      ds = distanceSquared(mouse, vertex);
      if (ds < 5*5) {
	 idNear = id;
	 dsNear = ds;
   if (idNear >= 0) {
   else {
You can check whether a mouse click location is inside a polygon by any of a number of methods, as we discussed in class. Probably the simplest is to precompute the half-plane coefficients (ie: the coefficients A,B,C that define Ax + By + C >= 0) associated with each edge of the polygon, and to check whether the mouse location is on the "inside" of each of these half-planes.

When I say "precompute", what I mean is that for efficiency, you should only calculate the half-plane equation coefficients at the following times:

  1. when the user has just finished defining the points of a new polygon or
  2. when the user has just finished dragging the vertex of a polygon.
Remember from our last class that you can compute coeffients for the line between (px,py) and (qx,qy) by:
   dx = qx - px
   dy = qy - py
   A = -dy
   B =  dx 
   C =  - ( pxA + pyB )

I'm going to give lots of options for extra credit on this assignment. Feel free to do however many of these you want: