In 3D I have been given a ray and a rectangle:
$$Ray=\mathbf{r_o}+t*\mathbf{r_d}$$ $$Rect=\mathbf{p_o}+p*\mathbf{p_x}+q*\mathbf{p_y}$$
where
- $\mathbf{r_o}$ is the ray origin
- $\mathbf{r_d}$ is the ray unit direction vector
- $t>0$
- $\mathbf{p_o}$ is the rectangle center
- $-rectWidth/2 < p < rectWidth/2$
- $-rectHeight/2 < q < rectHeight/2$
- $\mathbf{p_x}$ is the rectangle unit x-vector
- $\mathbf{p_y}$ is the rectangle unit y-vector
- $\mathbf{p_x}$ and $\mathbf{p_y}$ are orthogonal, i.e. $\mathbf{p_x} \cdot \mathbf{p_y} = 0$
I'm trying to find
$$Ray'=\mathbf{r_o} + t*\mathbf{r_d'}$$
that intersects the rectangle and minimizes the angle between $\mathbf{r_d}$ and $\mathbf{r_d'}$ (in other words maximizes $\mathbf{r_d} \cdot \mathbf{r_d'}$). If $\mathbf{r_d}$ intersects the rectangle then naturally $\mathbf{r_d'}=\mathbf{r_d}$ and otherwise $\mathbf{r_d'}$ points towards the rectangle edge.
I have tried couple of solutions which unfortunately do not give correct results:
1) Calculate $p$ and $q$ at the intersection between the ray and the plane of the rectangle, and clamp $p$ and $q$ to the rectangle domain. Then calculate $\mathbf{v}=\mathbf{p_o}+p*\mathbf{p_x} + q*\mathbf{p_y} - \mathbf{r_o}$ and $\mathbf{r'_d}=\mathbf{v}/||\mathbf{v}||$. This works "mostly right", but breaks down when the ray points away from the rectangle (i.e. there's no intersection). Even if the ray points towards the rectangle, clamping $p$ and $q$ between $-rectWidth/2 < p < rectWidth/2$, and $-rectHeight/2 < q < rectHeight/2$ doesn't give correct result in all cases.
2) Project the ray to the rectangle plane and calculate intersection of the infinite line going along the projected ray and the rectangle. If the line intersects the rectangle, test which of the two intersection point gives the smallest angle. If the line doesn't intersect the rectangle, test which of the 4 corners of the rectangle gives the smallest angle. This seems to be quite wrong result and worse than option 1)
I don't need the exact solution for my application, so if there are some approximations that doesn't have too large errors I'm happy to try those out. If it helps, the rectangle parameters can also be simplified with affine transformation of the ray so that $\mathbf{p_o}=[0, 0, 0]$, $\mathbf{p_x}=[1, 0, 0]$, $\mathbf{p_y}=[0, 1, 0]$, $rectWidth=1$ and $rectHeight=1$.