3d 从WebGL片段着色器输出的颜色在不同平台之间存在显著差异

3d 从WebGL片段着色器输出的颜色在不同平台之间存在显著差异,3d,three.js,webgl,shader,fragment-shader,3d,Three.js,Webgl,Shader,Fragment Shader,我有一个网站,使大量使用WebGL着色器。在各种平台上测试时,我发现WebGL画布上的颜色并不总是匹配的,特别是着色器的输出,该着色器使用大量计算来绘制表示天空的渐变。有些窗户的颜色要暗得多 天空明暗器是此明暗器的(非常轻微)修改版本: 着色器代码可在此处找到: 正确加载页面后,天空着色器将输出以下内容: 但是,在某些Windows机器上,它看起来像: 到目前为止,我得到的一个线索是,在(Firefox)Windows上,控制台中有大量日志警告: warning: X3571: pow(f,

我有一个网站,使大量使用WebGL着色器。在各种平台上测试时,我发现WebGL画布上的颜色并不总是匹配的,特别是着色器的输出,该着色器使用大量计算来绘制表示天空的渐变。有些窗户的颜色要暗得多

天空明暗器是此明暗器的(非常轻微)修改版本:

着色器代码可在此处找到:

正确加载页面后,天空着色器将输出以下内容:

但是,在某些Windows机器上,它看起来像:

到目前为止,我得到的一个线索是,在(Firefox)Windows上,控制台中有大量日志警告:

warning: X3571: pow(f, e) will not work for negative f, use abs(f) or conditionally handle negative values if you expect them
编辑,我已经按照gman的建议,添加了安全功能,下面是我修改的着色器。它仍然表现出与以前一样的行为。我注意到的一件事是,定义了许多具有大值或小值的常量,例如

const float N = 2.545E25;
这可能是问题的根源吗?例如,某种浮点精度问题?注:目标机器确实报告高精度

完整着色器位于此处:

uniform vec3 sunPosition;
uniform float luminance;
uniform float turbidity;
uniform float reileigh;
uniform float mieCoefficient;
uniform float mieDirectionalG;

varying vec3 vWorldPosition;

// constants for atmospheric scattering
const float e = 2.71828182845904523536028747135266249775724709369995957;
const float pi = 3.141592653589793238462643383279502884197169;

const float n = 1.0003; // refractive index of air
const float N = 2.545E25; // number of molecules per unit volume for air at
// 288.15K and 1013mb (sea level -45 celsius)
const float pn = 0.035; // depolatization factor for standard air

// wavelength of used primaries, according to preetham
const vec3 lambda = vec3(680E-9, 550E-9, 450E-9);

// mie stuff
// K coefficient for the primaries
const vec3 K = vec3(0.686, 0.678, 0.666);
const float v = 4.0;

// optical length at zenith for molecules
const float rayleighZenithLength = 8.4E3;
const float mieZenithLength = 1.25E3;
const vec3 up = vec3(0.0, 1.0, 0.0);

const float EE = 1000.0;
const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;
// 66 arc seconds -> degrees, and the cosine of that

// earth shadow hack
const float cutoffAngle = pi/1.95;
const float steepness = 1.5;

// Safe functions
float spow( const float x, const float y ) {
  return pow( abs( x ), y );
}

vec3 spow( const vec3 x, const vec3 y ) {
  return pow( abs( x ), y );
}

vec3 ssqrt( const vec3 x ) {
  return sqrt( abs( x ) );
}

float slog2( const float x ) {
  return log2( abs( x ) );
}

float sacos( const float x ) {
  return acos( clamp( x, 0.0, 1.1 ) );
}

vec3 totalRayleigh(vec3 lambda)
{
  float nn = n * n - 1.0;
  return (8.0 * pi * pi * pi * nn * nn * (6.0 + 3.0 * pn)) / (3.0 * N * spow( lambda, vec3(4.0)) * (6.0 - 7.0 * pn));
}

float rayleighPhase(float cosTheta)
{    
  return (3.0 / (16.0*pi)) * (1.0 + cosTheta * cosTheta);
}

vec3 totalMie(vec3 lambda, vec3 K, float T)
{
  float c = (0.2 * T ) * 10E-18;
  vec3 ll = (2.0 * pi) / lambda;
  return 0.434 * c * pi * spow( ll, vec3(v - 2.0)) * K;
}

float hgPhase(float cosTheta, float g)
{
  return (1.0 / (4.0*pi)) * ((1.0 - g * g) / spow( 1.0 - 2.0 * g * cosTheta + g * g, 1.5));
}

float sunIntensity(float zenithAngleCos)
{
  return EE * max(0.0, 1.0 - exp(-((cutoffAngle - sacos(zenithAngleCos))/steepness)));
}

// float logLuminance(vec3 c)
// {
//  return log(c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722);
// }

// Filmic ToneMapping http://filmicgames.com/archives/75
const float A = 0.15;
const float B = 0.50;
const float C = 0.10;
const float D = 0.20;
const float E = 0.02;
const float F = 0.30;
const float W = 1000.0;

vec3 Uncharted2Tonemap(vec3 x)
{
  return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;
}

void main() 
{
  vec3 cameraPos = vec3( 0.0 );
  vec3 sunDirection = normalize(sunPosition.xzy);
  float reileighCoefficient = reileigh;

  float sunfade = 1.0-clamp(1.0-exp((sunPosition.z/450000.0)),0.0,1.0);

  // luminance =  1.0 ;// vWorldPosition.y / 450000. + 0.5; //sunPosition.y / 450000. * 1. + 0.5;

  // gl_FragColor = vec4(sunfade, sunfade, sunfade, 1.0);

  reileighCoefficient = reileighCoefficient - (1.0* (1.0-sunfade));

  float sunE = sunIntensity(dot(sunDirection, up));

  // extinction (absorbtion + out scattering) 
  // rayleigh coefficients
  vec3 betaR = totalRayleigh(lambda) * reileighCoefficient;

  // mie coefficients
  vec3 betaM = totalMie(lambda, K, turbidity) * mieCoefficient;

  // optical length
  // cutoff angle at 90 to avoid singularity in next formula.
  float zenithAngle = sacos(max(0.0, dot(up, normalize(vWorldPosition - cameraPos))));
  float denom = (cos(zenithAngle) + 0.15 / spow( 93.885 - ((zenithAngle * 180.0) / pi ), 1.253 ));
  float sR = rayleighZenithLength / denom;
  float sM = mieZenithLength / denom;



  // combined extinction factor 
  vec3 Fex = exp(-(betaR * sR + betaM * sM));

  // in scattering
  float cosTheta = dot(normalize(vWorldPosition - cameraPos), sunDirection);

  float rPhase = rayleighPhase(cosTheta*0.5+0.5);
  vec3 betaRTheta = betaR * rPhase;

  float mPhase = hgPhase(cosTheta, mieDirectionalG);
  vec3 betaMTheta = betaM * mPhase;

  vec3 tmp = sunE * ((betaRTheta + betaMTheta) / (betaR + betaM));
  vec3 Lin = spow( tmp * ( 1.0 - Fex ), vec3(1.5));
  Lin *= mix(vec3(1.0), ssqrt( tmp * Fex ), clamp( spow( 1.0 - dot( up, sunDirection ), 5.0), 0.0, 1.0 ) );

  //nightsky
  vec3 L0 = vec3( 0.1 ) * Fex;

  // composition + solar disc
  //if (cosTheta > sunAngularDiameterCos)
  float sundisk = smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);
  // if (normalize(vWorldPosition - cameraPos).y>0.0)
  L0 += (sunE * 19000.0 * Fex)*sundisk;


  vec3 whiteScale = 1.0 / Uncharted2Tonemap(vec3(W));

  vec3 texColor = (Lin+L0);   
  texColor *= 0.04 ;
  texColor += vec3(0.0,0.001,0.0025)*0.3;

  float g_fMaxLuminance = 1.0;
  float fLumScaled = 0.1 / luminance;     
  float fLumCompressed = (fLumScaled * (1.0 + (fLumScaled / (g_fMaxLuminance * g_fMaxLuminance)))) / (1.0 + fLumScaled); 

  float ExposureBias = fLumCompressed;

  vec3 curr = Uncharted2Tonemap( ( slog2( 2.0 / spow( luminance, 4.0 ) ) ) * texColor);
  vec3 color = curr*whiteScale;

  vec3 retColor = spow( color, vec3( 1.0 / ( 1.2 + ( 1.2 * sunfade ) ) ) );


  gl_FragColor.rgb = retColor;

  gl_FragColor.a = 1.0;
}
问题机器的www.webglreport.com输出如下:

