]> gitweb.factorcode.org Git - factor.git/blob - extra/bunny/cel-shaded/cel-shaded.factor
core, basis, extra: Remove DOS line endings from files.
[factor.git] / extra / bunny / cel-shaded / cel-shaded.factor
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
5
6 STRING: vertex-shader-source
7 varying vec3 position, normal, viewer;
8
9 void
10 main()
11 {
12     gl_Position = ftransform();
13
14     position = gl_Vertex.xyz;
15     normal = gl_Normal;
16     viewer = vec3(0, 0, 1) * gl_NormalMatrix;
17 }
18
19 ;
20
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;
27
28 float
29 modulate(vec3 direction, vec3 normal)
30 {
31     return dot(direction, normal) * 0.5 + 0.5;
32 }
33
34 float
35 cel(float m)
36 {
37     return smoothstep(0.25, 0.255, m) * 0.4 + smoothstep(0.695, 0.70, m) * 0.5;
38 }
39
40 vec4
41 cel_light()
42 {
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);
48 }
49
50 ;
51
52 STRING: cel-shaded-fragment-shader-main-source
53 vec4 cel_light();
54
55 void
56 main()
57 {
58     gl_FragColor = cel_light();
59 }
60
61 ;
62
63 TUPLE: bunny-cel-shaded program ;
64
65 : cel-shading-supported? ( -- ? )
66     "2.0" { "GL_ARB_shader_objects" }
67     has-gl-version-or-extensions? ;
68
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 ;
79
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 ;
90
91 M: bunny-cel-shaded draw-bunny
92     program>> (draw-cel-shaded-bunny) ;
93
94 M: bunny-cel-shaded dispose
95     program>> delete-gl-program ;