/*exampleNFF.c
  Example program to write an nff file

  Compile

  cc exampleNFF.c -o exampleNFF

  Eric Pepke
*/

#include <stdio.h>

#define FLOORMINX	-2.0	/*Min x of floor*/
#define FLOORMAXX	2.0	/*Max x of floor*/
#define FLOORMINY	-1.0	/*Min y of floor*/
#define FLOORMAXY	1.0	/*Max y of floor*/
#define FLOORZ		0.0	/*Min z of floor*/

#define BALLX		-2.0	/*Starting x of ball*/
#define BALLY		0.0	/*Starting y of ball*/
#define BALLZ		2.0	/*Starting z of ball*/
#define BALLRADIUS	0.1	/*Radius of ball*/

#define BALLVX		1.0	/*X starting velocity of ball*/
#define BALLVY		0.0	/*Y starting velocity of ball*/

#define BOUNCE		0.8	/*Bounce coefficient*/

#define AG		10.0	/*Acceleration due to gravity*/

#define TIMESTEP	0.05	/*Time step*/

void Color(FILE *file, float r, float g, float b)
/*Sets to a color*/
{
    fprintf(file, "f %g %g %g 0 0 0 0 0\n", r, g, b);
}

void DrawFloor(FILE *file)
/*Draws the floor*/
{
    /*Color for floor*/
    Color(file, 0.0, 1.0, 1.0);

    /*Now polygon*/
    fprintf(file, "p 4\n");
    fprintf(file, "%g %g %g\n", FLOORMINX, FLOORMINY, FLOORZ);
    fprintf(file, "%g %g %g\n", FLOORMAXX, FLOORMINY, FLOORZ);
    fprintf(file, "%g %g %g\n", FLOORMAXX, FLOORMAXY, FLOORZ);
    fprintf(file, "%g %g %g\n", FLOORMINX, FLOORMAXY, FLOORZ);
}

void DrawBall(FILE *file, float bx, float by, float bz)
/*Draws the ball*/
{
    fprintf(file, "s %g %g %g %g\n", bx, by, bz, BALLRADIUS);
}

void Time(FILE *file, float t)
/*Emits a time marker*/
{
    fprintf(file, "t %g\n", t);
}

main()
{
    FILE *file;
    float bx, by, bz, bvx, bvy, bvz, t;

    file = fopen("example.nff", "w");
    if (file)
    {
	/*First draw the floor*/
	DrawFloor(file);

	/*Now do the simulation*/
	bx = BALLX;
	by = BALLY;
	bz = BALLZ;
	bvx = BALLVX;
	bvy = BALLVY;
	bvz = 0.0;
	t = 0.0;

	/*Set the color once for all balls*/
	Color(file, 1.0, 0.0, 0.0);

	do
	{
	    /*Set the time step.  Omit this line to keep all snapshots
	      in one time step to see them all at once*/
	    Time(file, t);

	    /*Emit the current ball position*/
	    DrawBall(file, bx, by, bz);

	    /*Go to next time step.  I know this is really cheesy
	      integration, but it's just a demo.*/

	    t += TIMESTEP;
	    bvz -= TIMESTEP * AG;

	    bx += bvx * TIMESTEP;
	    by += bvy * TIMESTEP;
	    bz += bvz * TIMESTEP;

	    if (bz < (FLOORZ + BALLRADIUS))
	    {
		/*Bounce*/
		bz = FLOORZ - bz + 2.0 * BALLRADIUS;
		bvz = -bvz * BOUNCE;
	    }
	    
	} while (bx >= FLOORMINX && bx <= FLOORMAXX && 
		 by >= FLOORMINY && by <= FLOORMAXY);


	fclose(file);
    }
    else
    {
	perror("example.nff");
    }
}