Jump to content

  • Log In with Google      Sign In   
  • Create Account

2D Scrolling in openGL ES 2.0 outside of ViewController


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
6 replies to this topic

#1 iant   Members   -  Reputation: 109

Like
0Likes
Like

Posted 14 May 2014 - 02:35 AM

Hey,

Longtime listener, firsttime caller.

I'm making a simple 2D game with openGL ES 2.0. In order to scroll in my ViewController I do the following:

self.effect.transform.projectionMatrix = GLKMatrix4Translate(self.effect.transform.projectionMatrix, 0,scrollDy,0);

This works fine except if I want to scroll outside of the ViewController class (by passing a GLKBaseEffect pointer) class I cannot access it as the transform is protected.

I have 2 questions:

  1. How do I scroll outside of the ViewController class?
  2. Given that I eventually want to parallax scroll with a background is the above method even a sensible way of doing it?

Thanks!



Sponsor:

#2 Vincent_M   Members   -  Reputation: 641

Like
0Likes
Like

Posted 14 May 2014 - 10:57 AM

You actually wouldn't want to move out of the ViewController. What you really want to do is move your camera (aka, your view matrix). The GLKView in your GLKViewController is just a viewport on your device's screen to view into your scene. I'm not sure how to do this with Apple's GLKit-specific APIs, but if you wanted to write your math from scratch with OpenGL, then I can be pretty helpful. I have a math library that does what you need pretty easily. This type of approach makes it easier to port to other systems should you want to test in other environments almost seamlessly. Could you post your current ViewController's code? That way, I can see what the scope is to give you a better work-around.



#3 iant   Members   -  Reputation: 109

Like
0Likes
Like

Posted 15 May 2014 - 06:44 AM

Here you go, theres a lot of it and I'm not sure its all relevant. Surely theres a standard way to move your camera outside of ViewController.There must be an API call?

 

 

//

//  ViewController.m

//  Stragglers

//

//  Created by Ian on 16/04/2014.

//  Copyright © 2014 IanTierney. All rights reserved.

//

 

#import "ViewController.h"

#import "Game.h"

#import "StatePlay.h"

#import "StateLevelWin.h"

 

 

Game* game;

 

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

 

 

 

// Uniform index. //TODO DELETE

enum

{

    UNIFORM_MODELVIEWPROJECTION_MATRIX,

    UNIFORM_NORMAL_MATRIX,

    NUM_UNIFORMS

};

GLint uniforms[NUM_UNIFORMS];

 

// Attribute index.

//todo delete

enum //TODO DELETE

{

    ATTRIB_VERTEX,

    ATTRIB_NORMAL,

    NUM_ATTRIBUTES

};

 

@interface ViewController ()

{

    GLuint _program;

    

    GLKMatrix4 _modelViewProjectionMatrix;

    GLKMatrix3 _normalMatrix;

    float _rotation;

    

    GLuint _vertexArray;

    GLuint _vertexBuffer;

    

    //todo Ian probably have these as cost as they wont change after you init

    CGFloat screenWidth;

    CGFloat screenHeight;

}

@property (strong, nonatomic) EAGLContext *context;

@property (strong, nonatomic) GLKBaseEffect *effect;

 

- (void)setupGL;

- (void)tearDownGL;

 

- (BOOL)loadShaders;

- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file;

- (BOOL)linkProgram:(GLuint)prog;

- (BOOL)validateProgram:(GLuint)prog;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

 

    if (!self.context) {

        NSLog(@"Failed to create ES context");

    }

    

    GLKView *view = (GLKView *)self.view;

    view.context = self.context;

    [EAGLContext setCurrentContext:self.context];

    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;//todo not sure what this is or why its needed. its not in

    //[EAGLContext setCurrentContext:self.context]; this is done in setupGL;

    [self setupGL];

}

 

- (void)dealloc

{    

    [self tearDownGL];

    

    if ([EAGLContext currentContext] == self.context) {

        [EAGLContext setCurrentContext:nil];

    }

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

 

    if ([self isViewLoaded] && ([[self view] window] == nil)) {

        self.view = nil;

        

        [self tearDownGL];

        

        if ([EAGLContext currentContext] == self.context) {

            [EAGLContext setCurrentContext:nil];

        }

        self.context = nil;

    }

    // Dispose of any resources that can be recreated.

}

 

/*

 converts window coordinates (half of actual pixels coordinates, with origin )

 to opnGL coodinates

 */

void toPixel(CGPoint* p, CGFloat w, CGFloat h)

