我正在尝试在
然而,当你移动相机(使其沿着
实时示例实际上是此GitHub问题的缩小测试用例。
three.js
中使用自定义着色器渲染背景和太阳。 我的想法是计算出太阳的屏幕空间位置,并在片段着色器中使用这些坐标进行渲染。期望的行为是太阳始终呈现在地平线上,位于(0,1000,-1000)
处。当你运行实时示例并抬头看时,似乎确实是这种情况。然而,当你移动相机(使其沿着
(0,-1,1)
向量看),你会注意到太阳突然被镜像和翻转,并且沿XY平面翻转。为什么会发生这种情况?这是否与在着色器中计算和评估屏幕空间坐标的方法有关?实时示例实际上是此GitHub问题的缩小测试用例。
var container;
var camera, cameraFX, scene, sceneFX, renderer;
var uniforms;
var sunPosition = new THREE.Vector3( 0, 1000, - 1000 );
var screenSpacePosition = new THREE.Vector3();
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 2000 );
camera.position.set( 0, 0, 10 );
cameraFX = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
scene = new THREE.Scene();
scene.add( new THREE.AxesHelper( 5 ) );
sceneFX = new THREE.Scene();
var geometry = new THREE.PlaneBufferGeometry( 2, 2 );
uniforms = {
"aspect": { value: window.innerWidth / window.innerHeight },
"sunPositionScreenSpace": { value: new THREE.Vector2() }
};
var material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent
} );
var quad = new THREE.Mesh( geometry, material );
sceneFX.add( quad );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
container.appendChild( renderer.domElement );
var controls = new THREE.OrbitControls( camera, renderer.domElement );
}
//
function animate( timestamp ) {
requestAnimationFrame( animate );
renderer.clear();
// background/sun pass
screenSpacePosition.copy( sunPosition ).project( camera );
screenSpacePosition.x = ( screenSpacePosition.x + 1 ) / 2;
screenSpacePosition.y = ( screenSpacePosition.y + 1 ) / 2;
uniforms[ "sunPositionScreenSpace" ].value.copy( screenSpacePosition );
renderer.render( sceneFX, cameraFX );
// beauty pass
renderer.clearDepth();
renderer.render( scene, camera );
}
body {
margin: 0;
}
canvas {
display: block;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.116.1/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.116.1/examples/js/controls/OrbitControls.js"></script>
<div id="container">
</div>
<script id="vertexShader" type="x-shader/x-vertex">
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4( position, 1.0 );
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
varying vec2 vUv;
uniform vec2 sunPositionScreenSpace;
uniform float aspect;
const vec3 sunColor = vec3( 1.0, 0.0, 0.0 );
const vec3 bgColor = vec3( 1.0, 1.0, 1.0 );
void main() {
vec2 diff = vUv - sunPositionScreenSpace;
diff.x *= aspect;
// background/sun drawing
float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 );
prop = 0.35 * pow( 1.0 - prop, 3.0 );
gl_FragColor.rgb = mix( sunColor, bgColor, 1.0 - prop );
gl_FragColor.a = 1.0;
}
</script>