#ifndef lint
static char *sccsid = "@(#)remove_backfaces.c	1.2 (UKC) 9/12/87";
#endif  lint
/*
 *	As our image is continuous and viewed from the outside,
 *	we can eliminate triangles which are facing away from us
 *	because they are backfaces.
 *
 *	they are facing away from us if the normal to the plane n = [a b c]
 *	pointing towards us, ie the C component is negative.
 *
 *	If the image is not the surface of a solid object, then you want to
 *	throw triangles away where h == 0 (edge-on) and invert the order of
 *	vertices in back-facing triangles so that the three points ABC
 *	track anticlockwise around the triangle as seen from the viewing side.
 */

#include <stdio.h>
#include "types.h"

remove_backfaces()
{
	trilist_t *tp;	 /* traces down the list of triangles */
	trilist_t **tpp; /* points to previous link field for removing cells */
#ifdef SOLID
	int nremoved = 0;
#endif

	/* scan down the list, keeping tp and tpp in step */
	/* tpp is reinitialised in the loop, and tp just copies it */
	tpp = &trilist;
	tp = *tpp;
	while ((tp = *tpp) != NULLTRI) {

#ifdef SOLID
		if (tp->c <= 0.0) {
			/* Backface: remove. */
			/* Point the previous cell (or head) at the next. */
			*tpp = tp->link;
			free((char *)tp);
			/* tpp does not change */
			nremoved++;
		} else {
			tpp = &(tp->link);
		}
#else
		if (tp->c < 0.0) {
			vertex_t v;
			/* turn the polygon round by swapping A and B */
			v = tp->A; tp->A = tp->B; tp->B = v;
			/* and invert the normal */
			tp->a = -tp->a; tp->b = -tp->b; tp->c = -tp->c;
			tp->h = -tp->h; /* i think */
		}
		tpp = &(tp->link);
#endif
	}
}
