// madnessEditorView.cpp : implementazione della classe CmadnessEditorView
//

#include "stdafx.h"
#include "madnessEditor.h"
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
#include <il/il.h>
#include <il/ilu.h>
#include <il/ilut.h>
#include "madnessEditorDoc.h"
#include "madnessEditorView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CmadnessEditorView

IMPLEMENT_DYNCREATE(CmadnessEditorView, CView)

BEGIN_MESSAGE_MAP(CmadnessEditorView, CView)

    ON_WM_DESTROY()
    ON_WM_ERASEBKGND()
    ON_WM_SIZE()
    ON_WM_MOUSEMOVE()
    ON_COMMAND(ID_VISTA_WIREFRAME, OnVistaWireframe)
    ON_COMMAND(ID_VISTA_SOLID, OnVistaSolid)
    ON_UPDATE_COMMAND_UI(ID_VISTA_SOLID, OnUpdateVistaSolid)
    ON_UPDATE_COMMAND_UI(ID_VISTA_WIREFRAME, OnUpdateVistaWireframe)
    ON_WM_LBUTTONDOWN()
    ON_WM_LBUTTONUP()
    ON_WM_RBUTTONDOWN()
    ON_WM_KEYDOWN()
    ON_WM_MOUSEWHEEL()
    ON_WM_RBUTTONUP()
    ON_COMMAND(ID_FUNZIONI_FRANARE, OnFunzioniFranare)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_FRANARE, OnUpdateFunzioniFranare)
    ON_COMMAND(ID_FUNZIONI_LIVELLARE, OnFunzioniLivellare)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_LIVELLARE, OnUpdateFunzioniLivellare)
    ON_COMMAND(ID_FUNZIONI_INCLINARE, OnFunzioniInclinare)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_INCLINARE, OnUpdateFunzioniInclinare)
    ON_COMMAND(ID_FUNZIONI_SPIANARE, OnFunzioniSpianare)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_SPIANARE, OnUpdateFunzioniSpianare)
    ON_COMMAND(ID_FUNZIONI_AREAGOAL, OnFunzioniAreagoal)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_AREAGOAL, OnUpdateFunzioniAreagoal)
    ON_COMMAND(ID_FUNZIONI_START, OnFunzioniStart)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_START, OnUpdateFunzioniStart)
    ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
    ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
    ON_COMMAND(ID_EDIT_MERGE, OnEditMerge)
    ON_UPDATE_COMMAND_UI(ID_EDIT_MERGE, OnUpdateEditMerge)
    ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateEditPaste)
    ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
    ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
    ON_COMMAND(ID_FUNZIONI_ALZARE, OnFunzioniAlzare)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_ALZARE, OnUpdateFunzioniAlzare)
    ON_COMMAND(ID_EDIT_CUT, OnEditCut)
    ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut)
    ON_COMMAND(ID_FUNZIONI_PIRAMIDE, OnFunzioniPiramide)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_PIRAMIDE, OnUpdateFunzioniPiramide)
    ON_COMMAND(ID_FUNZIONI_NEMICI, OnFunzioniNemici)
    ON_UPDATE_COMMAND_UI(ID_FUNZIONI_NEMICI, OnUpdateFunzioniNemici)
END_MESSAGE_MAP()

// diagnostica di CmadnessEditorView

#ifdef _DEBUG
void CmadnessEditorView::AssertValid() const
{
    CView::AssertValid();
}

void CmadnessEditorView::Dump(CDumpContext& dc) const
{
    CView::Dump(dc);
}

CmadnessEditorDoc* CmadnessEditorView::GetDocument() const // la versione non debug è inline.
{
    ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CmadnessEditorDoc)));
    return (CmadnessEditorDoc*)m_pDocument;
}
#endif


    // costruzione/eliminazione di CmadnessEditorView

CmadnessEditorView::CmadnessEditorView()
{



optionDraw=TEXTURED;    
m_pDC=0;
m_hrc=0;
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);


inittexture=false;
b_CameraZoom=false;
b_Selection=false;
Sel.first.X=25;
Sel.first.Z=25;
Sel.last.X=25;
Sel.last.Z=25;
SelX=25.5;
SelZ=25.5;
camera.PositionCamera(-20, 70, -20,   DEFAULT_X/2, 0, DEFAULT_Z/2,   0, 1, 0);
h=60;
hl=60;
v=1;
vl=1;
k=-2.3;
kl=-2.3;
 // posiziona la camera sul bordo della mappa rivolta al centro della stessa per ruotare la mappa attorno al suo centro
 

