// SingleViewModelingView.cpp : implementation of the CSingleViewModelingView class
//

#include "stdafx.h"
#include "SingleViewModeling.h"

#include "SingleViewModelingDoc.h"
#include "SingleViewModelingView.h"
#include "MainFrm.h"
#include "InputDialogForVanishPoints.h"
#include "Matrix.h"
#include "GetPointDialog.h"
#include "DialogforParameter.h"
#include "GenTextureDialog.h"
#include "QueryTexture.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CSingleViewModelingView

IMPLEMENT_DYNCREATE(CSingleViewModelingView, CView)

BEGIN_MESSAGE_MAP(CSingleViewModelingView, CView)
	//{{AFX_MSG_MAP(CSingleViewModelingView)
	ON_WM_ERASEBKGND()
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_WM_PAINT()
	ON_WM_SIZE()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_MOUSEMOVE()
	ON_COMMAND(IDR_LOAD_IMAGEFILE, OnLoadImagefile)
	ON_COMMAND(IDR_VX, OnInputVxLine)
	ON_COMMAND(IDR_VY, OnInputVyLine)
	ON_COMMAND(IDR_VZ, OnInputVzLine)
	ON_COMMAND(IDR_CACULATE, OnCaculateVanishPoints)
	ON_WM_LBUTTONDBLCLK()
	ON_COMMAND(IDR_LOAD_DATA, OnLoadData)
	ON_COMMAND(IDR_SAVE_DATA, OnSaveData)
	ON_COMMAND(IDR_GET_PAR, OnGetPar)
	ON_WM_RBUTTONDOWN()
	ON_COMMAND(IDR_SAVE_VRML, OnSaveVrml)
	ON_COMMAND(ID_QUERY_TEXTURE, OnQueryTexture)
	//}}AFX_MSG_MAP
	// Standard printing commands
	ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSingleViewModelingView construction/destruction

CSingleViewModelingView::CSingleViewModelingView()
{
	// TODO: add construction code here
    m_VxPointsptr.RemoveAll( );
    m_VyPointsptr.RemoveAll( );
    m_VzPointsptr.RemoveAll( );

}

CSingleViewModelingView::~CSingleViewModelingView()
{
}

BOOL CSingleViewModelingView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs
    cs.style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
	return CView::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CSingleViewModelingView drawing

void CSingleViewModelingView::OnDraw(CDC* pDC)
{
	CSingleViewModelingDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
}

/////////////////////////////////////////////////////////////////////////////
// CSingleViewModelingView printing

BOOL CSingleViewModelingView::OnPreparePrinting(CPrintInfo* pInfo)
{
	// default preparation
	return DoPreparePrinting(pInfo);
}

void CSingleViewModelingView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add extra initialization before printing
}

void CSingleViewModelingView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add cleanup after printing
}

/////////////////////////////////////////////////////////////////////////////
// CSingleViewModelingView diagnostics

#ifdef _DEBUG
void CSingleViewModelingView::AssertValid() const
{
	CView::AssertValid();
}

void CSingleViewModelingView::Dump(CDumpContext& dc) const
{
	CView::Dump(dc);
}

CSingleViewModelingDoc* CSingleViewModelingView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSingleViewModelingDoc)));
	return (CSingleViewModelingDoc*)m_pDocument;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CSingleViewModelingView message handlers

void CSingleViewModelingView::OnInitialUpdate() 
{
	CView::OnInitialUpdate();
	
	// TODO: Add your specialized code here and/or call the base class
	m_rcView.Initialize( );
	m_iOrigx = m_iOrigy = 0;
	
	m_bLBDown = FALSE;
	
}

BOOL CSingleViewModelingView::OnEraseBkgnd(CDC* pDC) 
{
	// TODO: Add your message handler code here and/or call default
	
	return CView::OnEraseBkgnd(pDC);
}

int CSingleViewModelingView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CView::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	// TODO: Add your specialized creation code here
	m_rcView.Create(this);
	
	return 0;
}

void CSingleViewModelingView::OnDestroy() 
{
	CView::OnDestroy();
	
	// TODO: Add your message handler code here
	m_rcView.Destroy( );
	
}

void CSingleViewModelingView::OnPaint() 
{
	CPaintDC dc(this); // device context for painting
	
	// TODO: Add your message handler code here
		BeginPaint( NULL );

	::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	 int view[4];
	::glGetIntegerv( GL_VIEWPORT, view );
	::glMatrixMode( GL_PROJECTION );
	::glLoadIdentity();	
	::gluOrtho2D( m_iOrigx, m_iOrigx + view[2] - view[0], m_iOrigy, m_iOrigy + view[3] - view[1] );

	::glMatrixMode( GL_MODELVIEW );
	::glLoadIdentity();
	::glTranslated( 0.0, 0.0, 1.0 );

	Rendering();

	m_rcView.FinishAndSwap();

	EndPaint( NULL );
	
	// Do not call CView::OnPaint() for painting messages
}

void CSingleViewModelingView::OnSize(UINT nType, int cx, int cy) 
{
	CView::OnSize(nType, cx, cy);

	if ( cx <= 0 || cy <= 0 )
		return;
	
	::glViewport( 0, 0, cx, cy );	
	
	// TODO: Add your message handler code here
	
}

void CSingleViewModelingView::OnLButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	m_bLBDown = TRUE;
	m_ptP0 = point;
	CView::OnLButtonDown(nFlags, point);
}

