Andy Ray
Andy Ray

Reputation: 32076

Threejs isolated reflection shader using cubeCamera not working

jsFiddle https://jsfiddle.net/t2pv9ku0/8/ demonstrates my problem.

I'm trying to re-create the reflection effect in ThreeJS using a RawShaderMaterial. There are several examples of this effect, which is pretty standard.

A cubeCamera is created and passed into the shader to provide the samplerCube:

material.uniforms.reflectionSampler.value = cubeCamera.renderTarget;

A reflection vector is calculated in the vertex shader:

varying vec3 vReflect;
...
vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {
    return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );
}
...
vec3 worldNormal = transformDirection( objectNormal, modelMatrix );
vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
vReflect = reflect( cameraToVertex, worldNormal );

It's used in the fragment shader to read from the cubeCamera's render:

gl_FragColor = vec4( vNormal.y ) + textureCube( reflectionSampler, vReflect );

However, as you can see in the jsFiddle, the effect does not appear to be working correctly. It appears to be reading the sample position incorrectly from the samplerCube. I've tried fiddling with everything

Upvotes: 0

Views: 793

Answers (1)

WestLangley
WestLangley

Reputation: 104833

Your cube camera is not part of the scene, so you must call

cubeCamera.updateMatrixWorld();

updated fiddle: https://jsfiddle.net/t2pv9ku0/9/

Alternatively, you can add the cubeCamera to the scene.

three.js r.71

Edit by Andy Here is a fiddle with reflection code https://jsfiddle.net/t2pv9ku0/11/ that mimics three's reflection

Upvotes: 2

Related Questions