{

    p->x= (2 * p->x);

    p->y= (2 * p->y);

    

    p->y = h - p->y;//flip the y coordinate

    

  //  NSLog(@"T X: %f, Y: %f \n", p->x ,p->y);

}

 

 

/*

 Stores touch position in touchPos.

 

 NOTE (0,0) is top Right of screen

 */

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

//---get all touches on the screen---

NSSet *allTouches = [event allTouches];

 

UITouch *touch = [[allTouches allObjects] objectAtIndex:0];

    

//- (CGPoint)locationInView:(UIView *)view

game->touchPos = [touch locationInView:nil];

    toPixel(&game->touchPos, screenWidth, screenHeight);

    

    //printf("x:%f y:%f \n", touchPos.x ,touchPos.y );

    

    //todo this should be in game code but I can't reset camera outside this class

    if(game->touchPos.x <20 && game->touchPos.y <20)//can reset game pressing bottom corner

    {

        [self resetCamera];

        game->resetLevel();

    }

    else

    {

        game->reactTouch();

    }

}

 

/*

 Stores touch position in touchPos.

 

 NOTE (0,0) is top Right of screen

 */

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

{

//---get all touches on the screen---

NSSet *allTouches = [event allTouches];

 

UITouch *touch = [[allTouches allObjects] objectAtIndex:0];

    

//- (CGPoint)locationInView:(UIView *)view

game->touchPos = [touch locationInView:nil];

    toPixel(&game->touchPos, screenWidth, screenHeight);

    

    printf("x:%f y:%f \n", game->touchPos.x ,game->touchPos.y );

    

    game->reactTouchEnd();

}

 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{

//---get all touches on the screen---

NSSet *allTouches = [event allTouches];

 

UITouch *touch = [[allTouches allObjects] objectAtIndex:0];

    

//- (CGPoint)locationInView:(UIView *)view

game->touchPos = [touch locationInView:nil];

    toPixel(&game->touchPos, screenWidth, screenHeight);

    

    game->reactMove();

}

 

 

 

void iansSetup(GLKBaseEffect *effect, int screenW, int screenH)

//-(void) iansSetup (GLKBaseEffect*) effect (int) screenW  (int) screenH

{

    NSLog(@"new Game(");

    game = new Game(effect, screenW, screenH);

    game->ChangeState( StatePlay::Instance());

    NSLog(@" END iansSetup(");

}

 

 

- (void)setupGL

{

    /*

    Ians setup of open gl from

    http://www.raywenderlich.com/9743/how-to-create-a-simple-2d-iphone-game-with-opengl-es-2-0-and-glkit-part-1

    */

    

    [super viewDidLoad];

    

    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    

    if (!self.context) {

        NSLog(@"Failed to create ES context");

    }

    

    GLKView *view = (GLKView *)self.view;

    view.context = self.context;

    [EAGLContext setCurrentContext:self.context];

    

    self.effect = [[GLKBaseEffect alloc] init];

    

    //todo these should be constants I think..not sure why they are floats either as they are in pixels

    //CGRect screenRect = [[UIScreen mainScreen] bounds];

    

    float scaleFactor = [[UIScreen mainScreen] scale];

    CGRect screen = [[UIScreen mainScreen] bounds];

    screenWidth = screen.size.width * scaleFactor;

    screenHeight = screen.size.height * scaleFactor;

    

    GLKMatrix4 projectionMatrix = GLKMatrix4MakeOrtho(0, screenWidth, 0, screenHeight, -1024, 1024);

    self.effect.transform.projectionMatrix = projectionMatrix;

    

    iansSetup(self.effect,screenWidth, screenHeight);

}

 

- (void)tearDownGL

{

    [EAGLContext setCurrentContext:self.context];

    

    glDeleteBuffers(1, &_vertexBuffer);

    glDeleteVertexArraysOES(1, &_vertexArray);

    

    self.effect = nil;

    

    if (_program) {

        glDeleteProgram(_program);

        _program = 0;

    }

}

 

#pragma mark - GLKView and GLKViewController delegate methods

 

- (void)update

{

   // Bothe of these should eb done within the respective state class

    //I can only seem to move camera inside this class

    State* curState = game->states.back();

    if(curState== StatePlay::Instance() )

        [self scrollCamera];

    

    //todo move to StateLevelWin::Update()

    /* this gives me a linker error

    if(curState == StateLevelWin::Instance() //if you have completed the level

       && curState->timer>5)//and the timer is up

       [self resetCamera];

     */

 

    game->update(self.timeSinceLastUpdate,NULL);

    

    //note render gets called via from drawInRect (in this file)

}

 

