remove math.blas.syntax and merge parsing words into math.blas.vectors/matrices
[factor/jcg.git] / extra / bunny / cel-shaded / cel-shaded.factor
blobb1e24243f08cd4e2de09b519e308561a1ae15725
1 USING: arrays bunny.model continuations destructors kernel
2 multiline opengl opengl.shaders opengl.capabilities opengl.gl
3 sequences accessors combinators ;
4 IN: bunny.cel-shaded
6 STRING: vertex-shader-source
7 varying vec3 position, normal, viewer;
9 void
10 main()
12     gl_Position = ftransform();
14     position = gl_Vertex.xyz;
15     normal = gl_Normal;
16     viewer = vec3(0, 0, 1) * gl_NormalMatrix;
21 STRING: cel-shaded-fragment-shader-lib-source
22 varying vec3 position, normal, viewer;
23 uniform vec3 light_direction;
24 uniform vec4 color;
25 uniform vec4 ambient, diffuse;
26 uniform float shininess;
28 float
29 modulate(vec3 direction, vec3 normal)
31     return dot(direction, normal) * 0.5 + 0.5;
34 float
35 cel(float m)
37     return smoothstep(0.25, 0.255, m) * 0.4 + smoothstep(0.695, 0.70, m) * 0.5;
40 vec4
41 cel_light()
43     vec3 direction = normalize(light_direction - position);
44     vec3 reflection = reflect(direction, normal);
45     vec4 ad = (ambient + diffuse * vec4(vec3(cel(modulate(direction, normal))), 1));
46     float s = cel(pow(max(dot(-reflection, viewer), 0.0), shininess));
47     return ad * color + vec4(vec3(s), 0);
52 STRING: cel-shaded-fragment-shader-main-source
53 vec4 cel_light();
55 void
56 main()
58     gl_FragColor = cel_light();
63 TUPLE: bunny-cel-shaded program ;
65 : cel-shading-supported? ( -- ? )
66     "2.0" { "GL_ARB_shader_objects" }
67     has-gl-version-or-extensions? ;
69 : <bunny-cel-shaded> ( gadget -- draw )
70     drop
71     cel-shading-supported? [
72         bunny-cel-shaded new
73         vertex-shader-source <vertex-shader> check-gl-shader
74         cel-shaded-fragment-shader-lib-source <fragment-shader> check-gl-shader
75         cel-shaded-fragment-shader-main-source <fragment-shader> check-gl-shader
76         3array <gl-program> check-gl-program
77         >>program
78     ] [ f ] if ;
80 : (draw-cel-shaded-bunny) ( geom program -- )
81     [
82         {
83             [ "light_direction" glGetUniformLocation 1.0 -1.0 1.0 glUniform3f ]
84             [ "color"           glGetUniformLocation 0.6 0.5 0.5 1.0 glUniform4f ]
85             [ "ambient"         glGetUniformLocation 0.2 0.2 0.2 0.2 glUniform4f ]
86             [ "diffuse"         glGetUniformLocation 0.8 0.8 0.8 0.8 glUniform4f ]
87             [ "shininess"       glGetUniformLocation 100.0 glUniform1f ]
88         } cleave bunny-geom
89     ] with-gl-program ;
91 M: bunny-cel-shaded draw-bunny
92     program>> (draw-cel-shaded-bunny) ;
94 M: bunny-cel-shaded dispose
95     program>> delete-gl-program ;