Clip a ray with a box. EDGE = clipRay(RAY, BOX); RAY is a straight ray given as a 4 element row vector: [x0 y0 dx dy], with (x0 y0) being the origin of the ray and (dx dy) its direction vector, BOX is the clipping box, given by its extreme coordinates: [xmin xmax ymin ymax]. The result is given as an edge, defined by the coordinates of its 2 extreme points: [x1 y1 x2 y2]. If the ray does not intersect the box, [NaN NaN NaN NaN] is returned. Function works also if RAY is a N-by-4 array, if BOX is a Nx4 array, or if both RAY and BOX are N-by-4 arrays. In these cases, EDGE is a N-by-4 array. See also: rays2d, boxes2d, edges2d, clipLine, drawRay
0001 function [edge, isInside] = clipRay(ray, bb) 0002 % Clip a ray with a box. 0003 % 0004 % EDGE = clipRay(RAY, BOX); 0005 % RAY is a straight ray given as a 4 element row vector: [x0 y0 dx dy], 0006 % with (x0 y0) being the origin of the ray and (dx dy) its direction 0007 % vector, BOX is the clipping box, given by its extreme coordinates: 0008 % [xmin xmax ymin ymax]. 0009 % The result is given as an edge, defined by the coordinates of its 2 0010 % extreme points: [x1 y1 x2 y2]. 0011 % If the ray does not intersect the box, [NaN NaN NaN NaN] is returned. 0012 % 0013 % Function works also if RAY is a N-by-4 array, if BOX is a Nx4 array, or 0014 % if both RAY and BOX are N-by-4 arrays. In these cases, EDGE is a N-by-4 0015 % array. 0016 % 0017 % See also: 0018 % rays2d, boxes2d, edges2d, clipLine, drawRay 0019 % 0020 0021 % ------ 0022 % Author: David Legland 0023 % e-mail: david.legland@inrae.fr 0024 % Created: 2010-05-13, using Matlab 7.4.0.287 (R2007a) 0025 % Copyright 2010 INRA - Cepia Software Platform. 0026 0027 % HISTORY 0028 % 2010-05-13 create from clipLine 0029 % 2017-09-21 simplify code 0030 0031 % adjust size of two input arguments 0032 if size(ray, 1) == 1 0033 ray = repmat(ray, size(bb, 1), 1); 0034 elseif size(bb, 1) == 1 0035 bb = repmat(bb, size(ray, 1), 1); 0036 elseif size(ray, 1) ~= size(bb, 1) 0037 error('bad sizes for input'); 0038 end 0039 0040 % first compute clipping of supporting line 0041 edge = clipLine(ray, bb); 0042 0043 % detects valid edges (edges outside box are all NaN) 0044 inds = find(isfinite(edge(:, 1))); 0045 0046 % compute position of edge extremities relative to the ray 0047 pos1 = linePosition(edge(inds,1:2), ray(inds,:), 'diag'); 0048 pos2 = linePosition(edge(inds,3:4), ray(inds,:), 'diag'); 0049 0050 % if first point is before ray origin, replace by origin 0051 edge(inds(pos1 < 0), 1:2) = ray(inds(pos1 < 0), 1:2); 0052 0053 % if last point of edge is before origin, set all edge to NaN 0054 edge(inds(pos2 < 0), :) = NaN; 0055 0056 % eventually returns result about inside or outside 0057 if nargout > 1 0058 isInside = isfinite(edge(:,1)); 0059 end