GLSL shader example

Glass Sphere Background Refraction

Compute a refracted direction from a sphere normal and use its lateral component to offset the background. This single-interface screen-space approximation omits internal bounces.

Live example

Edit the code and the preview updates as you type.

What to observe

Glass Sphere Background Refraction.

Mechanism

Compute a refracted direction from a sphere normal and use its lateral component to offset the background. This single-interface screen-space approximation omits internal bounces.

The controlling code

float r=length(p);vec2 q=uv;if(r<.65){float z=sqrt(.65*.65-r*r);vec3 n=normalize(vec3(p,z));vec3 refracted=refract(vec3(0,0,-1),n,1./1.45);q+=refracted.xy*(.12+.25*u_parameter);}c=texture2D(u_texture,q).rgb;if(r<.65)c+=pow(r/.65,8.)*.15;

Experiment

Change the refraction ratio 1./1.45 to 1./1.1. The refracted direction bends less, so the grid inside the circular mask lies closer to the undistorted background.

Debugging and cost

The shader samples the background once after a single refract call, then adds the artistic rim pow(r/.65,8.)*.15. Set the final .15 to 0. to remove that rim; this exposes the refraction alone and does not add an exit surface or internal reflections.

Built-in functions used

Learn it step by step