Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  How to check if v-sync is actually enabled  (Read 2303 times)
0 Members and 1 Guest are viewing this topic.
Offline Grimmov

Senior Newbie





« Posted 2013-10-20 22:35:11 »

I've looked for an answer to this question, but to no avail.

When using a BufferStrategy, how can I check whether VSync is currently enabled? I know that it can be overridden to "off" by graphics driver settings, and some situations may not support it, so I'd like to know when it fails so that I can compensate accordingly within my code.

Bonus question: when using triple buffering, is there any way I can synchronize some logic to the vsync pulse, despite my render thread being able to run at unlimited speed?
Offline opiop65

JGO Kernel


Medals: 161
Projects: 7
Exp: 4 years


JumpButton Studios


« Reply #1 - Posted 2013-10-21 00:19:53 »

Well, your FPS should be locked to a certain frame per second. Most likely 60.

Offline Grimmov

Senior Newbie





« Reply #2 - Posted 2013-10-21 00:32:21 »

Yes, I can tell whether vsync is enabled based on my in-game FPS counter... but making my rendering engine's code depend on the average results of the FPS counter to "guess" whether vsync is enabled seems like a very poor solution. Not to mention, framerate fluctuations could trigger false positives or negatives.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline opiop65

JGO Kernel


Medals: 161
Projects: 7
Exp: 4 years


JumpButton Studios


« Reply #3 - Posted 2013-10-21 00:38:47 »

So then have it always enabled or not. Your code really shouldn't be dependent on vSync anyway. I don't understand what you need to change when vSync is enabled?

Offline Grimmov

Senior Newbie





« Reply #4 - Posted 2013-10-21 01:37:55 »

You can't "always" enable vsync. Sometimes it is not supported or the graphics drivers override it, and then (it seems) there is no way to notice it's off, other than measuring the current framerate.

My rendering engine uses two different scrolling methods; one if vsync is enabled and one if vsync is disabled. The vsync-enabled method looks much nicer because it scrolls at whole pixel intervals per screen refresh, but this makes the scrolling speed (partially) dependent upon the framerate, and should be disabled if vsync is off.

In the end I've settled on measuring whether the current framerate is within +-5% of the monitor's refresh rate. This technique works well because it reverts to the non-vsync method if the rendering rate falls too far below the refresh rate.
Offline opiop65

JGO Kernel


Medals: 161
Projects: 7
Exp: 4 years


JumpButton Studios


« Reply #5 - Posted 2013-10-21 01:43:38 »

Well, I didn't think about that! Sorry about that Smiley
I would wait to see if anyone else has a solution because no offense, but your's seems a little to hackish. There has to be a better way!

The only problem I have with your solution is that well, vSync targets 60 FPS correct? So if your computer is to slow to even render at 60 FPS, then your code would fail, at least I think.

Of course, if you have vSync on and your computer can't handle it, you should probably not even have it on in the first place, so my problem isn't really relevant anymore... I think.

Offline zngga
« Reply #6 - Posted 2013-10-21 01:59:00 »

You could always adjust your scrolling code. The math behind your scroll code should have nothing to do with frame rate what-so-ever. Common technique is delta timing, making movement independent of frame rate by multiplying your math by the time between frames. If you still get issues after that, try flooring your values to Integers when you draw, making them line up with individual pixels nicely.

my two cents.

My code never has bugs... it just develops unexpected features!
Offline opiop65

JGO Kernel


Medals: 161
Projects: 7
Exp: 4 years


JumpButton Studios


« Reply #7 - Posted 2013-10-21 02:19:06 »

You could always adjust your scrolling code. The math behind your scroll code should have nothing to do with frame rate what-so-ever. Common technique is delta timing, making movement independent of frame rate by multiplying your math by the time between frames. If you still get issues after that, try flooring your values to Integers when you draw, making them line up with individual pixels nicely.

my two cents.
Damn I totally forgot about this. Definitely, your code should not be dependent on vSync, it should be dependent on the frame rate. Whether or not you have vSync enabled is irrelevant. Your code should not be hard coded to only scroll this way if vSync is enabled, and the other if it isn't. Just multiply your transition variables by the delta. I don't know if I would floor the transitions to Integers though, because then you would have a more "jumpy" affect. It might not be super noticeable on a fast computer, but on a slower computer, you'll see every single pixel transition, which wouldn't be good.

