-
Notifications
You must be signed in to change notification settings - Fork 4
/
bresenham2D.py
67 lines (59 loc) · 1.68 KB
/
bresenham2D.py
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
import numpy as np
# Bresenham's ray tracing algorithm in 2D.
# Inputs:
# (sx, sy) start point of ray
# (ex, ey) end point of ray
def bresenham2D(sx, sy, ex, ey):
sx = int(round(sx))
sy = int(round(sy))
ex = int(round(ex))
ey = int(round(ey))
dx = abs(ex-sx)
dy = abs(ey-sy)
steep = abs(dy)>abs(dx)
if steep:
dx,dy = dy,dx # swap
if dy == 0:
q = np.zeros((dx+1,1))
else:
q = np.append(0,np.greater_equal(np.diff(np.mod(np.arange( np.floor(dx/2), -dy*dx+np.floor(dx/2)-1,-dy),dx)),0))
if steep:
if sy <= ey:
y = np.arange(sy,ey+1)
else:
y = np.arange(sy,ey-1,-1)
if sx <= ex:
x = sx + np.cumsum(q)
else:
x = sx - np.cumsum(q)
else:
if sx <= ex:
x = np.arange(sx,ex+1)
else:
x = np.arange(sx,ex-1,-1)
if sy <= ey:
y = sy + np.cumsum(q)
else:
y = sy - np.cumsum(q)
return np.vstack((x,y))
def test_bresenham2D():
import time
sx = 0
sy = 1
print("Testing bresenham2D...")
r1 = bresenham2D(sx, sy, 10, 5)
r1_ex = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10],[1,1,2,2,3,3,3,4,4,5,5]])
r2 = bresenham2D(sx, sy, 9, 6)
r2_ex = np.array([[0,1,2,3,4,5,6,7,8,9],[1,2,2,3,3,4,4,5,5,6]])
if np.logical_and(np.sum(r1 == r1_ex) == np.size(r1_ex),np.sum(r2 == r2_ex) == np.size(r2_ex)):
print("...Test passed.")
else:
print("...Test failed.")
# Timing for 1000 random rays
num_rep = 1000
start_time = time.time()
for i in range(0,num_rep):
x,y = bresenham2D(sx, sy, 500, 200)
print("1000 raytraces: --- %s seconds ---" % (time.time() - start_time))
if __name__ == "__main__":
test_bresenham2D()