// posiziona la camera al centro della mappa  per ruotare intorno all'asse y della camera 
 
                                                               
}

CmadnessEditorView::~CmadnessEditorView()
{
}

BOOL CmadnessEditorView::PreCreateWindow(CREATESTRUCT& cs)
{
    // An OpenGL window must be created with the following flags and must not
    // include CS_PARENTDC for the class style. Refer to SetPixelFormat
    // documentation in the "Comments" section for further information.
   cs.style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CS_OWNDC;
    if(cs.style&CS_PARENTDC)
    {
        AfxMessageBox("Win OpenGL Internal Error!");
        return FALSE;
    }

    return CView::PreCreateWindow(cs);
}

// disegno di CmadnessEditorView

void CmadnessEditorView::OnDraw(CDC* pDC)
{
    
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    //if(!b_CameraZoom) TargetCamera(&(pDoc->Map), SelX,SelZ);
    SetGL();

pDoc->Map.setColoredArea(Sel.first,Sel.last);
    glInit();
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
   
    glLoadIdentity();
    //float light_0_pos=(10.0f,20.0f,30.0f,20.0f);
   
            if (!inittexture) { pDoc->Map.InitTexture();
                for (int i=0; i<MAXENEMY;i++)
        pDoc->enemy[i].setTexture(pDoc->Map.Tex[pDoc->Map.TexEnemy]);
    inittexture=true;   glTexEnvi(  GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
    
    }
    

           
                         glMatrixMode(GL_PROJECTION);   
                       glLoadIdentity();
                        // gluPerspective(55.0f,(GLfloat)800/(GLfloat)600, .5f, 150.0f);
                gluPerspective(55.0f,(GLfloat)ViewSizeX/(GLfloat)ViewSizeY, .5f, 150.0f);
                        
                
                camera.Draw();
  pDoc->Map.Draw(optionDraw);
    //
int x,z;
//glPushMatrix()

for (int i=0; i<MAXENEMY;i++) {
    x=pDoc->Map.Enemys[i].first.X;
    z=pDoc->Map.Enemys[i].first.Z;
    if( pDoc->Map.Enemys[i].first.X != -1)  {
      pDoc->enemy[i].init_posizione(x,pDoc->Map.Map[x][z].C,z);
glPushMatrix();
glLoadIdentity();
  pDoc->enemy[i].Draw(optionDraw);
  glPopMatrix();
    }
}
//glPopMatrix();

           glDisable(GL_TEXTURE_2D);
                glColor3f(0.0,1.0,0.0);
                glBegin(GL_LINES);
                    glVertex3f( 0,0,-100);  
                    glVertex3f( 0,0,100);
                 glEnd();
                
                 glBegin(GL_LINES);
                    glVertex3f( -100,0,0);  
                    glVertex3f(100,0,0 );
                 glEnd();
               
                 glBegin(GL_LINES);
                    glVertex3f(0,-100,0 );  
                    glVertex3f(0,100,0 );
                 glEnd();   
                 
                 glBegin(GL_LINES);
                 glVertex3f(pDoc->Map.Start.first.X+0.5,
                            pDoc->Map.getY(pDoc->Map.Start.first.X+0.5,
                                    pDoc->Map.Start.first.Z+0.5)-3,
                            pDoc->Map.Start.first.Z+0.5);
                glVertex3f(pDoc->Map.Start.first.X+0.5,
                            pDoc->Map.getY(pDoc->Map.Start.first.X+0.5,
                                    pDoc->Map.Start.first.Z+0.5)+3,
                            pDoc->Map.Start.first.Z+0.5);
                glEnd();
          SwapBuffers(m_pDC->GetSafeHdc());
 glFlush();

}
void CmadnessEditorView::glInit()
{       glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
    glEnable(GL_COLOR_MATERIAL);

    glEnable(GL_DEPTH_TEST); 

}





BOOL CmadnessEditorView::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext)
{
    if( ! CView::Create(lpszClassName, lpszWindowName, dwStyle, 
        rect, pParentWnd, nID, pContext))   return false;

  m_pDC = new CClientDC(this);
  ASSERT(m_pDC != NULL);
    
  // Setta il pixel format
  if (!SetupPixelFormat(m_pDC)) return FALSE;
  // Crea e setta il contesto OPENGL
  m_hrc = wglCreateContext(m_pDC->GetSafeHdc());
  if(m_hrc==NULL){
        AfxMessageBox("OpenGL contest fail");
        return FALSE;
    }
    return TRUE;
}

