My StarGenerator Program, and Optomizations...

Hi, I made this little star program in two days, well it woulda been one but I ran out of time.

What this program does, is that it generates how ever many stars u want from the int final STARS, and it then makes that many tiny ovals with various variables in the arrays using many for loops. This program seems to work fine, but I’m looking at optomizing it, and I’m a little confused about my commented out code in main() which controls the renderer, as obvious i did soemthing wrong and all of them seem to make no effect, and they do nothing. Also I want to make this program get higher fps, as it runs at 21 fps for me(2.6Ghz HT, 1.5GB,radeon9800(not sure if this prog even uses the video card…)) with 3200 stars and 40 fps with 1600 stars and 65fps with 800 stars, but the weird thing is that anything below 800 is still 65fps, when the cap is 100fps.

I ran this prog on an old pentium 3 machine (600Mhz, 128MB, onboard gfx) and the loading of the stars was not a few seconds like on my machine, it was MINUTES it was so slow at making the stars, well the comp at school uses java 1.3 i beleive so maybe that is part of the cause, but geeze it is WAY slower at rendering too like 14fps with 800 stars. So i want to optomize the prog, I think it scans too much and it causes major slow down.

My prog:

EDIT: updated code a bit, removed an extra unnecssary for-loop, seemed to increase .5fps lol.

