標(biāo)簽 : glsl, shader, opengl, android, 黑屏
自己寫(xiě)的 opengl shader 腳本有時(shí)會(huì)出現(xiàn)部分機(jī)型上運(yùn)行正常, 部分機(jī)型上黑屏的 bug. 下面是筆者開(kāi)發(fā)過(guò)程中遇到的問(wèn)題及解決方案.
1 部分機(jī)型不支持在 main()
函數(shù)中調(diào)用 return
原本計(jì)劃在著色器中實(shí)現(xiàn)以下 shader 邏輯
//...
varying vec2 textureCoordinate;
uniform samplerExternalOES s_texture;
uniform int flag;
void main() {
if (flag > 0) {
gl_FragColor = texture2D(s_texture, textureCoordinate);
return;
}
//...
}
該方法在大部分機(jī)型上都運(yùn)行正常, 但是少部分機(jī)型上黑屏. 調(diào)試發(fā)現(xiàn), 這部分機(jī)型不支持在 main()
函數(shù)中調(diào)用 return
. 所以唯一的修改方案是:
//...
varying vec2 textureCoordinate;
uniform samplerExternalOES s_texture;
uniform int flag;
void main() {
if (flag > 0) {
gl_FragColor = texture2D(s_texture, textureCoordinate);
} else {
//...
}
}
2 部分機(jī)型不支持在 main()
函數(shù)中申明新的浮點(diǎn)變量
這個(gè) bug 比較無(wú)語(yǔ). 預(yù)期想在圖片四角實(shí)現(xiàn)效果, 邏輯如下:
//...
varying vec2 textureCoordinate;
uniform samplerExternalOES s_texture;
void main() {
float r = abs(textureCoordinate.x - 0.5) + abs(textureCoordinate.y - 0.5) - 0.5;
if (r > 0.0) {
//...
} else {
//...
}
}
穩(wěn)定的解法是把原來(lái)的局部變量變成全局的:
//...
varying vec2 textureCoordinate;
uniform samplerExternalOES s_texture;
highp float r;
void main() {
r = abs(textureCoordinate.x - 0.5) + abs(textureCoordinate.y - 0.5) - 0.5;
if (r > 0.0) {
//...
} else {
//...
}
}
2 OpenGL ES 1.0 以后版本不支持在申明數(shù)組同時(shí)初始化數(shù)組
這個(gè)問(wèn)題比較變態(tài). 參考官方文檔 paragraph 4.1.9 Arrays (p. 24):
There is no mechanism for initializing arrays at declaration time from within a shader.