gpt4 book ai didi

Three.js - 光晕效果的着色器代码,法线需要转换

转载 作者:行者123 更新时间:2023-12-03 06:26:30 30 4
gpt4 key购买 nike

我正在尝试创建一个着色器以在 Three.js 中产生发光光环效果。我当前的尝试在这里:http://stemkoski.github.io/Three.js/Shader-Halo.html

当前着色器代码是:

<script id="vertexShader" type="x-shader/x-vertex">
varying vec3 vNormal;
void main()
{
vNormal = normalize( normalMatrix * normal );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
</script>

<script id="fragmentShader" type="x-shader/x-vertex">
varying vec3 vNormal;
void main()
{
float intensity = pow( 0.7 - dot( vNormal, vec3( 0.0, 0.0, 1.0 ) ), 4.0 );
gl_FragColor = vec4( 1.0, 1.0, 1.0, 1.0 ) * intensity;
}
</script>

只要对象保持在场景的中心,这种方法就可以正常工作。缩放或平移后,光晕效果似乎分别改变强度或看起来不平衡。

我想我明白为什么会这样,从数学上来说——在这段代码中,发光效果的强度是由网格法线向量的 z 坐标决定的,因为那是面向观察者的向量,所以在计算强度之前,我应该以某种方式对 (0,0,1) 应用类似的变换。

这样我就到达了

<script id="vertexShader" type="x-shader/x-vertex">
varying vec3 vNormal;
varying vec4 vector;
void main()
{
vNormal = normalize( normalMatrix * normal );
vector = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 1.0, 0.0 );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
</script>

<script id="fragmentShader" type="x-shader/x-vertex">
varying vec3 vNormal;
varying vec4 vector;
void main()
{
vec4 v = vec4( vNormal, 0.0 );
float intensity = pow( 0.7 - dot( v, vector ), 4.0 );
gl_FragColor = vec4( 1.0, 1.0, 1.0, 1.0 ) * intensity;
}
</script>

即使在原点,它看起来也与我的原始着色器完全不同,并且当我缩放和平移场景时继续改变外观。

我很茫然。有谁知道如何正确转换法线向量(或者应该进行哪些其他更改),以便在缩放/平移场景时该着色器产生的外观不会改变?

[更新]

似乎有一个有希望的领先优势 http://john-chapman-graphics.blogspot.com/2013/01/good-enough-volumetrics-for-spotlights.html

特别是,

The edges ... need to be softened somehow, and that's where the vertex normals come in. We can use the dot product of the view space normal (cnorm) with the view vector (the normalised fragment position, cpos) as a metric describing how how near to the edge ... the current fragment is.

有人知道计算 View 空间法线和 View 向量的代码吗?

最佳答案

明白了!

在上面的代码中,vNormal 是顶点法线。要获取 View 向量,请向着色器添加一个统一值,其值是网格位置与相机位置之间的差值。 (理论上,该值应该是每个顶点位置与相机位置之间的差值,但这对于我的目的来说已经足够接近了。)

有关实现,请查看:http://stemkoski.github.io/Three.js/Shader-Glow.html

关于Three.js - 光晕效果的着色器代码,法线需要转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17455776/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com