Skip to content

Instantly share code, notes, and snippets.

@boboboa32
Created October 11, 2012 14:16
Show Gist options
  • Save boboboa32/3872629 to your computer and use it in GitHub Desktop.
Save boboboa32/3872629 to your computer and use it in GitHub Desktop.
typedef struct {float x, y;} vec;
vec v(float x, float y){
vec a = {x, y}; // shorthand for declaration
return a;
}
float dot(vec a, vec b){
return a.x*b.x+a.y*b.y;
}
#include <math.h>
vec normalize(vec v){
float mag = sqrt(v.x*v.x + v.y*v.y);
vec b = {v.x/mag, v.y/mag}; // vector b is only of distance 1 from the origin
return b;
}
vec perp(vec v){
vec b = {v.y, -v.x};
return b;
}
typedef struct {vec p0, p1, dir;} seg;
seg segment(vec p0, vec p1){
vec dir = {p1.x-p0.x, p1.y-p0.y};
seg s = {p0, p1, dir};
return s;
}
typedef struct {int n; vec *vertices; seg *edges;} polygon; // Assumption: Simply connected => chain vertices together
polygon new_polygon(int nvertices, vec *vertices){
seg *edges = (seg*)malloc(sizeof(seg)*(nvertices));
int i;
for (i = 0; i < nvertices-1; i++){
vec dir = {vertices[i+1].x-vertices[i].x, vertices[i+1].y-vertices[i].y};seg cur = {vertices[i], vertices[i+1], dir}; // We can also use the segment method here, but this is more explicit
edges[i] = cur;
}
vec dir = {vertices[0].x-vertices[nvertices-1].x, vertices[0].y-vertices[nvertices-1].y};seg cur = {vertices[nvertices-1], vertices[0], dir};
edges[nvertices-1] = cur; // The last edge is between the first vertex and the last vertex
polygon shape = {nvertices, vertices, edges};
return shape;
}
polygon Polygon(int nvertices, ...){
va_list args;
va_start(args, nvertices);
vec *vertices = (vec*)malloc(sizeof(vec)*nvertices);
int i;
for (i = 0; i < nvertices; i++){
vertices[i] = va_arg(args, vec);
}
va_end(args);
return new_polygon(nvertices, vertices);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment