2014-11-23 2 views
0

Я делаю проект в центре внимания OpenGL. Наверное, я правильно написал код, но не смог увидеть круглое пятно на моем выходе. Ваша помощь будет высоко оценена. Здесь я пишу свой файл шейдера фрагмента и определение света.SpotLight не видно - OpenGL

fragmentShader.fs

#version 330 

in vec3 N; // interpolated normal for the pixel 
in vec3 v; // interpolated position for the pixel 

// Uniform block for the light source properties 
layout (std140) uniform LightSourceProp { 
    // Light source position in eye space (i.e. eye is at (0, 0, 0)) 
    uniform vec4 lightSourcePosition; 

    uniform vec4 diffuseLightIntensity; 
    uniform vec4 specularLightIntensity; 
    uniform vec4 ambientLightIntensity; 

    // for calculating the light attenuation 
    uniform float constantAttenuation; 
    uniform float linearAttenuation; 
    uniform float quadraticAttenuation; 

    // Spotlight direction 
    uniform vec3 spotDirection; 
    uniform float cutOffExponent; 
    // Spotlight cutoff angle 
    uniform float spotCutoff; 
}; 

// Uniform block for surface material properties 
layout (std140) uniform materialProp { 
    uniform vec4 Kambient; 
    uniform vec4 Kdiffuse; 
    uniform vec4 Kspecular; 
    uniform float shininess; 
}; 

out vec4 color; 

// This fragment shader is an example of per-pixel lighting. 
void main() { 

    // Now calculate the parameters for the lighting equation: 
    // color = Ka * Lag + (Ka * La) + attenuation * ((Kd * (N dot L) * Ld) + (Ks * ((N dot HV)^shininess) * Ls)) 
    // Ka, Kd, Ks: surface material properties 
    // Lag: global ambient light (not used in this example) 
    // La, Ld, Ls: ambient, diffuse, and specular components of the light source 
    // N: normal 
    // L: light vector 
    // HV: half vector 
    // shininess 
    // attenuation: light intensity attenuation over distance and spotlight angle 

    vec3 lightVector; 
    float attenuation = 1.0; 
    float se; 


    // point light source 
    lightVector = normalize(lightSourcePosition.xyz - v); 

    //Calculate Spoteffect 
    // calculate attenuation  


float angle = dot(normalize(spotDirection), 
       normalize(lightVector)); 
    angle = max(angle,0); 

    // Test whether vertex is located in the cone 
    if(acos (angle) > radians(5)) 
{ 

    float distance = length(lightSourcePosition.xyz - v); 
    angle = pow(angle,2.0); 

attenuation = angle/(constantAttenuation + (linearAttenuation * distance) 
     +(quadraticAttenuation * distance * distance)); 

      //calculate Diffuse Color 
    float NdotL = max(dot(N,lightVector), 0.0); 

    vec4 diffuseColor = Kdiffuse * diffuseLightIntensity * NdotL; 

    // calculate Specular color. Here we use the original Phong illumination model. 
    vec3 E = normalize(-v); // Eye vector. We are in Eye Coordinates, so EyePos is (0,0,0) 

    vec3 R = normalize(-reflect(lightVector,N)); // light reflection vector 

    float RdotE = max(dot(R,E),0.0); 

    vec4 specularColor = Kspecular * specularLightIntensity * pow(RdotE,shininess); 

    // ambient color 
    vec4 ambientColor = Kambient * ambientLightIntensity; 

    color = ambientColor + attenuation * (diffuseColor + specularColor); 

    } 
    else 
     color = vec4(1,1,0,1); // lit (yellow) 


} 

свет определение в main.cpp

struct SurfaceMaterialProp { 
    float Kambient[4]; //ambient component 
    float Kdiffuse[4]; //diffuse component 
    float Kspecular[4]; // Surface material property: specular component 
    float shininess; 
}; 

SurfaceMaterialProp surfaceMaterial1 = { 
    {1.0f, 1.0f, 1.0f, 1.0f}, // Kambient: ambient coefficient 
    {1.0f, 0.8f, 0.72f, 1.0f}, // Kdiffuse: diffuse coefficient 
    {1.0f, 1.0f, 1.0f, 1.0f}, // Kspecular: specular coefficient 
    5.0f // Shininess 
}; 

struct LightSourceProp { 
    float lightSourcePosition[4]; 
    float diffuseLightIntensity[4]; 
    float specularLightIntensity[4]; 
    float ambientLightIntensity[4]; 
    float constantAttenuation; 
    float linearAttenuation; 
    float quadraticAttenuation; 
    float spotlightDirection[4]; 
    float spotlightCutoffAngle; 
    float cutOffExponent; 
}; 

LightSourceProp lightSource1 = { 
    { 0.0,400.0,0.0, 1.0 }, // light source position 
    {1.0f, 0.0f, 0.0f, 1.0f}, // diffuse light intensity 
    {1.0f, 0.0f, 0.0f, 1.0f}, // specular light intensity 
    {1.0f, 0.2f, 0.0f, 1.0f}, // ambient light intensity 
    1.0f, 0.5, 0.1f, // constant, linear, and quadratic attenuation factors 
    {0.0,50.0,0.0}, // spotlight direction 
    {5.0f}, // spotlight cutoff angle (in radian) 
    {2.0f} // spotexponent 
    }; 
+0

В чем проблема с кодом? Вы получили сообщение об ошибке? –

+0

№. Я не могу правильно видеть место – user3791306

ответ

2

Порядок нескольких членов LightSourceProp структуры в коде C++ отличается от той, в единый блок.

Последние два члена единого блока:

uniform float cutOffExponent; 
    uniform float spotCutoff; 
}; 

Последние два члена C++ структуры:

float spotlightCutoffAngle; 
    float cutOffExponent; 
}; 

Эти два значения поменялись местами.

Кроме того, угол среза выглядит подозрительно большой:

{5.0f}, // spotlight cutoff angle (in radian) 

Это угол 286 градусов, что не так много внимания. Для реального внимания вы, вероятно, захотите что-то гораздо меньшее, например 0.1f или 0.2f.

Другой аспект, который может давать неожиданные результаты, что у вас есть много окружающей среды интенсивности:

{1.0f, 1.0f, 1.0f, 1.0f}, // Kambient: ambient coefficient 
... 
{1.0f, 0.2f, 0.0f, 1.0f}, // ambient light intensity 

В зависимости от того, как использовать эти значения в коде шейдера, вполне вероятно, что ваши цветы будут насыщенными от интенсивности окружающего воздуха, и вы не получите никакого видимого вклада от других условий источника света и материала. Поскольку интенсивность окружающей среды постоянна, это приведет к полностью плоскому цвету для всей геометрии.

+0

Спасибо за ответ. Я сделал то, что вы сказали. Мой вывод такой же. Plse увидит мой выход https://imageshack.us/i/hlHRDikrp – user3791306

+0

Похоже, что у вас может быть слишком интенсивная окружающая среда. Я добавил текст в ответ. –

+0

спасибо, но не работает так – user3791306