CPSC 120 -- Assignment #2

Point In Triangle
Due Friday, October 14, 2011 by 4 p.m.

In computer graphics surfaces are often represented using many triangles. Triangles are easier to render into images and with enough triangles, curved surfaces can be approximated. In order to render a collection of triangles into an image that can be displayed, the computer repeatedly performs tests to determine if a point is inside a triangle. For this assignment you will write a program that tests if a point is inside a triangle.

The program should draw a triangle that takes up the majority of the window. You can pick the location of each of the corners, or vertices, of the triangle, but the triangle should re-size with the window. To draw the triangle, use the drawLine method in the Graphics class. The program should also generate and draw a random point to the window. The point should have the potential to be any pixel in the window. To draw the point, draw an x using the drawLine method such that the two lines cross at the location of the point. Finally, the program should draw a string, centered at the top or bottom of the window, that informs the user if the point is inside the triangle, or not.

A point is inside a triangle if it is on the interior side of all three edges of the triangle. For example, the point P in the illustration below is on the interior side of the edge from B to C and the edge from C to A, but it is not on the interior side of the edge from A to B.

It is possible to determine which side of an edge a point is on using the equation:
    s = (V1x - V2x) * (V1y - Py) - (V1y - V2y) * (V1x - Px)
where V1 and V2 are vertices that define an edge of the triangle, and P is a point. The value of s is either positive or negative, depending on which side of the edge the point is on. However, this does not tell you which side is the interior side. Notice that the third vertex of a triangle is always on the interior side of the edge of the first two vertices. Therefore, to compute if a point is on the interior side of an edge compute s for both the point and the third vertex and compare the two values of s. The point is on the interior side if they are both positive, or they are both negative. Note, it is possible to create one if statement that tests if the point is in the triangle, but it would be enormous and difficult to debug. A simpler way to write the program would be to create variables for intermediary calculations, and use the variables in the if statement.

Requirements:

Submit to Inquire: A zip file containing your program.

Academic Integrity Reminder!!! Programming assignments are to be your own work. You may get help on the specifics of the assignment from no one except the instructor. You may not show your program to anyone or look at anyone else's program or share ideas with anyone about how to write the program.