# How to find N(gradient of plane) and L(direction to light) for implementing shading in polygon filling in Computer Graphics?

I have $3$ points $(x_1,y_1,z_1)$, $(x_2,y_2,z_2)$, $(x_3,y_3,z_3)$ of the $3D$ plane and light source $(x_s,y_s,z_s)$.

Now, how can I find out the $N$ vector and $L$ vector?

• where are these three points? – janmarqz Mar 19 '18 at 16:56
• @janmarqz these are in original object plane. – alhelal Mar 19 '18 at 17:02

Suppose, $P_1(x_1,y_1,z_1)$, $P_2(x_2,y_2,z_2)$, $P_3(x_3,y_3,z_3)$ and light source $S(x_s,y_s,z_s)$ are give. Then, $N$ is normal vector of cross product of $(P_2-P1)$ and $(P_3-P_1)$.

$(P_2-P1)=(x_2-x_1)\hat{i}+(y_2-y_1)\hat{j}+(z_2-z_1)\hat{k}$

$(P_3-P_1)=(x_3-x_1)\hat{i}+(y_3-y_1)\hat{j}+(z_3-z_1)\hat{k}$

$\begin{vmatrix}\hat{i} & \hat{j} & \hat{k} \\ x_2-x_1 & y_2-y_1 & z_2-z_1 \\x_3-x_1 & y_3-y_1 & z_3-z_1 \end{vmatrix}=N'$

$\hat{i} \{(y_2-y_1)(z_3-z_1)-(y_3-y_1)(z_2-z_1)\}-\hat{j}\{ (x_2-x_1)(z_3-z_1)-(x_3-x_1)(z_2-z_1)\}+\hat{k}\{(x_2-x_1)(y_3-y_1)-(x_3-x_1)(y_2-y_1)\}=N'$

$\hat{i} \{(y_2-y_1)(z_3-z_1)-(y_3-y_1)(z_2-z_1)\}+\hat{j}\{ (x_3-x_1)(z_2-z_1)-(x_2-x_1)(z_3-z_1)\}+\hat{k}\{(x_2-x_1)(y_3-y_1)-(x_3-x_1)(y_2-y_1)\}=N'$

$N=\frac{N'}{||N'||}$

Now, if $P_n(x,y,z)$ is a new point on the given plane then,(If you assume that brightness of each pixel of the polygon is same then you can consider this point as center of the polygon)
$L'=(S-P_n)$
$L'=(x_s-x)\hat{i}+(y_s-y)\hat{j}+(z_s-z)\hat{k}$
$L=\frac{L'}{||L'||}$
$N.L=N_xL_x+N_yL_y+N_zL_z$
$N.L=\{(y_2-y_1)(z_3-z_1)-(y_3-y_1)(z_2-z_1)\}(x_s-x)+\{(x_3-x_1)(z_2-z_1)-(x_2-x_1)(z_3-z_1)\}(y_s-y)+\{(x_2-x_1)(y_3-y_1)-(x_3-x_1)(y_2-y_1)\}(z_s-z)$

$N.L$ is needed for shading/brightness of a pixel(e.g. glcolor3f(N.L, N.L, N.L))

• Great answer. I'd suggest one small change: often the vector from the surface to the light source is expected to be a unit vector, so I'd replace your $L$ with $L/\|L\|$. Also: sometimes light sources are "at infinity", and simply specified by the direction in which the light travels, i.e., some (unit) vector $v$; in that case, $L = -v$. – John Hughes Mar 20 '18 at 12:04
• @JohnHughes Yes, you are right. Thank you. – alhelal Mar 20 '18 at 16:49
• Also, in the second to last line of equations, you have a $1/\|N\|$, which is unnecessary because you already normalized $N$. I think perhaps you should just simplify the expansion and says\ $N \cdot L = N_x L_x + N_y L_y + N_z L_z$, which then refers to the already-normallized coordinates. – John Hughes Mar 20 '18 at 17:10