void CSingleViewModelingView::OnLButtonUp(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	m_bLBDown = FALSE;
	CView::OnLButtonUp(nFlags, point);
}

void CSingleViewModelingView::OnMouseMove(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CRect viewport;
	GetClientRect( &viewport );
	int x = point.x + m_iOrigx;
	int y = viewport.Height() - 1 - point.y + m_iOrigy;

	
	CString prompt;
	char buffer[256];
	prompt += "x = ";
	prompt += _itoa( x, buffer, 10 );
	prompt += ", y = ";
	prompt += _itoa( y, buffer, 10 );

	CMainFrame *pFrame = ( CMainFrame * )AfxGetApp()->m_pMainWnd;
	CStatusBar *pStatus = &pFrame->m_wndStatusBar;
	pStatus->SetPaneText( 0, prompt );

	if ( m_bLBDown )
	{
		m_iOrigx += point.x - m_ptP0.x;
		m_iOrigy += m_ptP0.y - point.y;
		SendMessage( WM_PAINT );
	}
	
		
	CView::OnMouseMove(nFlags, point);
}

void CSingleViewModelingView::Rendering()
{
    const CSingleImage *singleimageptr = GetDocument()->GetSingleImage( );
	
	if ( singleimageptr == NULL )
		return;

    GLuint texname = singleimageptr->GetTexName();
	GLint width = singleimageptr->GetWidth();
	GLint height = singleimageptr->GetHeight();

    ::glEnable( GL_TEXTURE_2D );
	::glBindTexture( GL_TEXTURE_2D, texname );
	::glBegin( GL_QUADS );
	::glTexCoord2d( 0.0, 0.0 );
	::glVertex2i( 0, 0 );	
	::glTexCoord2d( 1.0, 0.0 );
	::glVertex2i( width, 0 );	
	::glTexCoord2d( 1.0, 1.0 );
	::glVertex2i( width, height );	
	::glTexCoord2d( 0.0, 1.0 );
	::glVertex2i( 0, height );	
	::glEnd();
	::glDisable( GL_TEXTURE_2D );



	
}

void CSingleViewModelingView::OnLoadImagefile() 
{
	// TODO: Add your command handler code here
	CFileDialog LoadSourceImageDialog(TRUE );
	if ( LoadSourceImageDialog.DoModal()  == IDOK )
	{    
	
		CString FileName;
		FileName.Empty( );
		FileName = LoadSourceImageDialog.GetPathName( );
		CSingleImage * SingleImageptr = new CSingleImage(FileName);
		CSingleImage * OriginImageptr = GetDocument( )->GetSingleImage( );
		if (OriginImageptr!= NULL) delete OriginImageptr;
		GetDocument( )->StoreSingleImage(SingleImageptr);
		m_VxPointsptr.RemoveAll( );
        m_VyPointsptr.RemoveAll( );
        m_VzPointsptr.RemoveAll( );

		SendMessage(WM_PAINT);
	}
}

void CSingleViewModelingView::OnInputVxLine() 
{
	// TODO: Add your command handler code here

	CSingleViewModelingDoc *pDoc;
	pDoc =(CSingleViewModelingDoc *) GetDocument( );
    CSingleImage *ptr = pDoc->GetSingleImage( );
	double u0;
	double v0;
	u0 = ptr->GetWidth( )/2.0;
	v0 = ptr->GetHeight( )/2.0;
	CInputDialogForVanishPoints dlg;
	if(dlg.DoModal( )== IDOK){
		CLineEndPoints * lineptr = new CLineEndPoints;
		lineptr->point1[0] = dlg.m_point1_x-u0;
		lineptr->point1[1] = dlg.m_point1_y-v0;
		lineptr->point2[0] = dlg.m_point2_x-u0;
		lineptr->point2[1] = dlg.m_point2_y-v0;

		int counter;
		counter = m_VxPointsptr.AddTail(lineptr);
	};
}

void CSingleViewModelingView::OnInputVyLine() 
{
	// TODO: Add your command handler code here
	CSingleViewModelingDoc *pDoc;
	pDoc =(CSingleViewModelingDoc *) GetDocument( );
    CSingleImage *ptr = pDoc->GetSingleImage( );
	double u0;
	double v0;
	u0 = ptr->GetWidth( )/2.0;
	v0 = ptr->GetHeight( )/2.0;
	CInputDialogForVanishPoints dlg;
	if(dlg.DoModal( )== IDOK){
		CLineEndPoints * lineptr = new CLineEndPoints;
		lineptr->point1[0] = dlg.m_point1_x-u0;
		lineptr->point1[1] = dlg.m_point1_y-v0;
		lineptr->point2[0] = dlg.m_point2_x-u0;
		lineptr->point2[1] = dlg.m_point2_y-v0;

		int counter;
		counter = m_VyPointsptr.AddTail(lineptr);
	};
	
}

