-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathray.cpp
More file actions
64 lines (53 loc) · 1.64 KB
/
Copy pathray.cpp
File metadata and controls
64 lines (53 loc) · 1.64 KB
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
// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: https://pvs-studio.com
#include "template.h"
#include "Sphere.h"
Ray::Ray( const float3 origin, const float3 direction, const float rayLength )
: m_origin( origin ), m_direction( normalize( direction ) ), m_normal(0), m_length( rayLength )
{
}
float3 Ray::GetNormal() const
{
if (m_axis == AXIS_ARBITRARY_AXIS) // return the voxel normal at the nearest intersection
{
return m_normal;
}
const float xsign = (*(uint*)&m_direction.x >> 31 == 0) ? -1.f : 1.f;
const float ysign = (*(uint*)&m_direction.y >> 31 == 0) ? -1.f : 1.f;
const float zsign = (*(uint*)&m_direction.z >> 31 == 0) ? -1.f : 1.f;
return float3( m_axis == 0 ? xsign : 0.f, m_axis == 1 ? ysign : 0.f, m_axis == 2 ? zsign : 0.f );
}
Ray::SphereIntersection Ray::TrySphere(const Sphere& sphere) const
{
SphereIntersection result;
result.exists = false;
const float3 c = sphere.m_center - m_origin;
const float t = dot(c, m_direction);
const float3 q = c - t * m_direction;
const float sqrq = dot(q, q);
const float sqrr = sphere.m_radius * sphere.m_radius;
if (sqrq > sqrr)
{
return result;
}
const float thc = sqrt(sqrr - sqrq);
const float t0 = t - thc;
const float t1 = t + thc;
float tHit = t0;
if (tHit <= 0.0f)
{
tHit = t1;
if (tHit <= 0.0f)
return result;
}
result.exists = true;
result.distance = tHit;
result.material = sphere.m_material;
result.closest = m_origin + m_direction * tHit;
result.normal = (result.closest - sphere.m_center) / sphere.m_radius;
if (t0 <= 0.0f)
{
result.normal *= -1.0f;
}
return result;
}