Question

I'm working on an OpenGL project using GLKit for the iPhone and need to draw several different objects at once and rotate and translate them independently. Nearly every GLKit example I've seen places the vertex/color/texture data within the render class (usually the GLKViewController). What I need to do is create separate classes to hold the object data and simply call an object's draw method from a GLKViewController class. Something like:

-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect{
    [mycube draw:view];
}

-(void)glkViewControllerUpdate:(GLKViewController *)controller{
    [mycube updateposition:controller.timesincelastdraw];
}

How should I go about implementing this? How can I draw to an EAGLContext from a separate class? Are there any examples I can take a look at? Thanks.

Was it helpful?

Solution

Each object that should be drawn should conform to a certain protocol that would provide all the necessary information for one to be displayed. The render code would be contained inside a renderer class. For example:

@protocol Renderable <NSObject>
// returns a vertex array
-(GLfloat*)mesh;

@optional
-(GLKBaseEffect*)effect;
@end

@interface GLRenderer : NSObject

@property(nonatomic, strong) EAGLContext* context;

-(void)draw:(id<Renderable>)renderable;

@end

Drawing would be done inside the renderer class. So you'd simply call

[myRenderer draw:myCube];

In case(for some reason), you'd like to call the draw method on the cube itself, I suggest you keep the rendering code inside the renderer and simply handle rendering through inheritance by making a base drawable object for each of your objects. It would implement the Renderable protocol and implement the all the required methods.

I suggest you simply start by implementing the basic drawing operations and extend if needed. Try putting the generic code in the Renderer and object-specific code in objects, but provided through the Renderable protocol.

-(void)draw:(id<Renderable>)renderable{
     if([renderable respondsToSelector:@selector(effect)]){
          [[renderable effect] prepareToDraw];
     }
     GLFloat* data= [renderable mesh];
     glBufferData(GL_ARRAY_BUFFER, sizeof(data),
                     data, GL_STATIC_DRAW);
     // etc
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top