void CSingleViewModelingView::OnInputVzLine() 
{
	// TODO: Add your command handler code here

	CSingleViewModelingDoc *pDoc;
	pDoc =(CSingleViewModelingDoc *) GetDocument( );
    CSingleImage *ptr = pDoc->GetSingleImage( );
	double u0;
	double v0;
	u0 = ptr->GetWidth( )/2.0;
	v0 = ptr->GetHeight( )/2.0;
	CInputDialogForVanishPoints dlg;
	if(dlg.DoModal( )== IDOK){
		CLineEndPoints * lineptr = new CLineEndPoints;
		lineptr->point1[0] = dlg.m_point1_x-u0;
		lineptr->point1[1] = dlg.m_point1_y-v0;
		lineptr->point2[0] = dlg.m_point2_x-u0;
		lineptr->point2[1] = dlg.m_point2_y-v0;

		int counter;
		counter = m_VzPointsptr.AddTail(lineptr);
	};
	
}

void CSingleViewModelingView::OnCaculateVanishPoints() 
{
	// TODO: Add your command handler code here
    CMatrix MatrixItem;
   	double **caculatematrix,**tempmatrix;
	double vector[3];
	double a[9],u[9],v[9];
	
	caculatematrix = (double **)malloc(3*sizeof(double *));
	for(int k=0;k<3;k++)
		caculatematrix[k] = (double*)malloc(3*sizeof(double));

	tempmatrix = (double **)malloc(3*sizeof(double *));
	for(k=0;k<3;k++)
		tempmatrix[k] = (double*)malloc(3*sizeof(double));

	for(int i=0;i<3;i++)
		for(int j=0;j<3;j++){
			caculatematrix[i][j] = 0;
			tempmatrix[i][j] = 0;

		}

//caculate X-vanishing points:
		int number;
		number = m_VxPointsptr.GetSize( );
	    ASSERT(number>=2);
		for(i=0;i<number;i++){
			MatrixItem.getvectorcrossproduct(m_VxPointsptr[i]->point1,m_VxPointsptr[i]->point2,vector);
			MatrixItem.vectormultiplyvectorprim(vector,vector,tempmatrix,3);
			for(int m=0;m<3;m++)
				for(int n=0;n<3;n++){
					caculatematrix[m][n] = caculatematrix[m][n]+tempmatrix[m][n];
				};
		};

		//to SVD format
		for(i=0;i<9;i++){
			a[i]=0;
			u[i]=0;
			v[i]=0;
		};

		for(i=0;i<3;i++)
			for(int j=0;j<3;j++){
               a[i*3+j]=caculatematrix[i][j];
				
			};
     
        MatrixItem.SVD(a,3,3,u,v,0.0000001);

		int whichiseigenvalues=0;
		for(i=0;i<3;i++)
		{
			if(a[i*3+i]<a[whichiseigenvalues*3+whichiseigenvalues]){
				whichiseigenvalues = i;
			};
		};

		for(i=0;i<3;i++){
			GetDocument( )->GetSingleImage()->m_Vx[i]=u[i*3+whichiseigenvalues];
		};


		// test begin

        //double testline1[3];
        //double testline2[3];
		//double testline3[3];
    /*    MatrixItem.getvectorcrossproduct(m_VxPointsptr[0]->point1,m_VxPointsptr[0]->point2,testline1);
        MatrixItem.getvectorcrossproduct(m_VxPointsptr[1]->point1,m_VxPointsptr[1]->point2,testline2);
		MatrixItem.getvectorcrossproduct(testline1,testline2,testline3);
        double Vxx = testline3[0]/testline3[2];
		double Vxy = testline3[1]/testline3[2];

		double cxx = u[0*3+whichiseigenvalues]/u[2*3+whichiseigenvalues];
		double cxy = u[1*3+whichiseigenvalues]/u[2*3+whichiseigenvalues];
*/
		
	//caculate stop
//caculate y vanishing points
	for(i=0;i<3;i++)
		for(int j=0;j<3;j++){
			caculatematrix[i][j] = 0;
			tempmatrix[i][j] = 0;

		}
		number = m_VyPointsptr.GetSize( );
		ASSERT(number>=2);
		for(i=0;i<number;i++){
			MatrixItem.getvectorcrossproduct(m_VyPointsptr[i]->point1,m_VyPointsptr[i]->point2,vector);
			MatrixItem.vectormultiplyvectorprim(vector,vector,tempmatrix,3);
			for(int m=0;m<3;m++)
				for(int n=0;n<3;n++){
					caculatematrix[m][n] = caculatematrix[m][n]+tempmatrix[m][n];
				};
		};

		//to SVD format
		for(i=0;i<9;i++){
			a[i]=0;
			u[i]=0;
			v[i]=0;
		};

		for(i=0;i<3;i++)
			for(int j=0;j<3;j++){
               a[i*3+j]=caculatematrix[i][j];
				
			};
     
        MatrixItem.SVD(a,3,3,u,v,0.0000001);

		 whichiseigenvalues=0;
		for(i=0;i<3;i++)
		{
			if(a[i*3+i]<a[whichiseigenvalues*3+whichiseigenvalues]){
				whichiseigenvalues = i;
			};
		};

		for(i=0;i<3;i++){
			GetDocument( )->GetSingleImage( )->m_Vy[i]=u[i*3+whichiseigenvalues];
		};

/*		MatrixItem.getvectorcrossproduct(m_VyPointsptr[0]->point1,m_VyPointsptr[0]->point2,testline1);
        MatrixItem.getvectorcrossproduct(m_VyPointsptr[1]->point1,m_VyPointsptr[1]->point2,testline2);
		MatrixItem.getvectorcrossproduct(testline1,testline2,testline3);
         Vxx = testline3[0]/testline3[2];
		 Vxy = testline3[1]/testline3[2];

		 cxx = u[0*3+whichiseigenvalues]/u[2*3+whichiseigenvalues];
		 cxy = u[1*3+whichiseigenvalues]/u[2*3+whichiseigenvalues];
*/	//caculate stop

	for(i=0;i<3;i++)
		for(int j=0;j<3;j++){
			caculatematrix[i][j] = 0;
			tempmatrix[i][j] = 0;

		}
		number = m_VzPointsptr.GetSize( );
		ASSERT(number>=2);
		for(i=0;i<number;i++){
			MatrixItem.getvectorcrossproduct(m_VzPointsptr[i]->point1,m_VzPointsptr[i]->point2,vector);
			MatrixItem.vectormultiplyvectorprim(vector,vector,tempmatrix,3);
			for(int m=0;m<3;m++)
				for(int n=0;n<3;n++){
					caculatematrix[m][n] = caculatematrix[m][n]+tempmatrix[m][n];
				};
		};

		//to SVD format
		for(i=0;i<9;i++){
			a[i]=0;
			u[i]=0;
			v[i]=0;
		};

		for(i=0;i<3;i++)
			for(int j=0;j<3;j++){
               a[i*3+j]=caculatematrix[i][j];
				
			};
     
        MatrixItem.SVD(a,3,3,u,v,0.0000001);

		whichiseigenvalues=0;
		for(i=0;i<3;i++)
		{
			if(a[i*3+i]<a[whichiseigenvalues*3+whichiseigenvalues]){
				whichiseigenvalues = i;
			};
		};

		for(i=0;i<3;i++){
			GetDocument( )->GetSingleImage()->m_Vz[i]=u[i*3+whichiseigenvalues];
		};
	//caculate stop
	/*	MatrixItem.getvectorcrossproduct(m_VzPointsptr[0]->point1,m_VzPointsptr[0]->point2,testline1);
        MatrixItem.getvectorcrossproduct(m_VzPointsptr[1]->point1,m_VzPointsptr[1]->point2,testline2);
		MatrixItem.getvectorcrossproduct(testline1,testline2,testline3);
       double   Vxx = testline3[0]/testline3[2];
		double  Vxy = testline3[1]/testline3[2];

		 double cxx = u[0*3+whichiseigenvalues]/u[2*3+whichiseigenvalues];
		 double cxy = u[1*3+whichiseigenvalues]/u[2*3+whichiseigenvalues];
*/

		for(i=0;i<3;i++){
			delete tempmatrix[i];
		    delete caculatematrix[i];
		}

		delete tempmatrix;
		delete caculatematrix;
  }

