iPhone螺旋3D

OpenGLを使って3Dの螺旋を表示するiPhoneアプリのサンプルコードを描いてみます

#import <GLKit/GLKit.h>

@interface ViewController : GLKViewController

@end

#import “ViewController.h”

@interface ViewController () {

    GLuint v;

}

@property (nonatomic, strong) GLKBaseEffect *baseEffect;

@property (nonatomic, weak) GLKView *gv;

@property NSUInteger animationType;

@end

@implementation ViewController

typedef struct

{

    float Position[3];

    float Color[4];

} Vertex;

– (void)loadView

{

    self.view = [[GLKView alloc] initWithFrame:[[UIScreen mainScreen] bounds] context:[[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]];

}

– (void)viewDidLoad

{

    [super viewDidLoad];

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

    self.gv.drawableColorFormat = GLKViewDrawableDepthFormat16;

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

}

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

{

    glClearColor(0.4, 0.2, 0.2, 1.0);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    

    Vertex vertices[1001];

    float dAngel = M_PI / 50.0;

    for (int i=0; i<1001; i++) {

        float x = cos(dAngel * i) * (i * 0.001);

        float y = sin(dAngel * i) * (i * 0.001);

        float z = i * 0.001;

        Vertex vertex = {{x, y, z}, {(i % 20) < 10 ? 0.8f : 0.2f, 255.0f/255.0f, 178.0f/255.0f,1}};

        vertices[i] = vertex;

    }

    

    glGenBuffers(1, &v);

    glBindBuffer(GL_ARRAY_BUFFER, v);

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    

    glEnableVertexAttribArray(GLKVertexAttribPosition);

    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), NULL + 0);

    glEnableVertexAttribArray(GLKVertexAttribColor);

    glVertexAttribPointer(GLKVertexAttribColor, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), NULL + offsetof(Vertex, Color));

    

    const GLfloat aspectRatio = (GLfloat)view.drawableWidth / (GLfloat)view.drawableHeight;

    self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeOrtho(-2 * aspectRatio, 2 * aspectRatio, –2, 2, –5, 5);

    

    glLineWidth(6);

    

    [self.baseEffect prepareToDraw];

    for (int i=0; i<1000; i++) {

        glDrawArrays(GL_LINES, i, 2);

    }

    

    if (self.animationType == 1) {

        self.baseEffect.transform.modelviewMatrix = GLKMatrix4Rotate(self.baseEffect.transform.modelviewMatrix, GLKMathDegreesToRadians(1), 1, 0, 0);

    } else if (self.animationType == 2) {

        self.baseEffect.transform.modelviewMatrix = GLKMatrix4Rotate(self.baseEffect.transform.modelviewMatrix, GLKMathDegreesToRadians(1), 0, 0, 1);

    }

}

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

{

    self.animationType = (self.animationType + 1) % 3;

}

@end