#include <assert.h>
#include <math.h>
#include <GL/glut.h>
#include "drawPlant.h"


/* Matrix to store current modeling transformation;
   2D version of OpenGL MODELVIEW matrix. */
GLdouble Turtle[3][3] = 
  {{1.0, 0.0, 0.0},
   {0.0,  1.0, 0.0},
   {0.0,  0.0, 1.0}};


/*************************************

Interface which loads and stores the 2D turtle matrix it into OpenGL's
3D MODELVIEW matrix in the right order, padding it out properly. 

*************************************/

void loadTurtle(void) {

  GLfloat M3D [16];  /* three dimensional matrix doing same transform */

  M3D[0]=Turtle[0][0]; M3D[1]=Turtle[1][0]; M3D[2]=0.0; M3D[3]=Turtle[2][0];
  M3D[4]=Turtle[0][1]; M3D[5]=Turtle[1][1]; M3D[6]=0.0; M3D[7]=Turtle[2][1];
  M3D[8] = 0.0;  M3D[9] = 0.0; M3D[10] = 1.0; M3D[11] = 0.0;
  M3D[12]=Turtle[0][2]; M3D[13]=Turtle[1][2]; M3D[14]=0.0; M3D[15]=Turtle[2][2];

  glMatrixMode(GL_MODELVIEW);
  glLoadMatrixf(M3D);
}


void getTurtle (void) {

  GLfloat M3D [16];  /* three dimensional matrix doing same transform */

  glGetFloatv(GL_MODELVIEW_MATRIX,M3D);

  Turtle[0][0]=M3D[0]; Turtle[1][0]=M3D[1]; Turtle[2][0]=M3D[3];
  Turtle[0][1]=M3D[4]; Turtle[1][1]=M3D[5]; Turtle[2][1]=M3D[7];
  Turtle[0][2]=M3D[12]; Turtle[1][2]=M3D[13]; Turtle[2][2]=M3D[15];

}

/*************************************

End interface for turtle matrix; begin actual plant drawing code.

*************************************/

/*
Code to draw a leaf, with the bottom at the (0,0)
*/
void drawLeaf(void) {

  glColor3f(0.1,0.9,0.1); 
  glBegin(GL_POLYGON);
  glVertex2f(0.0,0.0);
  glVertex2f(1.0,0.7);
  glVertex2f(1.3,1.8);
  glVertex2f(1.0,2.8);
  glVertex2f(0.0,4.0);
  glVertex2f(-1.0,2.8);
  glVertex2f(-1.3,1.8);
  glVertex2f(-1.0,0.7);
  glEnd();

}

/* 
   Stub for plant-drawing function. Loads a trasformation 
   matrix and draws a transformed
   leaf.
*/

void drawPlant(void) {


  loadTurtle();

  drawLeaf();

  getTurtle();

  /* Here's a line that prints out the turtle matrix, should be handy...*/
  printf("%f %f %f \n %f %f %f \n %f %f %f \n",
	 Turtle[0][0], Turtle[0][1], Turtle[0][2],
	 Turtle[1][0], Turtle[1][1], Turtle[1][2],
	 Turtle[2][0], Turtle[2][1], Turtle[2][2]);

}