/*void CSingleViewModelingView::OnTest() 
{
	// TODO: Add your command handler code here
	static char BASED_CODE szFilter[] = "bmp";
 

	CFileDialog SaveFinalImageDialog(FALSE,szFilter );
	if ( SaveFinalImageDialog.DoModal()  == IDOK )
	{    
	
		CString FileName;
		FileName.Empty( );
		FileName = SaveFinalImageDialog.GetPathName( );
		CSingleImage * pSingleImage;
		pSingleImage =(CSingleImage *) GetDocument( )->GetSingleImage( );
		pSingleImage->GenerateImageTexture(447,135,766,359,819,684,456,525,200,400,FileName);

	
 


	}
	
}
*/
void CSingleViewModelingView::OnLButtonDblClk(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CRect viewport;
	GetClientRect( &viewport );
	int u = point.x + m_iOrigx;
	int v = viewport.Height() - 1 - point.y + m_iOrigy;
	CSingleViewModelingDoc *pDoc;
	pDoc = (CSingleViewModelingDoc *) GetDocument( );
	CSingleImage * pImageptr;
	pImageptr = pDoc->GetSingleImage( );

	double u0,v0;
	u0 = pImageptr->GetWidth()/2.0;
	v0 = pImageptr->GetHeight()/2.0;

	CGetPointDialog getpoint(this);
	getpoint.m_u = u;
	getpoint.m_v = v;
	getpoint.m_pointid = pImageptr->m_maxid+1;
	if(getpoint.DoModal( )== IDOK){
		CViewPoint * newpointptr = new CViewPoint;
		newpointptr->m_pointid = pImageptr->m_maxid+1;
		pImageptr->m_maxid++;
		newpointptr->m_u = getpoint.m_u-u0;
		newpointptr->m_v = getpoint.m_v-v0;
		newpointptr->m_wx = getpoint.m_wx;
		newpointptr->m_wxrefid = getpoint.m_wxrefid;
		newpointptr->m_wy = getpoint.m_wy;
		newpointptr->m_wyrefid = getpoint.m_wyrefid;
		newpointptr->m_wz = getpoint.m_wz;
		newpointptr->m_wzrefid = getpoint.m_wzrefid;
		int index = pImageptr->m_ViewPointListptr.AddTail(newpointptr);
	
	};

	CView::OnLButtonDblClk(nFlags, point);
}

