Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Computer Graphics with WebGL / Project / shaders.js
blob: d9597df75248732e243fe137b79ca6c1486e7801 (plain) (blame)
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
61
62
63
64
65
66
67
68
69
70
var vShader =`
	uniform mat4 uProjectionMatrix;
	uniform mat4 uViewMatrix;
	uniform mat4 uModelMatrix;
	uniform mat4 uNormalMatrix;
	uniform bool uUseNormalMatrix;
	
	uniform vec3 uAmbientColor;
	uniform vec3 uDiffuseColor;
	
	uniform vec3 uLightDir;
	
	attribute vec3 aXYZ;
	attribute vec3 aColor;
	attribute vec3 aNormal;

	attribute vec4 aSphere;
	varying vec4 vSphere;
	
	varying vec3 vColor;
	varying vec3 vXYZ;
	
	void main ()
	{
		mat4 mvMatrix = uViewMatrix * uModelMatrix;
		gl_Position = uProjectionMatrix * mvMatrix * vec4(aXYZ,1);
		mat4 nMatrix = uUseNormalMatrix?uNormalMatrix:mvMatrix;
	
		vColor = uAmbientColor*aColor;
	
		vec3 light = normalize(-uLightDir);
		vec3 normal = vec3(normalize(nMatrix*vec4(aNormal,0)));
		vColor += aColor*uDiffuseColor*max(dot(normal,light),0.0);
		vXYZ = (uModelMatrix * vec4(aXYZ,1)).xyz;

		vSphere = aSphere;
	}
`;
	
var fShader = `
	precision mediump float;
	
	varying vec3 vColor;
	varying vec3 vXYZ;
	varying vec4 vSphere;

	uniform vec3 uEye;
	uniform vec3 uEyeForward;

	void main()
	{
		vec3 ray = uEye;
		vec3 step = normalize(uEyeForward);

		for (int i = 0; i < 100; i++) {
			float dist = distance(ray, vSphere.xyz) - vSphere.a;
			if (dist < 0.001) {
				if (vSphere.a == 0.0) {
					gl_FragColor = vec4(vColor,1.0);
				}
				else {
					gl_FragColor = vec4(1,0,0,1);
				}
				return;
			}
			ray += step * dist;
		}
		gl_FragColor = vec4(0,0,0,1);
	}
`;