Platform:  Win32
Browser User Agent:  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0
Context Name:  webgl
GL Version:  WebGL 1.0
Shading Language Version:  WebGL GLSL ES 1.0
Vendor:  Mozilla
Renderer:  Mozilla
Antialiasing:  Available
ANGLE:  Yes, D3D9
Major Performance Caveat:  Not implemented
Vertex Shader
Max Vertex Attributes:  16
Max Vertex Uniform Vectors:  254
Max Vertex Texture Image Units:  4
Max Varying Vectors:  10
Best float precision:  [-2127, 2127] (23)
Rasterizer
Aliased Line Width Range:  [1, 1]
Aliased Point Size Range:  [1, 256]
Fragment Shader
Max Fragment Uniform Vectors:  221
Max Texture Image Units:  16
float/int precision:  highp/highp
Best float precision:  [-2127, 2127] (23)
Framebuffer
Max Color Buffers:  1
RGBA Bits:  [8, 8, 8, 8]
Depth / Stencil Bits:  [24, 8]
Max Render Buffer Size:  4096
Max Viewport Dimensions:  [4096, 4096]
Textures
Max Texture Size:  4096
Max Cube Map Texture Size:  4096
Max Combined Texture Image Units:  20
Max Anisotropy:  16
Supported Extensions:
ANGLE_instanced_arrays
EXT_frag_depth
EXT_texture_filter_anisotropic
OES_element_index_uint
OES_standard_derivatives
OES_texture_float
OES_texture_float_linear
OES_texture_half_float
OES_texture_half_float_linear
OES_vertex_array_object
WEBGL_compressed_texture_s3tc
WEBGL_depth_texture
WEBGL_lose_context
MOZ_WEBGL_lose_context
MOZ_WEBGL_compressed_texture_s3tc
MOZ_WEBGL_depth_texture