void CSingleViewModelingView::OnLoadData() 
{
	// TODO: Add your command handler code here

	CFileDialog OpenDataDialog(TRUE);
	if ( OpenDataDialog.DoModal()  == IDOK )
	{    
	
		CString FileName;
		FileName.Empty( );
		FileName = OpenDataDialog.GetPathName( );

		FILE *fp;
	
    	if ( ( fp = fopen( FileName, "r" ) ) == NULL ) 
		{
		  TRACE( "can't read datafile %s!", FileName );
		  return;
		}

		CSingleViewModelingDoc * pDoc;
		pDoc = (CSingleViewModelingDoc *)GetDocument( );

		CSingleImage * ptr = pDoc->GetSingleImage( );
		fscanf(fp,"X Vanishing Point is %lf,%lf,%lf \n",&ptr->m_Vx[0],&ptr->m_Vx[1],&ptr->m_Vx[2]);
		fscanf(fp,"Y Vanishing Point is %lf,%lf,%lf \n",&ptr->m_Vy[0],&ptr->m_Vy[1],&ptr->m_Vy[2]);
		fscanf(fp,"Z Vanishing Point is %lf,%lf,%lf \n",&ptr->m_Vz[0],&ptr->m_Vz[1],&ptr->m_Vz[2]);

		fscanf(fp," a is : %lf \n",&ptr->a);
		fscanf(fp," b is : %lf \n",&ptr->b);
		fscanf(fp," A is : %lf \n",&ptr->A);

		fscanf(fp," Standard Origin is x = %lf,y = %lf\n", &ptr->x0,&ptr->y0);
		fscanf(fp," l vector is %lf,%lf,%lf \n",&ptr->m_l[0],&ptr->m_l[1],&ptr->m_l[2]);
		fscanf(fp," HMatrix First Line is: %lf,%lf,%lf \n",&ptr->HMatrix[0][0],&ptr->HMatrix[0][1],&ptr->HMatrix[0][2]);
		fscanf(fp," HMatrix Secon Line is: %lf,%lf,%lf \n",&ptr->HMatrix[1][0],&ptr->HMatrix[1][1],&ptr->HMatrix[1][2]);
		fscanf(fp," HMatrix Third Line is: %lf,%lf,%lf \n",&ptr->HMatrix[2][0],&ptr->HMatrix[2][1],&ptr->HMatrix[2][2]);

		fscanf(fp," lScale vector is %lf,%lf,%lf \n",&ptr->m_lScale[0],&ptr->m_lScale[1],&ptr->m_lScale[2]);
		fscanf(fp," HStandardMatrix First Line is: %lf,%lf,%lf \n",&ptr->HStandardMatrix[0][0],&ptr->HStandardMatrix[0][1],&ptr->HStandardMatrix[0][2]);
		fscanf(fp," HStandardMatrix Secon Line is: %lf,%lf,%lf \n",&ptr->HStandardMatrix[1][0],&ptr->HStandardMatrix[1][1],&ptr->HStandardMatrix[1][2]);
		fscanf(fp," HStandardMatrix Third Line is: %lf,%lf,%lf \n",&ptr->HStandardMatrix[2][0],&ptr->HStandardMatrix[2][1],&ptr->HStandardMatrix[2][2]);


		fscanf(fp," Max id is %d \n",&ptr->m_maxid);

		int pointnum ;

		fscanf(fp, "The number of the point is %d \n",&pointnum);

		ptr->m_ViewPointListptr.RemoveAll( );
		for(int i=0;i<pointnum;i++){

			CViewPoint *pointptr = new CViewPoint;

			fscanf(fp," The id of the point is:%d \n",&pointptr->m_pointid);
			fscanf(fp," Image value of the point is: %lf,%lf \n",&pointptr->m_u,&pointptr->m_v);
			fscanf(fp," x=%lf,y=%lf,z=%lf \n",&pointptr->m_wx,&pointptr->m_wy,&pointptr->m_wz);
			fscanf(fp," refx=%d,refy=%d,refz=%d \n",&pointptr->m_wxrefid,&pointptr->m_wyrefid,&pointptr->m_wzrefid);
		    ptr->m_ViewPointListptr.AddTail(pointptr);
		};


		int texturenum;


		fscanf(fp, "The number of the textures is %d \n",&texturenum);

		ptr->m_TextureImageListptr.RemoveAll( );
		for( i=0;i<texturenum;i++){

			CTextureImage * textureptr = new CTextureImage;

			fscanf(fp," The name of the texture is:%s \n",&textureptr->m_filename);
			fscanf(fp," The id num of the first point is: %d \n",&textureptr->m_ptid1);
			fscanf(fp," The id num of the secon point is: %d \n",&textureptr->m_ptid2);
			fscanf(fp," The id num of the third point is: %d \n",&textureptr->m_ptid3);
			fscanf(fp," The id num of the fourt point is: %d \n",&textureptr->m_ptid4);

			ptr->m_TextureImageListptr.AddTail(textureptr);
			

        }


		fclose(fp);
		

	
}


	

	
}