//TODO this should really be in the playState code or game objecy

- (void) scrollCamera

{

    //TODO clean up, this is scrolling camera

    if(game->scrollV)//if camera is moving

    {

        //this doesn't work, says projectionMatrix is temporary object

        //game->update(self.timeSinceLastUpdate,&self.effect.transform.projectionMatrix);

        

        int scrollDy = self.timeSinceLastUpdate * -game->scrollV;

        game->scrollY -=scrollDy;

        self.effect.transform.projectionMatrix = GLKMatrix4Translate(self.effect.transform.projectionMatrix, 0,scrollDy,0);

        

        // printf("dt %f \n", self.timeSinceLastUpdate);

    }

}

 

//TODO this should really be in the playState code or game objecy

- (void) resetCamera

//resetCamera

{

    GLKMatrix4 projectionMatrix = GLKMatrix4MakeOrtho(0, screenWidth, 0, screenHeight, -1024, 1024);

    self.effect.transform.projectionMatrix = projectionMatrix;

    //self->_modelViewProjectionMatrix=projectionMatrix;// seems to have no effect

    

}

 

void drawRect(GLfloat left, GLfloat bottom, GLfloat right, GLfloat top, GLfloat R, GLfloat G, GLfloat B)

{

    GLfloat rect[] = {

        left, bottom,

        right, bottom,

        right, top,

        left, top

    };

    

    //

    // Enable vertex data to be fed down the graphics pipeline to be drawn

    

    // Create an handle for a buffer object array

    GLuint bufferObjectNameArray;

    

    // Have OpenGL generate a buffer name and store it in the buffer object array

    glGenBuffers(1, &bufferObjectNameArray);

    

    // Bind the buffer object array to the GL_ARRAY_BUFFER target buffer

    glBindBuffer(GL_ARRAY_BUFFER, bufferObjectNameArray);

    

    

    glEnableVertexAttribArray(GLKVertexAttribPosition);

    

    // Specify how the GPU looks up the data

    glVertexAttribPointer(

                          GLKVertexAttribPosition, // the currently bound buffer holds the data

                          2,                       // number of coordinates per vertex

                          GL_FLOAT,                // the data type of each component

                          GL_FALSE,                // can the data be scaled

                          2*4,                     // how many bytes per vertex (2 floats per vertex)

                          NULL);

    

    

    

    /////////////////////////////////////

    

    

    glEnableClientState(GL_VERTEX_ARRAY);

    glColor4f(R,G,B,1);

    glVertexPointer(2, GL_FLOAT, 0, rect);

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

}

 

void drawGrid(GLKBaseEffect* effect)

{

    //glClearColor(0.65f, 0.65f, 0.65f, 1.0f);

    //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    

    // Prepare the effect for rendering

    [effect prepareToDraw];

    glLineWidth(4);

 

    

    const GLfloat line[] =

    {

        0.0f, 150.0f, //point A

        100.0f, 150.0f, //point B

    };

    

    // Create an handle for a buffer object array

    GLuint bufferObjectNameArray;

    

    // Have OpenGL generate a buffer name and store it in the buffer object array

    glGenBuffers(1, &bufferObjectNameArray);

    

    // Bind the buffer object array to the GL_ARRAY_BUFFER target buffer

    glBindBuffer(GL_ARRAY_BUFFER, bufferObjectNameArray);

    

    // Send the line data over to the target buffer in GPU RAM

    glBufferData(

                 GL_ARRAY_BUFFER,   // the target buffer

                 sizeof(line),      // the number of bytes to put into the buffer

                 line,              // a pointer to the data being copied

                 GL_STATIC_DRAW);   // the usage pattern of the data

    

    // Enable vertex data to be fed down the graphics pipeline to be drawn

    glEnableVertexAttribArray(GLKVertexAttribPosition);

    

    // Specify how the GPU looks up the data

    glVertexAttribPointer(

                          GLKVertexAttribPosition, // the currently bound buffer holds the data

                          2,                       // number of coordinates per vertex

                          GL_FLOAT,                // the data type of each component

                          GL_FALSE,                // can the data be scaled

                          2*4,                     // how many bytes per vertex (2 floats per vertex)

                          NULL);                   // offset to the first coordinate, in this case 0

    

    glColor4f(0.5f, 0.5f, 0.5f, 1.0f);

    

    glDrawArrays(GL_LINES, 0, 2); // render

 

    glBindBuffer(GL_ARRAY_BUFFER, 0);

}

 

 

 

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect

{

    game->render();

}

 

#pragma mark -  OpenGL ES 2 shader compilation

 

- (BOOL)loadShaders

{

    //todo remove

    GLuint vertShader, fragShader;

    NSString *vertShaderPathname, *fragShaderPathname;

    

    // Create shader program.

    _program = glCreateProgram();

    

    // Create and compile vertex shader.

    vertShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"vsh"];

    if (![self compileShader:&vertShader type:GL_VERTEX_SHADER file:vertShaderPathname])

    {

        NSLog(@"Failed to compile vertex shader");

        return NO;

    }

    

    // Create and compile fragment shader.

    fragShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"fsh"];

    if (![self compileShader:&fragShader type:GL_FRAGMENT_SHADER file:fragShaderPathname]) {

        NSLog(@"Failed to compile fragment shader");

        return NO;

    }

    

    // Attach vertex shader to program.

    glAttachShader(_program, vertShader);

    

    // Attach fragment shader to program.

    glAttachShader(_program, fragShader);

    

    // Bind attribute locations.

    // This needs to be done prior to linking.

    glBindAttribLocation(_program, GLKVertexAttribPosition, "position");

    glBindAttribLocation(_program, GLKVertexAttribNormal, "normal");

    

    // Link program.

    if (![self linkProgram:_program]) {

        NSLog(@"Failed to link program: %d", _program);

        

        if (vertShader) {

            glDeleteShader(vertShader);

            vertShader = 0;

        }

        if (fragShader) {

            glDeleteShader(fragShader);

            fragShader = 0;

        }

        if (_program) {

            glDeleteProgram(_program);

            _program = 0;

        }

        

        return NO;

    }

    

    // Get uniform locations. TODO what is this?

    uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX] = glGetUniformLocation(_program, "modelViewProjectionMatrix");

    uniforms[UNIFORM_NORMAL_MATRIX] = glGetUniformLocation(_program, "normalMatrix");

    

    // Release vertex and fragment shaders.

    if (vertShader) {

        glDetachShader(_program, vertShader);

        glDeleteShader(vertShader);

    }

    if (fragShader) {

        glDetachShader(_program, fragShader);

        glDeleteShader(fragShader);

    }

    

    return YES;

}

 

- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file

{

       //todo remove

    GLint status;

    const GLchar *source;

    

    source = (GLchar *)[[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] UTF8String];

    if (!source) {

        NSLog(@"Failed to load vertex shader");

        return NO;

    }

    

    *shader = glCreateShader(type);

    glShaderSource(*shader, 1, &source, NULL);

    glCompileShader(*shader);

    

#if defined(DEBUG)

    GLint logLength;

    glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength);

    if (logLength > 0) {

        GLchar *log = (GLchar *)malloc(logLength);

        glGetShaderInfoLog(*shader, logLength, &logLength, log);

        NSLog(@"Shader compile log:\n%s", log);

        free(log);

    }

#endif

    

    glGetShaderiv(*shader, GL_COMPILE_STATUS, &status);

    if (status == 0) {

        glDeleteShader(*shader);

        return NO;

    }

    

    return YES;

}

 

- (BOOL)linkProgram:(GLuint)prog

{

    GLint status;

    glLinkProgram(prog);

    

#if defined(DEBUG)

    GLint logLength;

    glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);

    if (logLength > 0) {

        GLchar *log = (GLchar *)malloc(logLength);

        glGetProgramInfoLog(prog, logLength, &logLength, log);

        NSLog(@"Program link log:\n%s", log);

        free(log);

    }

#endif

    

    glGetProgramiv(prog, GL_LINK_STATUS, &status);

    if (status == 0) {

        return NO;

    }

    

    return YES;

}

 

- (BOOL)validateProgram:(GLuint)prog

{

    GLint logLength, status;

    

    glValidateProgram(prog);

    glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);

    if (logLength > 0)

    {

        GLchar *log = (GLchar *)malloc(logLength);

        glGetProgramInfoLog(prog, logLength, &logLength, log);

        NSLog(@"Program validate log:\n%s", log);

        free(log);

    }

    

    glGetProgramiv(prog, GL_VALIDATE_STATUS, &status);

    if (status == 0)

    {

        return NO;

    }

    

    return YES;

}

 

@end



#4 Vincent_M   Members   -  Reputation: 641

