Opengl es 为什么人们使用sqrt(dot(distanceVector,distanceVector))而不是OpenGL';s距离函数?

Opengl es 为什么人们使用sqrt(dot(distanceVector,distanceVector))而不是OpenGL';s距离函数?,opengl-es,glsl,shader,webgl,Opengl Es,Glsl,Shader,Webgl,在使用ShaderToy时,我经常看到人们使用以下内容: vec2 uv = fragCoord / iResolution; vec2 centerPoint = vec2(0.5); vec2 distanceVector = uv - centerPoint; float dist = sqrt(dot(distanceVector, distanceVector)); 通过OpenGL的距离功能: vec2 uv = fragCoord / iResolution; vec2 cen

在使用ShaderToy时,我经常看到人们使用以下内容:

vec2 uv = fragCoord / iResolution;
vec2 centerPoint = vec2(0.5);

vec2 distanceVector = uv - centerPoint;
float dist = sqrt(dot(distanceVector, distanceVector));
通过OpenGL的
距离
功能:

vec2 uv = fragCoord / iResolution;
vec2 centerPoint = vec2(0.5);

float dist = distance(uv, centerPoint);
我只是好奇为什么会这样(我猜这与速度或对距离的支持有关)


我大致理解,如果参数相同,点积的平方根等于向量的长度:距离?

基本上做相同的事情,人们通常选择sqrt选项,原因有两个: 1.他们不知道/不记得距离函数
2.他们相信他们自己和他们自己的数学能够证明这不是一个引起bug的问题(避免OpenGL问题)

使用点可以让你快速实验距离的二次/线性函数。

根据,
距离()
长度()
在内部使用平方根(
sqrt()
)。使用
sqrt()
和所有依赖它的函数可能会很昂贵。如果可能,只需使用
dot()


我猜
sqrt()
是一种数学计算,但
dot()
是一种矢量计算,GPU擅长于此。

有时会优化早期出口,例如轻量:

float distSquared( vec3 A, vec3 B )
{

    vec3 C = A - B;
    return dot( C, C );

}

// Early escape when the distance between the fragment and the light 
// is smaller than the light volume/sphere threshold.
//float dist = length(lights[i].Position - FragPos);
//if(dist < lights[i].Radius)
// Let's optimize by skipping the expensive square root calculation
// for when it's necessary.
float dist = distSquared( lights[i].Position, FragPos );
if( dist < lights[i].Radius * lights[i].Radius )
{ 
 
    // Do expensive calculations.
编辑:另一个例子


我最近学习的另一个用例是,假设您想要两个位置:
vec3 posOne
vec3 posTwo
,并且您想要到每个位置的距离。最简单的方法是独立计算它们:
float distance one=distance(posOne,otherPos)
float distance two=distance(posTwo,otherPos)
。但是你想利用SIMD!你可以这样做:
posOne-=otherPos;posTwo-=otherPos
因此您可以通过SIMD计算欧几里德距离:
vec2 SIMDDistance=vec2(点(posOne),点(posTwo))SIMDDistance=sqrt(SIMDDistance)到posOne的距离在SimdInstance变量的.x分量上,而.y分量包含到posTwo的距离。

是否更快?或者你能比较两个功能循环吗?
dist = sqrt( dist )