void CSingleViewModelingView::OnSaveData() 
{
	// TODO: Add your command handler code here
	CFileDialog SaveDataDialog(FALSE );
	if ( SaveDataDialog.DoModal()  == IDOK )
	{    
	
		CString FileName;
		FileName.Empty( );
		FileName = SaveDataDialog.GetPathName( );

		FILE *fp;
	
    	if ( ( fp = fopen( FileName, "w" ) ) == NULL ) 
		{
		  TRACE( "can't save datafile %s!", FileName );
		  return;
		}

		CSingleViewModelingDoc * pDoc;
		pDoc = (CSingleViewModelingDoc *)GetDocument( );

		CSingleImage * ptr = pDoc->GetSingleImage( );
		fprintf(fp,"X Vanishing Point is %lf,%lf,%lf \n",ptr->m_Vx[0],ptr->m_Vx[1],ptr->m_Vx[2]);
		fprintf(fp,"Y Vanishing Point is %lf,%lf,%lf \n",ptr->m_Vy[0],ptr->m_Vy[1],ptr->m_Vy[2]);
		fprintf(fp,"Z Vanishing Point is %lf,%lf,%lf \n",ptr->m_Vz[0],ptr->m_Vz[1],ptr->m_Vz[2]);

		fprintf(fp," a is : %lf \n",ptr->a);
		fprintf(fp," b is : %lf \n",ptr->b);
		fprintf(fp," A is : %lf \n",ptr->A);

		fprintf(fp," Standard Origin is x = %lf,y = %lf\n", ptr->x0,ptr->y0);
		fprintf(fp," l vector is %lf,%lf,%lf \n",ptr->m_l[0],ptr->m_l[1],ptr->m_l[2]);
		fprintf(fp," HMatrix First Line is: %lf,%lf,%lf \n",ptr->HMatrix[0][0],ptr->HMatrix[0][1],ptr->HMatrix[0][2]);
		fprintf(fp," HMatrix Secon Line is: %lf,%lf,%lf \n",ptr->HMatrix[1][0],ptr->HMatrix[1][1],ptr->HMatrix[1][2]);
		fprintf(fp," HMatrix Third Line is: %lf,%lf,%lf \n",ptr->HMatrix[2][0],ptr->HMatrix[2][1],ptr->HMatrix[2][2]);

		fprintf(fp," lScale vector is %lf,%lf,%lf \n",ptr->m_lScale[0],ptr->m_lScale[1],ptr->m_lScale[2]);
		fprintf(fp," HStandardMatrix First Line is: %lf,%lf,%lf \n",ptr->HStandardMatrix[0][0],ptr->HStandardMatrix[0][1],ptr->HStandardMatrix[0][2]);
		fprintf(fp," HStandardMatrix Secon Line is: %lf,%lf,%lf \n",ptr->HStandardMatrix[1][0],ptr->HStandardMatrix[1][1],ptr->HStandardMatrix[1][2]);
		fprintf(fp," HStandardMatrix Third Line is: %lf,%lf,%lf \n",ptr->HStandardMatrix[2][0],ptr->HStandardMatrix[2][1],ptr->HStandardMatrix[2][2]);


		fprintf(fp," Max id is %d \n",ptr->m_maxid);

		int pointnum = ptr->m_ViewPointListptr.GetSize( );

		fprintf(fp, "The number of the point is %d \n",pointnum);
		for(int i=0;i<pointnum;i++){
			fprintf(fp," The id of the point is:%d \n",ptr->m_ViewPointListptr[i]->m_pointid);
			fprintf(fp," Image value of the point is: %lf,%lf \n",ptr->m_ViewPointListptr[i]->m_u,ptr->m_ViewPointListptr[i]->m_v);
			fprintf(fp," x=%lf,y=%lf,z=%lf \n",ptr->m_ViewPointListptr[i]->m_wx,ptr->m_ViewPointListptr[i]->m_wy,ptr->m_ViewPointListptr[i]->m_wz);
			fprintf(fp," refx=%d,refy=%d,refz=%d \n",ptr->m_ViewPointListptr[i]->m_wxrefid,ptr->m_ViewPointListptr[i]->m_wyrefid,ptr->m_ViewPointListptr[i]->m_wzrefid);
		};

		int texturenum = ptr->m_TextureImageListptr.GetSize( );

		fprintf(fp, "The number of the textures is %d \n",texturenum);
		for( i=0;i<texturenum;i++){
			fprintf(fp," The name of the texture is:%s \n",ptr->m_TextureImageListptr[i]->m_filename);
			fprintf(fp," The id num of the first point is: %d \n",ptr->m_TextureImageListptr[i]->m_ptid1);
			fprintf(fp," The id num of the secon point is: %d \n",ptr->m_TextureImageListptr[i]->m_ptid2);
			fprintf(fp," The id num of the third point is: %d \n",ptr->m_TextureImageListptr[i]->m_ptid3);
			fprintf(fp," The id num of the fourt point is: %d \n",ptr->m_TextureImageListptr[i]->m_ptid4);
			

        }



		fclose(fp);
		

	
}

}

void CSingleViewModelingView::OnGetPar() 
{
	// TODO: Add your command handler code here
	CDialogforParameter dlg(this);
	if(dlg.DoModal( )==IDOK){
	CSingleViewModelingDoc *pDoc;
	pDoc = (CSingleViewModelingDoc *)GetDocument( );
	CSingleImage *pImageptr;
	pImageptr = (CSingleImage *)pDoc->GetSingleImage( );
	double u0,v0;
	u0 = pImageptr->GetWidth( )/2.0;
	v0 = pImageptr->GetHeight( )/2.0;

    pImageptr->A = dlg.m_A;
	pImageptr->a = dlg.m_a;
	pImageptr->b = dlg.m_b;

    double lstandard[3];
	CMatrix MatrixItem;
	MatrixItem.getvectorcrossproduct(pImageptr->m_Vx,pImageptr->m_Vy,lstandard);
	MatrixItem.getstandardvector(lstandard,3);

	for(int i=0;i<3;i++){
		pImageptr->m_lScale[i] = lstandard[i];
	};



	pImageptr->m_l[0] =dlg.m_uo-u0;
	pImageptr->m_l[1] = dlg.m_vo-v0;
	pImageptr->m_l[2] = 1;

	for(i=0;i<3;i++){
		pImageptr->HMatrix[i][0] = pImageptr->a*pImageptr->m_Vx[i];
		pImageptr->HMatrix[i][1] = pImageptr->b*pImageptr->m_Vy[i];
        pImageptr->HMatrix[i][2] = pImageptr->m_l[i];
        
	};


	double ** HCMatrix,** HCSMatrix,** HCIMatrix,** Displacement;


	HCMatrix = (double **)malloc(3*sizeof(double *));
	HCSMatrix = (double **)malloc(3*sizeof(double *));
	HCIMatrix = (double **)malloc(3*sizeof(double *));
	Displacement = (double **)malloc(3*sizeof(double *));
	for(int k=0;k<3;k++){
		HCMatrix[k] = (double*)malloc(3*sizeof(double));
		HCSMatrix[k] = (double*)malloc(3*sizeof(double));
	    HCIMatrix[k] = (double*)malloc(3*sizeof(double));
	    Displacement[k] = (double *)malloc(3*sizeof(double));
	}
	for( i=0;i<3;i++)
		for(int j=0;j<3;j++){
			HCMatrix[i][j] = 0;
			HCSMatrix[i][j] = 0;
			HCIMatrix[i][j] = 0;
			Displacement[i][j] = 0;
		};

     for( i=0;i<3;i++)
	   	for(int j=0;j<3;j++){
		   HCMatrix[i][j] = pImageptr->HMatrix[i][j];
		};

     MatrixItem.inversematrix(HCMatrix,HCIMatrix,3);

	 double standardl[3];
	 for(i=0;i<3;i++){
		standardl[i] = pImageptr->m_lScale[i];
	 };

	 double x0y0[3];
	 MatrixItem.matrixvectormultiply(HCIMatrix,standardl,x0y0,3,3);

	 pImageptr->x0 = x0y0[0]/x0y0[2];
	 pImageptr->y0 = x0y0[1]/x0y0[2];


     Displacement[0][0] =1;
	 Displacement[1][1] =1;
	 Displacement[2][2] =1;

	 Displacement[0][2] = pImageptr->x0;
	 Displacement[1][2] = pImageptr->y0;

	 MatrixItem.matrixmultiply(HCMatrix,Displacement,HCSMatrix,3,3,3);

	 double  tempvector[3];
	 for(i=0;i<3;i++){
		tempvector[i] = HCSMatrix[i][2];
	 };

	 double tempmol;
	 tempmol = MatrixItem.getmol(tempvector,3);
	 double scale;
	 scale = 1;
	 for(i=0;i<3;i++){
		double mul;
		mul = tempvector[i]*pImageptr->m_lScale[i];
		if(mul<0){
			scale= -1;
			break;
		};
	 };
	 scale = scale/tempmol;

	 for(i=0;i<3;i++)
		 for(int j=0;j<3;j++){
			HCSMatrix[i][j] = scale*HCSMatrix[i][j];
		 };

		
	 
    for(i=0;i<3;i++)
		 for(int j=0;j<3;j++){
			pImageptr->HStandardMatrix[i][j]= HCSMatrix[i][j]; 
		 };


  
		 for(k=0;k<3;k++){
					
			delete HCMatrix[k];
			delete HCSMatrix[k];
			delete HCIMatrix[k];
			delete Displacement[k];
		 };

		 	delete HCMatrix;
			delete HCSMatrix;
			delete HCIMatrix;
			delete Displacement;



	
	
	};
	
}

void CSingleViewModelingView::OnRButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	
	CSingleViewModelingDoc *pDoc;
	pDoc = (CSingleViewModelingDoc *) GetDocument( );
	CSingleImage * pImageptr;
	pImageptr = pDoc->GetSingleImage( );

	

	CGenTextureDialog gettex(this);
	
	if(gettex.DoModal( )== IDOK){
		CTextureImage * newtexptr = new CTextureImage;
		strcpy(newtexptr->m_filename,gettex.m_filename);
		newtexptr->m_ptid1 = gettex.m_ptid1;
		newtexptr->m_ptid2 = gettex.m_ptid2;
		newtexptr->m_ptid3 = gettex.m_ptid3;
		newtexptr->m_ptid4 = gettex.m_ptid4;

		int index = pImageptr->m_TextureImageListptr.AddTail(newtexptr);
	
	};
	CView::OnRButtonDown(nFlags, point);
}

