]> git.tdb.fi Git - libs/gl.git/blob - shaderlib/common.glsl
Move lighting calculations to world space
[libs/gl.git] / shaderlib / common.glsl
1 import msp_interface;
2 import shadow;
3
4 uniform EnvMap
5 {
6         mat3 env_world_matrix;
7 };
8
9 uniform sampler2D normal_map;
10 uniform samplerCube environment_map;
11
12 layout(constant_id=auto) const bool use_normal_map = false;
13
14 #pragma MSP stage(vertex)
15 virtual vec4 get_vertex_position()
16 {
17         return vertex;
18 }
19
20 virtual vec3 get_vertex_normal()
21 {
22         return normal;
23 }
24
25 virtual mat4 get_vertex_transform()
26 {
27         return world_obj_matrix;
28 }
29
30 virtual mat3 get_normal_transform()
31 {
32         return world_obj_normal_matrix;
33 }
34
35 void standard_transform()
36 {
37         mat4 vertex_tf = get_vertex_transform();
38         mat3 normal_tf = get_normal_transform();
39
40         vec4 world_vertex = vertex_tf*get_vertex_position();
41         vec4 eye_vertex = eye_world_matrix*world_vertex;
42         gl_Position = clip_eye_matrix*eye_vertex;
43
44         out vec3 world_normal = normal_tf*get_vertex_normal();
45         vec3 world_tangent = normal_tf*tangent;
46         vec3 world_binormal = cross(world_normal, world_tangent);
47         out mat3 world_tbn_matrix = mat3(world_tangent, world_binormal, world_normal);
48
49         vec3 eye_pos = (inverse(eye_world_matrix)*vec4(0.0, 0.0, 0.0, 1.0)).xyz;
50         out vec3 world_look_dir = normalize(world_vertex.xyz-eye_pos);
51
52         out vec3 world_light_dir = light_sources[0].position.xyz-world_vertex.xyz*light_sources[0].position.w;
53
54         out vec3 world_halfway_dir = normalize(world_light_dir-world_look_dir);
55
56         out float fog_coord = eye_vertex.z;
57
58         if(use_clipping)
59         {
60                 for(int i=0; i<max_clip_planes; ++i)
61                         gl_ClipDistance[i] = dot(world_vertex, clip_planes[i].equation);
62         }
63
64         shadow_transform(world_vertex);
65 }
66
67 virtual void custom_transform()
68 {
69 }
70
71 void main()
72 {
73         standard_transform();
74         custom_transform();
75         passthrough;
76 }
77
78 #pragma MSP stage(fragment)
79 virtual vec3 get_fragment_normal()
80 {
81         if(use_normal_map)
82                 return normalize(world_tbn_matrix*(texture(normal_map, texcoord.xy).xyz*2.0-1.0));
83         else
84                 return normalize(world_normal);
85 }
86
87 virtual vec3 get_environment_sample(vec3 direction)
88 {
89         return texture(environment_map, env_world_matrix*direction).rgb;
90 }
91
92 virtual vec3 get_reflection(vec3 normal, vec3 look)
93 {
94         vec3 reflect_dir = reflect(look, normal);
95         return get_environment_sample(reflect_dir);
96 }
97
98 vec3 apply_fog(vec3 color)
99 {
100         float fog_value = exp(fog_coord*fog_density);
101         return mix(fog_color.rgb, color, fog_value);
102 }