/********************
 * StarField Program
 * Star Generator 
 * v1.0
 *******************/

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class StarField extends Canvas implements Runnable {
	
	Random r = new Random();
	private int rand,rand2;

	Thread a;

	private Image image;
	private Graphics gfx;

	private final int DELAY = 10; // loop delay, target 100fps
	
	private boolean firstRun=true;
	
	private final int STARS = 3200;
	
	private int[] starXpos,starYpos,starSize,starColor,starTwinklePos,starSpeed;
	
	private boolean failPositionTest=false;
	
	private long startTime=0;
	private int Global_I,yMove,fps=0,frameCount=0;
	
	/*StarField Constructor*/
	public StarField() {
		// create a window to display StarField
		JFrame container = new JFrame("StarField Generator v1.0");

		// Set dimentions of the newly created window
		JPanel panel = (JPanel) container.getContentPane();
		panel.setPreferredSize(new Dimension(800, 600));
		panel.setLayout(null);

		// canvas size within the new frame
		setBounds(0, 0, 800, 600);
		panel.add(this);

		// Tells AWT not to bother repainting the canvas since
		// accelerated mode will do it
		setIgnoreRepaint(true);

		// make the window visible
		container.pack();
		container.setResizable(false);
		container.setVisible(true);

		// listens if user closes the window, it will then exit the game
		container.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	public void paint(Graphics g) {
		
		//calculate fps
		frameCount++;
		if (System.currentTimeMillis() > startTime + 1000) {
			startTime = System.currentTimeMillis();
			fps = frameCount;
			frameCount=0;
		}
		
		g.setColor(Color.cyan);
		 
		if (firstRun==true) { g.drawString("L o a d i n g . . .", 10, 20); }
		
		g.drawString("Fps: " + fps, 10, 590); //display calculated fps
		
		for (int i = 0; i < STARS; i++)
		{			
			//scan for color reference
			if (starColor[i]==0) { g.setColor(Color.yellow); }
			if (starColor[i]==1) { g.setColor(Color.orange); }
			if (starColor[i]==2) { g.setColor(Color.red);    }
			if (starColor[i]==3) { g.setColor(Color.cyan);   }
			if (starColor[i]>=4) { 
					//star twinkle effector
					if (starTwinklePos[i]>500)   { g.setColor(Color.darkGray); }
					if (starTwinklePos[i]>=500)  { g.setColor(Color.lightGray);}
					if (starTwinklePos[i]>=5000) {  g.setColor(Color.white);   }
					if (starTwinklePos[i]>=10000){ starTwinklePos[i]=0; g.setColor(Color.darkGray); }
				}
			
			//position maintainer
			if (starXpos[i] >= 800) { starXpos[i]=0;   }
			if (starYpos[i] >= 600) { starYpos[i]=0;   }
			if (starYpos[i] <= 0)   { starYpos[i]=600; }
			
			//minor vertical effector
			rand2 = r.nextInt(101);
			if (rand2==0)
			{
				rand = r.nextInt(5);
				if (rand==0) { yMove=1; }
				if (rand==1) { yMove=-1;}
				if (rand>=2) { yMove=0;}
			}
			else { yMove=0; }
			
			//draw the planet of i from the array
			g.fillOval(starXpos[i]+=starSpeed[i], starYpos[i]+=yMove, starSize[i], starSize[i]);
			
			starTwinklePos[i]++;
		}
	}

	public void run() {
		
		setBackground( Color.black );
		
		if (firstRun==true) { generateStarField(); }
		
		while (true)
		{						
			fpsController();
			repaint();
		}
	}

	public void fpsController() {
		// Thread sleep timer for 10milis, should be around 100fps cap
		try { a.sleep(DELAY); } catch (Exception e) {}
	}
	
	public void generateStarField() {
		
		//System.out.println("generateStarField Initilized.");
		
		//create the star arrays
		starXpos  = new int[STARS];
		starYpos  = new int[STARS];
		starSize  = new int[STARS];
		starColor = new int[STARS];
		starSpeed = new int[STARS];
		starTwinklePos = new int [STARS];
		
		for (int i = 0; i < STARS; i++)
		{
			//generate star x position
			rand = r.nextInt(799)+1;
			starXpos[i] = rand;				//System.out.println("Star" + i + " X POS: " + rand);
			//generate star y position
			rand = r.nextInt(599)+1;
			starYpos[i] = rand;				//System.out.println("Star" + i + " Y POS: " + rand);
			
			//check to insure no star overlaps
			Global_I=i;
			positionCheck(starXpos[i], starYpos[i]); 
			if (positionCheck(starXpos[i], starYpos[i])==false) { i--; System.out.println("Star" + i + " Failed Position Test.");}
			
			//generate star size
			rand = r.nextInt(5); // create high percentage of distant stars
			if (rand!=0) { rand = 1; }
			if (rand==0) { rand = r.nextInt(4)+1; }
			starSize[i] = rand;				//System.out.println("Star" + i + " SIZE: " + rand);
			//generate star color reference
			rand = r.nextInt(21);
			starColor[i] = rand;			//System.out.println("Star" + i + " COLOR REF: " + rand);
			
			rand = r.nextInt(3)+1;
			starSpeed[i] = rand;			//System.out.println("Star" + i + " SPEED: " + rand);
			
			rand = r.nextInt(10001);
			starTwinklePos[i] = rand;		//System.out.println("Star" + i + " TWINKLE PHASE: " + rand);
			
			repaint(); // load effects :)
		}
		
		firstRun=false;
	}
	
	public boolean positionCheck(int x, int y)
	{
		for (int k = STARS-1; k > Global_I; k--)
		{
			if (x==starXpos[k] && y==starYpos[k]) { failPositionTest=true; break; }
		}
		if (failPositionTest==true) { failPositionTest=false; return false; }
		 else return true;
	}

	/***************************************************************************
	 * Creates double buffering double buffering smoothens the animation
	 **************************************************************************/
	public void update(Graphics g) {
		// initialize buffer
		if (image == null) {
			image = createImage(this.getSize().width, this.getSize().height);
			gfx = image.getGraphics();
		}

		// clear screen in background
		gfx.setColor(getBackground());
		gfx.fillRect(0, 0, this.getSize().width, this.getSize().height);

		// draw elements in background
		gfx.setColor(getForeground());
		paint(gfx);

		// draw image on the screen
		g.drawImage(image, 0, 0, this);
	}

	public static void main(String argv[]) {

		StarField prog = new StarField();

		// Begin the StarField program
		//using the run() method. 
		
		//System.setProperty("sun.java2d.opengl","True");
		//System.setProperty("sun.java2d.noddraw","");
		//System.setProperty("sun.java2d.accthreshold", "0");
		//System.setProperty("sun.java2d.ddforcevram", "true");
		
		prog.run();
	}
}

hi,
there are a lot of

integerArray = integer;

which should be

integerArray[i] = integer;

for example:

      for (int i = 0; i < STARS; i++)
      {         
         //scan for color reference
         if (starColor==0) { g.setColor(Color.yellow); }
         if (starColor==1) { g.setColor(Color.orange); }
         if (starColor==2) { g.setColor(Color.red);    }
         if (starColor==3) { g.setColor(Color.cyan);   }

which editor do you use? maybe you should try eclipse.org

this topic seems out of place, -> shared code?

on second thought, if you have just four different speeds at which the stars move, you could draw all stars with the same speed to an image, and then just move/draw the four images. aka http://en.wikipedia.org/wiki/Parallax_scrolling

this would save a hell of a lot callculations :wink:

Actually it is like that, but its odd, for some reason when I pasted the code, it did not put the brackets [.i], i beleive its my mistake that i did not wrap this in [.code][./code] and then it may like have accidently made them ittalic! opps, here it is again… edits post… check it again…

I use eclipse 3.2 btw, and i dont want to draw images, because the white stars twinkle and the user (in the code) can set how many stars to render, and the y axis of each star moves slightly at times.

also i need help on the “nodraw” and other stuff in main.

Take a look at http://www.java-gaming.org/forums/index.php?topic=14988.0.

I think it will give you some ideas.

Ah, you did it in a way that is much more advanced in style. Hmm, your prog generates the stars quickly and the fps is high. Good job!

EDIT: actually i found out that my prog can load up and generate the stars on instant, i removed the debugging print statements, and the program generates the stars immedtiatly now.