void CSingleViewModelingView::OnSaveVrml() 
{
	// TODO: Add your command handler code here

	static char BASED_CODE szFilter[] = "wrl";
	CFileDialog SaveVRMLDialog(FALSE,szFilter );
	if ( SaveVRMLDialog.DoModal()  == IDOK )
	{    
	
		CString FileName;
		FileName.Empty( );
		FileName = SaveVRMLDialog.GetPathName( );

		FILE *fp;
	
    	if ( ( fp = fopen( FileName, "w" ) ) == NULL ) 
		{
		  TRACE( "can't save VRMLfile %s!", FileName );
		  return;
		}

		CSingleViewModelingDoc * pDoc;
		pDoc = (CSingleViewModelingDoc *)GetDocument( );

		CSingleImage * ptr = pDoc->GetSingleImage( );

		fprintf(fp,"#VRML V1.0 ascii \n");
		fprintf(fp,"PointLight{ intensity 1 location 50 100 300 } \n");
		fprintf(fp,"PointLight{ intensity 1 location 40 100 250 } \n");
		fprintf(fp,"PointLight{ intensity 1 location 60 100 250 } \n");
		fprintf(fp,"PointLight{ intensity 1 location 20 100 100 } \n");
		fprintf(fp,"PointLight{ intensity 3 location 80 100 100 } \n");
		fprintf(fp,"PointLight{ intensity 5 location 50 400 50 } \n");

		fprintf(fp,"ShapeHints { \n");
		fprintf(fp," vertexOrdering  COUNTERCLOCKWISE \n");
		fprintf(fp," shapeType       SOLID \n");
		fprintf(fp," }  \n");


		fprintf(fp,"Separator { \n");
		fprintf(fp,"Transform {      rotation 1 0 0 0   } \n");
		fprintf(fp,"Transform {      rotation 0 0 1 0   } \n");
		
		
		int texturesize;
		texturesize = ptr->m_TextureImageListptr.GetSize( );

		for(int i=0;i<texturesize;i++){
            int id1,id2,id3,id4;
			char filename[50];
			double x1,y1,z1;
			double x2,y2,z2;
			double x3,y3,z3;
            double x4,y4,z4;

			id1 = ptr->m_TextureImageListptr[i]->m_ptid1;
			id2 = ptr->m_TextureImageListptr[i]->m_ptid2;
			id3 = ptr->m_TextureImageListptr[i]->m_ptid3;
			id4 = ptr->m_TextureImageListptr[i]->m_ptid4;
			strcpy(filename,ptr->m_TextureImageListptr[i]->m_filename);

			BOOL isvalid = TRUE;
	        int index;
	        index = ptr->GetIndex(id1);
	        if(index<0){
	            isvalid = FALSE;
			}else{
	              x1 = -ptr->m_ViewPointListptr[index]->m_wy;
		          y1 = ptr->m_ViewPointListptr[index]->m_wz;
				  z1 = -ptr->m_ViewPointListptr[index]->m_wx;
			};

			index = ptr->GetIndex(id2);
	        if(index<0){
	            isvalid = FALSE;
			}else{
	              x2 = -ptr->m_ViewPointListptr[index]->m_wy;
		          y2 = ptr->m_ViewPointListptr[index]->m_wz;
				  z2 = -ptr->m_ViewPointListptr[index]->m_wx;
			};

			index = ptr->GetIndex(id3);
	        if(index<0){
	            isvalid = FALSE;
			}else{
	              x3 = -ptr->m_ViewPointListptr[index]->m_wy;
		          y3 = ptr->m_ViewPointListptr[index]->m_wz;
				  z3 = -ptr->m_ViewPointListptr[index]->m_wx;
			};

			index = ptr->GetIndex(id4);
	        if(index<0){
	            isvalid = FALSE;
			}else{
	              x4 = -ptr->m_ViewPointListptr[index]->m_wy;
		          y4 = ptr->m_ViewPointListptr[index]->m_wz;
				  z4 = -ptr->m_ViewPointListptr[index]->m_wx;
			};
			if(isvalid){
			
		fprintf(fp,"Separator { \n");
        fprintf(fp," Coordinate3 { point [ \n");

		fprintf(fp," %lf %lf %lf ,\n",x1,y1,z1);
		fprintf(fp," %lf %lf %lf ,\n",x2,y2,z2);
		fprintf(fp," %lf %lf %lf ,\n",x3,y3,z3);
		fprintf(fp," %lf %lf %lf ,\n",x4,y4,z4);

		fprintf(fp,"]} \n");

		fprintf(fp,"Texture2 { filename \"%s\" } \n",filename);

		fprintf(fp,"TextureCoordinate2 { point [ \n");
		fprintf(fp,"0 0, \n");
		fprintf(fp,"1 0, \n");
		fprintf(fp,"1 1, \n");
		fprintf(fp,"0 1, \n");
		fprintf(fp," ]} \n");

		fprintf(fp,"IndexedFaceSet { coordIndex [0, 1, 2, 3]} \n");
		fprintf(fp,"} \n");
			}else{
				::AfxMessageBox("Can't find Vertex when save VRML!!");
				break;
			};
		}
		
		
		
		
		
		
		fprintf(fp,"} \n");//add the end }

		fclose(fp);




	}
	 

	
}

void CSingleViewModelingView::OnQueryTexture() 
{
	// TODO: Add your command handler code here
	CSingleViewModelingDoc *pDoc;
	pDoc = (CSingleViewModelingDoc *) GetDocument( );
	CSingleImage * pImageptr;
	pImageptr = pDoc->GetSingleImage( );

	

	CQueryTexture querytexture(this);
	
	if(querytexture.DoModal( )== IDOK){

		int size;
	    size = pImageptr->m_TextureImageListptr.GetSize( );
	    if((querytexture.m_idnum>=0)&&(querytexture.m_idnum<size)){
		
		strcpy(pImageptr->m_TextureImageListptr[querytexture.m_idnum]->m_filename,querytexture.m_filename);

		
	
	};
	
}
}