Like
1Likes
Like

Posted 18 May 2014 - 03:11 PM

After looking through your code, there are a few basic things related to OpenGL and 3D math that you should learn. They can be really helpful in the future :)

 

If you look through your project's files, you'll notice two files: Shader.vsh and Shader.fsh. If you view them, they're just text files containing C-like code. The thing is, it is not C. The code that's written in there is called GLSL, or the GL Shader Language. The .vsh file is your vertex shader's source, and the .fsh file is your fragment shader's source. Your "loadShaders" method in your code above opens those two files, reads their contents into your program as if it's a giant text string, and uses OpenGL to send it to the GPU for compilation. Once both shaders have been compiled, they are attached to a "program" object, which is a mini-program run by the GPU. Whenever you want to render something with glDrawArrays or glDrawElements, you must first use that program using glUseProgram, and pass in the program ID you got back upon successful compilation and linkage (assuming your vertex and fragment shaders had no compiler errors). Then, the vertex shader runs once per vertex you pass in to transform your vertices from local (aka, "object space") to eye-space. Those vertices are eventually linked up into triangles, and rasterized to the screen in the rendering pipeline for that frame, and the fragment shader of that program runs once for each pixel of the frame buffer that the triangles take up on the screen.

 

Anyway, now that your have a basic understanding of that, how do we transform the vertices' positions from object space to pixel coordinates onto the viewport on your device's screen? You'll need a few matrices to do this: projection matrix, view matrix and a model matrix. Older versions of OpenGL used to handle all of this for you back in the day, but now that we live in the world of shaders where developers have so much control over how to process their graphical data, these methods have been stripped away. OpenGL ES 2.0 doesn't provide you with matrix modes, etc.

 

First off, you'll need a projection matrix. If you were rendering in 3D, then you'd be using a perspective projection matrix so that objects that are further away from the screen appear smaller, just like as perceive far-away objects in real-life. Since we are using 2D, however, we're going to use another matrix called an orthographic matrix. This allows your objects to as far away from the camera you want (provided it's not outside of your viewing bounds), and it'll appear as the same size as your close-up objects. You'll uses setup your projection matrix once, then rarely have to change it.

 

Next off, you'll need a view matrix which is just an inverse of a model matrix. More on how to inverse a matrix is here. Due to this, I'll cover the model matrix first: it's a matrix describing how to translate (or move), rotate and/or scale your objects. The model matrix is actually a combination of matrices: translation matrix, scale matrix, and various rotation matrices. There's 3 Euler rotation matrices for each axis: X, Y and Z. If you ever get into full-3D-like games, you'll want to learn about quaternions, and how to convert that into a rotation matrix.

 

So, let's say you wanted to move your camera around your scene, in this case, left or right. You'd keep track of the current position, and even the rotation of your camera if you'd like. Since you're not using some sort of transformation hierarchy, you could make a view matrix simply by creating a translation matrix using the negative x, y and z components for your camera's position in the world. Additionally, if you wanted to rotate your camera in your 2D game, you could use make a z-rotation matrix from your camera's negative z-rotation angle. Then, you'd multiply the two matrices together like so: translation * rotation to get your final view matrix.

 

Now, why are we plugging in negative values? Well, it's because your view matrix is a model matrix, except the scale. We developers like to think of the camera as some separate object you can move through the 3D world to capture certain parts of its at different spots, different angles, etc, but that's actually not how it works. If we want to draw an object in our world, we just pass its vertex data to the GPU, and transform the vertices in the vertex shader. Makes sense, right? Well, if we want to view our world at a specific position and orientation in the world, we'd have to offset everything we see by that camera. That's where the view matrix comes in. How do we apply the view matrix? Simple: matrix multiplication. Multiply the view matrix by the model matrix, and you're all set. We are missing one piece of that puzzle, however. We need to take perspective into account, so we need to apply our camera's projection matrix into everything we render with that camera as well. You'd typically want to create a camera class that holds a perspective matrix (in your case, it's an orthogonal projection matrix), and a view matrix. Again, you'd only setup the perspective once, and rarely, if ever, change it. The view matrix, on the other hand, will need to be re-computed whenever your camera's position or rotation changes.

 

The way you multiply these matrices together are also very important. Multiplying the projection * view * model matrices together is different than multiplying model * view * projection together, unless you transpose the matrices first as shown here. I've suggested a book on OpenGL ES 2.0 below that can give you some really good information on this.

 

