demotool/shaders/raymarcher.glsl
Emmanuel BENOîT df06cf16ad PBR-ish stuff
Subsurface scattering doesn't work, though
2017-10-02 16:34:08 +02:00

98 lines
2.4 KiB
GLSL

vec3 getNormal( vec3 pos )
{
vec2 v = vec2( .01 , 0 );
return normalize( vec3(
map( pos + v.xyy ).x - map( pos - v.xyy ).x ,
map( pos + v.yxy ).x - map( pos - v.xyx ).x ,
map( pos + v.yyx ).x - map( pos - v.yyx ).x ) );
}
// -----------------------------------------------------------------------------
vec3 march( vec3 o , vec3 d , int steps , float factor )
{
int i = 0;
float dist = .01 , mat = -1;
for ( ; i < steps ; ++ i ) {
vec2 res = map( o + d * dist );
if ( abs( res.x ) < u_Render.z || dist > u_Render.w ) {
break;
}
dist += res.x * factor;
mat = res.y;
}
return vec3( dist , dist >= u_Render.w ? -1 : mat , i );
}
// -----------------------------------------------------------------------------
void main( )
{
setCamFromUniforms( );
vec2 uv = ( gl_FragCoord.xy / u_Resolution ) * 2 - 1;
vec3 camDir = normalize( lookAt - camPos );
vec3 side = normalize( cross( camUp , camDir ) );
vec3 up = normalize( cross( camDir , side ) );
vec3 rayDir = normalize( camDir * nearPlane
+ uv.x * side * u_Resolution.x / u_Resolution.y
+ uv.y * up );
vec3 r = march( camPos , rayDir , int( u_Render.x ) , u_Render.y );
vec3 hitPos = camPos + rayDir * r.x;
vec3 bc = vec3( 0 );
if ( r.y >= 0. ) {
const int midx = int( r.y );
const vec3 normal = getNormal( hitPos );
#if defined( USE_BP )
// Blinn-Phong only
bc = BP_Shade( BPMaterials[ midx ] ,
rayDir , normal , -u_LightDir );
#else
#if defined( USE_PBR )
// PBR only
T_PBRMaterial material = PBRMaterials[ midx ];
T_PBRPrecomputed precomputed = PBR_Precompute(
material , rayDir , normal );
bc = PBR_Shade( material , precomputed ,
rayDir , normal , -u_LightDir );
#else
#if defined( USE_MAP_MATERIAL )
// Remap materials through mapMaterials
int mtype , mtidx , glowidx;
mapMaterial( midx , mtype , mtidx , glowidx );
if ( mtype == 0 ) {
bc = BP_Shade( BPMaterials[ mtidx ] ,
rayDir , normal , -u_LightDir );
} else {
T_PBRMaterial material = PBRMaterials[ mtidx ];
T_PBRPrecomputed precomputed = PBR_Precompute(
material , rayDir , normal );
bc = PBR_Shade( material , precomputed ,
rayDir , normal , -u_LightDir );
}
#if defined( USE_GLOW )
if ( glowidx > 0 ) {
bc += Glow[ glowidx ];
}
#endif
#endif
#endif
#endif
#ifdef USE_GLOW
#ifndef USE_MAP_MATERIAL
bc += Glow[ midx ];
#endif
#endif
}
o_Color = bc;
o_Z = r.x;
}