Last active
February 19, 2016 01:57
-
-
Save kusma/731853 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "clip.h" | |
#include <math.h> | |
#include <stdio.h> | |
void clip_polygon(polygon *in, polygon *out, Vector4 eq) | |
{ | |
int edge; | |
out->vertex_count = 0; | |
for (edge = 0; edge < in->vertex_count; ++edge) { | |
/* we consider an edge the edge that goes from the current vertex and to the next */ | |
Vertex curr_vert = in->vertices[edge]; | |
Vertex next_vert = in->vertices[(edge + 1) % in->vertex_count]; | |
/* calculate distances to planes */ | |
float curr_dot = curr_vert.attrib[0].x * eq.x + curr_vert.attrib[0].y * eq.y + curr_vert.attrib[0].z * eq.z + curr_vert.attrib[0].w * eq.w; | |
float next_dot = next_vert.attrib[0].x * eq.x + next_vert.attrib[0].y * eq.y + next_vert.attrib[0].z * eq.z + next_vert.attrib[0].w * eq.w; | |
bool curr_in = curr_dot >= 0.f; | |
bool next_in = next_dot >= 0.f; | |
/* if current vertex is inside, add it to the outgoing polygon. */ | |
if (curr_in) { | |
out->vertices[out->vertex_count] = curr_vert; | |
out->vertex_count++; | |
} | |
/* if vertices are on different sides, | |
* we need to interpolate between them | |
* until the distance is 0 | |
*/ | |
if (curr_in != next_in) { | |
float t = 0.f; | |
float diff; | |
/* we absolutely need to make sure that we allways clip in the same direction. | |
* we're currently hacking it by simply swapping the pointers to the vertices ;) | |
* as there's no need for the pointers later on, we don't restore them afterwards... | |
*/ | |
if (!curr_in) { | |
float temp_dot; | |
Vertex temp_vert; | |
/* vertex */ | |
temp_vert = curr_vert; | |
curr_vert = next_vert; | |
next_vert = temp_vert; | |
/* distance */ | |
temp_dot = curr_dot; | |
curr_dot = next_dot; | |
next_dot = temp_dot; | |
} | |
diff = curr_dot - next_dot; | |
/* we don't want to divide by zero (or a very very small value), | |
* as we'll most likely end up with +/-iNF | |
*/ | |
if (fabs(diff) > 1e-10) | |
t = curr_dot / diff; | |
out->vertices[out->vertex_count] = curr_vert + (next_vert - curr_vert) * t; | |
out->vertex_count++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment