1 | #include "dxstdafx.h" |
---|
2 | #include "cylinder.h" |
---|
3 | |
---|
4 | bool Cylinder::intersectBackSide (const Ray& ray, float& depth, float rayMin, float rayMax) |
---|
5 | { |
---|
6 | return false; |
---|
7 | } |
---|
8 | |
---|
9 | bool Cylinder::intersect (const Ray& ray, float& depth, float rayMin, float rayMax) |
---|
10 | { |
---|
11 | lastTestedRayId = ray.id; |
---|
12 | lastTestedRayResult.isIntersect = false; |
---|
13 | Vector diff = (ray.origin - centre); |
---|
14 | diff.y = 0.0f; |
---|
15 | float b = 2.0f * (ray.dir * diff); |
---|
16 | float c = diff * diff - radius * radius; |
---|
17 | float a = ray.dir.x * ray.dir.x + ray.dir.z * ray.dir.z; |
---|
18 | |
---|
19 | float discriminant = b * b - 4.0f * a * c; |
---|
20 | if(discriminant < 0.0f) |
---|
21 | return false; |
---|
22 | else |
---|
23 | { |
---|
24 | float sqrtdisc = sqrtf(discriminant); |
---|
25 | float depth1 = (-b - sqrtdisc) * 0.5f / a; |
---|
26 | if(ray.origin.y + depth1 * ray.dir.y < top) |
---|
27 | { |
---|
28 | if(ray.origin.y + depth1 * ray.dir.y > bottom) |
---|
29 | { |
---|
30 | depth = depth1; |
---|
31 | lastTestedRayResult.isIntersect = true; |
---|
32 | lastTestedRayResult.material = this->material; |
---|
33 | lastTestedRayResult.depth = depth; |
---|
34 | lastTestedRayResult.point = ray.origin + ray.dir * depth; |
---|
35 | lastTestedRayResult.object = this; |
---|
36 | lastTestedRayResult.normal.setDifference(lastTestedRayResult.point, centre); |
---|
37 | lastTestedRayResult.normal.y = 0.0f; |
---|
38 | lastTestedRayResult.normal *= 1.0f / radius; |
---|
39 | return true; |
---|
40 | } |
---|
41 | else |
---|
42 | { |
---|
43 | float depth2 = (-b + sqrtdisc) * 0.5f / a; |
---|
44 | float h = (bottom - ray.origin.y) / ray.dir.y; |
---|
45 | if( h > depth1 && h < depth2) |
---|
46 | { |
---|
47 | depth = h; |
---|
48 | lastTestedRayResult.normal = Vector(0.0f, -1.0f, 0.0f); |
---|
49 | } |
---|
50 | else |
---|
51 | return false; |
---|
52 | } |
---|
53 | } |
---|
54 | else |
---|
55 | { |
---|
56 | float depth2 = (-b + sqrtdisc) * 0.5f / a; |
---|
57 | float h = (top - ray.origin.y) / ray.dir.y; |
---|
58 | if( h > depth1 && h < depth2) |
---|
59 | { |
---|
60 | depth = h; |
---|
61 | lastTestedRayResult.normal = Vector(0.0f, 1.0f, 0.0f); |
---|
62 | } |
---|
63 | else |
---|
64 | return false; |
---|
65 | } |
---|
66 | |
---|
67 | lastTestedRayResult.isIntersect = true; |
---|
68 | lastTestedRayResult.material = this->material; |
---|
69 | lastTestedRayResult.depth = depth; |
---|
70 | lastTestedRayResult.point = ray.origin + ray.dir * depth; |
---|
71 | lastTestedRayResult.object = this; |
---|
72 | return true; |
---|
73 | } |
---|
74 | } |
---|