Skip to main content
gamedev.net
🔒 Locked

Triangle Clipping

Started by nes8bit Sep 16, 2000 at 4:21 PM 2 replies 2.8k views
Original Post
nes8bit
nes8bit
How would I clip 2d triangles against lines/boxes? I''m doing this for my PVS system. --------------------------- "Don't die for your country, make some other dumb bastard die for his" -General George S. Patton
Zipster
Zipster
as you draw each pixel in a triangle, you can test it to see if it''s withing a specified rectangle: if not, don''t draw it.

=======================================
A man with no head is still a man.
A head with no man is plain freaky.
NBGH
NBGH
Here's a function that will help a lot:

int Intersect(float x1, float y1, float dx1, float dy1, float x2, float y2, float dx2, float dy2, float * i, float * j) {
float a = ( dx2 * dy1 - dx1 * dy2);
float b = ( dx1 * dy2 - dx2 * dy1);
if(a == 0 || b == 0)
return 0;
*i = ( dy2 * (x1 - x2) - dx2 * (y1 - y2 ) ) / a;
*j = ( dx1 * (y1 - y2) - dy1 * (x1 - x2 ) ) / b;
if(*i >=0 && *i <= 1 && *j >=0 && *j <=1)
return 1;
return 0;
}

It can be used to tell you if two lines intersect, and exactly where if they do. Each line has a starting point (x1, y1 etc) and a displacement from that starting point that makes the end point (dx1, dy1 etc). So if the first line is (1, 2) to (3, 5) then x1 = 1, y1 = 2, dx1 = 3 - 1 and dy1 = 5 - 2. Easy.

When the function returns, the coordinate of the intersection is this:
(x1 + i * dx1, y1 + i * dy1) or (x2 + j * dx2, y2 + j * dy2) which works out to the same coordinate (obviously!).

So if you've got a triangle and a box and you want to know where the triangle is to be clipped you just test each side of the box with each side of the triangle and you will know if it intersects, and if so where. Its a bit of a struggle to get to grips with, but just copy the code out and play with it, you'll understand whats going on.

Edited by - NBGH on September 17, 2000 11:23:01 AM
nes8bit
nes8bit
quote:
Original post by Zipster

as you draw each pixel in a triangle, you can test it to see if it''s withing a specified rectangle: if not, don''t draw it.

=======================================
A man with no head is still a man.
A head with no man is plain freaky.


Jimmy, why don''t you go into the gamedictionary, and look up PVS

NBGH: Coolness. I''ll find out how it works and such.

---------------------------
"Don't die for your country, make some other dumb bastard die for his" -General George S. Patton

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.