24

There are a few similar questions out there on SO (links at end), but none of them has allowed me to fix my problem, so here goes:

I'm using OpenGL rendering to make an image tiling and caching library for use in a game project, and I want to hijack the physics of the UIScrollView to allow the user to navigate around the images (since it has nice bounce behaviour, might as well use it). So I have a UIScrollView which I'm using to get the rendering view for my textures, but there's a problem - moving around on the scroll view prevents the CADisplayLink from firing until the user has finished scrolling (which looks horrible). One temporary fix has been to use NSRunLoopCommonModes instead of the default run mode, but unfortunately this breaks some aspects of scroll view behaviour on certain phones I'm testing on (the 3GS and simulator seem to work fine, while the iPhone4 and the 3G don't).

Does anyone know how I could get around this clash between the CADisplayLink and the UIScrollView, or know how to fix the UIScrollView working in other run modes? Thanks in advance :)

Promised links to similar questions: UIScrollView broken and halts scrolling with OpenGL rendering (related CADisplayLink, NSRunLoop)

Animation in OpenGL ES view freezes when UIScrollView is dragged on iPhone

1

4 Answers 4

43

It's possible that slow updates on the main thread triggered by the CADisplayLink are what's breaking UIScrollView's scrolling behavior here. Your OpenGL ES rendering might be taking long enough for each frame to throw off the timing of a UIScrollView when using NSRunLoopCommonModes for the CADisplayLink.

One way around this is to perform your OpenGL ES rendering actions on a background thread by using a Grand Central Dispatch serial queue. I did this in my recent update to Molecules (source code for which can be found at that link), and in testing with using NSRunLoopCommonModes on my CADisplayLink, I don't see any interruption of the native scrolling behavior of a table view that's onscreen at the same time as the rendering.

For this, you can create a GCD serial dispatch queue and use it for all of your rendering updates to a particular OpenGL ES context to avoid two actions writing to the context at the same time. Then, within your CADisplayLink callback you can use code like the following:

if (dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_NOW) != 0)
{
    return;
}

dispatch_async(openGLESContextQueue, ^{

    [EAGLContext setCurrentContext:context];

    // Render here

    dispatch_semaphore_signal(frameRenderingSemaphore);
});

where frameRenderingSemaphore is created earlier as follows:

frameRenderingSemaphore = dispatch_semaphore_create(1);

This code will only add a new frame rendering action onto the queue if one isn't in the middle of executing. That way, the CADisplayLink can fire continuously, but it won't overload the queue with pending rendering actions if a frame takes longer than 1/60th of a second to process.

Again, I tried this on my iPad here and found no disruption to the scrolling action of a table view, just a little slowdown as the OpenGL ES rendering consumed GPU cycles.

22
  • 1
    We plan to target 3.1+ devices, although maybe you are right and we should drop 3.x altogether... May 15, 2011 at 22:49
  • 3
    @ranReloaded - By making your rendering occur on a non-main thread, you can see some nice performance improvements due to parallelizing the GPU- and CPU-bound processing (uploading data from the CPU while the GPU is still working on the last set, etc.). This can be of particular help on a multicore system, where I've seen boosts of up to 40% in rendering performance just from backgrounding the frame rendering. Even on single-core machines, I saw a 10-20% improvement.
    – Brad Larson
    Jun 22, 2012 at 18:00
  • 1
    @ranReloaded - It's not so bad, if you use a serial dispatch queue. Using a single serial dispatch queue for all actions that touch a particular OpenGL ES context will guarantee that you won't get simultaneous access to that context from multiple threads. In my case, it was easy to migrate to that from running everything on the main thread. Just wrap all actions that touch this context in blocks in dispatch then synchronously or asynchronously to the serial queue as needed.
    – Brad Larson
    Jun 22, 2012 at 19:10
  • 1
    I just implemented this solution with a GLKView which is owned by a GLKViewController, and found that I had to call '[(GLKView*)self.view display];' on the main thread at the end of the displayLink callback in order to get everything to update. Many thanks to the contributors on this thread; my opengl world's perspective is now controlled by a UIScrollView, getting me all that nice fluid motion for free.
    – jankins
    Jun 29, 2012 at 22:04
  • 1
    @Xavier - That's a good question, and one that I've experimented with myself. In my experience, CADisplayLink seems to fire a little before the screen refreshes, so you have a few milliseconds to render before you get kicked into the next refresh. Still, a synchronous dispatch has severe downsides in that it blocks the main queue and breaks rendering, like is the problem in this question. Asynchronous dispatches for OpenGL ES rendering also nicely parallelize data upload and rendering, and can lead to huge performance wins on multicore devices. I've tested both approaches, and async wins here.
    – Brad Larson
    Oct 18, 2012 at 22:32
4

My simple solution is to halve the rendering rate when the run loop is in tracking mode. All my UIScrollViews now work smoothly.

Here is the code fragment:

- (void) drawView: (CADisplayLink*) displayLink
{
    if (displayLink != nil) 
    {
        self.tickCounter++;

        if(( [[ NSRunLoop currentRunLoop ] currentMode ] == UITrackingRunLoopMode ) && ( self.tickCounter & 1 ))
        {
            return;
        }

        /*** Rendering code goes here ***/
     }
}
2
  • Doesn't this only helps when there is a touch event? Lets say you scroll but there is momentum left. I thought the tracking mode only restrict when there is a touch event?
    – mskw
    Mar 17, 2013 at 17:58
  • 1
    Quite the opposite. It helps when there is any tracking or momentum. However, I've deprecated this approach in favour of Brad Larson's GCD solution detailed above, which works superbly.
    – Mindbrix
    Mar 18, 2013 at 16:24
4

The answer at the following post works very well for me (it appears to be quite similar to Till's answer):

UIScrollView pauses NSTimer until scrolling finishes

To summarize: disable the CADisplayLink or GLKViewController render loop when the UIScrollView appears and start a NSTimer to perform the update/render loop at the desired framerate. When the UIScrollView is dismissed/removed from the view hierarchy, re-enable the displayLink/GLKViewController loop.

In the GLKViewController subclass I use the following code

on appear of UIScrollView:

// disable GLKViewController update/render loop, it will be interrupted
// by the UIScrollView of the MPMediaPicker
self.paused = YES;
updateAndRenderTimer = [NSTimer timerWithTimeInterval:1.0f/60.0f target:self selector:@selector(updateAndRender) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:updateAndRenderTimer forMode:NSRunLoopCommonModes];

on dismiss of UIScrollView:

// enable the GLKViewController update/render loop and cancel our own.
// UIScrollView wont interrupt us anymore
self.paused = NO;
[updateAndRenderTimer invalidate];
updateAndRenderTimer = nil;

Simple and effective. I'm not sure if this could cause artifacts/tearing of some sort since the rendering is decoupled from screen refreshes, but using CADisplayLink with NSRunLoopCommonModes totally breaks the UIScrollView in our case. Using NSTimer looks just fine for our app and definitely a whole lot better than no rendering.

1
  • This is honestly the best solution. Constant framerate, doesn't allow UI to block it... Should be selected answer.
    – Keegan Jay
    Jun 20, 2013 at 22:52
0

Even though this is not the perfect solution, it still might work as a workaround; You could ignore the display link availability and use NSTimer for updating your GL-layer instead.

2
  • The current solution we have is not exactly perfect either (ignoring the display loop altogether and calling render on the didScroll delegate method). The real problem is that we want this class I'm writing to fit into a pre-existing framework for OpenGL games on the iPhone that we have. Ultimately, if the display link can't play nicely with the scroll view we might have to just re-implement the bits of scroll view behaviour we like, but that would take a while :(
    – Adam
    May 10, 2011 at 2:07
  • 1
    Been there, got the T-shirt ;).... Friction scrolling with bounce-back is not thaaat trivial to implement.
    – Till
    May 10, 2011 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.