Offline Grimmov

Senior Newbie





« Reply #8 - Posted 2013-10-21 02:20:34 »

Edit: Modified for clarity.

@zngga: If you want scrolling to be perfectly smooth, simple delta timing isn't good enough. It will result in an inconsistent number of pixels scrolled per frame. Calculating the distance based upon the time delta then flooring/rounding the result works well, but the result is highly dependent upon the current framerate, since it is functionally very similar to scrolling a specified number of pixels per frame (assuming the framerate stays constant). Either way, absolutely smooth scrolling requires moving the same number of pixels per screen refresh; this makes scrolling speed partly to directly proportional to the current framerate while using this technique. And thus, it is only a good idea if the FPS meets four conditions: 1) not too high, 2) not too low, 3) stable, 4) in sync with the monitor's refresh rate to prevent strobe/tearing effects. VSync ensures that all of these conditions are typically true (assuming the framerate does not drop from rendering issues).

This kind of perfectly smooth scrolling is much more apparent in a low-res pixelated 2d game engine, so it isn't much of an issue in higher-res or 3d games. Perhaps you haven't seen just how smooth it can look while using this technique, but it is very impressive. It makes purely delta-based timing look horrible in a side-by-side comparison.

The downside is that if you attempt this kind of scrolling without vsync, it creates an extremely distracting strobe-like effect, in addition to the typical screen tearing issues.

@opiop65: I agree that it is "hackish"... I suppose I will have to give up on detecting actual vsync status since there seems to be no airtight way to do it.

Instead, I will make "smooth scrolling" a graphics option within my game engine, off by default, and recommend its use only if vsync is enabled. Technically illiterate end-users might wind up turning it on without knowing about vsync, and the smooth scrolling effect will have distracting tears and jerks... but if they notice it looks bad, hopefully they will be smart enough to turn it back off.

Offline opiop65

JGO Kernel


Medals: 161
Projects: 7
Exp: 4 years


JumpButton Studios


« Reply #9 - Posted 2013-10-21 02:29:03 »

Wait... how is there no way to detect if vSync is on or not? Just create a boolean and set it to true when you enable it. Why can't you just do that? Or am I missing something blatantly obvious here?

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Grimmov

Senior Newbie





« Reply #10 - Posted 2013-10-21 02:31:45 »

You can't just "enable" vsync, you have to create a bufferstrategy and that object internally decides whether to use it or not based on whether it's possible under the current conditions. There seems to be no way to simply ask it whether it's using vsync or not.
Offline opiop65

JGO Kernel


Medals: 161
Projects: 7
Exp: 4 years


JumpButton Studios


« Reply #11 - Posted 2013-10-21 02:34:08 »

Oh, you're using Java2D. Well then, just restart the game with a new bufferstrategy and enable vSync? Then set the boolean to true? Honestly, I have no idea. I'm just throwing things out there.

Offline Grimmov

Senior Newbie





« Reply #12 - Posted 2013-10-21 02:42:55 »

Whether vsync works or not just depends upon the conditions of the computer that's running the program. Some people have vsync forced to off in their graphics driver options; some computers just don't support it under certain circumstances. There's no perfect way to predict or observe the outcome from within the code (using java2d at least). In the end this just amounts to an extra graphics option that I wanted to automatically enable if vsync was detected, but now I'll have to leave that up to the end user.

I am currently using java2d; perhaps LibGDX has better vsync support? I somehow doubt it, but I'd be pleasantly surprised if it were true. I do plan to switch to it at a certain point, anyway.
Offline zngga
« Reply #13 - Posted 2013-10-21 05:38:06 »

@Grimmov: My friend, welcome to frame clamp loops! (it is what I call them anyway)

I assume that your run loop functions similar to this:
  • Gather input
  • Update the scene
  • Render the scene
  • repeat

What you want to do is remove the frame rates dependence on how fast the game can update. So instead of the above do something similar to this:

target frame rate = 60 frames
time between frames = 1 second / target frame rate

render time = 0;
delta time

start loop

while render time < time between frames,
  record the current time
  gather user input
  update the scene(using delta)
  subtract the recorded time from the current time and set delta equal to it
  then add delta to render time
  As soon as render time becomes equal to, or greater than, time between frames this loop ends and you move on to rendering

render
set render time = 0

repeat



Now your loop keeps updating the scene (doing calculations, gathering user input, and running all your math) until you need to render. Then you render, reset some variables and repeat the process.

obviously the above is not code, but when you implement this right, you get rock solid frame rates, and a loop that preforms the same on most computers (I only say most because there are some dinosaurs out there)

This is a fairly common approach to your problem (not the vsync part, but the reason you think you HAVE to have vsync)
If I wasn't so lazy I would link you to a good post from this forum on game loops, but for now I hope this is helpful.

My code never has bugs... it just develops unexpected features!
Offline Grimmov

Senior Newbie





« Reply #14 - Posted 2013-10-21 10:55:43 »

I've seen it referred to as CPU sync (as opposed to vsync). It clamps framerate to the target interval by waiting to draw each graphics update. I prefer not to use this method, as non-vsync users can actually get a better experience by allowing graphics to update as quickly as possible, even if they are not rendered, as the frame that does get rendered will be more up-to-date this way. It also interferes with vsync because the CPU sync is not perfectly matched to the vsync rate.

I am trying to attain a level of smoothness that goes beyond the typical methods. In the end, I found that the best appearance was achieved by simply using delta-based scrolling combined with rounding the result to the nearest integer. My main problem with this was that extremely high FPS would cause the result to round down to 0. However, I added a check for this and use the non-rounded value when this happens, and all is well. Effectively it is a hybrid of my previous (vsync and non-vsync) approaches that works well regardless of vsync status, however, it only exhibits the actual smooth scrolling effect while vsync is enabled.

If anyone is curious, I've actually gone so far as to use a concurrent rendering thread while waiting for vsync to finish in my quest for smoothness... This basically gives me the benefits of double buffering (every graphics update is pushed to the screen, necessary for smooth scrolling) and triple buffering (game state and certain graphical updates can continue mid-frame) at the same time. Of course, concurrency leads to nightmares, but after a few days studying the concepts I've gotten a handle on it.
Offline Abuse

JGO Knight


Medals: 15


falling into the abyss of reality


« Reply #15 - Posted 2013-10-21 12:57:12 »

Grimmov; the answer is to use a better API.

Java2D has many limitations; its inability to query hardware capabilities is one of the big ones.

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline SHC
« Reply #16 - Posted 2013-10-21 13:42:20 »

If you want to have smoother movement, don't use vsync. vsync is just a technique where the renderer limits the framerate to the refresh rate of the monitor so you don't waste the cpu cycles by doing unnecessary renders which enables more cpu for logic, however this is not required for us. The best thing is to forget about the vsync and do as many renders you can do after one logic and keep constant update rate. An example would be

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
private void gameLoop()
{
    long now = getCurrentTime();
    long gameTime = getCurrentTime();

    long updatesPerSecond = 60;
    long updateRate = updatesPerSecond / 1000;

    long maxFrameSkips = 2;
    long skippedFrames = 0;

    while (gameRunning)
    {
        skippedFrames = 0;
        now = getCurrentTime();

        while (now + updateRate > gameTime && skippedFrames <= maxFrameSkips)
        {
            update();
            gameTime += updateRate;

            skippedFrames++;
        }

        render();
    }
}

This game loop prefers game updates first while doing some frameskipping. After the updates are done, it keeps re-drawing the scene until the next update is required. This gives me a large frame-rate on my pc ranging from 750-790 with Java2D. If you really want to use vsync, just query the refresh rate of the monitor and limit the frame-rate. For example, this gameloop does this.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
private void gameLoop()
{
    long now = getCurrentTime();
    long gameTime = getCurrentTime();

    // Query the monitor refresh rate
    int refreshRate = GraphicsEnvironment.getLocalGraphicsEnivironment().getDefaultScreenDevice.getRefreshRate();

    // update rate
    long updatesPerSecond = refreshRate == DisplayMode.UNKNOWN_REFRESH_RATE ? 60 : refreshRate;
    long updateRate = updatesPerSecond / 1000;

    while (gameRunning)
    {
        now = getCurrentTime();

        while (now + updateRate > gameTime)
        {
            // Use the updateRate as the delta time.
            update(updateRate);
            render();

            gameTime += updateRate;
        }
    }
}

This only does required frames.

Offline Grimmov

Senior Newbie





« Reply #17 - Posted 2013-10-21 14:04:02 »

Grimmov; the answer is to use a better API.

Java2D has many limitations; its inability to query hardware capabilities is one of the big ones.

This is the most correct answer in the thread... I will do this at some point, but I wanted to get the basics of my game sorted in Java2D before switching to a better API, so that I can understand the differences.

@SHC: as I have explained in depth in this thread, the method you have presented is insufficient for my purposes. Vsync with double buffering is the only way to ensure that each frame is rendered to the screen in sequence without skips, which is the only way to perfectly scroll by the same number of pixels per displayed frame. As I mentioned before, "CPU-sync" has its own limitations.
Offline theagentd

« JGO Bitwise Duke »


Medals: 366
Projects: 2
Exp: 8 years



« Reply #18 - Posted 2013-10-23 12:28:18 »

If you want to have smoother movement, don't use vsync. vsync is just a technique where the renderer limits the framerate to the refresh rate of the monitor so you don't waste the cpu cycles by doing unnecessary renders which enables more cpu for logic, however this is not required for us.
Nope. The main point of V-sync is to prevent the GPU from updating the front buffer while it is being sent to the monitor, causing a visible tear where it started reading from the new frame. That it limits the FPS to the refresh rate of the monitor is just a side effect that can be worked around by using triple buffering.

The best thing is to forget about the vsync and do as many renders you can do after one logic and keep constant update rate. An example would be

1  
...

This game loop prefers game updates first while doing some frameskipping. After the updates are done, it keeps re-drawing the scene until the next update is required. This gives me a large frame-rate on my pc ranging from 750-790 with Java2D. If you really want to use vsync, just query the refresh rate of the monitor and limit the frame-rate. For example, this gameloop does this.

1  
...

This only does required frames.

There's a bug in your code.
long updateRate = updatesPerSecond / 1000;
should be
1000 / updatesPerSecond;
, but it still won't be accurate due to integer rounding resulting in 16 instead of 16.6666... causing an update rate of 62,5 instead of 60. Use nano time instead or floating point values.

The first game loop is decent for when a computer can render at <=60 FPS, but there's no point in re-rendering the exact same frame multiple times. If you only have 60 unique frames each second to render, why render at 750 FPS in the first place?

The second game loop has even more problems.
 - You should probably not base the update speed on the screen's refresh rate. Sure, it'll help with getting enough unique frames each second, but things like physics may behave very differently depending on the update rate. Example: I run my monitor at 90Hz, but I can run it at as low as 29Hz, which is a 3x difference in the time step.
 - It'll start slowing down if the computer can't maintain 60 FPS, and if the load lessens afterwards it'll run as fast as it can until it catches up again.
 - Although you're not needlessly rendering duplicate frames, you're instead spinning until it's time for an update. That's a 100% CPU load on one core for no good reason.

For Java2D I'd probably recommend the first game loop since it works well in the most important cases, although it could be improved to only render when there's anything new to render at all. The ultimate solution which handles both low and high frame rates while still having a fixed time step is to use interpolation when rendering to generate unique frames. Probably a bit overkill for a simple 2D game though.


You can read more about game loops in this excellent article: http://gafferongames.com/game-physics/fix-your-timestep/

Myomyomyo.
Offline SHC
« Reply #19 - Posted 2013-10-23 12:43:10 »

@theagentd
Thanks for a long informative post. Also thanks for pointing out that bug, I wrote that post during the college lab and I'm being worried about the chemistry assignment I didn't complete. That ate my mind. I too wondered about the more number of updates than the required, thank you so much for explaining. And finally the article you referenced is very more informative. +1. Why didn't I find that before Huh

Offline kappa
« League of Dukes »

JGO Kernel


Medals: 81
Projects: 15


★★★★★


« Reply #20 - Posted 2013-10-23 15:58:22 »

Speaking of V-Sync, Nvidia's recently announced G-Sync technology sounds like a really great idea, if such a tech does ever get standardised and become widely adopted, should be pretty nice for smooth looking games and solve the age old V-Sync/tearing problems properly.
Offline theagentd

« JGO Bitwise Duke »


Medals: 366
Projects: 2
Exp: 8 years



« Reply #21 - Posted 2013-10-23 19:32:22 »

Speaking of V-Sync, Nvidia's recently announced G-Sync technology sounds like a really great idea, if such a tech does ever get standardised and become widely adopted, should be pretty nice for smooth looking games and solve the age old V-Sync/tearing problems properly.
All the advantages of V-sync without all the disadvantages of V-sync? Oh, yes.

Myomyomyo.
Offline Cero
« Reply #22 - Posted 2013-10-23 19:50:12 »

Speaking of V-Sync, Nvidia's recently announced G-Sync technology sounds like a really great idea, if such a tech does ever get standardised and become widely adopted, should be pretty nice for smooth looking games and solve the age old V-Sync/tearing problems properly.
All the advantages of V-sync without all the disadvantages of V-sync? Oh, yes.

Yeah but it would take a loooooooooooong time for wide adoption.

Offline opiop65

JGO Kernel


Medals: 161
Projects: 7
Exp: 4 years


JumpButton Studios


« Reply #23 - Posted 2013-10-23 21:12:46 »

That just sounds awesome, a supplementary GPU in the monitor? Unfortunately, it probably would be a while before its used widely, but it would be worth it to adopt the technology early. vSync is just nasty... This sounds like it solves all the problems. Guess I should switch over to nvidia now! I didn't read the whole thing, so I don't know if you would need a nvidia GPU to interface with it.

Offline Grimmov

Senior Newbie





« Reply #24 - Posted 2013-10-24 05:57:44 »

Speaking of V-Sync, Nvidia's recently announced G-Sync technology sounds like a really great idea, if such a tech does ever get standardised and become widely adopted, should be pretty nice for smooth looking games and solve the age old V-Sync/tearing problems properly.
All the advantages of V-sync without all the disadvantages of V-sync? Oh, yes.

Yeah but it would take a loooooooooooong time for wide adoption.

It sounds like most games don't need to do anything special to support g-sync. You just need to purchase a monitor that supports it, then turn it on in your driver options. Of course, most people are still using shitty 60hz monitors, so it's going to take a while for the concept of vsync to disappear...
Offline Grunnt

JGO Kernel


Medals: 95
Projects: 8
Exp: 5 years


Complex != complicated


« Reply #25 - Posted 2013-10-24 07:59:25 »

As theagentd said, v-sync is designed to avoid "tearing" that may occur if the frame buffer is flipped precisely while the monitor is drawing the contents of the buffer on screen, leading to the effect that part of the screen shows the game view at t = n, and part at t = n + 1. This may cause some minor visual disturbances. V-sync avoids this by syncing the buffer fips with the monitor rendering cycles, as I understand it.

However, in practice v-sync usually means that the framerate will be effectively limited to the rate at which the monitor updates, which is usually 60 times per second. This means it's an easy "hack" to limit the frame rate of your game. However, it's much better to use a well-designed game loop to control your frame rate and rendering as, again, theagentd said Grin

G-sync sounds pretty awesome indeed. It's not just for games, but also for movies etc, making every 24fps movie smoother. I would expect that to be clearly noticeable. I like this kind of tech much more than even-higher-HD or 3D video techs.

Edit: I've been bulshitting about movies, never mind that. Its mostly a real-time rendering tech.

Offline Abuse

JGO Knight


Medals: 15


falling into the abyss of reality


« Reply #26 - Posted 2013-10-24 08:55:17 »

First I'd heard of gsync; though it makes perfect sense in a post-crt world.

Shame nvidia have gone down a proprietary route; it'll take ages(perhaps never) to become widespread without cooperation & collaboration from AMD & Intel.

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline nsigma
« Reply #27 - Posted 2013-10-24 09:51:34 »

I've been bulshitting about movies, never mind that.

hmm ... that makes me think one answer to the OP's problem with differing pixel jumps per frame (know exactly what you mean!) would be to incorporate some sort of motion blur, or other form of interpolation between frames.  Mind you, doing that in Java2D  Undecided

Praxis LIVE - open-source intermedia toolkit and live interactive visual editor
Digital Prisoners - interactive spaces and projections
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (33 views)
2014-12-15 09:26:44

Mr.CodeIt (23 views)
2014-12-14 19:50:38

BurntPizza (51 views)
2014-12-09 22:41:13

BurntPizza (84 views)
2014-12-08 04:46:31

JscottyBieshaar (45 views)
2014-12-05 12:39:02

SHC (59 views)
2014-12-03 16:27:13

CopyableCougar4 (59 views)
2014-11-29 21:32:03

toopeicgaming1999 (123 views)
2014-11-26 15:22:04

toopeicgaming1999 (114 views)
2014-11-26 15:20:36

toopeicgaming1999 (32 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!