Search code examples
objective-copengl-escadisplaylink

CADisplayLink and static variable magic in Apple OpenGl ES Sample


I would like an explanation of why XCode's OpenGl ES Sample works, please. It does the following to start the drawFrame method (in the blablaViewController.m - name is dependent on the project's name):

//sets up a CADisplayLink to do a regular (draw & update) call like this
CADisplayLink *aDisplayLink = [[UIScreen mainScreen] displayLinkWithTarget:self 
    selector:@selector(drawFrame)];
[aDisplayLink setFrameInterval:animationFrameInterval];
[aDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

and inside the drawFrame method it does the following:

//start of method
...
static float transY = 0.0f;
...
//Quite a lot of OpenGl code, I am showing only parts of the OpenGL ES1 version:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, (GLfloat)(sinf(transY)/2.0f), 0.0f);
transY += 0.075f;
...
//end of method

I don't know a lot of Objective C yet, but the way this transY variable is reset, then incremented in the same method is very weird. Since the GL_MODELVIEW matrix is reset to identity before being shifted, I don't think it could keep an accumulated value in opengl somewhere.

Is the static keyword the trick here? Does Objective C ignore all future variable declarations once something has been declared static once?

Thanks for the help!


Solution

  • Static variables get initializated at compile time in the binary, so only once, and for that reason you're forbidden to assign dynamic values for their initialization. Here, the variable transY is not set to 0.0 at every method call, but just on startup. That's why subsequent calls of the method can retrieve the old value.