So, we've briefly gone over the concepts on how transformations work in vertex shader above, how do we apply these concepts in code? Well, Apple's GLKit provides you with a matrix class, among other things, to make writing OpenGL apps easier. I'd recommend against it, unless you like Objective-C, and don't plan on working on other platforms, such as Linux, UNIX, Mac, Windows, Android, etc, other mobile devices. There are some good math libraries out there, such as the GLM (GL Math) library. I've got my own math library that'll set you up pretty well, but it's integrated into my engine right now, and it's broken. I'm also not near my computer, so I will have to post when everything works again.

 

Until then, let's assume you have your projection and view matrices setup for your camera, and a model matrix setup for each of your objects. Before you call glDrawArrays(), or glDrawElements() to draw your object, make sure you're using the shader you want by calling glUseProgram() passing in the program handle you want. Then, we want to send those matrices to your shaders. To do this, let's look at a snippet from your own code :)

// Get uniform locations. TODO what is this?
uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX] = glGetUniformLocation(_program, "modelViewProjectionMatrix");
uniforms[UNIFORM_NORMAL_MATRIX] = glGetUniformLocation(_program, "normalMatrix");

When you loaded the shader in your loadShaders method, your code grabs handles to your shader's uniforms. A uniform is an input variable to can inject into your shader before you draw something with it, and your shader will use that variable in its calculations. You could think of it as a parameter in a function. You can have uniforms in both your vertex and fragment shaders, and it looks like the shaders you use has two of them: one called modelViewProjectionMatrix and another called normalMatrix. If you look in your Shader.vsh file, you'll probably see two lines of code with declaring a mat4 for modelViewProjectionMatrix and normalMatrix. The name is also model-view-projection, suggesting that this is the order it's multiplied by. This means Apple stores its matrix data in a row-major fashion (common), but the old way OpenGL did it was column-major.

 

Judging from your uniform names, I'm guessing you're building from Apple's 3D cube demo that also does lighting calculations, if I remember correctly. You won't need 3D lighting for what you're doing. To be honest, this shader does some advanced things you don't really need, and it's much more processing-heavy than you'll need.

 

I read the book, "OpenGL ES 2.0 Programming Guide" back in early 2010 to get up to speed with how OES 2.0 differs from OES 1.1, and how shaders work. This book is great because it covers things like matrices, shaders, how to pass data (attributes and uniforms) from your Objective-C code to your shaders, etc. Here's a link to it:

http://www.barnesandnoble.com/w/open-gl-es-20-programming-guide-aaftab-munshi/1100835208?cm_mmc=googlepla-_-textbook_instock_26to75_pt104-_-q000000633-_-9780321502797&ean=9780321502797&isbn=9780321502797&r=1

 

Also, one huge performance issue I see you doing are making many unnecessary gl* calls. Any time you're calling a function beginning with "gl" in the name, it's related to OpenGL, and almost all of them can be very costly as they're usually used to talk back and forth with your device's GPU. All of your app's code is written for the CPU, except shaders. So, whenever you tell your code to talk to the GPU with one of those "gl" calls, you're halting the thread doing those GPU calls until it finishes talking to the other hardware. These devices are really fast nowadays, but you don't want to be calling "glDrawArrays" once per rectangle --push all rectangles into a giant vertex buffer, and call it once ;) We can go into detail about that in another time, though.

 

 

If I have time this week, I'd like to cook up a simple demo for you that does what I've discussed above.



#5 iant   Members   -  Reputation: 109

Like
-1Likes
Like

Posted 23 May 2014 - 06:57 AM

Cheers but I am aware of all the concepts above, shaders/transforms etc and although the code is clearly just a hack, I'm not sure what makes you think I'm not. Clearly I'm not doing everything in an optimised way but I'm just trying to get something on screen and optimise later. Also its a 2-d engine.

 

​Anyway although I appreciate you taking the time, my original question was quite straight forward:

  1. How do I move the camera outside of the ViewController class?

Edited by iant, 24 May 2014 - 04:41 AM.


#6 namar777   Members   -  Reputation: 268

Like
0Likes
Like

Posted 24 May 2014 - 04:32 PM

I'd suggest you keep camera info internal to your game and not rely on ViewController. You have to handle transforms anyways. 

Do a test on assets who's bounding boxes are intersecting with viewport and draw them.



#7 iant   Members   -  Reputation: 109

Like
0Likes
Like

Posted 25 May 2014 - 03:17 PM

The relevant transforms are members of the effect (shader) are you saying move these into game code?






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS