利用OpenGL固定功能流水线绘制球体

// // MyView.m // OpenGLTest // // Created by Zenny Chen on 4/25/10. // Copyright 2010 GreenGames Studio. All rights reserved. // P44 #import "MyView.h" #include <OpenGL/OpenGL.h> #include <math.h> @implementation MyView - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code here. } return self; } // timer event - (void)timerFireMethod:(NSTimer*)theTimer { static GLfloat degree = 0.0f; glLoadIdentity(); glTranslatef(0.0f, 0.0f, -2.0f); glRotatef(degree, 1.0f, 1.0f, 1.0f); if(degree >= 360.0) degree = 0.0; else degree += 1.0f; [self setNeedsDisplay:YES]; } static GLfloat *vertices = NULL; static GLushort **indices = NULL; static GLsizei *counts = NULL; - (void)prepareOpenGL { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_MULTISAMPLE); glEnableClientState(GL_VERTEX_ARRAY); glFrontFace(GL_CCW); glCullFace(GL_BACK); glShadeModel(GL_FLAT); glClearColor(0.4, 0.4, 0.4, 1.0); // Generate half sphere vertices vertices = (GLfloat*)malloc(91 * 360 * 4 * sizeof(*vertices)); double xy_theta = 0.0, xz_theta = 0.0; const double radius = 0.5; int innerCount = 0; for(int i = 0; i < 360 * 91 * 4; i += 4) { double r_xy = xy_theta * M_PI / 180.0; double r_xz = xz_theta * M_PI / 180.0; double x = radius * cos(r_xy) * cos(r_xz); double y = radius * sin(r_xy); double z = -radius * cos(r_xy) * sin(r_xz); xy_theta += 1.0; innerCount++; if(innerCount == 91) { innerCount = 0; xy_theta = 0.0; xz_theta += 1.0; } vertices[i] = (GLfloat)x; vertices[i + 1] = (GLfloat)y; vertices[i + 2] = (GLfloat)z; vertices[i + 3] = 1.0f; } // Generate the indices indices = (GLushort**)malloc(360 * sizeof(*indices)); for(int i = 0; i < 360; i++) { indices[i] = (GLushort*)malloc(91 * 2 * sizeof(*indices[0])); int base = i * 91; int next = base + 91; if(next == 91 * 360) next = 0; for(int j = 0; j < 91; j++) { indices[i][j * 2] = base + j; indices[i][j * 2 + 1] = next + j; } } counts = (GLsizei*)malloc(360 * sizeof(*counts)); for(int i = 0; i < 360; i++) counts[i] = 91 * 2; glVertexPointer(4, GL_FLOAT, 0, vertices); glViewport(0, 0, 320, 320); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1.0, 1.0, -1.0, 1.0, 1.0, 5.0); glMatrixMode(GL_MODELVIEW); [[NSTimer scheduledTimerWithTimeInterval:0.050f target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES] retain]; } - (void)drawRect:(NSRect)dirtyRect { // Drawing code here. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4f(0.0f, 0.6f, 0.4f, 1.0f); glMultiDrawElements(GL_TRIANGLE_STRIP, counts, GL_UNSIGNED_SHORT, (GLvoid const**)indices, 360); glFlush(); } @end  

 

完整的工程请见:

 

http://www.cocoachina.com/bbs/read.php?tid-33172.html

你可能感兴趣的:(timer,buffer,360,float,initialization,math.h)