1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
#version 410 core
out vec4 FragColor;
in float near; //0.01
in float far; //100
in vec3 nearPoint;
in vec3 farPoint;
in mat4 fragView;
in mat4 fragProj;
// void main() {
// // FragColor = vec4(1.0, 0.0, 0.0, 1.0);
// float t = -nearPoint.y / (farPoint.y - nearPoint.y);
// if (t > 0) {
// FragColor = vec4(1.0, 0.0, 0.0, 1.0);
// } else {
// FragColor = vec4(0.0);
// }
// // FragColor = vec4(1.0, 0.0, 0.0, 1.0 * float(t > 0)); // opacity = 1 when t > 0, opacity = 0 otherwise
// }
vec4 grid(vec3 fragPos3D, float scale, bool drawAxis) {
vec2 coord = fragPos3D.xz * scale;
vec2 derivative = fwidth(coord);
vec2 grid = abs(fract(coord - 0.5) - 0.5) / derivative;
float line = min(grid.x, grid.y);
float minimumz = min(derivative.y, 1);
float minimumx = min(derivative.x, 1);
vec4 color = vec4(0.2, 0.2, 0.2, 1.0 - min(line, 1.0));
// z axis
if(fragPos3D.x > -0.1 * minimumx && fragPos3D.x < 0.1 * minimumx)
color.z = 1.0;
// x axis
if(fragPos3D.z > -0.1 * minimumz && fragPos3D.z < 0.1 * minimumz)
color.x = 1.0;
return color;
}
float computeDepth(vec3 pos) {
vec4 clip_space_pos = fragProj * fragView * vec4(pos.xyz, 1.0);
return (clip_space_pos.z / clip_space_pos.w);
}
float computeLinearDepth(vec3 pos) {
vec4 clip_space_pos = fragProj * fragView * vec4(pos.xyz, 1.0);
float clip_space_depth = (clip_space_pos.z / clip_space_pos.w) * 2.0 - 1.0; // put back between -1 and 1
float linearDepth = (2.0 * near * far) / (far + near - clip_space_depth * (far - near)); // get linear value between 0.01 and 100
return linearDepth / far; // normalize
}
void main() {
float t = -nearPoint.y / (farPoint.y - nearPoint.y);
vec3 fragPos3D = nearPoint + t * (farPoint - nearPoint);
gl_FragDepth = computeDepth(fragPos3D);
float linearDepth = computeLinearDepth(fragPos3D);
float fading = max(0, (0.5 - linearDepth));
FragColor = (grid(fragPos3D, 10, true) + grid(fragPos3D, 1, true))* float(t > 0); // adding multiple resolution for the grid
FragColor.a *= fading;
}
|