
import objectdraw.*;
import java.awt.*;

/*
 * Draw spirals on the screen as the mouse is moved.
 * This version includes a more interesting spiral
 * equation:  radius = theta * (1 + m * sin(b * theta))
 *   - m is the magnitude of the wave placed over the
 *       spiral curve
 *   - b is the frequency (or number of bumps) of the
 *       wave placed over the spiral curve.
 * 
 *  This version also uses a linear scale to fade from
 *  blue to red.
 */

public class Spirals extends WindowController {

    private static final double THETA_STEP = 0.1;
    private static final double MAX_THETA = 40 * Math.PI;

    // pick the number of "bumps" and magnitude
    private RandomDoubleGenerator randomBumps = new RandomDoubleGenerator(0.5, 10);
    private RandomDoubleGenerator randomMagnitude = new RandomDoubleGenerator(0.5, 10);

    // Draws a new spiral where the mouse is clicked.
    public void onMouseClick(Location center) {
        canvas.clear();
        Location lastPoint = center;
        
        // I invert the magnitude random number to get a more 
        // interesting distribution of values. (Most magnitudes
        // will then be < 1, with some between 1-2.)  
        double magnitude = 1 / randomMagnitude.nextValue();
        double bumps = randomBumps.nextValue();
        
        double theta = 0;
        while (theta < MAX_THETA) {
            double radius = theta * (1 + Math.sin(bumps * theta) * magnitude);

            // Convert polar to cartesian
            Location newPoint = 
                new Location(center.getX() + radius * Math.cos(theta),
                             center.getY() + radius * Math.sin(theta));

            Line line = new Line(lastPoint, newPoint, canvas);
            
            // Compute the color of the line segment
            // When theta is small, we want very little red
            //   and lots of blue.  As theta grows, the opposite
            //   is true.  the (int)(...) is a type cast to
            //   force Java to treat a double value as an int.
            int red = (int)(255 * theta / MAX_THETA);
            line.setColor(new Color(red,0,255-red));
            
            lastPoint = newPoint;
            theta = theta + THETA_STEP;
        }
    }
}