void CmadnessEditorView::OnDestroy()
{
  CView::OnDestroy();
SetGL(); // wglMakeCurrent(m_pDC->GetSafeHdc(),m_hrc);
  glFinish();
  wglMakeCurrent(NULL,  NULL);
  if (m_hrc) ::wglDeleteContext(m_hrc);
  if (m_pDC) delete m_pDC;
}



BOOL CmadnessEditorView::OnEraseBkgnd(CDC* pDC)
{
    return TRUE;
}

BOOL CmadnessEditorView::SetupPixelFormat( CDC * pDC )
{
    static PIXELFORMATDESCRIPTOR pfd = 
     {
        sizeof(PIXELFORMATDESCRIPTOR),  //  size of this pfd
            1,                     // version number
            PFD_DRAW_TO_WINDOW |   // support window
            PFD_SUPPORT_OPENGL |   // support OpenGL
            PFD_DOUBLEBUFFER,      // double buffered
            PFD_TYPE_RGBA,         // RGBA type 
            24,                    // 24-bit color depth 
            0, 0, 0, 0, 0, 0,      // color bits ignored
            0,                     // no alpha buffer
            0,                     // shift bit ignored
            0,                     // no accumulation buffer
            0, 0, 0, 0,            // accum bits ignored
            32,                    // 32-bit z-buffer
            0,                     // no stencil buffer
            0,                     // no auxiliary buffer
            PFD_MAIN_PLANE,        // main layer
            0,                     // reserved
            0, 0, 0                // layer masks ignored
     };
    int pixelformat;

    if ( (pixelformat = ChoosePixelFormat(pDC->GetSafeHdc(), &pfd)) == 0 )
    {
        AfxMessageBox("ChoosePixelFormat failed");
        return FALSE;
    }

    if (SetPixelFormat(pDC->GetSafeHdc(), pixelformat, &pfd) == FALSE)
    {
        AfxMessageBox("SetPixelFormat failed");
        return FALSE;
    }

    return TRUE;
}
void CmadnessEditorView::OnSize(UINT nType, int cx, int cy)
{
    //TRACE("OnSize\n ");
    if(SetGL()){
    glMatrixMode (GL_PROJECTION);   
    glLoadIdentity ();
    //float ratio=(float)cx/(float)cy;
    //glOrtho(100,-100,100,-100,100,-100);
    ViewSizeX=cx;
    ViewSizeY=cy;
    glViewport (0, 0, (GLsizei) cx, (GLsizei) cy); 
    glMatrixMode (GL_MODELVIEW);    /*  back to modelview matrix    */

    //trackball
//m_tb.Resize( cx,cy );
    }
}




// gestori di messaggi di CmadnessEditorView

void CmadnessEditorView::OnMouseMove(UINT nFlags, CPoint point)
{
        CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
//  TRACE("nFlags %d",nFlags);


switch(nFlags)
{
case (MK_LBUTTON+MK_RBUTTON):
    if (b_CameraZoom) {
        
        CameraMove(point.x,point.y,2);

TargetCamera(&(pDoc->Map), SelX,SelZ);
    }
        if (b_Selection){
            
            Sel.function(&(pDoc->Map),&(pDoc->UndoMap),optionEdit,(now.y-point.y)*100/ViewSizeY);
            now.y=point.y;
        pDoc->UpdateAllViews(this);
        }
        break;
case (MK_LBUTTON):
        if(!SetLastPick(point.x, point.y))returnLastPick=returnFirstPick;
        else 
        if (optionEdit==5) 
            if (!SetFirstPick(point.x,point.y)) returnFirstPick=returnLastPick;
        break;
case (MK_RBUTTON):
        //  if(!b_CameraZoom) 
TargetCamera(&(pDoc->Map), camera.m_vView.x(),camera.m_vView.z());
         CameraMove(point.x,point.y,1);
         break;
}



OnPaint();
pDoc->UpdateAllViews(this);
    CView::OnMouseMove(nFlags, point);

}

