1 | function endPnts = cropLineInBox(n, c, cropBox) |
---|
2 | % endPnts = cropLineInBox(n, c, cropBox) |
---|
3 | % For a line defined by n(1) x(1) + n(2) x(2) + c = 0, b |
---|
4 | % and a box determined by cropBox = [x(1) y(1) x(2) y(2)] with |
---|
5 | % x(1) <= x(2), y(1) <= y(2), return |
---|
6 | % endPts = [x1 y1 x2 y2] where the line from x1,y1 to x2,y2 |
---|
7 | % is the segment of the original line cropped to be within |
---|
8 | % crop box. If there is no such line, then x1 is nan. |
---|
9 | |
---|
10 | if (size(n,1) == 1) n = n'; end |
---|
11 | % |
---|
12 | % Check for sign change between successive vertices. |
---|
13 | pts = [cropBox(1:2); cropBox(3:-1:2); cropBox(3:4); cropBox(1:3:4)]; |
---|
14 | err = pts * n + c; |
---|
15 | cntPnts = 1; |
---|
16 | endPnts = zeros(2,2); |
---|
17 | for j= 1:4 |
---|
18 | |
---|
19 | k = mod(j,4) + 1; |
---|
20 | if err(j) * err(k) < 0 |
---|
21 | % Sign change, find endpoint |
---|
22 | r = err(k)/(err(k) - err(j)); |
---|
23 | endPnts(cntPnts, :) = pts(j,:) * r + (1-r) * pts(k,:); |
---|
24 | cntPnts = cntPnts+1; |
---|
25 | elseif err(k) == 0 % Be careful to find zeroes at corners just once. |
---|
26 | endPnts(cntPnts, :) = pts(k,:); |
---|
27 | cntPnts = cntPnts+1; |
---|
28 | end |
---|
29 | if cntPnts == 3 |
---|
30 | break; |
---|
31 | end |
---|
32 | end |
---|
33 | |
---|
34 | if (cntPnts ~= 3) |
---|
35 | endPnts = endPnts * NaN; |
---|
36 | end |
---|
37 | |
---|
38 | return; |
---|
39 | |
---|