我只是猜测这是一个错误

我尝试在片段着色器的不同位置显示结果。经过几次平分,我发现这条线在Windows和OSX上产生了不同的结果

vec3 betaR = totalRayleigh(lambda) * reileighCoefficient;
totalRayleigh
看起来像这样

vec3 totalRayleigh(vec3 lambda) {
    return (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / 
            (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn));
}
vec3 totalRayleigh(vec3 lambda) {
    return vec3(0.000005804542996261093, 
                0.000013562911419845635, 
                0.00003026590629238531);
}
这段代码完全是一个常量编译时表达式。因此,我将其粘贴到JavaScript中,在
pow
s前面添加
Math.
,然后计算结果的
x
y
z

将其更改为仅使用这样的结果

vec3 totalRayleigh(vec3 lambda) {
    return (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / 
            (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn));
}
vec3 totalRayleigh(vec3 lambda) {
    return vec3(0.000005804542996261093, 
                0.000013562911419845635, 
                0.00003026590629238531);
}
解决了这个问题


如果你好奇的话,我不清楚问题是什么。使用
WEBGL\u debug\u着色器
扩展显示传递给驱动程序的着色器。该函数在GLSL和HLSL上看起来相同

--GLSL--

--HLSL--

呼叫点也是

--GLSL--

--HLSL--

一个想法是HLSL的编译器没有足够的分辨率来处理这些微小的值?可能是用浮点数来计算编译时常量而不是双精度?所以,我试着把这个函数转换成C++

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

const float pi = 3.141592653589793238462643383279502884197169f;

const float n = 1.0003f; // refractive index of air",
const float N = 2.545E25f; // number of molecules per unit volume for air at",
                            // 288.15K and 1013mb (sea level -45 celsius)",
const float pn = 0.035f;    // depolatization factor for standard air",

float totalRayleigh(float lambda) {
    return (8.0f * powf(pi, 3.0f) * powf(powf(n, 2.0f) - 1.0f, 2.0f) * (6.0f + 3.0f * pn)) /
            (3.0f * N * powf(lambda, 4.0f) * (6.0f - 7.0f * pn));
}

int main() {
  //const vec3 lambda = vec3(680E-9, 550E-9, 450E-9);
  printf("%g, %g, %g", totalRayleigh(680E-9), totalRayleigh(550E-9), totalRayleigh(450E-9));
  return EXIT_SUCCESS;
}
将它们插入到totalRayleigh中仍然可以产生正确的结果,因此这不是问题所在


将totalRayleigh更改为只返回vec3(0,0,0)会产生错误的蓝色结果。

gman上面的回答很好,我只是添加以下内容,以防对其他人有用。我还继续,在可能的情况下,用预计算的值替换大的小常数,用于瑞利系数和米氏系数:

