/*
 * the star module
 * makes stars on the background
 * Burton Rosenberg
 * May 2004
 */

import java.awt.Dimension ;

// concept:

//    project on an [-N,N] x [-N,N] raster a star
//    selected on a [-M,M] x [-M,M] world at location z
//    there is a current z, and initially the star is
//    at z + INITIAL_DISTANCE. 

//    at each time step increment current z, project star 
//    onto the raster by dividing the star's x and y
//    by the diistance to the star (z_s - z).

//    remove star (and generate another) when either the
//    star projects off the raster or (z_s-z) is less then
//    FINAL_DISTANCE.

// difficulty:

//    TheView might not be ready all the time.

class StarModule {

    private final static int NUM_STARS = 40 ;
    private final static int INITIAL_DISTANCE = 100 ;
    private final static int FINAL_DISTANCE = 10 ;
    private final static int RASTER_TO_WORLD_MULT = 15 ;

    int [] starX ;
    int [] starY ;
    int [] starZ ;

    int [] projectedX ;
    int [] projectedY ;

    int currentZ ;

    int rasterX, rasterY ;
    int worldX, worldY ;
   
    StarModule () {

        starX = new int[NUM_STARS] ;
        starY = new int[NUM_STARS] ;
        starZ = new int[NUM_STARS] ;

        projectedX = new int[NUM_STARS] ;
        projectedY = new int[NUM_STARS] ;

    }

    private void makeNewStar( int starIndex ) {
        starX[starIndex] = (int)(2.0 * Math.random() * worldX) - worldX ;
        starY[starIndex] = (int)(2.0 * Math.random() * worldY) - worldY ;
       
        starZ[starIndex] = currentZ + FINAL_DISTANCE + 
                (int)(Math.random() * INITIAL_DISTANCE) ;
    }

    void moveStars(Dimension d) {

         rasterX = d.width/2 ;
         rasterY = d.height/2 ;
         worldX = rasterX * RASTER_TO_WORLD_MULT ;
         worldY = rasterY * RASTER_TO_WORLD_MULT ;
         currentZ ++ ;

         for ( int i=0; i<starX.length; i++ ) {
             if ( starZ[i] - currentZ < FINAL_DISTANCE ) {
                  makeNewStar(i) ;
             }
             else { 
                projectedX[i] = starX[i] / ( starZ[i] - currentZ ) + rasterX ;
                projectedY[i] = starY[i] / ( starZ[i] - currentZ ) + rasterY ;
                // check if star should be removed.
                if ( projectedX[i] > d.width ||
                  projectedX[i] < 0 ||
                  projectedY[i] > d.height  ||
                  projectedY[i] < 0 ) 
                {
                  // replace star
                  makeNewStar(i) ;
                }
             }
         }
      }
}