void CmadnessEditorView::OnVistaWireframe()
{
    optionDraw=WIREFRAME;
    OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnVistaSolid()
{
    
    optionDraw=TEXTURED;
    OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateVistaSolid(CCmdUI *pCmdUI)
{
    if (optionDraw == TEXTURED )
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnUpdateVistaWireframe(CCmdUI *pCmdUI)
{
    if (optionDraw == WIREFRAME)
        pCmdUI->SetCheck(1);
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}




void CmadnessEditorView::OnLButtonDown(UINT nFlags, CPoint point)
{   
    
    
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc); 
    now.x=point.x;
    now.y=point.y;
    old.x=point.x;
    old.y=point.y;
//  if (pDoc->Busy) return;
    switch(nFlags)
    {
        case MK_RBUTTON+MK_LBUTTON:
            b_CameraZoom=true;
            break;
        case MK_LBUTTON:
        
            if (!SetFirstPick(point.x,point.y)) returnFirstPick=returnLastPick;
            if (optionEdit==START )  {pDoc->Map.Start.set(Sel.first,Sel.first);
                                 optionEdit=oldoptionEdit;
                                    }
            if (optionEdit==ENEMY) { 
                    pDoc->Map.Enemys[pDoc->numEnemy].set(Sel.first,Sel.first);
                    pDoc->numEnemy++;
                    if (pDoc->numEnemy==MAXENEMY) pDoc->numEnemy=0;
                    optionEdit=oldoptionEdit;
                    }
            OnPaint();
            break;
    }

//pDoc->UpdateAllViews(this);
    CView::OnLButtonDown(nFlags, point);
}

void CmadnessEditorView::OnLButtonUp(UINT nFlags, CPoint point)
{
    

    
b_CameraZoom=false;
b_Selection=false;
SelX=((Sel.first.X)+(Sel.last.X))/2+0.5;
SelZ=((Sel.first.Z)+(Sel.last.Z))/2+0.5;
    CView::OnLButtonUp(nFlags, point);
}

void CmadnessEditorView::OnInitialUpdate()
{

    CView::OnInitialUpdate();

CRect rc; 
GetClientRect(&rc); 
SetGL();

}

void CmadnessEditorView::OnRButtonDown(UINT nFlags, CPoint point)
{   CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    // TODO: Add your message handler code here and/or call default
//TargetCamera(&(pDoc->Map), SelX,SelZ);
    now.x=point.x;
    now.y=point.y;
    old.x=point.x;
    old.y=point.y;
    switch(nFlags)
    {
    case MK_RBUTTON+MK_LBUTTON:
            Sel.function(&(pDoc->Map),&(pDoc->UndoMap),optionEdit,0);
            b_Selection=true;
        break;
    }

    CView::OnRButtonDown(nFlags, point);
OnPaint();
}



void CmadnessEditorView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    if (pDoc->Busy) return;
    // TODO: Add your message handler code here and/or call default

     switch(nChar)
    {
    case VK_UP:

    break; // Move our camera forward by a positive speed
    case VK_DOWN:           // If we hit the DOWN arrow key
    // Move our camera backward by a negative speed
    break;
    

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

    // We made 2 changes from the camera2 tutorial.  Instead of gcamera.RotateView()
    // we use our new RotateAroundPoint() function.  We pass in the camera's view
    // point.  This will be the point that we rotate our camera position around.
    
    case VK_LEFT:           // If we hit the LEFT arrow key


    break;  


    case VK_RIGHT:          

    
    break;
    case 0x41:
        camera.RotateView(0.1,0,1,0);
        break;
    case 0x53:
        camera.RotateView(-0.1,0,1,0);
        break;

    case 0x57:

        break;
    case 0x5a: 

        break; 
    default:
        break;
}

OnPaint();
    CView::OnKeyDown(nChar, nRepCnt, nFlags);
}


BOOL CmadnessEditorView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
    // TODO: Add your message handler code here and/or call default
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
//  if (pDoc->Busy) return false;
    //TargetCamera(&(pDoc->Map), SelX,SelZ);
            //if (zDelta > 0)
            Sel.function(&(pDoc->Map),&(pDoc->UndoMap),optionEdit,zDelta/100);
    /*
            if (zDelta < 0)
            pDoc->Map.Function(optionEdit,-1);
    */  
        

    
     pDoc->UpdateAllViews(this);
     OnPaint();
     return CView::OnMouseWheel(nFlags, zDelta, pt);
}

void CmadnessEditorView::OnRButtonUp(UINT nFlags, CPoint point)
{
    // TODO: Add your message handler code here and/or call default

b_Selection=false;
    now.x=point.x;
    now.y=point.y;
    old.x=point.x;
    old.y=point.y;
    CView::OnRButtonUp(nFlags, point);
}


