该程序应允许用户选择茶壶的材质,该材质会动态变化。因此,我创建了一个菜单。
我使用setRGB(在实用程序文件中声明)来设置3个GLfloat数组的颜色。
createMenu仅创建从va_list读取语音的菜单。
setMaterial根据枚举传递的值设置材质:

typedef enum
{
    BlackPlastic= 0,
    Brass,
    Bronze,
    Chrome,
    Copper,
    Gold,
    Peweter,
    Silver,
    PolishedSilver
}MaterialType;


自工作以来,我将省略已测试功能的主体:

int createMenu(void (*callback) (int),int key, const char* const first, ...)
{
    // creates a menu, the number of entries depends on the list length,
    // the value starts from zero
}

void setRGB( GLfloat* color, GLfloat red, GLfloat green, GLfloat blue)
{
    // Sets the color
}


void setMaterial (GLfloat** material, MaterialType type)
{
    // Sets the material color (ambient, diffuse, specular).
}


这就是整个程序。我在这里担心的是我做错了什么,所以由于OpenGL进入无效状态而无法绘制茶壶。
问题是有时我看不到窗口中画的茶壶,而只是看到一个黑色的窗口,有时我工作时却看到茶壶,而且我能够改变材质的颜色。

#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#include "utility.h"
#include <stdlib.h>


GLfloat width=500, height=500;
GLfloat** material;
GLfloat light[3][3]= { {1,1,0}, {1,0.5,0}, {1,0,0} };


void menuCallback (int choice)
{
    setMaterial((GLfloat**)material, choice);
    glutPostRedisplay();
}

void init()
{
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-width/2, width/2, -height/2, height/2, 1, 1000);

    material= malloc(4*sizeof(GLfloat*));
    for(GLuint i=0; i<4; i++)
    {
        material[i]=malloc(3*sizeof(GLfloat));
    }

    setRGB(material[3], 1, 1, 0);
    setMaterial(material, BlackPlastic);
}

void display()
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    glShadeModel(GL_FLAT);

    glMaterialfv(GL_FRONT, GL_AMBIENT, material[0] );
    glMaterialfv(GL_FRONT, GL_DIFFUSE, material[1]);
    glMaterialfv(GL_FRONT, GL_SPECULAR, material[2]);
    glMaterialfv(GL_FRONT, GL_SHININESS, material[3] );

    glLightfv(GL_LIGHT0, GL_AMBIENT, light[0]);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light[1]);
    glLightfv(GL_LIGHT0, GL_SPECULAR, light[2]);

    glEnable(GL_LIGHT0);
    glEnable(GL_LIGHTING);

    glutSolidTeapot(100);

    glutSwapBuffers();
}

void keyboard(unsigned char key, int x, int y)
{
}

int main(int argc,char * argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE );
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(width,height);
    glutCreateWindow(*argv);
    createMenu(menuCallback, GLUT_LEFT_BUTTON, "Black Plastic", "Brass", "Bronze", "Chrome", "Copper", "Gold", "Peweter", "Silver", "Polished Silver", NULL);
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    init();
    glutMainLoop();
    return 0;
}

最佳答案

您要画一个实心茶壶吗?我假设您启用了深度测试(尽管glutInitDisplayMode缺少深度缓冲位)。无论如何,您可能还应该清除深度缓冲区。现在,您只清除颜色缓冲区

glClear(GL_COLOR_BUFFER_BIT);


改成

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

关于c - 更改茶壶的颜色有时不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13895411/

10-11 20:57