~zjm/Moon3D

f25ed389018b188c0309a64fbb8af3469ddbf3bf — Zack Michener a month ago 9f4af74
add triangularization of polygons
4 files changed, 34 insertions(+), 1 deletions(-)

M src/mesh.c
M src/mesh.h
M src/pool.h
M src/renderer.c
M src/mesh.c => src/mesh.c +28 -0
@@ 100,3 100,31 @@ void PrintRect(Rect r)
	printf("              │   │\n");
	printf("%6.2f, %6.2f└───┘%6.2f, %6.2f\n", r.bottom, r.left, r.bottom, r.right);
}

void Triangularize(int *polygon, Mesh *mesh)
{
	/* points to last vertex */
	int *t = PoolPeek(mesh->faces) - 1;
	/* make space for new triangles */
	int new_slots = 4*(NumPolygonVertices(polygon) - 2) - NumPolygonVertices(polygon) - 1;
	PoolBump(mesh->faces, new_slots);
	/* points to last open slot */
	int *u = PoolPeek(mesh->faces) - 1;

	/* work around the polygon in reverse order, making triangles by copying
	 * vertices to the end of our allocated slots (working backward) */
	while(t != u) {
		/* copy last vertex */
		*(u--) = *(t--);
		/* copy second to last vertex (but don't move t, this vertex will be the
		 * last vertex of the next triangle) */
		*(u--) = *t;
		/* copy the polygon's first vertex */
		*(u--) = *(polygon + 1);
		/* mark the triangle as a polygon */
		*(u--) = 3;
	}
	/* we didn't touch the first three vertices,
	 * we just need to mark them as a triangle */
	*polygon = 3;
}

M src/mesh.h => src/mesh.h +1 -0
@@ 35,3 35,4 @@ int *NewPolygon(int *pool);
void PrintPolygon(int *polygon, Vertex *vertices);
Rect PolygonBounds(int *polygon, Vertex *vertices);
void PrintRect(Rect r);
void Triangularize(int *polygon, Mesh *mesh);
\ No newline at end of file

M src/pool.h => src/pool.h +1 -0
@@ 15,6 15,7 @@
#define UnrawPool(pool, type)	(type *)(pool + 1)
#define PoolTotal(pool)			RawPool(pool)[0]
#define PoolNext(pool)			&(pool[PoolTotal(pool)++])
#define PoolBump(pool, i)		(PoolTotal(pool) += (i))
#define PoolPeek(pool)			&(pool[PoolTotal(pool)])
#define PoolPush(pool, value)	(pool[PoolTotal(pool)++]) = value
#define DrainPool(pool)			(PoolTotal(pool) = 0)

M src/renderer.c => src/renderer.c +4 -1
@@ 85,7 85,10 @@ void Render(Renderable renderable, Renderer *renderer, Transform camera_transfor
	for (i = 0, polygon = renderable.mesh->faces;
		 i < PoolTotal(renderable.mesh->faces);
		 i += NumPolygonVertices(polygon)+1, NextPolygon(polygon)) {
		ClipPolygon(polygon, &renderMesh, renderer);
		int *clipped = ClipPolygon(polygon, &renderMesh, renderer);
		if (NumPolygonVertices(clipped) > 3) {
			Triangularize(clipped, &renderMesh);
		}
	}

	/* viewmap all vertices */