I've just exported my Eclipse project to a runnable jar file. I have no lag issues when I run it in Eclipse, but have extreme lag when running it in the jar. (Running MacOSX 10.9.4)
According to my FPS counter, I'm getting over 900 frames a second, and the game is actually running, but nothing is actually being rendered for a while.
Not sure what code to show because there is a lot of it, as it is an almost completed game. But let me know what code you might need.
Here's my game loop:
public void run() {
long start = System.nanoTime();
final double numUpdates = 30.0;
double ns = 1000000000 / numUpdates;
double delta = 0;
int updates = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while(running) {
long current = System.nanoTime();
delta += (current - start) / ns;
start = current;
if(delta >= 1) {
update();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer = System.currentTimeMillis();
Window.frame.setTitle("Rage Mage UPS: " + updates + ", FPS: " + frames);
updates = 0;
frames = 0;
}
}
}
render() method:
private void render() {
statusHandler.render(g); // statusHandler is a class that handles the current state of the game
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);
}
I don't think the game loop is the problem though, because I was getting the same issues before with a different loop, and then I changed to this loop, and nothing has changed.
Thanks!
Related
I'm working on a java 2d game, using this simple game loop to cap the FPS and UpdatesPS to 60:
public void run() {
final int MAX_FPS = 60;
final int MAX_UPS = 60;
final double fOPTIMAL_TIME = 1000000000 / MAX_FPS;
final double uOPTIMAL_TIME = 1000000000 / MAX_UPS;
double uDeltaTime = 0, fDeltaTime = 0;
int frames = 0, updates = 0;
long startTime = System.nanoTime();
long timer = System.currentTimeMillis();
// GameLOOP starts here
while (running) {
long currentTime = System.nanoTime();
uDeltaTime += (currentTime - startTime);
fDeltaTime += (currentTime - startTime);
startTime = currentTime;
if (uDeltaTime >= uOPTIMAL_TIME) {
gameUpdate();
updates++;
uDeltaTime -= uOPTIMAL_TIME;
}
if (fDeltaTime >= fOPTIMAL_TIME) {
gameRender();
gameDraw();
frames++;
fDeltaTime -= fOPTIMAL_TIME;
}
if (System.currentTimeMillis() - timer >= 1000) {
fps = frames; //saves the current FPS
ups = updates; //saves the current UPS
updates = 0;
frames = 0;
timer += 1000;
}
}
}
The loop works, but I get only 30 FPS for the first ~10 Seconds after starting the game.
After I wait, the FPS raises up to the wanted 60. I don't have a problem to wait a few seconds to let the program stabilize and reach the wanted framerate. But I can't find the reason like a methode who drops the FPS because it's fetching a big file after startup.
Do you have any idea why my engine needs so long to stabilize the framerate?
Thanks for your help!
I think this should do the trick:
public static void run()
{
final int desiredFPS = 60;
final int desiredUPS = 60;
final long updateThreshold = 1000000000 / desiredUPS;
final long drawThreshold = 1000000000 / desiredFPS;
long lastFPS = 0, lastUPS = 0, lastFPSUPSOutput = 0;
int fps = 0, ups = 0;
loop:
while(true)
{
if((System.nanoTime() - lastFPSUPSOutput) > 1000000000)
{
System.out.println("FPS: " + (double)fps);
System.out.println("UPS: " + (double)ups);
fps = 0;
ups = 0;
lastFPSUPSOutput = System.nanoTime();
}
if((System.nanoTime() - lastUPS) > updateThreshold)
{
lastUPS = System.nanoTime();
updateGame();
ups++;
}
if((System.nanoTime() - lastFPS) > drawThreshold)
{
lastFPS = System.nanoTime();
drawGame();
fps++;
}
// Calculate next frame, or skip if we are running behind
if(!((System.nanoTime() - lastUPS) > updateThreshold || (System.nanoTime() - lastFPS) > drawThreshold))
{
long nextScheduledUP = lastUPS + updateThreshold;
long nextScheduledDraw = lastFPS + drawThreshold;
long minScheduled = Math.min(nextScheduledUP, nextScheduledDraw);
long nanosToWait = minScheduled - System.nanoTime();
// Just in case
if(nanosToWait <= 0)
continue loop;
try
{
Thread.sleep(nanosToWait / 1000000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Edit: I fixed the issue now! The issue was that I was saving the lastFPS/lastUPS after the scene was updated/drawn, and when I set both lastUPS/lastFPS before the scene is drawn/updated, we get the desired fps!Another neat thing about this code is that it doesn't consume a whole cpu core(I measured the difference, your code was consuming 100%, whilest my code only consumed about 10%. If you want to measure it yourself, please note that for some reason, the core on which the code is executed regularly switches(at least this was the case when I measured the code))By the way if you use LWJGL (or have direct access to a windowing library like GLFW) you can activate V-Sync, which would cut your fps down to 60 fps.
I'm fairly new to Swing, and I'm attempting to make a simple game in which, at its current stage, you move a box around with w-a-s-d and it faces the mouse cursor. In terms of those functions, I'm having no issues.
Unfortunately, where I am having issues is with the application stuttering when few actions are being performed.
For example, if I am moving the box around but the cursor is still, the game starts stuttering badly. However, if I wiggle the cursor, the game runs fine.
After some research, it appears that the issue is related to Swing's Component.repaint(). After implementing my understanding of this, though, the stuttering issues are unchanged.
The way I implemented it was by having my abstract base GameObject class extend Component, with all objects displayed in the game being descendants of that class.
In the Game class, the main class of the application, the run function is responsible for updating the objects in the game.
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
if (running) {
render();
}
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
The tick() and render() functions call the handler, which handles all of the objects.
private void tick() {
handler.tick();
}
The Handler class, complete with my additions of repainting the objects. I added repaint after calling both the tick and render functions of the object, but neither had any major effect.
public class Handler {
LinkedList<GameObject> objects = new LinkedList<GameObject>();
public void tick() {
for (int i = 0; i < objects.size(); i++) {
GameObject object = objects.get(i);
object.tick();
object.repaint();
}
}
public void render(Graphics g) {
for (int i = 0; i < objects.size(); i++) {
GameObject object = objects.get(i);
object.render(g);
object.repaint();
}
}
}
So while these changes didn't seem to help the stuttering in my program, something else did - a print statement in the run function, printing a simple string.
I can't for the life of me think how that could possibly be affecting anything, and it certainly isn't a permanent fix, so any advice on the situation would be greatly appreciated
I'm trying to render the positions of multiple fighters onscreen. The relevant code is as follows:
public void run() {
double ns = 1000000000.0 / tps;
double delta = 0;
int frames = 0;
int updates = 0;
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1) {
update();
updates++;
delta--;
}
frame.getContentPane().repaint();
frames++;
if(System.currentTimeMillis() - timer >= 1000) {
timer += 1000;
frame.setTitle(title + " | " + updates + " ups, " + frames + " fps");
frames = 0;
updates = 0;
}
}
stop();
}
private void update() {
if (Math.random() < .1) {
Fighter newFighter = new Fighter();
fighterList.add(newFighter);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g); // paint background
setBackground(Color.BLUE);
System.out.println(fighterList.size());
for (int i = 0; i<fighters; i++) {
System.out.println("Attempted");
g.setColor(Color.GREEN);
g.drawRect((int) fighterList.get(i).xPos,
(int) fighterList.get(i).yPos,
fighterList.get(i).radius,
fighterList.get(i).radius);
System.out.println("Rendered");
}
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setContentPane(new Game());
game.frame.setResizable(false);
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
Issue is, nothing is being drawn to the screen. Additionally, running System.out.println(fighterList.size()); gives different outputs based on where it's run - when run inside paintComponent it always returns zero, wheras when run inside update it returns the proper amount. Is this an issue with scope, or is there something else I'm missing?
Most likely a synchronization issue. Your paintComponent() method is always called from the EDT (Event Dispatch Thread) while your run() method runs in its own separate thread. This is where update() gets called which adds new Fighters to the list.
You need proper synchronization so both (or all) threads will see the same consistent data.
Also since your model (data) may be modified during a repaint, you should also "clone" the model to avoid inconsistent model being painted. Or if you don't want to clone it, synchronize access to the model so it can't get modified while it is painted.
I have created a little program that runs openGL ES 1.1; I also used Log to print my fps.
There is something strange though, when i check the log the fps counter says that each frame i got more than 2000 fps. How is that even possible? If i am not mistake vsync automatically cap your upper frame limit to 60. Thanks in advance.
public class FPSCounter {
long startTime = System.nanoTime();
int frames = 0;
public void logFrame() {
frames++;
if(System.nanoTime() - startTime >= 1000000000) {
Log.d("FPSCounter", "fps: " + frames);
startTime = System.nanoTime();
}
}
}
Reset your counter frames.
if(System.nanoTime() - startTime >= 1000000000) {
Log.d("FPSCounter", "fps: " + frames);
startTime = System.nanoTime();
**frames = 0;**
}
I am writing a game loop, I found the code in the example below here. I have also looked at other ways to do a game loop, such as from this article. I couldn't get any of those ones working though. So I kept with the one from the first link.
What I would like to know:
Is the way I wrote my game loop a good way to do this?
Any suggestions?
Should I be using Thread.sleep(); in my game loop?
Here is my current code:
public void run(){
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
long lastFpsTime = 0;
while(true){
long now = System.nanoTime();
long updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ((double)OPTIMAL_TIME);
lastFpsTime += updateLength;
if(lastFpsTime >= 1000000000){
lastFpsTime = 0;
}
this.updateGame(delta);
this.repaint();
try{
Room.gameTime = (lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000;
System.out.println(Room.gameTime);
Thread.sleep(Room.gameTime);
}catch(Exception e){
}
}
Eventually you'll want to move to something like LWJGL, but let me stress, keep doing what you're doing here for now. It will teach you fundamentals.
Good job on your loop. Looks nice, let me offer a few pointers:
Repaint will not render the screen immediately. It tells the RepaintManager to render when its ready. Use invalidate paintImmediately instead. paintImmediately will block execution until the component has been redrawn so you can measure rendering time.
Thread.sleep typically has a few milliseconds drift. You should be using it to keep your loop from using too much CPU, but make sure you understand if you sleep 10 milliseconds you might sleep 5 milliseconds or you might sleep 20.
Lastly:
double delta = updateLength / ((double)OPTIMAL_TIME);
If updateLength is less than OPTIMAL_TIME, don't call update. In other words, if delta is less than one, don't update. This tutorial explains why better than I ever could.
Overall, it is a good loop, but there are a few missing aspects to what I have found in experience to be the best loop.
You will eventually want to move to LWJGL or some other java game API, but for now, learn the basics of how game-loops work, and what best suits your needs.
Firstly, in answer to one of your points, no. You will do better staying away from
Thread.sleep()
this can stray from the real amount of time you set it to sleep.
e.g. if you set it to sleep for 10 milliseconds, it could sleep the program for 5 to 20 milliseconds.
The second problem I cam immediately see is that you do not have any way to stop the game-loop for a custom stop() method. Try
boolean running = true;
while (running) {
// Your Code Here //
}
Thirdly, you may want to consider changing how you use your delta variable. The way in the code below may be a better use and construction for you.
This is an example of my game-loop that I use in my programs:
#Override
public void run() {
long initialTime = System.nanoTime();
final double timeU = 1000000000 / UPS;
final double timeF = 1000000000 / FPS;
double deltaU = 0, deltaF = 0;
int frames = 0, ticks = 0;
long timer = System.currentTimeMillis();
while (running) {
long currentTime = System.nanoTime();
deltaU += (currentTime - initialTime) / timeU;
deltaF += (currentTime - initialTime) / timeF;
initialTime = currentTime;
if (deltaU >= 1) {
getInput();
update();
ticks++;
deltaU--;
}
if (deltaF >= 1) {
render();
frames++;
deltaF--;
}
if (System.currentTimeMillis() - timer > 1000) {
if (RENDER_TIME) {
System.out.println(String.format("UPS: %s, FPS: %s", ticks, frames));
}
frames = 0;
ticks = 0;
timer += 1000;
}
}
}
the simplest way to refresh repainting could be like this:
public class GameLoop extends JPanel {
private final BufferedImage back_buffer;
bool state = true;
public void init() {
while (state) {
updatePlayer();
delay(5);
}
}
public void delay(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
repaint();
}
and the repaint function is who update all of the graphics
#Override
public void paint(Graphics g) {
super.paint(g);
grapicDoble.setColor(Color.white);
grapicDoble.fillRect(0, 0, 500, 500);
game.reset();
g.drawImage(back_buffer, 0, 0, this);
}