Matlab calculate reflection of Vector
-
14-06-2021 - |
Question
I have to calculate the Specular Highlights (phong) of an Image. the normal Vector and the "light vector" are given. Now I have to calculate the light reflection - is there an efficient matlab function to flip the light Vector over the normal vector to get the reflected-light-vector?
Ispec = ks * I * (r * v)p
Where:
l
is the light vector
n
is the normal vector of surface
r
is the reflection vector
v
is the vector from reflection point to viewer
p
is the shininess
Solution
I would solve this mathematically:
Let N
be the normal vector.
Let V
be the light vector.
Let O
be the reflected vector.
O
is in the same plane asN
,V
- The cosine of the angle between
V
andN
is the same as the cosine of the angle betweenV
andO
(With a minus sign). O
has the same same length asV
This yields 3 equations:
- dot(O, cross(N,V)) = 0
- dot(N,V)/ norm(N) / norm(V) = - dot(N,O) / norm(N) / norm(O)
- norm(O) = norm(V)
After manipulating these equations, you will reach a 3x3 equations system. All that is left is to solve it.
Edit My colleague has just told me of an easier way:
V
can be separated into 2 parts, V = Vp + Vn
Vp
- parallel toN
Vn
- has straight angle withN
O
has the same parallel part Vp
, but exactly the opposite Vn
Thus, O = Vp - Vn
, but V = Vp + Vn
and then O = V - 2 * Vn
Where Vn = dot(V,N) * N
(Assuming that N
has norm of 1)
So the final answer is:
function O = FindReflected(V,N)
N = N / norm(N);
O = V - 2 * dot(V,N) * N;
end
Edit 2
I've just found a much better explanation on Math.stackexchange
:
https://math.stackexchange.com/questions/13261/how-to-get-a-reflection-vector