调整光源大小

时间:2015-11-10 22:41:29

标签: c++ opengl glut

我正在尝试从屏幕左下角开始定位一个灯光,并朝着我的屏幕中心照亮,但我的光源看起来并不是圆形的(光线似乎不是来自一个点)。 enter image description here

移动光源后,它会照亮整个物体,但所需的效果是光源仅向右侧照射(基于一个点)。

enter image description here

void init()
{
    camPos[0]= -(size/2)*.1;
    camPos[1]= size*.1;
    camPos[2]= -(size/2)*.1;
    zoom = size/10;
    glClearColor(0,0,0,0);
    glColor3f(1, 1, 1);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    //Enable backface culling
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CW);  

    //Enable Lighting
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    light_pos[0] = 1;
    light_pos[1] = 10;
    light_pos[2] = 1;
    light_pos[3] = 1;

    gluPerspective(45, 1, 1, 100);

};

void display()
{

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    //Camera
    radians =  float(pi*(angle-90.0f)/180.0f);
    //initialize look
    look[0] = (size/2)*.1;
    look[1] = 1;
    look[2] = (size/2)*.1;

    camPos[0] = look[0] + sin(radians)*zoom;
    camPos[1] = size/10;
    camPos[2] = look[2] + cos(radians)*zoom;

    gluLookAt(camPos[0], camPos[1], camPos[2], look[0],look[1],look[2], 0,1,0);
    //lighting
    //glColor3f(1,1,1);


    float m_amb[] = {0.2, 0.2, 0.2, 1.0};
    float m_dif[] = {1, 1, 1, 1.0};
    float m_spec[] = {1, 1, 1, 1.0};
    float shiny = 27;

    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_dif);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny);


    glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
    glShadeModel(GL_SMOOTH);
    drawTerrain(terrainA, size);
    glutSwapBuffers();

};

int main (int argc, char** argv)
{
    srand(time(NULL));
    //When program starts enter value

    printf("Enter an int between 50 and 300: ");
    scanf("%i",&size);

    if ( size < 50 || size > 300){
        printf("Invalid size! Please re-run \n");
        return 0;
    }
    populateArray();
    //Starts glut
    glutInit(&argc, argv);
    //Init display
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(800, 800);
    glutInitWindowPosition(600, 100);
    glutCreateWindow("Terrain");glEnable(GL_DEPTH_TEST);
    //Registering Callbacks
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(special);

    glEnable(GL_DEPTH_TEST);
    init();

    glutMainLoop(); 


    return 0;
};

1 个答案:

答案 0 :(得分:0)

一般的实践是将光衰减因子定义为光方程的系数。

enter image description here

glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.5);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.5);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.2);

其中kc是恒定衰减系数,kl - 线性衰减系数,kq - 二次衰减系数,d - 距离光源的距离。您可以修改此系数以达到您想要的效果。

此示例无法正常工作,因此我建议使用着色器构建您自己的光线分解功能,获得所需效果并且更有效(并且始终有效)将非常简单。