picksquare.c
上传用户:tengyuc
上传日期:2007-08-14
资源大小:722k
文件大小:3k
-
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
int board[3][3]; // 每个方块的颜色值
// 清除每个方块的颜色值
void init(void)
{
int i, j;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j ++)
board[i][j] = 0;
glClearColor (0.0, 0.0, 0.0, 0.0);
}
// 方块绘制函数,在选择模式下,每个方块的名字以所在的行和列表示
- // 方块的颜色值保存在board[][]中
void drawSquares(GLenum mode)
{
- GLuint i, j;
- for (i = 0; i < 3; i++)
- {
- if (mode == GL_SELECT)
- glLoadName (i);
- for (j = 0; j < 3; j ++)
- {
- if (mode == GL_SELECT)
- glPushName (j);
- glColor3f ((GLfloat) i/3.0, (GLfloat) j/3.0,
(GLfloat) board[i][j]/3.0);
- glRecti (i, j, i+1, j+1);
- if (mode == GL_SELECT)
- glPopName ();
- }
- }
}
// 处理鼠标单击一些其它信息
void processHits (GLint hits, GLuint buffer[])
{
- unsigned int i, j;
- GLuint ii, jj, names, *ptr;
- printf ("hits = %dn", hits);
- ptr = (GLuint *) buffer;
- for (i = 0; i < hits; i++)
- {
- names = *ptr;
- printf (" number of names for this hit = %dn", names); ptr++;
- printf(" z1 is %g;", (float) *ptr/0x7fffffff); ptr++;
- printf(" z2 is %gn", (float) *ptr/0x7fffffff); ptr++;
- printf (" names are ");
- for (j = 0; j < names; j++)
- {
- printf ("%d ", *ptr);
- if (j == 0)
- ii = *ptr;
- else if (j == 1)
- jj = *ptr;
- ptr++;
- }
- printf ("n");
- board[ii][jj] = (board[ii][jj] + 1) % 3;
- }
}
// 设置选择模式,名字堆栈和投影矩阵,然后绘制对象
#define BUFSIZE 512
void pickSquares(int button, int state, int x, int y)
{
- GLuint selectBuf[BUFSIZE];
- GLint hits;
- GLint viewport[4];
- if (button != GLUT_LEFT_BUTTON || state != GLUT_DOWN)
- return;
- glGetIntegerv (GL_VIEWPORT, viewport);
- glSelectBuffer (BUFSIZE, selectBuf);
- (void) glRenderMode (GL_SELECT);
- glInitNames();
- glPushName(0);
- glMatrixMode (GL_PROJECTION);
- glPushMatrix ();
- glLoadIdentity ();
- // 在鼠标位置生成5X5像素区域
- gluPickMatrix ((GLdouble) x, (GLdouble) (viewport[3] - y),
5.0, 5.0, viewport);
- gluOrtho2D (0.0, 3.0, 0.0, 3.0);
- drawSquares (GL_SELECT);
- glMatrixMode (GL_PROJECTION);
- glPopMatrix ();
- glFlush ();
- hits = glRenderMode (GL_RENDER);
- processHits (hits, selectBuf);
- glutPostRedisplay();
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
drawSquares (GL_RENDER);
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (0.0, 3.0, 0.0, 3.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (200, 200);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutReshapeFunc (reshape);
glutDisplayFunc(display);
glutMouseFunc (pickSquares);
glutKeyboardFunc (keyboard);
glutMainLoop();
return 0;
}