-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHit.js
executable file
·89 lines (67 loc) · 2.35 KB
/
Hit.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var Hit = function (shape, t, coord, normal) { return (function (self) {
// ray parameter (origin + dir.scale(t))
self.t = t;
self.coord = vec3.create();
self.normal = vec3.create();
vec3.copy(self.coord, coord);
vec3.copy(self.normal, normal);
self.shape = shape;
var color = vec3.create(),
lightVec = vec3.create(),
H = vec3.create(),
view = vec3.create(),
ambient = vec3.create(),
nh = 0,
specCoeff = 0,
inShadow = false,
distSquare = 0,
ambientIntensity = 1.0,
difIntensity = 1.0,
specIntensity = 1.0;
self.getColor = function (lights) {
var ambientFactor = 1.0;
var mat = self.shape.getMaterial(self.coord);
vec3.copy(color, mat.ambient);
vec3.scale(color, color, 0.5);
lights.forEach(function(l) {
if (l.on) {
vec3.subtract(lightVec, l.position, self.coord);
var lightRay = Ray(self.coord, l.position);
distSquare = vec3.squaredLength(lightVec);
ambientFactor *= l.intensity[0] / distSquare;
inShadow = lightRay.isShadowCast(l.scene.geometry, self, distSquare);
if (! inShadow) {
vec3.normalize(lightVec, lightVec);
difIntensity = l.intensity[1] / distSquare;
specIntensity = l.intensity[2] / distSquare;
// diffuse
vec3.scaleAndAdd(color, color, mat.diffuse, difIntensity);
// specular
// blinn approximation for V dot R (view dot reflect)
vec3.subtract(view, l.scene.camera.eye, self.coord);
vec3.normalize(view, view);
// H = (view + light) / 2
vec3.add(H, view, lightVec);
vec3.scale(H, H, 0.5);
// N dot H = cos(theta / 2)
nh = vec3.dot(H, self.normal);
specCoeff = Math.pow(nh, mat.shiny);
if (nh > 0) {
vec3.scaleAndAdd(color, color, mat.specular, specCoeff * specIntensity);
}
}
}
});
// amb + amb * lightingAddtlFactor
vec3.scaleAndAdd(color, color, mat.ambient, ambientFactor);
vec3.add(color, color, ambient);
if ( color[0] > 255 ) color[0] = 255;
if ( color[1] > 255 ) color[1] = 255;
if ( color[2] > 255 ) color[2] = 255;
return color;
}
self.distance = function (from) {
return vec3.distance(self.coord, from);
}
return self;
})(Object.create(null))};