由於框是軸對齊的,所以您只需檢查每個座標中的區間交集。
這是python中的一個例子,有一些測試。請注意,這是通用的N個維度,並且它是箱盒相交的算法相同:
def are_intervals_intersecting(a0, a1, b0, b1):
'''
@param a0: float
@param a1: float
@param b0: float
@param b1: float
'''
if (a1 < a0):
a1, a0 = a0, a1
if (b1 < b0):
b1, b0 = b0, b1
# 6 conditions:
# 1)
# a0 ---------- a1 a0 < b0 and a1 < b0
# b0 ---------- b1 (no intersection)
# 2)
# a0 ---------- a1
# b0 ---------- b1 (intersection)
# 3)
# a0 ------------------------ a1
# b0 ---------- b1 (intersection)
# 4)
# a0 ---------- a1
# b0 ------------------------ b1 (intersection)
# 5)
# a0 ---------- a1 (intersection)
# b0 ---------- b1
# 6)
# a0 ---------- a1 b0 < a0 and b1 < a0
# b0 ---------- b1 (no intersection)
if b0 < a0:
# conditions 4, 5 and 6
return a0 < b1 # conditions 4 and 5
else:
# conditions 1, 2 and 3
return b0 < a1 # conditions 2 and 3
def is_segment_intersecting_box(P0, P1, B0, B1):
'''
@param P0: tuple(float)
@param P1: tuple(float)
@param B0: tuple(float)
@param B1: tuple(float)
'''
for i in xrange(len(P0)):
if not are_intervals_intersecting(P0[i], P1[i], B0[i], B1[i]):
return False
return True
if __name__ == '__main__':
assert not is_segment_intersecting_box(
(0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0))
assert not is_segment_intersecting_box(
(0.0, 0.0, 0.0), (4.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0))
assert not is_segment_intersecting_box(
(1.5, 1.5, 0.0), (4.0, 2.5, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0))
assert is_segment_intersecting_box(
(1.5, 1.5, 0.0), (4.0, 2.5, 2.5), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0))
assert is_segment_intersecting_box(
(1.5, 1.5, 1.5), (2.5, 2.5, 2.5), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0))
assert is_segment_intersecting_box(
(2.5, 2.5, 2.5), (2.6, 2.6, 2.6), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0))
assert is_segment_intersecting_box(
(2.5, 2.5), (2.5, 3.5), (2.0, 2.0), (3.0, 3.0))
print 'ok'
謝謝 - 非常有幫助!如果片段的兩個點位於不相鄰的體素中,我想測試片段是否與中間體素相交(片段經過的中間體素,但兩個點都位於外面)? – jbrown 2010-08-05 22:29:52
@jbrown - 是的,我也意識到了;我修改了我的答案,看看。 – tzaman 2010-08-06 11:23:38