Skip to content

Instantly share code, notes, and snippets.

@shinmai
Forked from Gitmoko/box.glsl
Created November 14, 2017 08:18
Show Gist options
  • Save shinmai/6180a4699e30ddda0b29099d06bbf4d6 to your computer and use it in GitHub Desktop.
Save shinmai/6180a4699e30ddda0b29099d06bbf4d6 to your computer and use it in GitHub Desktop.
#ifdef GL_ES
precision mediump float;
#endif
#extension GL_OES_standard_derivatives : enable
uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
//反復回数(constで書く方も多い)
#define ITE_MAX 190
#define DIST_COEFF .36
//打ち切り係数
#define DIST_MIN 0.01
//t最大
#define DIST_MAX 10000.0
#define inf 100000
#define PI 3.14159276
#define UnitWindow_Size 50.0
mat3 rotM(vec3 axis,float angle){
axis = normalize(axis);
float s = sin(angle);
float c = cos(angle);
float oc = 1.0 - c;
return mat3(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s,
oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s,
oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c);}
vec3 GenRay(vec3 dir,vec3 up,float angle){
vec2 p = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y);
vec3 u = normalize(cross(up, dir));
vec3 v = normalize(cross(dir, u));
float fov = angle * PI * 0.5 / 180.;
return normalize(sin(fov) * u * p.x + sin(fov) * v * p.y + cos(fov) * dir);}
float map(vec3 p){
float d = 0.;
//p = mod(p,12.) - vec3(6);
//d = length(p) - 3.;
d = length(max(abs(p)-vec3(1.,2.,1.),0.0));
//d = hivemap(p);
return d;
}
vec3 getnormal(vec3 p){
float d = 0.01;
return normalize(vec3(
map(p + vec3(d, 0.0, 0.0)) - map(p + vec3(-d, 0.0, 0.0)),
map(p + vec3(0.0, d, 0.0)) - map(p + vec3(0.0, -d, 0.0)),
map(p + vec3(0.0, 0.0, d)) - map(p + vec3(0.0, 0.0, -d))
));
}
void main( void) {
vec3 l = normalize(vec3(.0, -.99, .99));
//eye座標
vec3 pos = vec3(1.+2.*cos(time), 4. * sin(time), 1.5);
vec3 target = vec3(0.,0., 0.);
vec3 center_dir = (target - pos);
vec3 dir;
vec3 up = vec3(.0, 0., 1.);
dir = GenRay(normalize(center_dir), up, 120.);
float t = 0.0;
float dist = 0.;
//SphereTracing。ここintersectって名前で別に作る人も多いです
for(int i = 0 ; i < ITE_MAX; i++) {
//形状表現した陰関数を反復しながら解く
//0(DIST_MIN)に近くなったら解に近いので打ち切り
dist = map((t * dir + pos));
if(dist < DIST_MIN) {
break;
}
//tを更新。DIST_COEFFは複雑な形状を描画する際に小さく為につけています。
//ちょっとずつレイを進める事ができます。
t += dist * DIST_COEFF;
if(t > DIST_MAX){
break;
}
}
//option形状の近くの位置を出しておく
vec3 ip = pos + dir * t;
//色を作ります。ここでは進めたtの位置(深度)をただ出力するだけ
vec3 color = vec3(0.);
vec3 n = getnormal(ip);
if(dist < DIST_MIN){
float diff = dot(l,n);
color = vec3(0.3,0.8,0.9) * clamp(diff,0.1,1.);
color += vec3(.5) * clamp(dot(n,normalize(dir+l)),0.,1.);
//color += ip.z*vec3(2.0,1.,0.);
}
color += clamp((1.-20./t),0.,1.)*vec3(.8,.9,.9);
gl_FragColor = vec4(color, 1.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment