2016-06-21 66 views
-1

所以我想寫一個折射着色器,在飛機上有一個玻璃球。我的問題是紋理是紋理沒有顯示在飛機上。紋理不能在平面上顯示

平面代碼:

GLfloat plane[4][5] =       // s, t, x, y, z 
{ 
    0.0f, 0.0f,  0.0f, 0.0f, 0.0f, 
    0.0f, 1.0f,  0.0f, 0.0f, 100.0f, 
    1.0f, 1.0f,  80.0f, 0.0f, 100.0f, 
    1.0f, 0.0f,  80.0f, 0.0f, 0.0f, 
};  
void DrawPlane() 
{ 
    glBegin(GL_QUADS);  
    glVertex3fv(plane[0]+2);  
    glVertex3fv(plane[1]+2);  
    glVertex3fv(plane[2]+2);  
    glVertex3fv(plane[3]+2);  
    glEnd(); 
} 

我的片段着色器看起來是這樣的:

varying vec3 varPosition; 
varying vec2 varTexCoords; 

uniform vec3 sphere_center; 
uniform float sphere_radius; 
uniform float sphere_refractive_index; 

uniform vec3 eyePosition;  

uniform sampler2D texture; 

out vec3 fragColor; 

void main() 
{ 
    vec3 ray_direction = normalize(varPosition - eyePosition); 

    float a = dot(ray_direction, ray_direction); 
    float b = 2.0 * dot(ray_direction, eyePosition - sphere_center); 
    float c = dot(sphere_center, sphere_center) + dot(eyePosition, eyePosition) - 2.0 * dot(sphere_center, eyePosition) - sphere_radius*sphere_radius; 

    float test = b*b - 4.0*a*c; 

    if (test >= 0.0) { 
     //there is an intersection with the sphere 
     //here I refract the ray 
    } else { 
     //no intersection with the sphere 
     //we test for shadow  
     if (test >= 0.0) { 
      //the point is in shadow 
      vec3 black = vec3(0.0); 
      fragColor = mix(texture2D(texture, varTexCoords).rgb,black,shadowIntensity).rgb; 
     } else { 
      //the point is not in shadow 
      fragColor = texture2D(texture, varTexCoords).rgb; 
     }   
    }  
} 

的情況是,球被畫,但飛機仍然是灰色的。問題可能出在我的texCoords上,因爲如果我改變了texture2D函數中的varTexCoords參數(如position.xz),它會繪製飛機(當然不正確)。但在我看來,我擁有必要的一切。

屬性數組:

glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, 0, 5 * sizeof(GLfloat), (GLvoid*)(plane[0]+2));  
glVertexAttribPointer(ATTRIB_TEX_COORDS, 2, GL_FLOAT, 0, 5 * sizeof(GLfloat), (GLvoid*)(plane[0])); 

我綁定屬性的位置和我啓用頂點屬性陣列:

glBindAttribLocation(program->id(), ATTRIB_VERTEX, "position"); 
glBindAttribLocation(program->id(), ATTRIB_TEX_COORDS, "texCoords"); 

glEnableVertexAttribArray(ATTRIB_VERTEX); 
glEnableVertexAttribArray(ATTRIB_TEX_COORDS); 

我已經試過一切。也許這個錯誤是微不足道的,我不能再想直了,因爲我這個接近失去理智。

任何提示讚賞。

+0

glEnable(TEXTURE_2D); OpenGL是基於狀態的。 – Krythic

+0

我有我的initGL()函數。 – Wanderer

+0

@Krythic:'glEnable(TEXTURE_2D);'與着色器完全不相關,它隻影響固定功能的流水線。 – derhass

回答

0

你是而不是使用你的紋理座標。 YOu確實設置了一些屬性指針,但是這些指針永遠不會被使用,因爲您正在使用即時模式glBegin()/glEnd()繪製平面,而未指定任何tex-coords(所以着色器將爲該屬性看到一個常量值)。您設置的屬性指針只會在您實際發出基於頂點數組的繪製調用時使用,如glDrawArrays()glDrawElements()

+0

好的,如果我在每個'glVertex3fv(plane [0] +2)'之前寫入'glTexCoord2f(x.0f,y.0f)',它應該是正確的(其中_x_和_y_將是相應的一個和零)?可悲的是,事實並非如此。 – Wanderer

+0

不,它不應該。使用'glVertex','glColor','glTexCoord'等將爲固定功能流水線設置棄用的內置屬性。您正在使用帶有_generic_屬性的着色器,因此您必須使用具有各種屬性索引的'​​glVertexAttrib'。 OpenGL只保證'glVertex'等價於設置泛型屬性0,所以至少得到正確的頂點座標的原因很可能是'ATTRIB_VERTEX'碰巧是'0'。但是,你會更好地完全放棄即時模式。 – derhass