-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.rs
125 lines (107 loc) · 3.1 KB
/
tree.rs
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use crate::bvh;
use crate::math;
use crate::geom;
#[derive(Copy, Clone, Debug)]
pub struct Tree<'scene, S>(pub &'scene [Node<S>]);
impl<'scene, S> geom::Surface<'scene> for Tree<'scene, S> where S: geom::Surface<'scene> {
fn bound(&self) -> geom::Box3 {
self.0[0].bound()
}
fn hit(&self, ray: &mut math::Ray, hit: &mut geom::Hit<'scene>) -> bool {
let mut next = 0;
let mut this = 0;
let mut visit = [0; 32];
let mut success = false;
macro_rules! push { ($i:expr) => {{
visit[next] = $i;
next += 1;
}}}
macro_rules! pop { () => {{
if next == 0 { break success }
next -= 1;
this = visit[next];
}}}
loop {
if !self.0[this].bound().hit_any(ray) {
#[cfg(feature = "stats")]
crate::stats::BVH_MISSES.inc();
pop!();
continue
}
#[cfg(feature = "stats")]
crate::stats::BVH_HITS.inc();
match &self.0[this] {
| Node::Leaf(leaf) => {
success |= leaf.hit(ray, hit);
pop!();
}
| Node::Node { child, axis, .. } => {
if ray.sign[*axis as usize] == 1 {
push!(this + 1);
this = *child as usize;
} else {
push!(*child as usize);
this += 1;
}
}
}
}
}
fn hit_any(&self, ray: &math::Ray) -> bool {
let mut next = 0;
let mut this = 0;
let mut visit = [0; 32];
macro_rules! push { ($i:expr) => {{
visit[next] = $i;
next += 1;
}}}
macro_rules! pop { () => {{
if next == 0 { return false }
next -= 1;
this = visit[next];
}}}
loop {
if !self.0[this].bound().hit_any(ray) {
#[cfg(feature = "stats")]
crate::stats::BVH_MISSES.inc();
pop!();
continue
}
#[cfg(feature = "stats")]
crate::stats::BVH_HITS.inc();
match &self.0[this] {
| Node::Leaf(leaf) => {
if leaf.hit_any(ray) { return true }
pop!();
}
| Node::Node { axis, child, .. } => {
if ray.sign[*axis as usize] == 1 {
push!(this + 1);
this = *child as usize;
} else {
push!(*child as usize);
this += 1;
}
}
}
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Node<S> {
Leaf(bvh::Leaf<S>),
Node {
axis: math::Axis,
bound: geom::Box3,
child: u32,
}
}
impl<'scene, S> Node<S> where S: geom::Surface<'scene> {
pub fn bound(&self) -> geom::Box3 {
use geom::Surface;
match self {
| Node::Leaf(leaf) => leaf.bound(),
| Node::Node { bound, .. } => *bound,
}
}
}