demotool/shaders/raymarcher.glsl

105 lines
2.5 KiB
Text
Raw Normal View History

2017-09-30 10:46:01 +02:00
vec3 getNormal( vec3 pos )
{
2017-10-03 10:06:26 +02:00
vec2 v = vec2( .0005 , 0 );
2017-09-30 10:46:01 +02:00
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 );
2017-09-30 11:23:14 +02:00
if ( r.y >= 0. ) {
const int midx = int( r.y );
const vec3 normal = getNormal( hitPos );
2017-10-03 10:06:26 +02:00
const vec3 lightDir = normalize( -u_LightDir );
#if defined( USE_BP )
// Blinn-Phong only
bc = BP_Shade( BPMaterials[ midx ] ,
2017-10-03 10:06:26 +02:00
rayDir , normal , lightDir );
#else
#if defined( USE_PBR )
// PBR only
2017-10-03 10:06:26 +02:00
T_PBRMaterialOld material = PBRMaterialsOld[ midx ];
T_PBRPrecomputedOld precomputed = PBR_PrecomputeOld(
material , rayDir , normal );
2017-10-03 10:06:26 +02:00
bc = PBR_ShadeOld( material , precomputed ,
rayDir , normal , 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 ] ,
2017-10-03 10:06:26 +02:00
rayDir , normal , lightDir );
2017-09-30 10:46:01 +02:00
} else {
2017-10-03 10:06:26 +02:00
#if 0
T_PBRMaterialOld material = PBRMaterialsOld[ mtidx ];
T_PBRPrecomputedOld precomputed = PBR_PrecomputeOld(
material , rayDir , normal );
2017-10-03 10:06:26 +02:00
bc = PBR_ShadeOld( material , precomputed ,
rayDir , normal , lightDir );
#else
bc = PBR_Shade( PBRMaterials[ mtidx ] ,
-rayDir , normal , lightDir );
#endif
2017-09-30 10:46:01 +02:00
}
#if defined( USE_GLOW )
2017-10-03 10:06:26 +02:00
if ( glowidx >= 0 ) {
bc += Glow[ glowidx ];
2017-09-30 10:46:01 +02:00
}
#endif
#endif
#endif
#endif
#ifdef USE_GLOW
#ifndef USE_MAP_MATERIAL
bc += Glow[ midx ];
#endif
#endif
2017-09-30 10:46:01 +02:00
}
o_Color = bc;
o_Z = r.x;
2017-09-30 10:46:01 +02:00
}