I\'m trying to draw a triangle using an OpenGL fragment shader.
I succeeded in drawing a circle but I have a problem with handling the equation/logic or the code to draw
Hope you are rendering QUAD covering the view/screen...
The fragment shader friendly way of rendering triangle is to:
compute barycentric s,t coordinates of fragment
go for the matrix approach as you got mat3,vec3
in GLSL ...
decide if it is inside or outside
simply by testing s+t<=1.0
then set output color or discard;
however discard is not an option for you as you got more shapes...
So compute:
--------------------------------------------------------
| s | | (p1.a - p0.a) , (p2.a - p0.a) , p0.a | | p.a |
| t | = inverse | (p1.b - p0.b) , (p2.b - p0.b) , p0.b | * | p.b |
| 1 | | 0 , 0 , 1 | | 1 |
------------------------------------------------------------------
if (s+t<=1.0) set output color
You can also use the s,t
for texturing (even procedural one).
To compute if a point is in a triangle using the same side technique, you need to test the candidate point against three lines to see which side of each line it is on. If it meets the sidedness test for all three lines, then it is inside the triangle.
The condition test will be C(0) && C(1) && C(2)
.
Where C(n)
means: "Is the point on the correct side of edge n"
The condition "which side of the line AB is the point X" is typically checked by checking the sign of the cross product of AB × AX
. You could, by convention, assign a winding order to your triangle, and always check that the sign of this cross product is positive.
This, of course, depends on the winding order of the vertices of your triangle. (For example, clockwise vertices require a negative cross product, and counterclockwise vertices require a positive cross product. Choose whichever convention you like or is most convenient given the definition of your polygon.)
You can, alternatively, test using the barycentric technique.
See: this site for more details.