#!/usr/bin/python 
import math

# Poor man's vector lib
def dot( a, b ):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]

def scale( v, n ):
    return map( lambda x: x * n, v )

def vpow( v, n ):
    return map( lambda x: math.pow( x, n ), v )

# Input constants
n = 1.0003 # refractive index of air   
N = 2.545E25 # number of molecules per unit volume for air at
pn = 0.035 # depolatization factor for standard air

lamb = (680E-9, 550E-9, 450E-9)
K = (0.686, 0.678, 0.666)

# Rayleigh
nn = n * n - 1.0;
rayleigh = ( 8.0 * math.pow( math.pi, 3 ) * math.pow( nn, 2 ) * ( 6.0 + 3.0 * pn) ) / (3.0 * N *( 6.0 - 7.0 * pn ) )

print "totalRayleigh = rayleigh / pow( lambda, vec3( 4.0 ) )"
print "const float rayleigh =", rayleigh

rayleigh = scale( vpow( lamb, -4.0 ), rayleigh )
print "Fold in lambda..."
print "const vec3 rayleigh =", rayleigh

# Mie
mie = scale( K, 3.472E-18 * math.pow( math.pi, 3 ) / dot( lamb, lamb ) )

print "totalMie = mie * T"
print "const vec3 mie =", mie

你能把着色器发布到某个地方吗?着色器的来源在这里:我会用
mypow
搜索并替换
pow
log2
mylog2
acos
用my
myacos
并提供安全的实现。示例
float mypow(float a,float b){return pow(a,abs(b));}
float mylog2(float a){return log2(abs(a));}
float myacos(float a){return acos(clamp(a,0.0,1.1));}
等等。。。我想您还需要一个
vec3
版本的
pow
。基本上确保你没有使用任何未定义的行为。我没有电脑可以给出不同的结果,但通常这就是原因。我的电脑也输出蓝色版本。尝试一点四舍五入浮动,这可能会奏效。另外,你有没有测试过它,看它是否可能是一个角度问题?设置
——使用gl=desktop
标志来显示Chrome之类的东西?哇,回答得很好-谢谢。我需要测试确认,但手头没有Windows机器。FWIW我去做了类似的事情,见下面的答案
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

const float pi = 3.141592653589793238462643383279502884197169f;

const float n = 1.0003f; // refractive index of air",
const float N = 2.545E25f; // number of molecules per unit volume for air at",
                            // 288.15K and 1013mb (sea level -45 celsius)",
const float pn = 0.035f;    // depolatization factor for standard air",

float totalRayleigh(float lambda) {
    return (8.0f * powf(pi, 3.0f) * powf(powf(n, 2.0f) - 1.0f, 2.0f) * (6.0f + 3.0f * pn)) /
            (3.0f * N * powf(lambda, 4.0f) * (6.0f - 7.0f * pn));
}

int main() {
  //const vec3 lambda = vec3(680E-9, 550E-9, 450E-9);
  printf("%g, %g, %g", totalRayleigh(680E-9), totalRayleigh(550E-9), totalRayleigh(450E-9));
  return EXIT_SUCCESS;
}
5.80703e-06, 1.35687e-05, 3.02789e-05
#!/usr/bin/python 
import math

# Poor man's vector lib
def dot( a, b ):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]

def scale( v, n ):
    return map( lambda x: x * n, v )

def vpow( v, n ):
    return map( lambda x: math.pow( x, n ), v )

# Input constants
n = 1.0003 # refractive index of air   
N = 2.545E25 # number of molecules per unit volume for air at
pn = 0.035 # depolatization factor for standard air

lamb = (680E-9, 550E-9, 450E-9)
K = (0.686, 0.678, 0.666)

# Rayleigh
nn = n * n - 1.0;
rayleigh = ( 8.0 * math.pow( math.pi, 3 ) * math.pow( nn, 2 ) * ( 6.0 + 3.0 * pn) ) / (3.0 * N *( 6.0 - 7.0 * pn ) )

print "totalRayleigh = rayleigh / pow( lambda, vec3( 4.0 ) )"
print "const float rayleigh =", rayleigh

rayleigh = scale( vpow( lamb, -4.0 ), rayleigh )
print "Fold in lambda..."
print "const vec3 rayleigh =", rayleigh

# Mie
mie = scale( K, 3.472E-18 * math.pow( math.pi, 3 ) / dot( lamb, lamb ) )

print "totalMie = mie * T"
print "const vec3 mie =", mie