• open GL 在使用材质属性glMaterial设置物体颜色效果时,使用shader和使用固定管线后颜色区别


    在学习shader编程时,对于一个颜色显示有分别的问题产生了疑惑,以下是详细问题。

    我的疑惑:在统一的光源和材质设置下,先使用固定管线画一个茶壶,再使用shader画一个茶壶,物体颜色显示的区别。然而,换一下顺序,就几乎一样了。另外,把材质属性设置的四行代码复制一份,置于两个茶壶中间,颜色显示也几乎一样。

    示例代码:

    main:

    // OpenGLStarter.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    //需要包含的头文件
    #include <stdio.h>
    #include <windows.h>
    
    //#include <GL/glew.h>
    #include <glew.h>
    //#include <GL/freeglut.h>
    #include <freeglut.h>
    
    #pragma comment(lib, "glew32.lib")
    
    
    //定义输出窗口的大小
    #define WINDOW_HEIGHT 300
    #define WINDOW_WIDTH 500
    
    GLuint G_vShader_simple;
    GLuint G_fShader_simple;
    GLuint G_shaderProgram;
    
    //摄像机离物体的距离
    float G_fDistance = 3.6f;
    //物体的旋转角度 
    float G_fAngle_horizon = 0.0;
    float G_fAngle_vertical = 0.0f;
    
    ////////////////////////////////////////////////
    //光照参数
    float G_vLit0Position[4] = { 5.0f, 5.0f, 5.0f, 1.0f };
    float G_vLit0Ambient[4] = { 0.3f, 0.3f, 0.3f, 1.0f };
    float G_vLit0Diffuse[4] = { 0.3f, 0.3f, 0.3f, 1.0f };
    float G_vLit0Specular[4] = { 0.6f, 0.6f, 0.6f, 1.0f };
    
    float G_vMaterialAmbient[4] = { 0.0f, 0.8f, 0.0f, 1.0f };
    float G_vMaterialDiffuse[4] = { 0.0f, 1.0f, 0.0f, 1.0f };
    float G_vMaterialSpecular[4] = { 0.8f, 0.8f, 0.8f, 1.0f };
    float G_iShininess = 50;
    
    ////////////////////////////////////////////////
    void myinit(void);
    void myReshape(GLsizei w, GLsizei h);
    void display(void);
    void setShaders(void);
    void printShaderInfoLog(GLuint shaderObject);
    void printProgramInfoLog(GLuint programObject);
    char* textFileRead(const char *textFileName);
    
    //响应键盘输入, 从而设定物体移近移远以及旋转的回调函数
    void processSpecialKeys(int key, int x, int y);
    void processNormalKeys(unsigned char key,int x,int y);
    
    
    ////////////////////////////////////////////////
    //主函数
    int main(int argc, char* argv[])
    {
        glutInit(&argc, argv);
    
        //初始化OPENGL显示方式
        glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA);
    //    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGBA);
    
        //设定OPENGL窗口位置和大小
        glutInitWindowSize (WINDOW_WIDTH, WINDOW_HEIGHT); 
        glutInitWindowPosition (100, 100);
            
        //打开窗口
        glutCreateWindow ("OpenGL");
    
        //调用初始化函数
        myinit();
    
        //设定窗口大小变化的回调函数
        glutReshapeFunc(myReshape);
    
        //设定键盘控制的回调函数
        glutSpecialFunc(processSpecialKeys);
        glutKeyboardFunc(processNormalKeys);
        
        //开始OPENGL的循环
        glutDisplayFunc(display); 
    //    glutIdleFunc(display);
    
        glutMainLoop();
    
        return 0;
    }
    
    ////////////////////////////////////////////////
    //用户初始化函数
    void myinit(void)
    {
        //your initialization code
        glEnable(GL_DEPTH_TEST);
    
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
        //glEnable(GL_COLOR_MATERIAL);
        //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT);
        //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
    
        GLenum err = glewInit();   
        if (GLEW_OK != err)   
        {   
            printf("glew initionlize error: %s
    ", glewGetErrorString(err));
        }
        if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)
            printf("Ready for GLSL
    ");
        else {
            printf("Not totally ready 
    ");
            exit(1);
        }
    
        if (glewIsSupported("GL_VERSION_2_0"))
            printf("Ready for OpenGL 2.0
    ");
        else 
        { 
            printf("OpenGL 2.0 not supported
    "); 
            exit(1);
        }
    
        setShaders();
    }
    
    //窗口大小变化时的回调函数
    void myReshape(GLsizei w, GLsizei h)
    {
        //设定视区
        glViewport(0, 0, w, h);
    
        //设定透视方式
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(60.0, 1.0*(GLfloat)w/(GLfloat)h, 1.0, 30.0);
    //    gluPerspective(60.0, 1.0, 1.0, 30.0);
    //  glFrustum (-1.0, 1.0, -1.0, 1.0, 1.0, 30.0);
    }
    
    //每桢OpenGL都会调用这个函数,用户应该把显示代码放在这个函数中
    void display(void)
    {
        //设置清除屏幕的颜色,并清除屏幕和深度缓冲
        glClearColor(1.0f,1.0f,1.0f,0.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        //设置光照、材质参数
        glLightfv(GL_LIGHT0, GL_POSITION, G_vLit0Position);        //设置光源的位置
        glLightfv(GL_LIGHT0, GL_AMBIENT, G_vLit0Ambient);
        glLightfv(GL_LIGHT0, GL_DIFFUSE, G_vLit0Diffuse);
        glLightfv(GL_LIGHT0, GL_SPECULAR, G_vLit0Specular);
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, G_vMaterialAmbient);
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, G_vMaterialDiffuse);
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, G_vMaterialSpecular);
        glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, G_iShininess);
    
        //坐标中心向Z轴平移-G_fDistance(使坐标中心位于摄像机前方),并设置旋转角度
        glTranslatef(0.0, 0.0, -G_fDistance);
        glRotatef(G_fAngle_horizon, 0.0f, 1.0f, 0.0f);
        glRotatef(G_fAngle_vertical, 1.0f, 0.0f, 0.0f);
    
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        // 下面是问题处
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        //绘制物体
    
        //用固定管线画一个茶壶
        //glColor3f(0.0f, 1.0f, 0.0f);
        glPushMatrix();
        glTranslatef(1.5f, 0.0f, 0.0f);
        glutSolidTeapot(1.0);
        //glutSolidSphere(1.0, 10, 10);
        glPopMatrix();
    
        // 使用下面四句话或不使用,shader画出的茶壶颜色有区别
    
        //glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, G_vMaterialAmbient);
        //glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, G_vMaterialDiffuse);
        //glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, G_vMaterialSpecular);
        //glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, G_iShininess);
    
        //用shader画一个茶壶
        glUseProgram(G_shaderProgram);
    
        //glColor3f(0.0f, 1.0f, 0.0f);
        glPushMatrix();
        glTranslatef(-1.0f, 0.0f, 0.0f);
        glutSolidTeapot(1.0);
        //glutSolidSphere(1.0, 10, 10);
        glPopMatrix();
    
        glUseProgram(0);
    
        glutSwapBuffers();
    }
    
    
    void processSpecialKeys(int key, int x, int y)
    {
        switch(key) {
            case GLUT_KEY_LEFT:
                G_fAngle_horizon -= 5.0f;
                break;
            case GLUT_KEY_RIGHT:
                G_fAngle_horizon += 5.0f;
                break;
            case GLUT_KEY_UP:
                G_fAngle_vertical -= 5.0f;
                break;
            case GLUT_KEY_DOWN:
                G_fAngle_vertical += 5.0f;
                break;
        }
        glutPostRedisplay();
    }
    
    void processNormalKeys(unsigned char key,int x,int y)
    {
        switch(key) {
            case 97:    //"a"
                G_fDistance -= 0.3f;
                break;
            case 65:        //"A"
                G_fDistance += 0.3f;
                break;
            case 27:    //"esc"
                exit(0);
        }
        glutPostRedisplay();
    }
    
    void setShaders(void)
    {  
        char *vs,*fs;  
      
        G_vShader_simple = glCreateShader(GL_VERTEX_SHADER);  
        G_fShader_simple = glCreateShader(GL_FRAGMENT_SHADER);    
      
        vs = textFileRead("Shader/simple.vert");  
        fs = textFileRead("Shader/simple.frag");  
      
        const char *vv = vs;  
        const char *ff = fs;  
      
        glShaderSource(G_vShader_simple, 1, &vv, NULL);  
        glShaderSource(G_fShader_simple, 1, &ff, NULL);  
      
        free(vs);
        free(fs);
        /////////////////////////////////////////////////////////
        glCompileShader(G_vShader_simple);  
        glCompileShader(G_fShader_simple);  
    
        int checkResult;
        glGetShaderiv(G_vShader_simple, GL_COMPILE_STATUS, &checkResult);  
        if(GL_FALSE == checkResult)
        {
            printf("vertex shader compile error
    ");
            printShaderInfoLog(G_vShader_simple);
        }
    
        glGetShaderiv(G_fShader_simple, GL_COMPILE_STATUS, &checkResult);  
        if(GL_FALSE == checkResult)
        {
            printf("fragment shader compile error
    ");
            printShaderInfoLog(G_fShader_simple);
        }
        ////////////////////////////////////////////////////////////
        G_shaderProgram = glCreateProgram();  
      
        glAttachShader(G_shaderProgram, G_vShader_simple);  
        glAttachShader(G_shaderProgram, G_fShader_simple);  
      
        glLinkProgram(G_shaderProgram);  
        glGetProgramiv(G_fShader_simple, GL_LINK_STATUS, &checkResult);  
        if(GL_FALSE == checkResult)
        {
            printf("shader link error
    ");
            printProgramInfoLog(G_shaderProgram);
        }
    //    glUseProgram(G_shaderProgram);  
    }  
    
    char* textFileRead(const char *textFileName)
    {
        FILE *fp;
    
        if(NULL == (fp = fopen(textFileName, "r")))  
        {  
            printf("text file read error
    ");  
            exit(1);  
        }  
      
        char ch;
        int fileLen = 0;
        //首先得到文件长度
        while(EOF != (ch=fgetc(fp)))  
        {  
            fileLen ++;  
        }
    
        char *fileStr = (char *)malloc((fileLen+1)*sizeof(char));
        //第二次读取文件
        rewind(fp);
        int i = 0;
        while(EOF != (ch=fgetc(fp)))  
        {  
            fileStr[i] = ch;
            i++;
        }  
        fileStr[fileLen] = '';    //注意这个一定要加。
      
        fclose(fp);
        return fileStr;
    }
    
    void printShaderInfoLog(GLuint shaderObject)
    {
        GLint logLen = 0;
        GLint writtenLen = 0;
        GLchar* info_log;
    
        glGetShaderiv(shaderObject, GL_INFO_LOG_LENGTH , &logLen);       
    
        if (logLen > 1)
        {
            info_log = (GLchar*)malloc(logLen);
    //        glGetInfoLogARB(shaderObject, logLen, &writtenLen, info_log);    //也许这是老版本的函数了。
            glGetShaderInfoLog(shaderObject, logLen, &writtenLen, info_log);  
    //        printf("Information log: 
    ");
            printf("%s
    ", info_log);
            free (info_log);
        }
    }
    
    void printProgramInfoLog(GLuint programObject)
    {
        GLint logLen = 0;
        GLint writtenLen = 0;
        GLchar* info_log;
    
        glGetShaderiv(programObject, GL_INFO_LOG_LENGTH , &logLen);       
    
        if (logLen > 1)
        {
            info_log = (GLchar*)malloc(logLen);
    //        glGetInfoLogARB(shaderObject, logLen, &writtenLen, info_log);
            glGetProgramInfoLog(programObject, logLen, &writtenLen, info_log);  
    //        printf("Information log: 
    ");
            printf("%s
    ", info_log);
            free (info_log);
        }
    }
    View Code

    vert:

    out vec4 diffuse, ambient, specular, globalAmbient;
    out vec3 normal, lightDir, eyeDir;
    
    void main(void)
    {
        //计算光照方向
        vec4 v = gl_ModelViewMatrix * gl_Vertex;
        lightDir = vec3(gl_LightSource[0].position - v);
        lightDir = normalize(lightDir);
    
        //计算物体的法向
        normal = normalize(vec3(gl_NormalMatrix * gl_Normal));  
        
        //计算视线方向
    //    eyeDir = vec3((vec4(0.0) - v));
        eyeDir = vec3(-v);
        eyeDir = normalize(eyeDir);
    
        //计算ambient分量
        ambient = gl_FrontMaterial.ambient * gl_LightSource[0].ambient;
        globalAmbient = gl_FrontMaterial.ambient * gl_LightModel.ambient;  //这是全局的环境光
        
        //计算diffuse分量的不变部分 
        diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
    
        //计算specular分量的不变部分
        specular = gl_FrontMaterial.specular * gl_LightSource[0].specular;
    
        gl_Position = ftransform();
    }
    View Code

    frag:

    in vec4 diffuse, ambient, specular, globalAmbient;
    in vec3 normal, lightDir, eyeDir;
    
    void main (void)
    {
        vec3 normalizedLightDir = normalize(lightDir);
        vec3 normalizedEyeDir = normalize(eyeDir);
        vec3 normalizedNormal = normalize(normal);
      
        //计算NdotL
        float NdotL = dot(normalizedNormal, normalizedLightDir);
    
        //计算NdotH
        vec3 H = normalize(normalizedEyeDir + normalizedLightDir);
        float NdotH = dot(normalizedNormal, H);
        if(NdotL > 0.0)
            NdotH = max(NdotH, 0.0);
        else
            NdotH = 0.0;
        NdotL = max(NdotL, 0.0);
    
        //计算光照颜色
        vec4 col = globalAmbient + ambient + diffuse * NdotL + specular * pow(NdotH, gl_FrontMaterial.shininess);
    
        gl_FragColor = col;
    }
    View Code

    效果图:

      

    如有各路大牛路过,烦请指教!!!

     

     

  • 相关阅读:
    OpenCV 2.48配置
    win进入当前文件夹,启动当前文件夹的程序
    C++程序运行效率的10个简单方法
    银行国际清算业务平台架构
    股票证券交易系统架构分析与设计
    负载均衡|六种负载均衡算法
    Intelli IDEA快捷键(配合IdeaVim)(转)
    [易学易懂系列|golang语言|零基础|快速入门|(三)]
    [易学易懂系列|golang语言|零基础|快速入门|(二)]
    [易学易懂系列|golang语言|零基础|快速入门|(一)]
  • 原文地址:https://www.cnblogs.com/dgz-bb1304/p/12912834.html
Copyright © 2020-2023  润新知