#include "view.hpp"



void
QtView::initializeGL(){
  glClearColor(1,1,1,1);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHTING);
  glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
  glEnable(GL_COLOR_MATERIAL);
}

void
QtView::resizeGL(int w,int h){
  glViewport(0,0,w,h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(0,geometry->lX,0,1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

void
QtView::paintGL(){
  cout<<"PaintGL"<<endl;
  glBegin(GL_TRIANGLES);
  for(size_t i=0;i<geometry->nX-1;++i){
    size_t max_left=geometry->nZ[i];
    size_t max_right=geometry->nZ[i+1];
    size_t left=0;
    size_t right=0;
    while(left<max_left-1 and right<max_right-1){
      if(geometry->Z[i][left+1]<geometry->Z[i+1][right+1]){
	drawTriangle(i,left,i+1,right,i,left+1);
	++left;
      }
      else{
	drawTriangle(i,left,i+1,right,i+1,right+1);
	++right;
      }
    }
    if(left==max_left-1){
      while(right<max_right-1){
	drawTriangle(i,left,i+1,right,i+1,right+1);
	++right;
      }
    }
    if(right==max_right-1){
      while(left<max_left-1){
	drawTriangle(i,left,i+1,right,i,left+1);
	++left;
      }
    }
  }
  glEnd();
}

void
QtView::drawTriangle(size_t ix1,size_t iz1,size_t ix2,size_t iz2,size_t ix3,size_t iz3){
  double dX=geometry->dX;
  double x1=ix1*dX;
  double x2=ix2*dX;
  double x3=ix3*dX;
  double y1=geometry->Z[ix1][iz1];
  double y2=geometry->Z[ix2][iz2];
  double y3=geometry->Z[ix3][iz3];
  glColor3f(1,0,0);
  glVertex2f(x1,y1);
  glVertex2f(x2,y2);
  glVertex2f(x3,y3);

}