void CmadnessEditorView::OnFunzioniFranare()
{
    optionEdit=SLIDE;
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
   Sel.function(&(pDoc->Map),&(pDoc->UndoMap),optionEdit,0);
        OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniFranare(CCmdUI *pCmdUI)
{
    if (optionEdit == SLIDE)
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnFunzioniLivellare()
{
    optionEdit=LEVEL;
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
   Sel.function(&(pDoc->Map),&(pDoc->UndoMap),optionEdit,0);
        OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniLivellare(CCmdUI *pCmdUI)
{
 if (optionEdit == LEVEL)
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnFunzioniInclinare()
{
    optionEdit=INCLINE;

        OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniInclinare(CCmdUI *pCmdUI)
{
 if ((Sel.first.X-Sel.last.X)==(Sel.first.Z-Sel.last.Z)) pCmdUI->Enable(false);
 else pCmdUI->Enable(true);
 if (optionEdit == INCLINE)
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnFunzioniSpianare()
{
    optionEdit=FLAT;
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
      Sel.function(&(pDoc->Map),&(pDoc->UndoMap),optionEdit,0);
        OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniSpianare(CCmdUI *pCmdUI)
{
 if (optionEdit == FLAT)
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnFunzioniAreagoal()
{

    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    for (int j=pDoc->Map.Colored.first.X;j<=pDoc->Map.Colored.last.X;j++)
    for (int i=pDoc->Map.Colored.first.Z;i<=pDoc->Map.Colored.last.Z;i++)
    pDoc->Map.Map[j][i].goal=!pDoc->Map.Map[j][i].goal;

        OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniAreagoal(CCmdUI *pCmdUI)
{

}

void CmadnessEditorView::OnFunzioniStart()
{
    if (optionEdit==START )optionEdit=oldoptionEdit;
    else {oldoptionEdit=optionEdit;
        optionEdit=START ;}
    
    OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniStart(CCmdUI *pCmdUI)
{
     if (optionEdit == START )
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}





bool CmadnessEditorView::SetLastPick(int x, int y)
{
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);

returnLastPick=pDoc->Map.PickElement(x,y,optionDraw);
     if ( returnLastPick>=0)    
         if (optionEdit!=5)
        Sel.set(returnFirstPick,returnLastPick);

return (returnLastPick!=-1);
}

int CmadnessEditorView::CameraMove(int x1, int y1, int option)
{
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);

   old.x=now.x;
   old.y=now.y;
   now.x=x1;
   now.y=y1;

double a= (now.x-old.x);
double b=-(now.y-old.y);

switch (option)
{ case ROTATE:

    vl=vl-b*5/ViewSizeY;

    kl=kl+a*5/ViewSizeX;

    if (vl<=0.1) vl=0.1;
    if (vl>=(M_PI/2-0.1)) vl=M_PI/2-0.1;
            if (h<=1) h=1;

break;
case ZOOM: 

    hl=hl+b*50/ViewSizeY;
            kl=kl+a*5/ViewSizeX;
    if (hl<=1) hl=1;


break;

default: break;
} 

return 0; 
}
bool CmadnessEditorView::SetFirstPick(int x, int y)
{
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
  returnFirstPick=pDoc->Map.PickElement(x,y,optionDraw);

 if ( returnFirstPick>=0) 
            Sel.set(returnFirstPick,returnFirstPick);

return (returnFirstPick!=-1);
}







void CmadnessEditorView::OnEditCopy()
{
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    pDoc->Map.copy(&(theApp.AppMap),Sel.first,Sel.last);


}

void CmadnessEditorView::OnEditPaste() 
 { 
      CmadnessEditorDoc* pDoc = GetDocument(); 
      ASSERT_VALID(pDoc); 
pDoc->Map.copy(&(pDoc->UndoMap));
      pDoc->Map.paste(&(theApp.AppMap),Sel.first,Sel.last); 
Sel.applied=false;
        Sel.last.X = pDoc->Map.Colored.last.X;   
    Sel.last.Z = pDoc->Map.Colored.last.Z; 
OnPaint();
     pDoc->UpdateAllViews(this);

 
 
 }



void CmadnessEditorView::OnEditMerge()
{
CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
pDoc->Map.copy(&(pDoc->UndoMap));
    pDoc->Map.merge(&(theApp.AppMap),Sel.first,Sel.last);
Sel.applied=false;
        Sel.last.X = pDoc->Map.Colored.last.X;   
    Sel.last.Z = pDoc->Map.Colored.last.Z; 
OnPaint();
     pDoc->UpdateAllViews(this);
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateEditMerge(CCmdUI *pCmdUI)
{
    pCmdUI->Enable(theApp.AppMap.Meaningful);
    // TODO: Add your command update UI handler code here
}



void CmadnessEditorView::OnUpdateEditPaste(CCmdUI *pCmdUI)
{
    pCmdUI->Enable(theApp.AppMap.Meaningful);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnEditUndo()
{   
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    pDoc->UndoMap.copy(&(pDoc->Map));
    Sel.applied=false;
    OnPaint();
     pDoc->UpdateAllViews(this);
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateEditUndo(CCmdUI *pCmdUI)
{   
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    pCmdUI->Enable(pDoc->UndoMap.Meaningful);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnFunzioniAlzare()
{
 optionEdit = UP;
     OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniAlzare(CCmdUI *pCmdUI)
{
     if (optionEdit == UP)
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnEditCut()
{
    CmadnessEditorDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    pDoc->Map.copy(&(theApp.AppMap),Sel.first,Sel.last);
    Sel.function(&(pDoc->Map),&(pDoc->UndoMap),ZERO,pDoc->Map.getY(Sel.first.X,Sel.first.Z));
    Sel.applied=false;
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateEditCut(CCmdUI *pCmdUI)
{
    // TODO: Add your command update UI handler code here
}



void CmadnessEditorView::OnFunzioniPiramide()
{
optionEdit = PYRAMID;
OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniPiramide(CCmdUI *pCmdUI)
{
 if ((Sel.first.X-Sel.last.X)!=(Sel.first.Z-Sel.last.Z)) pCmdUI->Enable(false);
 else pCmdUI->Enable(true);
 if (optionEdit == PYRAMID)
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);

    // TODO: Add your command update UI handler code here
}

void CmadnessEditorView::OnFunzioniNemici()
{   if (optionEdit==ENEMY )optionEdit=oldoptionEdit;
    else {oldoptionEdit=optionEdit;
        optionEdit=ENEMY ;}
 OnPaint();
    // TODO: Add your command handler code here
}

void CmadnessEditorView::OnUpdateFunzioniNemici(CCmdUI *pCmdUI)
{
 if (optionEdit == ENEMY)
                pCmdUI->SetCheck(1);
    
    else pCmdUI->SetCheck(0);
    // TODO: Add your command update UI handler code here
}
void CmadnessEditorView::TargetCamera(MadMap *mp, float target_x, float target_z)
{


    if  (!mp->intersect((camera.m_vPosition.x()+camera.m_vView.x()+sin(v)*h*sin(k))/2,
                          (camera.m_vPosition.y()+camera.m_vView.y()+cos(v)*h)/2,
                          (camera.m_vPosition.z()+camera.m_vView.z()+sin(v)*h*cos(k))/2,
                        target_x,mp->getY(target_x,target_z)+1,target_z))
        {   
            v=v-0.1;
            if (v<0.1) v=0.1; 
        
        }  
    if  (mp->intersect((camera.m_vPosition.x()+camera.m_vView.x()+sin(vl)*h*sin(k))/2,
                         (camera.m_vPosition.y()+camera.m_vView.y()+cos(vl)*h)/2,
                         (camera.m_vPosition.z()+camera.m_vView.z()+sin(vl)*h*cos(k))/2,
                          target_x,mp->getY(target_x,target_z)+1, target_z))
            v=vl;
        
    h=hl;   
    if (h<1.5) h=1.5;

    k=kl;

    if (camera.m_vPosition.y()<mp->getY(camera.m_vPosition.x(),camera.m_vPosition.z())+1)
        {if (h>=2.5) h=h-1;}

    camera.PositionCamera((camera.m_vPosition.x()+camera.m_vView.x()+sin(v)*h*sin(k))/2,(camera.m_vPosition.y()+camera.m_vView.y()+cos(v)*h)/2,(camera.m_vPosition.z()+camera.m_vView.z()+sin(v)*h*cos(k))/2,
                        (camera.m_vView.x()+target_x)/2,mp->getY(target_x,target_z),(camera.m_vView.z()+target_z)/2,0, 1, 0);
}