// MapEditorView.cpp : implementation of the CMapEditorView class
//

#include "stdafx.h"
#include "MapEditor.h"
#include "MapEditorDoc.h"
#include "MapEditorView.h"

#include "DXUtil.h"
#include "stdio.h"
#include "Dbgout_C.h"
#include "InsertTileDlg2.h"
//#include "InsertObjectDlg.h"
#include "FileHeader.h"
#include "NewWorkspace.h"
#include "NewProjectDlg.h"
#include "NewTileSetDlg.h"
#include "SetHeightDlg.h"
#include <direct.h>
#include <io.h>
#include <fcntl.h>

#include "ObjectChild.h"
#include "EffectSetDetailDlg.h"
#include "LoadObjectDlg.h"
#include "MapTileSaveDlg.h"
#include "MFCUtil.h"
#include "roam.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

extern CMapEditorView*     g_AppFormView = NULL;
extern LPDIRECT3DDEVICE8	g_pD3dDev;
/////////////////////////////////////////////////////////////////////////////
// CMapEditorView
#define D3DFVF_SPRITEVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)

IMPLEMENT_DYNCREATE(CMapEditorView, CFormView)

BEGIN_MESSAGE_MAP(CMapEditorView, CFormView)
	//{{AFX_MSG_MAP(CMapEditorView)
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_MOUSEMOVE()
	ON_WM_RBUTTONDOWN()
	ON_WM_RBUTTONUP()
	ON_WM_MOUSEWHEEL()
	ON_BN_CLICKED(IDC_CHECK_LINE, OnCheckLine)
	ON_BN_CLICKED(IDC_RADIO_COMMAND, OnRadioCommand)
	ON_BN_CLICKED(IDC_RADIO_DOWN, OnRadioDown)
	ON_BN_CLICKED(IDC_RADIO_FLAT, OnRadioFlat)
	ON_BN_CLICKED(IDC_RADIO_HEIGHT, OnRadioHeight)
	ON_BN_CLICKED(IDC_RADIO_UPDOWN, OnRadioUp)
	ON_LBN_SELCHANGE(IDC_LIST_TILE, OnSelchangeListTile)
	ON_BN_CLICKED(IDC_BUTTON_CAMERAMOVE_LEFT, OnButtonCameramoveLeft)
	ON_BN_CLICKED(IDC_BUTTON_CAMERAMOVE_RIGHT, OnButtonCameramoveRight)
	ON_EN_CHANGE(IDC_EDIT_UPDOWN_VALUE, OnChangeEditUpdownValue)
	ON_EN_CHANGE(IDC_EDIT_FLAT_SIZE, OnChangeEditFlatSize)
	ON_CBN_SELCHANGE(IDC_COMBO_CONTORL_SIZE, OnSelchangeComboContorlSize)
	ON_CBN_SELCHANGE(IDC_COMBO_OBJECT_SELECT, OnSelchangeComboObjectSelect)
	ON_BN_CLICKED(IDC_RADIO_OBJECT, OnRadioObject)
	ON_EN_CHANGE(IDC_EDIT_OBJECT_CREATECONT, OnChangeEditObjectCreatecont)
	ON_EN_CHANGE(IDC_EDIT_OBJECT_DELETE, OnChangeEditObjectDelete)
	ON_BN_CLICKED(IDC_RADIO_OBJECT_DELETE, OnRadioObjectDelete)
	ON_BN_CLICKED(IDC_RADIO_WATER, OnRadioWater)
	ON_EN_CHANGE(IDC_EDIT_WATER, OnChangeEditWater)
	ON_NOTIFY(NM_RELEASEDCAPTURE, IDC_SLIDER_OBJECT_DIR, OnReleasedcaptureSliderObjectDir)
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_COMMAND(ID_EVENT_SET, OnEventSet)
	ON_UPDATE_COMMAND_UI(ID_EVENT_SET, OnUpdateEventSet)
	ON_COMMAND(ID_NEW_WORKSPACE, OnNewWorkspace)
	ON_COMMAND(ID_NEW_PROJECT, OnNewProject)
	ON_COMMAND(ID_OPEN_PROJECT, OnOpenProject)
	ON_COMMAND(ID_OPEN_WORKSPACE, OnOpenWorkspace)
	ON_COMMAND(ID_SAVE_PROJECT, OnSaveProject)
	ON_COMMAND(ID_WORKSPACE_VIEW, OnWorkspaceView)
	ON_UPDATE_COMMAND_UI(ID_WORKSPACE_VIEW, OnUpdateWorkspaceView)
	ON_LBN_SELCHANGE(IDC_LIST_TILEBASE, OnSelchangeListTilebase)
	ON_COMMAND(ID_CAMERA_SET, OnCameraSet)
	ON_COMMAND(ID_FLYING_VIEW, OnFlyingView)
	ON_UPDATE_COMMAND_UI(ID_FLYING_VIEW, OnUpdateFlyingView)
	ON_COMMAND(ID_MINIMAP_VIEW, OnMinimapView)
	ON_UPDATE_COMMAND_UI(ID_MINIMAP_VIEW, OnUpdateMinimapView)
	ON_BN_CLICKED(IDC_CHECK_OBJECTALPHA, OnCheckObjectalpha)
	ON_BN_CLICKED(IDC_BUTTON_INSERTTILE2, OnButtonInserttile2)
	ON_COMMAND(ID_BUTTON_OBJECT, OnButtonObject)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_OBJECT, OnUpdateButtonObject)
	ON_COMMAND(ID_BUTTON_MONSTER, OnButtonMonster)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_MONSTER, OnUpdateButtonMonster)
	ON_BN_CLICKED(IDC_BUTTON_TILESET_INSERT, OnButtonTileSetInsert)
	ON_CBN_SELCHANGE(IDC_COMBO_TILESET, OnSelchangeComboTileset)
	ON_COMMAND(ID_BUTTON_PICTURE, OnButtonPicture)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_PICTURE, OnUpdateButtonPicture)
	ON_COMMAND(ID_BUTTON_LOADDATA, OnButtonLoaddata)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_LOADDATA, OnUpdateButtonLoaddata)
	ON_COMMAND(ID_BUTTON_LOADDATA256, OnButtonLoaddata256)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_LOADDATA256, OnUpdateButtonLoaddata256)
	ON_BN_CLICKED(IDC_CHECK_TILESET_POINT, OnCheckTilesetPoint)
	ON_BN_CLICKED(IDC_CHECK_TILESET_REGION, OnCheckTilesetRegion)
	ON_EN_CHANGE(IDC_EDIT_WATER_HEIGHT, OnChangeEditWaterHeight)
	ON_BN_CLICKED(IDC_BUTTON_DELETETILE, OnButtonDeletetile)
	ON_BN_CLICKED(IDC_BUTTON_UPDATETILE, OnButtonUpdatetile)
	ON_COMMAND(ID_BUTTON_SETLIGHT, OnButtonSetlight)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_SETLIGHT, OnUpdateButtonSetlight)
	ON_EN_CHANGE(IDC_EDIT_HEIGHTMAX, OnChangeEditHeightmax)
	ON_EN_CHANGE(IDC_EDIT_HEIGHTMIN, OnChangeEditHeightmin)
	ON_COMMAND(ID_BUTTON_FLIGHTMIN, OnButtonFlightmin)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_FLIGHTMIN, OnUpdateButtonFlightmin)
	ON_BN_CLICKED(IDC_BUTTON_OBJECTTURNRIGHT, OnButtonObjectturnright)
	ON_BN_CLICKED(IDC_BUTTON_OBJECTTURNLEFT, OnButtonObjectturnleft)
	ON_BN_CLICKED(IDC_BUTTON_TILESET_DELETE, OnButtonTilesetDelete)
	ON_CBN_SELCHANGE(IDC_COMBO_TILESETSCALE, OnSelchangeComboTilesetscale)
	ON_EN_CHANGE(IDC_EDIT_OBJECT_BLOCKCONT, OnChangeEditObjectBlockcont)
	ON_EN_CHANGE(IDC_EDIT_OBJECT_NORMALCONT, OnChangeEditObjectNormalcont)
	ON_BN_CLICKED(IDC_BUTTON_OBJECT_UPDATE, OnButtonObjectUpdate)
	ON_BN_CLICKED(IDC_CHECK_OBJECTNORMAL, OnCheckObjectnormal)
	ON_COMMAND(ID_BUTTON_EDIT, OnButtonObjectReset)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_EDIT, OnUpdateButtonObjectReset)
	ON_BN_CLICKED(IDC_RADIO_CAMERA, OnRadioCamera)
	ON_BN_CLICKED(IDC_RADIO_DEFAULT, OnRadioDefault)
	ON_BN_CLICKED(IDC_CHECK_FOG, OnCheckFog)
	ON_COMMAND(ID_BUTTON_EFFECT, OnButtonEffect)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_EFFECT, OnUpdateButtonEffect)
	ON_BN_CLICKED(IDC_RADIO_EFFECT, OnRadioEffect)
	ON_COMMAND(ID_BUTTON_SETLIGHT2, OnButtonSetlight2)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_SETLIGHT2, OnUpdateButtonSetlight2)
	ON_BN_CLICKED(IDC_RADIO_LIGHT, OnRadioLight)
	ON_BN_CLICKED(IDC_CHECK_OBJECTALLRENDER, OnCheckObjectallrender)
	ON_BN_CLICKED(IDC_CHECK_LAND, OnCheckLand)
	ON_COMMAND(ID_BUTTON_ALLLIST, OnButtonAlllist)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_ALLLIST, OnUpdateButtonAlllist)
	ON_BN_CLICKED(IDC_CHECK_OBJECTALLNOTRENDER, OnCheckObjectallnotrender)
	ON_COMMAND(ID_BUTTON_LOAD_OBJECT, OnButtonLoadObject)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_LOAD_OBJECT, OnUpdateButtonLoadObject)
	ON_COMMAND(ID_BUTTON_SAVE_X, OnButtonSaveX)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_SAVE_X, OnUpdateButtonSaveX)
	ON_COMMAND(ID_BUTTON_MAP, OnButtonMap)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_MAP, OnUpdateButtonMap)
	ON_COMMAND(ID_BUTTON_LIGHT_VIEW, OnButtonLightView)
	ON_UPDATE_COMMAND_UI(ID_BUTTON_LIGHT_VIEW, OnUpdateButtonLightView)
	ON_COMMAND(ID_BUTTON_SET_BACK_TEXTURE, OnButtonSetBackTexture)
	ON_EN_CHANGE(IDC_EDIT_WATER_TYPE, OnChangeEditWaterType)	
	ON_BN_CLICKED(IDC_BUTTON_SMOOTH, OnButtonSmooth)
	ON_COMMAND(ID_BUTTON_GENERATE_BACK_TEXTURE, OnButtonGenerateBackTexture)
	ON_EN_CHANGE(IDC_EDIT_RED, OnChangeEditRed)
	ON_EN_CHANGE(IDC_EDIT_GREEN, OnChangeEditGreen)
	ON_EN_CHANGE(IDC_EDIT_BLUE, OnChangeEditBlue)
	ON_BN_CLICKED(IDC_CHECK_ROAMLAND, OnCheckRoamland)
	//}}AFX_MSG_MAP
	// Standard printing commands
	ON_COMMAND(ID_FILE_PRINT, CFormView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_DIRECT, CFormView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_PREVIEW, CFormView::OnFilePrintPreview)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMapEditorView construction/destruction

CMapEditorView::CMapEditorView()
	: CFormView(CMapEditorView::IDD)
{
	//{{AFX_DATA_INIT(CMapEditorView)
	m_bRenderLine = TRUE;
	m_nCommand = 0;
	m_nUpdown = 0;
	m_editUpDownRate = 5.0f;
	m_editFlatRate = 5.0f;
	m_editObjectNumber = 1;
	m_editObjectDelete = 1;
	m_editWater = 1;
	m_checkAlphaBlending = FALSE;
	m_checkTilesetPoint = FALSE;
	m_checkTilesetRegion = FALSE;
	m_editWaterHeight = 0;
	m_editHeightMax = 2000.0f;
	m_editHeightMin = -1000.0f;
	m_editObjectBlockCont = 0;
	m_editObjectNormalCont = 0;
	m_checkObjectNormal = FALSE;
	m_checkFog = FALSE;
	m_bAllObjectRender = FALSE;
	m_bLandView = FALSE;
	m_bRoamLandView = FALSE;
	m_bAllObjectNotRender = FALSE;
	m_dwWaterType = 1;
	//}}AFX_DATA_INIT
	// TODO: add construction code here
	m_dwBackRed = 0;
	m_dwBackGreen = 0;
	m_dwBackBlue = 255;
    g_AppFormView = this;
	m_pCamera = NULL;
	m_pBackground = NULL;
	m_pObject = NULL;
	m_pEffectRender = NULL;
	m_pEffectList = NULL;
	m_bUseDepthBuffer = TRUE;
	m_bReady = FALSE;
	m_ptOldPoint.x = -999;
	m_ptOldPoint.y = -999;
    m_pFont = new CD3DFont( _T("Arial"), 12, D3DFONT_BOLD );
	m_strDump[0] = 0;
	m_nTileTextype = -1;
	m_nBaseTileTextype = 0;
	m_nControlSizeType = 0;
	m_nTileSetScaleType = 0;
	m_dwObjectType = 0;
//	m_nObjectNum = 0;
	m_pTex = NULL;
	m_nOldLookX = -1;
	m_nOldLookZ = -1;
	m_vObjectVel = D3DXVECTOR3(0,0,1);
	m_bCheckEventSet = FALSE;
	m_bLButtonCheck = FALSE;
	m_bRButtonCheck = FALSE;
	m_bFlyingViewMax = FALSE;
	m_bFlyingViewMin = FALSE;
	m_bCheckMiniMapView = FALSE;
	m_pObjectInfo = NULL;
	m_pObjectInfoDetail = NULL;
	m_pWorkspace = NULL;
	m_bCheckWorkspaceView = FALSE;
	m_bSaveWorkspace = TRUE;
	m_bSaveProject = TRUE;
	m_pMiniMap = NULL;
	m_bCheckObject = FALSE;
	m_bCheckMonsterSet = FALSE;
	m_bCheckLightSet = FALSE;
	m_bEdit = FALSE;
	m_bEffect = FALSE;
	m_bCheckLightSet2 = FALSE;

	m_bObjectDir = 0;

	m_nObjectNormalCont = 0;
	m_nObjectBlockCont = 0;
	m_nUseTileset = 0;

	GetCurrentDirectory(sizeof(m_strCurrentDir),m_strCurrentDir);

	m_nMaxLightNum = 0;
	m_nUseLightNum = 0;

	m_bCheckBrush = TRUE; // 07-05-07 by shkim, brush check
	m_nBrushSize = 2; // 07-05-07 by shkim, brush size	

	m_bAllList = FALSE;
	m_bCamDirType = 0;
	m_pLight = NULL;
	m_bShowLight = FALSE;
	m_pLightRender = NULL;
	m_bCtrl = FALSE;
}

CMapEditorView::~CMapEditorView()
{
	SAFE_DELETE( m_pCamera );
	SAFE_DELETE( m_pBackground );
	SAFE_DELETE( m_pFont );
	SAFE_DELETE_ARRAY( m_pObjectInfo );
	SAFE_DELETE_ARRAY( m_pObjectInfoDetail );
	SAFE_DELETE( m_pMiniMap );
	SAFE_DELETE( m_pWorkspace );
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pEffectRender);
	SAFE_DELETE(m_pEffectList);
	SAFE_DELETE(m_pLightRender);
	m_listEffectInfo.clear();
	m_listLightInfo.clear();
}

void CMapEditorView::DoDataExchange(CDataExchange* pDX)
{
	CFormView::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMapEditorView)
	DDX_Control(pDX, IDC_COMBO_TILESETSCALE, m_comboTileSetScale);
	DDX_Control(pDX, IDC_COMBO_TILESET, m_comboTileSet);
	DDX_Control(pDX, IDC_LIST_TILEBASE, m_ctrlBaseTileList);
	DDX_Control(pDX, IDC_SLIDER_OBJECT_DIR, m_sliderObjectDir);
	DDX_Control(pDX, IDC_COMBO_OBJECT_SELECT, m_comboObjectSelect);
	DDX_Control(pDX, IDC_COMBO_CONTORL_SIZE, m_comboControlSizeType);
	DDX_Control(pDX, IDC_LIST_TILE, m_ctrlTileList);
	DDX_Check(pDX, IDC_CHECK_LINE, m_bRenderLine);
	DDX_Radio(pDX, IDC_RADIO_COMMAND, m_nCommand);
	DDX_Radio(pDX, IDC_RADIO_UPDOWN, m_nUpdown);
	DDX_Text(pDX, IDC_EDIT_UPDOWN_VALUE, m_editUpDownRate);
	DDX_Text(pDX, IDC_EDIT_FLAT_SIZE, m_editFlatRate);
	DDX_Text(pDX, IDC_EDIT_OBJECT_CREATECONT, m_editObjectNumber);
	DDX_Text(pDX, IDC_EDIT_OBJECT_DELETE, m_editObjectDelete);
	DDX_Text(pDX, IDC_EDIT_WATER, m_editWater);
	DDX_Check(pDX, IDC_CHECK_OBJECTALPHA, m_checkAlphaBlending);
	DDX_Check(pDX, IDC_CHECK_TILESET_POINT, m_checkTilesetPoint);
	DDX_Check(pDX, IDC_CHECK_TILESET_REGION, m_checkTilesetRegion);
	DDX_Text(pDX, IDC_EDIT_WATER_HEIGHT, m_editWaterHeight);
	DDX_Text(pDX, IDC_EDIT_HEIGHTMAX, m_editHeightMax);
	DDX_Text(pDX, IDC_EDIT_HEIGHTMIN, m_editHeightMin);
	DDX_Text(pDX, IDC_EDIT_OBJECT_BLOCKCONT, m_editObjectBlockCont);
	DDX_Text(pDX, IDC_EDIT_OBJECT_NORMALCONT, m_editObjectNormalCont);
	DDX_Check(pDX, IDC_CHECK_OBJECTNORMAL, m_checkObjectNormal);
	DDX_Check(pDX, IDC_CHECK_FOG, m_checkFog);
	DDX_Check(pDX, IDC_CHECK_OBJECTALLRENDER, m_bAllObjectRender);
	DDX_Check(pDX, IDC_CHECK_LAND, m_bLandView);
	DDX_Check(pDX, IDC_CHECK_OBJECTALLNOTRENDER, m_bAllObjectNotRender);
	DDX_Text(pDX, IDC_EDIT_WATER_TYPE, m_dwWaterType);
	DDX_Text(pDX, IDC_EDIT_RED, m_dwBackRed);
	DDX_Text(pDX, IDC_EDIT_GREEN, m_dwBackGreen);
	DDX_Text(pDX, IDC_EDIT_BLUE, m_dwBackBlue);
	DDX_Check(pDX, IDC_CHECK_ROAMLAND, m_bRoamLandView);
	//}}AFX_DATA_MAP
}

BOOL CMapEditorView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return CFormView::PreCreateWindow(cs);
}

void CMapEditorView::OnInitialUpdate()
{
	CFormView::OnInitialUpdate();
//	GetParentFrame()->RecalcLayout();
//	ResizeParentToFit();

	srand( (unsigned)time( NULL ) );
	
	m_sliderObjectDir.SetRange(1,1000);
	m_sliderObjectDir.SetPos(1);
    CD3DApplication::m_hWnd = GetDlgItem(IDC_MAPVIEW)->GetSafeHwnd();
    CD3DApplication::Create( AfxGetInstanceHandle() );

	m_dlgEventSet.Create(IDD_DIALOG_EVENTSET,this);
	m_dlgWorkspace.Create(IDD_DIALOG_WORKSPACE, this);
	m_dlgObjectSet.Create(IDD_DIALOG_OBJECTSET, this);
	m_dlgMonsterSet.Create(IDD_DIALOG_MONSTERSET, this);
	m_dlgLightSet.Create(IDD_DIALOG_LIGHTSET,this);
	m_dlgEdit.Create(IDD_DIALOG_EDIT,this);
	m_dlgEffect.Create(IDD_DIALOG_EFFECT,this);
	m_dlgLightList.Create(IDD_DIALOG_SUPPORTLIGHT,this);
	m_dlgAllList.Create(IDD_DIALOG_ALLLIST,this);
	m_dlgLightSetDetail.Create(IDD_DIALOG_LIGHTSET2,this);
//	m_dlgProjectDetail.Create(IDD_DIALOG_PROJECT_DETAIL,this);

	// 07-05-04 by shkim, 셋팅
	m_nComboCtrlSizeType = m_comboControlSizeType.SetCurSel( 0 );
	if( m_nComboCtrlSizeType == 0 )
	{
		m_nBrushSize = 2;
	}


	// Tile Set File 로딩
	int usetileset;
	CFile ReadFile;
	char strpath[256];
	_chdir(m_strCurrentDir);
	wsprintf(strpath,"TileSet");
	TileSetInfo tileset;
	if(ReadFile.Open(strpath, CFile::modeRead))
	{
		ReadFile.Seek(20,CFile::begin);
		ReadFile.Read(&usetileset,sizeof(int));
		for(int i = 0; i < usetileset; i++)
		{
			ReadFile.Read(&tileset,sizeof(tileset));
			m_comboTileSet.AddString(tileset.TileSetName);
		}
		ReadFile.Close();
	}
	else
	{
		if(ReadFile.Open(strpath,CFile::modeCreate | CFile::modeReadWrite))
		{
			usetileset = 0;
			ReadFile.Seek(20,CFile::begin);
			ReadFile.Write(&usetileset,sizeof(int));
			ReadFile.Close();
		}
	}	
}

/////////////////////////////////////////////////////////////////////////////
// CMapEditorView printing

BOOL CMapEditorView::OnPreparePrinting(CPrintInfo* pInfo)
{
	// default preparation
	return DoPreparePrinting(pInfo);
}

void CMapEditorView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add extra initialization before printing
}

void CMapEditorView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add cleanup after printing
}

void CMapEditorView::OnPrint(CDC* pDC, CPrintInfo* /*pInfo*/)
{
	// TODO: add customized printing code here	
}

/////////////////////////////////////////////////////////////////////////////
// CMapEditorView diagnostics

#ifdef _DEBUG
void CMapEditorView::AssertValid() const
{
	CFormView::AssertValid();
}

void CMapEditorView::Dump(CDumpContext& dc) const
{
	CFormView::Dump(dc);
}

CMapEditorDoc* CMapEditorView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMapEditorDoc)));
	return (CMapEditorDoc*)m_pDocument;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMapEditorView message handlers
HRESULT CMapEditorView::OneTimeSceneInit()
{
	D3DAdapterInfo* pAdapterInfo = &m_Adapters[m_dwAdapter];
	D3DDeviceInfo*  pDeviceInfo  = &pAdapterInfo->devices[pAdapterInfo->dwCurrentDevice];
	m_nMaxLightNum = pDeviceInfo->d3dCaps.MaxActiveLights;
	m_nUseLightNum = USED_LIGHT_NUM;
	m_dlgLightList.m_sLightMaxNum = m_nMaxLightNum - m_nUseLightNum;
	m_pObject = new CObjectRender();
	m_pCamera = new CD3DCamera();
	m_pCamera->InitCam();
	m_pEffectRender = new CEffectRender();
 	m_pEffectList = new CAtumNode;
   return S_OK;
}

void CMapEditorView::InitMapData()
{
	CFile ReadTexDataFile,RedaObjDataFile, ReadMapDataFile, ReadMapDataFileBase;
	CFileHeader header;
	TEXFILEINFO info;
	int usetex;
	int i,n;
	char strpath[256];
	_chdir(m_strCurrentDir);
	m_nUseTileset = m_pBackground->m_projectInfo.m_useTileSetIndex;
	m_comboTileSet.SetCurSel(m_nUseTileset);
	wsprintf(strpath,".\\Tile\\%d\\Texdata.mtd",m_nUseTileset);
	if(ReadTexDataFile.Open(strpath,CFile::modeRead))
	{
		ReadTexDataFile.Seek(20,CFile::begin);
		ReadTexDataFile.Read(&usetex,sizeof(int));
		for(i=0;i<usetex;i++)
		{
			ReadTexDataFile.Read(&info,sizeof(info));
 			m_pBackground->LoadTex(i,info);
		}
		ReadTexDataFile.Close();
	}

	int usetile;
	char tilename[20];
	char filename[20];
	n = m_ctrlTileList.GetCount();
	for(i=0; i<n;i++)
		m_ctrlTileList.DeleteString(n-i-1);
	n = m_ctrlBaseTileList.GetCount();
	for(i=0; i<n;i++)
		m_ctrlBaseTileList.DeleteString(n-i-1);
	_chdir(m_strCurrentDir);
	wsprintf(strpath,".\\Tile\\%d\\Mapdata.trd",m_pBackground->m_projectInfo.m_useTileSetIndex);
	if(ReadMapDataFile.Open(strpath,CFile::modeRead))
	{
		ReadMapDataFile.Seek(20,CFile::begin);
		ReadMapDataFile.Read(&usetile,sizeof(int));
		for(i=0;i<usetile;i++)
		{
			ReadMapDataFile.Read(&tilename,sizeof(char)*20);
			m_ctrlTileList.AddString(tilename);
			for(int j=0;j<MAX_BASETILERANDOM_NUM;j++)
			{
				ReadMapDataFile.Read(&filename,sizeof(char)*20);
				_chdir(m_strCurrentDir);
				wsprintf(strpath,".\\Res-Tile\\%s",filename);
				m_pBackground->InsertTile(strpath);
			}
			m_ctrlBaseTileList.AddString(tilename);
		}
		ReadMapDataFile.Close();
	}
	if(m_pBackground)
	{
		m_ctrlBaseTileList.SetCurSel(0);
		m_nBaseTileTextype = 0;
		m_pBackground->SetBaseTile(0);
	}
}


HRESULT CMapEditorView::InitDeviceObjects()
{
	g_pD3dDev = m_pd3dDevice;

	if(m_pBackground)
		m_pBackground->InitDeviceObjects();

	CFile ReadFile;
	if(ReadFile.Open("Object", CFile::modeRead))
	{
		ReadFile.Seek(20,CFile::begin);
		ReadFile.Read(&m_nObjectNormalCont,sizeof(INT));
		ReadFile.Read(&m_nObjectBlockCont,sizeof(INT));
		ReadFile.Close();
	}
	else
	{
		if(ReadFile.Open("Object",CFile::modeCreate | CFile::modeReadWrite))
		{
			ReadFile.Seek(20,CFile::begin);
			ReadFile.Write(&m_nObjectNormalCont,sizeof(INT));
			ReadFile.Write(&m_nObjectBlockCont,sizeof(INT));
			ReadFile.Close();
		}
	}

	m_editObjectNormalCont = m_nObjectNormalCont;
	m_editObjectBlockCont = m_nObjectBlockCont;

	UpdateData(FALSE);

	m_pObject->InitDeviceObjects();

	m_pFont->InitDeviceObjects( m_pd3dDevice );

	if(m_pMiniMap)
	{
		m_pMiniMap->InitDeviceObjects();
	}

	m_pEffectRender->InitDeviceObjects();

	_chdir(m_strCurrentDir);

	int nCont;
	if(ReadFile.Open("object.dat", CFile::modeRead))
	{
		ReadFile.Read(&nCont,sizeof(INT));
		for(int i=0;i<nCont;i++)
		{
			MAPOBJECTINFO *objectInfo = new MAPOBJECTINFO;
			ReadFile.Read(objectInfo,sizeof(MAPOBJECTINFO));
			map<int, MAPOBJECTINFO*>::iterator it = m_mapObjectInfo.find(objectInfo->Code);
			if(it == m_mapObjectInfo.end())
			{
				m_mapObjectInfo[objectInfo->Code] = objectInfo;
//				memcpy(&m_mapObjectInfo[objectInfo.Code],&objectInfo,sizeof(MAPOBJECTINFO));
			}
			else
			{
				SAFE_DELETE( objectInfo );
			}
		}
		ReadFile.Close();
	}

	m_pLightRender = new CLightRender;
	m_pLightRender->InitDeviceObjects();

	return S_OK;
}

HRESULT CMapEditorView::RestoreDeviceObjects()
{
    m_ArcBall.SetWindow( m_d3dsdBackBuffer.Width, m_d3dsdBackBuffer.Height, 2.0f );
	D3DMATERIAL8 mtrl;
	D3DUtil_InitMaterial( mtrl, 1.0f, 1.0f, 1.0f );
	g_pD3dDev->SetMaterial( &mtrl );
//	g_pD3dDev->SetRenderState( D3DRS_AMBIENT,  0x44444444 );

	g_pD3dDev->BeginStateBlock();
	g_pD3dDev->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
	g_pD3dDev->SetRenderState( D3DRS_ALPHATESTENABLE,  FALSE );
	g_pD3dDev->SetRenderState( D3DRS_ZENABLE,   TRUE );
	g_pD3dDev->SetRenderState( D3DRS_LIGHTING, TRUE );
	g_pD3dDev->SetTextureStageState( 0, D3DTSS_ADDRESSU,  D3DTADDRESS_CLAMP );
	g_pD3dDev->SetTextureStageState( 0, D3DTSS_ADDRESSV,  D3DTADDRESS_CLAMP );
	g_pD3dDev->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
	g_pD3dDev->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
	g_pD3dDev->SetRenderState( D3DRS_NORMALIZENORMALS, TRUE );	// 라이팅 엔진에서 사용하는 법선의 자동 표준화
	g_pD3dDev->EndStateBlock( &m_dwStateBlock );
	if(m_pBackground)
		m_pBackground->RestoreDeviceObjects();
	m_pObject->RestoreDeviceObjects();
	if(m_pMiniMap)
		m_pMiniMap->RestoreDeviceObjects();
	m_pFont->RestoreDeviceObjects();
	SetLight();
	m_bReady = TRUE;
	m_pEffectRender->RestoreDeviceObjects();
	m_pLightRender->RestoreDeviceObjects();

	// 2005-10-18 by ispark
	// Point 점 버퍼 생성
    if( FAILED( g_pD3dDev->CreateVertexBuffer(sizeof( POINT_VERTEX ),
		D3DUSAGE_WRITEONLY, D3DFVF_XYZ_DIFUSE_VERTEX, D3DPOOL_MANAGED, &m_pPointVB ) ) )
        return E_FAIL;
	
    return S_OK;
}


HRESULT CMapEditorView::FrameMove()
{
	if(m_pBackground)
	{
		m_pBackground->Tick();

		if(m_pMiniMap)
		{
			m_pMiniMap->Tick();
		}

		CheckMove();

		if(m_pEffectList)
		{
			m_pEffectList->Tick();
		}

		if(m_pEffectRender)
		{
			m_pEffectRender->Tick(m_fElapsedTime);
		}
	}

    return S_OK;
}

HRESULT CMapEditorView::Render()
{
    // 뷰포트를 지운다
	DWORD dwFogColor;
	if(m_checkFog)
		dwFogColor = D3DCOLOR_ARGB(0x00,(BYTE)131,(BYTE)191,(BYTE)255);
	else
		dwFogColor = D3DCOLOR_ARGB(0x00,(BYTE)m_dwBackRed,(BYTE)m_dwBackGreen,(BYTE)m_dwBackBlue);
	m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,dwFogColor, 1.0f, 0L );

	m_pd3dDevice->SetTransform( D3DTS_VIEW,       &m_pCamera->GetViewMatrix() );
	m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &m_pCamera->GetProjMatrix() );
    // Begin the scene
    if( SUCCEEDED( m_pd3dDevice->BeginScene() ) )
    {
		///////////////////////// FOG //////////////////////////////////////////
//		float fFogStartValue =  400.0f + (32)*40.0f;
//		float fFogEndValue = 450.0f + (32)*40.0f;
		float fFogStartValue =  (30)*40.0f;
		float fFogEndValue = (40)*40.0f;
		if(m_checkFog)
			g_pD3dDev->SetRenderState( D3DRS_FOGENABLE, TRUE );
		else
			g_pD3dDev->SetRenderState( D3DRS_FOGENABLE, FALSE );
		g_pD3dDev->SetRenderState( D3DRS_FOGCOLOR,  dwFogColor );
		// Vertex Fog Use
		g_pD3dDev->SetRenderState( D3DRS_FOGTABLEMODE,   D3DFOG_NONE );
		g_pD3dDev->SetRenderState( D3DRS_FOGSTART,   FtoDW(fFogStartValue) ); // 
		g_pD3dDev->SetRenderState( D3DRS_FOGEND,     FtoDW(fFogEndValue) );
		g_pD3dDev->SetRenderState( D3DRS_FOGVERTEXMODE,  D3DFOG_LINEAR );
		g_pD3dDev->SetRenderState( D3DRS_RANGEFOGENABLE, TRUE );
		g_pD3dDev->SetVertexShader( D3DFVF_FOGVERTEX );
		
		m_pd3dDevice->ApplyStateBlock( m_dwStateBlock );
//		SetLight();
		if(m_pBackground)
		{
//			m_pBackground->Render(m_pCamera->GetEyePt(),m_pCamera->GetLookatPt());
			m_pBackground->Render();//m_pCamera->GetEyePt(),m_pCamera->GetEyePt() + m_pCamera->GetViewDir()*16*40.0f);
			

			if(m_bCheckMiniMapView && m_pMiniMap)
			{
				m_pMiniMap->Render();
			}

			if(m_pEffectRender)
			{
				m_pEffectRender->Render();
				m_pEffectRender->RenderZEnable();
			}
		}
		g_pD3dDev->SetRenderState( D3DRS_FOGENABLE, FALSE );

		if ( m_bShowLight )
		{
			m_pLightRender->Render();
		}

		// LookAt 위치
//		POINT_VERTEX* v;
//
//		m_pPointVB->Lock( 0, 0, (BYTE**)&v, 0  );
//		v->p = m_pCamera->GetLookatPt();
//		v->c = D3DCOLOR_ARGB(0,255,255,0);
//		m_pPointVB->Unlock();
//		
//		float fPointSize = 6.0f;
//		g_pD3dDev->SetRenderState( D3DRS_POINTSIZE,*((DWORD*)&(fPointSize)));
//		g_pD3dDev->SetStreamSource( 0, m_pPointVB, sizeof(POINT_VERTEX) );
//		g_pD3dDev->DrawPrimitive( D3DPT_POINTLIST , 0,1);

		m_pFont->DrawText( 0,  0, D3DCOLOR_ARGB(255,255,255,0), MAP_EDITOR_VERSION );// 버전
		m_pFont->DrawText( 500,  0, D3DCOLOR_ARGB(255,255,255,0), m_strFrameStats );
        m_pFont->DrawText( 500,  20, D3DCOLOR_ARGB(255,255,255,0), m_strDump );

		TCHAR m_strLookAtHeight[90];
		sprintf( m_strLookAtHeight, "LootAt H %.01f", m_pCamera->GetLookatPt().y);
 		m_pFont->DrawText(2, 500, D3DCOLOR_ARGB(255,255,255,0), m_strLookAtHeight);

		m_pd3dDevice->EndScene();
    }

    return S_OK;
}

HRESULT CMapEditorView::InvalidateDeviceObjects()
{
	if(m_pBackground)
		m_pBackground->InvalidateDeviceObjects();
	m_pObject->InvalidateDeviceObjects();
	if(m_pMiniMap)
		m_pMiniMap->InvalidateDeviceObjects();
	m_pFont->InvalidateDeviceObjects();

//    if( m_pdeHead != NULL)
//        m_ArcBall.SetRadius( m_pdeHead->fRadius );
    m_ArcBall.SetRightHanded( TRUE );
	m_pEffectRender->InvalidateDeviceObjects();

	m_pLightRender->InvalidateDeviceObjects();
    return S_OK;
}

HRESULT CMapEditorView::DeleteDeviceObjects()
{
	if(m_pBackground)
		m_pBackground->DeleteDeviceObjects();

	m_pObject->DeleteDeviceObjects();
	SAFE_DELETE(m_pObject);
	if(m_pMiniMap)
		m_pMiniMap->DeleteDeviceObjects();
	m_pFont->DeleteDeviceObjects();
	SAFE_DELETE(m_pFont);
	SAFE_RELEASE(m_pTex);
	m_pEffectRender->DeleteDeviceObjects();
	SAFE_DELETE(m_pEffectRender);
	SAFE_DELETE(m_pEffectList);
 	m_listEffectInfo.clear();
	list<D3DLIGHT8*>::iterator itLight = m_listLightInfo.begin();
	while( itLight != m_listLightInfo.end() )
	{
		SAFE_DELETE( (*itLight) );
		itLight++;
	}
 	m_listLightInfo.clear();

	map<int, MAPOBJECTINFO*>::iterator it = m_mapObjectInfo.begin();
	while( it != m_mapObjectInfo.end() )
	{
		SAFE_DELETE( it->second );
		it++;
	}

	m_pLightRender->DeleteDeviceObjects();

	SAFE_RELEASE(m_pPointVB);
	return S_OK;
}

HRESULT CMapEditorView::FinalCleanup()
{
	SAFE_DELETE(m_pBackground);
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pFont);
	SAFE_DELETE(m_pMiniMap);
	SAFE_DELETE(m_pEffectRender);
 	SAFE_DELETE(m_pEffectList);
	m_listEffectInfo.clear();
	m_listLightInfo.clear();
	return S_OK;
}

HRESULT CMapEditorView::ConfirmDevice( D3DCAPS8* pCaps, DWORD dwBehavior,
                                          D3DFORMAT Format )
{
    // This sample wants mixed vertex processing rather than hardware
    // vertex processing so it can fallback to sw processing if the 
    // device supports fewer than three matrices when skinning.
    if( dwBehavior & D3DCREATE_HARDWARE_VERTEXPROCESSING )
        return E_FAIL;
 
    return S_OK;
}


VOID CMapEditorView::SetLight()
{
    ZeroMemory( &light, sizeof(D3DLIGHT8) );
	light.Type = D3DLIGHT_DIRECTIONAL;
	light.Diffuse.r  = m_dlgLightSet.m_editDiffuseR;
	light.Diffuse.g  = m_dlgLightSet.m_editDiffuseG;
	light.Diffuse.b  = m_dlgLightSet.m_editDiffuseB;
	light.Ambient.r  = m_dlgLightSet.m_editAmbientR;
	light.Ambient.g  = m_dlgLightSet.m_editAmbientG;
	light.Ambient.b  = m_dlgLightSet.m_editAmbientB;
	light.Direction.x  = m_dlgLightSet.m_editDirectionX;
	light.Direction.y  = m_dlgLightSet.m_editDirectionY;
	light.Direction.z  = m_dlgLightSet.m_editDirectionZ;
	g_pD3dDev->SetLight( 0, &light );
    g_pD3dDev->LightEnable( 0, TRUE );
    g_pD3dDev->SetRenderState( D3DRS_LIGHTING, TRUE );
	
    // 환경라이트 사용
//    m_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0x007777ff );
	/////////   light1   ///////////////////->오브젝트 비출때 사용 - 정면으로 비춘다.
	ZeroMemory( &m_light1, sizeof(D3DLIGHT8) );
	m_light1.Type       = D3DLIGHT_DIRECTIONAL;
	m_light1.Diffuse.r  = 1.0f;
	m_light1.Diffuse.g  = 1.0f;
	m_light1.Diffuse.b  = 1.0f;
	m_light1.Ambient.r  = 1.0f;
	m_light1.Ambient.g  = 1.0f;
	m_light1.Ambient.b  = 1.0f;
	m_light1.Direction = D3DXVECTOR3( -1, 0, 0 );
 	g_pD3dDev->SetLight( 1, &m_light1 );
	g_pD3dDev->LightEnable( 1, FALSE );
}

void CMapEditorView::OnLButtonDown(UINT nFlags, CPoint point) 
{	
	D3DXVECTOR3 vPickRayDir;
	D3DXVECTOR3 vPickRayOrig;

	// 07-05-11 by shkim, 픽킹 영역 계산
	m_pBackground->CalculatePickPostion( &vPickRayOrig, &vPickRayDir );


//	m_bLButtonCheck = FALSE;
	m_bLButtonCheck = TRUE;

	m_ptOldPoint = point;
	
	if(m_bCheckMiniMapView) 
	{
		CRect rect;
		GetDlgItem(IDC_MAPVIEW)->GetWindowRect(&rect);
		ScreenToClient(&rect);
		if( point.x >= rect.left &&
			point.x <= (rect.left+m_pBackground->m_sXSize) &&
			point.y >= rect.top &&
			point.y <= (rect.top+m_pBackground->m_sYSize) )
		{
			float fx,fz;
			fz = 40.0f*(point.x-rect.left);
			fx = 40.0f*(point.y-rect.top);

			D3DXVECTOR3 vEye,vLookat,vUp;
			vEye = m_pCamera->GetEyePt();
			vLookat = m_pCamera->GetLookatPt();
//			D3DXVec3Normalize(&vLookat,&m_pCamera->GetViewDir());

			float fxD, fzD;
			fxD = fx - vLookat.x;
			fzD = fz - vLookat.z;

			vLookat.x += fxD;
			vLookat.z += fzD;
			vEye.x += fxD;
			vEye.z += fzD;

			m_pCamera->SetViewParams(vEye, vLookat, D3DXVECTOR3(0,1,0));
			return;
		}
	}
	if(m_pBackground)
	{
		if(m_bCheckObject)
		{
	
			m_pBackground->SeekObject();//point);
//			m_pBackground->ObjectAction(vPickRayOrig,vPickRayDir);

			return;
		}

		if(m_bCheckEventSet && m_dlgEventSet.m_checkEventSetMode)
		{
			m_pBackground->EventAction(&m_dlgEventSet,vPickRayOrig,vPickRayDir);
		}
		else if(m_bCheckMonsterSet)
		{
			m_pBackground->MonsterAction(&m_dlgMonsterSet,vPickRayOrig,vPickRayDir);
		}
		else
		{
			m_pBackground->MouseAction(m_nCommand,vPickRayOrig,vPickRayDir);//,m_nTileTextype);
		}
	}
	
	CFormView::OnLButtonDown(nFlags, point);
}

void CMapEditorView::OnLButtonUp(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	D3DXVECTOR3 vPickRayDir;
	D3DXVECTOR3 vPickRayOrig;

	m_pBackground->CalculatePickPostion( &vPickRayOrig, &vPickRayDir );// 픽킹 영역 계산

	m_bLButtonCheck = FALSE;
	if(m_pBackground)
	{
		if(m_bCheckEventSet && m_dlgEventSet.m_checkEventSetMode)
		{
			m_pBackground->EventAction(&m_dlgEventSet,vPickRayOrig,vPickRayDir);
		}
		else if(m_bCheckMonsterSet)
		{
			m_pBackground->MonsterAction(&m_dlgMonsterSet,vPickRayOrig,vPickRayDir);
		}
		else if(m_nCommand == 0 && m_checkTilesetRegion)
		{
			m_pBackground->MouseAction(m_nCommand,vPickRayOrig,vPickRayDir);//,m_nTileTextype);
		}
		else if(m_nCommand == 7)
		{
			CheckSetEffect(vPickRayOrig,vPickRayDir);
		}
		else if(m_nCommand == 8)
		{
			CheckSupprotLight(vPickRayOrig,vPickRayDir);
		}
	}

	m_strDump[0] = 0;
	CFormView::OnLButtonUp(nFlags, point);
}

void CMapEditorView::OnMouseMove(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	if(m_bCheckObject && m_dlgObjectSet.m_bMoveRotation)
		return;
	// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
	float moveSpeed = 1.0f;
	if((GetAsyncKeyState(VK_LCONTROL) & 0x8000) > 0)
	{
		moveSpeed = 0.1f;
	}
	// end by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
	switch(nFlags)
	{
		case MK_LBUTTON:
		{
			if(m_nCommand == 6)
			{
				float fSide,fUp;
				fSide = point.x - m_ptOldPoint.x;
				fUp = point.y - m_ptOldPoint.y;
				D3DXVECTOR3 vEye,vLookat,vUp,vTemp,vSide,vUp2;
				vUp2 = D3DXVECTOR3(0,1,0);
				D3DXVec3Normalize(&vSide,&m_pCamera->GetCross());
				vEye = m_pCamera->GetEyePt();
				D3DXVec3Normalize(&vLookat,&m_pCamera->GetViewDir());
				D3DXVec3Cross(&vUp,&vSide,&vLookat);
				D3DXMATRIX mat;
				D3DXMatrixRotationAxis(&mat,&vUp2,-0.001f*fSide);
				D3DXVec3TransformCoord(&vLookat, &vLookat, &mat);
				D3DXVec3TransformCoord(&vUp, &vUp, &mat);

				D3DXVec3Cross(&vSide,&vLookat,&vUp);
				D3DXMatrixRotationAxis(&mat,&vSide,0.001f*fUp);
				D3DXVec3TransformCoord(&vLookat, &vLookat, &mat);
				D3DXVec3TransformCoord(&vUp, &vUp, &mat);
				m_pCamera->SetViewParams(vEye,vEye+vLookat,vUp);
			}
			else
			{
				D3DXVECTOR3 vPickRayDir;
				D3DXVECTOR3 vPickRayOrig;

				// 07-05-11 by shkim, 픽킹 영역 계산
				m_pBackground->CalculatePickPostion( &vPickRayOrig, &vPickRayDir );

				// MiniMap

				if(m_bCheckMiniMapView)
				{
					CRect rect;
					GetDlgItem(IDC_MAPVIEW)->GetWindowRect(&rect);
					ScreenToClient(&rect);
					if(point.x >= rect.left && point.x <= (rect.left+m_pBackground->m_sXSize) && point.y >= rect.top && point.y <= (rect.top+m_pBackground->m_sYSize))
					{
						float fx,fz;
						fz = 40.0f*(point.x-rect.left);
						fx = 40.0f*(point.y-rect.top);

						D3DXVECTOR3 vEye,vLookat,vUp;
						vEye = m_pCamera->GetEyePt();
						vLookat = m_pCamera->GetLookatPt();
			//			D3DXVec3Normalize(&vLookat,&m_pCamera->GetViewDir());

						float fxD, fzD;
						fxD = fx - vLookat.x;
						fzD = fz - vLookat.z;

						vLookat.x += fxD;
						vLookat.z += fzD;
						vEye.x += fxD;
						vEye.z += fzD;

						m_pCamera->SetViewParams(vEye, vLookat, D3DXVECTOR3(0,1,0));
						return;
					}
				}

				if(m_pBackground)
				{
					if(m_bCheckEventSet && m_bLButtonCheck && m_dlgEventSet.m_checkEventSetMode)
					{
						m_pBackground->EventAction(&m_dlgEventSet,vPickRayOrig,vPickRayDir);
					}
					else if(m_bCheckMonsterSet)
					{
						m_pBackground->MonsterAction(&m_dlgMonsterSet,vPickRayOrig,vPickRayDir);
					}
					else
					{
						if(m_nCommand==3)
						{
							return;
						}
						
						m_pBackground->MouseAction(m_nCommand,vPickRayOrig,vPickRayDir);//, m_nTileTextype);
					}
				}
			}
			break;
		}
		case MK_RBUTTON:
		case MK_CONTROL|MK_RBUTTON:// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
		{
			if(m_ptOldPoint.x != -999 && m_ptOldPoint.y != -999 )
			{
				D3DXVECTOR3 vSide,vFront,vUp,vEye,vLookat;
				vEye = m_pCamera->GetEyePt();
//				vUp = D3DXVECTOR3(0,1,0);
				D3DXVec3Normalize(&vSide,&m_pCamera->GetCross());
				vFront = m_pCamera->GetViewDir() + m_pCamera->GetUpVec();
				vFront.y = 0.0f;
				D3DXVec3Normalize(&vFront,&vFront);
				CPoint move = point - m_ptOldPoint;

				move.x *= moveSpeed;// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
				move.y *= moveSpeed;// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.

				if(m_bCheckLightSet2 && m_dlgLightList.m_bLightPosition)
				{
					m_dlgLightList.SetLightPosition(vSide*(float)move.x + vFront*(float)move.y);
				}
				else
				{
//					vEye += (vSide*(float)move.x + vFront*(float)move.y);
//					m_pCamera->SetViewParams(vEye,vEye + m_pCamera->GetViewDir(),m_pCamera->GetUpVec());
					CPoint pointTemp;
					pointTemp.x = point.x - m_ptOldPoint.x;
					pointTemp.y = m_ptOldPoint.y - point.y;

					pointTemp.x *= moveSpeed;
					pointTemp.y *= moveSpeed;

					m_pCamera->RotationLocal3X(pointTemp.y);
					m_pCamera->RotationLocal3Y(pointTemp.x);
				}

				RenderScene();
			}
			break;
		}
		case MK_MBUTTON:
		case MK_CONTROL|MK_MBUTTON:// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
		{
			CPoint pointTemp;
			pointTemp.x = point.x - m_ptOldPoint.x;
			pointTemp.y = point.y - m_ptOldPoint.y;

			pointTemp.x *= moveSpeed;// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
			pointTemp.y *= moveSpeed;// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.

			m_pCamera->MoveLocalX(pointTemp.x);
			m_pCamera->MoveLocalZ(pointTemp.y);		
			break;
		}
	}
	m_ptOldPoint = point;

	// 화면에 마우스가 가르키는 좌표 찍기

	D3DXVECTOR3 vPickRayDir(0.0f, 0.0f, 0.0f);
	D3DXVECTOR3 vPickRayOrig(0.0f, 0.0f, 0.0f);

	// 07-05-11 by shkim, 픽킹 영역 계산
	m_pBackground->CalculatePickPostion( &vPickRayOrig, &vPickRayDir );
	
	if(m_pBackground)
	{
		// 07-05-11 by shkim, 반복문 탈출후 값이 들어 갔다.
		int nX = 0, nZ = 0;
		D3DXVECTOR3 vVec( 0.0f, 0.0f, 0.0f );
		BOOL bNearLengthCheck = m_pBackground->NearPickCheck( vPickRayOrig, vPickRayDir );

		if( bNearLengthCheck == TRUE ) // 07-05-11 by shkim, 반복문 탈출후 값이 들어 갔다.
		{
			m_pBackground->PickPos( &vVec ); // 07-05-11 by shkim, 픽킹의 현재 위치를 알아 온다.

			char chTmp[256];
			sprintf(chTmp, " PickPos 위 => [X:%.2f], [Y:%.2f], [Z:%.2f] \n", vVec.x, vVec.y, vVec.z );

			DBGOUT(" %s \n", chTmp);

			nX = (int)( vVec.x/40.0f );
			nZ = (int)( vVec.z/40.0f );
			
			sprintf( m_strDump, "X:%d, Z:%d, H:%.0f, W:%d",
					 nX, nZ, vVec.y,
					 m_pBackground->m_pTileInfo[nX * m_pBackground->m_sYSize + nZ].waterType );
		}
	}

	

	CFormView::OnMouseMove(nFlags, point);
}

void CMapEditorView::OnRButtonDown(UINT nFlags, CPoint point) 
{
	D3DXVECTOR3 vPickRayDir;
	D3DXVECTOR3 vPickRayOrig;

	m_pBackground->CalculatePickPostion( &vPickRayOrig, &vPickRayDir );// 픽킹 영역 계산


	m_ptOldPoint = point;

	m_bRButtonCheck = TRUE;

	if(m_bCheckEventSet)
	{
		if(m_pBackground)
			m_pBackground->EventAction(&m_dlgEventSet,vPickRayOrig,vPickRayDir);
	}
	m_dlgEventSet.UpdateDataEvent();
	SetCapture();
	CFormView::OnRButtonDown(nFlags, point);
}

void CMapEditorView::OnRButtonUp(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	m_ptOldPoint.x = -999;
	m_ptOldPoint.y = -999;
	ReleaseCapture();
	CFormView::OnRButtonUp(nFlags, point);
}

BOOL CMapEditorView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) 
{
	// TODO: Add your message handler code here and/or call default
//	D3DXVECTOR3 vEye,vUp;
//	vUp = D3DXVECTOR3(0,1,0);
//	D3DXVec3Normalize(&vUp, &m_pCamera->GetUpVec());
//	D3DXVECTOR3 vOld = m_pCamera->GetEyePt();
//	vEye = vOld;
//	D3DXVECTOR3 vDirect = m_pCamera->GetViewDir();
//	D3DXVec3Normalize(&vDirect, &vDirect);
//	zDelta /= WHEEL_DELTA/24;
//	vEye -= (vDirect * zDelta);
//	if(vEye.y > 5000.0f && vOld.y < vEye.y)
//	{
//		vEye = vOld;
//	}
//	if(vEye.y < -1000.0f && vOld.y > vEye.y)
//	{
//		vEye = vOld;
//	}
//	m_pCamera->SetViewParams(vEye,vEye+vDirect,vUp);
	// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
	float moveSpeed = 1.0f;
	if((GetAsyncKeyState(VK_LCONTROL) & 0x8000) > 0)
	{
		moveSpeed = 0.1f;
	}
	// end by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
	if(zDelta > 0)
	{
		m_pCamera->SetCamMove(300.0f*moveSpeed);// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.	
	}
	else
	{
		m_pCamera->SetCamMove(-300.0f*moveSpeed);// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.	
	}
	
	return CFormView::OnMouseWheel(nFlags, zDelta, pt);
}

void CMapEditorView::CheckSupprotLight(D3DXVECTOR3 vOrig,D3DXVECTOR3 vDir)
{
//	int tempX,tempZ;
	D3DXVECTOR3 vLookat;
	D3DXVec3Normalize(&vLookat,&m_pCamera->GetViewDir());
	vLookat = m_pCamera->GetEyePt() + 32*40.0f*vLookat;
	int xi = (int)(vLookat.x/40.0f);
	int zi = (int)(vLookat.z/40.0f);

	for(int i=xi-32;i<xi+32;i++)
	{
		for(int j=zi-32;j<zi+32;j++)
		{
			FLOAT fBary1, fBary2;
			FLOAT fDist;
			D3DXVECTOR3 v,v2;
			if(i >= 0 && i < m_pBackground->m_sXSize && j >= 0 && j < m_pBackground->m_sYSize)
			{
				if(m_pBackground->IntersectTriangle(vOrig,vDir,m_pBackground->m_pTileVertexArray[i*(m_pBackground->m_sYSize+1)+j].pos,
					m_pBackground->m_pTileVertexArray[i*(m_pBackground->m_sYSize+1)+(j+1)].pos,m_pBackground->m_pTileVertexArray[(i+1)*(m_pBackground->m_sYSize+1)+(j+1)].pos,
					&fDist, &fBary1, &fBary2 ))
				{
					v = vOrig + vDir*fDist;
					SetLight(v);
					return;
				}
				if(m_pBackground->IntersectTriangle(vOrig,vDir,m_pBackground->m_pTileVertexArray[i*(m_pBackground->m_sYSize+1)+j].pos,
					m_pBackground->m_pTileVertexArray[(i+1)*(m_pBackground->m_sYSize+1)+(j+1)].pos,m_pBackground->m_pTileVertexArray[(i+1)*(m_pBackground->m_sYSize+1)+j].pos,
					&fDist, &fBary1, &fBary2 ))
				{
					v = vOrig + vDir*fDist;
					SetLight(v);
					return;
				}
			}
		}
	}
}

void CMapEditorView::SetLightAll()
{
	int cont = USED_LIGHT_NUM;
	list<D3DLIGHT8*>::iterator it = m_listLightInfo.begin();
	while(it != m_listLightInfo.end())
	{
		D3DLIGHT8 light;
		memcpy(&light,(*it),sizeof(D3DLIGHT8));
		g_pD3dDev->SetLight( cont, &light );
		g_pD3dDev->LightEnable( cont, TRUE );
		cont++;
		it++;
	}
	while(cont < 8)
	{
		g_pD3dDev->LightEnable( cont, FALSE );
		cont++;
	}
}

void CMapEditorView::SetLight(D3DXVECTOR3 vPos)
{
	if(m_nMaxLightNum - USED_LIGHT_NUM > m_dlgLightList.m_listLight.GetCount())
	{
/*		CLightSetDetailDlg *pDlg = new CLightSetDetailDlg();
		pDlg->m_light.Position = vPos;
		pDlg->m_fLightPosX = vPos.x;
		pDlg->m_fLightPosY = vPos.y;
		pDlg->m_fLightPosZ = vPos.z;

		UpdateData(FALSE);
		if(pDlg->DoModal()==IDOK)
		{
			m_listLightInfo.push_back(pDlg->m_light);
			char buf[256];
			sprintf(buf,"라이트 [%d] 번째",(++m_nUseLightNum - USED_LIGHT_NUM));
			m_dlgLightList.m_listLight.AddString(buf);
			SetLightAll();
//			UpdateData();
		}
		delete pDlg;
*/
//		CLightSetDetailDlg *pDlg = new CLightSetDetailDlg();
		m_dlgLightSetDetail.m_light.Position = vPos;
		m_dlgLightSetDetail.m_fLightPosX = vPos.x;
		m_dlgLightSetDetail.m_fLightPosY = vPos.y;
		m_dlgLightSetDetail.m_fLightPosZ = vPos.z;

		UpdateData(FALSE);
		D3DLIGHT8 *light = new D3DLIGHT8;
		memcpy( light, &(m_dlgLightSetDetail.m_light), sizeof( D3DLIGHT8 ) );
		m_pLight = light;
		m_listLightInfo.push_back(light);
		char buf[256];
		sprintf(buf,"Library updated [%d] first",(++m_nUseLightNum - USED_LIGHT_NUM));
		m_dlgLightList.m_listLight.AddString(buf);

//		if(pDlg->DoModal()==IDOK)
//		{
//			m_listLightInfo.push_back(pDlg->m_light);
//			char buf[256];
//			sprintf(buf,"라이트 [%d] 번째",(++m_nUseLightNum - USED_LIGHT_NUM));
//			m_dlgLightList.m_listLight.AddString(buf);
//			SetLightAll();
//			UpdateData();
//		}
//		m_pLight = NULL;

//		delete pDlg;
	
	}
	else
		AfxMessageBox("The library has exceeded the number of available updates.");
}

void CMapEditorView::CheckSetEffect(D3DXVECTOR3 vOrig,D3DXVECTOR3 vDir)
{
//	int tempX,tempZ;
	D3DXVECTOR3 vLookat;
	D3DXVec3Normalize(&vLookat,&m_pCamera->GetViewDir());
	vLookat = m_pCamera->GetEyePt() + 32*40.0f*vLookat;
	int xi = (int)(vLookat.x/40.0f);
	int zi = (int)(vLookat.z/40.0f);

	for(int i=xi-32;i<xi+32;i++)
	{
		for(int j=zi-32;j<zi+32;j++)
		{
			FLOAT fBary1, fBary2;
			FLOAT fDist;
			D3DXVECTOR3 v,v2;
			if(i >= 0 && i < m_pBackground->m_sXSize && j >= 0 && j < m_pBackground->m_sYSize)
			{
				if(m_pBackground->IntersectTriangle(vOrig,vDir,m_pBackground->m_pTileVertexArray[i*(m_pBackground->m_sYSize+1)+j].pos,
					m_pBackground->m_pTileVertexArray[i*(m_pBackground->m_sYSize+1)+(j+1)].pos,m_pBackground->m_pTileVertexArray[(i+1)*(m_pBackground->m_sYSize+1)+(j+1)].pos,
					&fDist, &fBary1, &fBary2 ))
				{
					v = vOrig + vDir*fDist;
					SetEffect(v);
					return;
				}
				if(m_pBackground->IntersectTriangle(vOrig,vDir,m_pBackground->m_pTileVertexArray[i*(m_pBackground->m_sYSize+1)+j].pos,
					m_pBackground->m_pTileVertexArray[(i+1)*(m_pBackground->m_sYSize+1)+(j+1)].pos,m_pBackground->m_pTileVertexArray[(i+1)*(m_pBackground->m_sYSize+1)+j].pos,
					&fDist, &fBary1, &fBary2 ))
				{
					v = vOrig + vDir*fDist;
					SetEffect(v);
					return;
				}
			}
		}
	}
}

void CMapEditorView::SetEffect(D3DXVECTOR3 vPos)
{
	CEffectSetDetailDlg *pDlg = new CEffectSetDetailDlg();
	pDlg->m_fPosX = vPos.x;
	pDlg->m_fPosY = vPos.y;
	pDlg->m_fPosZ = vPos.z;
	if(pDlg->DoModal()==IDOK)
	{
		if(strlen(pDlg->m_strEffectName))
		{
			EFFECTINFO effInfo;
			wsprintf(effInfo.strEffectName,"%s",pDlg->m_strEffectName);
			effInfo.nType = pDlg->m_nEffectType;
			effInfo.bRegion = pDlg->m_bRegion;
			effInfo.bLoop = pDlg->m_bLoop;
			effInfo.fReTime = pDlg->m_fReTime;
			effInfo.fCheckTime = pDlg->m_fReTime;
			effInfo.vPos.x = pDlg->m_fPosX;
			effInfo.vPos.y = pDlg->m_fPosY;
			effInfo.vPos.z = pDlg->m_fPosZ;

			m_listEffectInfo.push_back(effInfo);
			m_dlgEffect.m_listEffect.AddString(effInfo.strEffectName);
		}
	}
	delete pDlg;
}

void CMapEditorView::OnCheckLine() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnRadioCommand() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 0;
	UpdateData(TRUE);
	
}

void CMapEditorView::OnRadioDown() 
{
	// TODO: Add your control notification handler code here

//	m_nUpdown = -1;

//  	if( m_bCtrl )
//  	{
//  		// 07-04-26 shkim, Up 으로 바뀐다.
// 		m_nUpdown = TERRAIN_UP;
// 		UpdateData(FALSE);
// 		UpdateData(TRUE);
// 
// 		return;
//	}

	UpdateData(TRUE);
	
}

void CMapEditorView::OnRadioUp() 
{
// TODO: Add your control notification handler code here

//	m_nUpdown = 1;

//  	if( m_bCtrl )
//  	{
//  		// 07-04-26 shkim, down 으로 바뀐다.
// 		m_nUpdown = TERRAIN_DOWN;
// 		UpdateData(FALSE);
// 		UpdateData(TRUE);
// 		return;
//	}

	UpdateData(TRUE);
	
}

void CMapEditorView::OnRadioHeight() 
{
	m_nCommand = 1;
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	
}

void CMapEditorView::OnRadioFlat() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 2;
	UpdateData(TRUE);
	
}

//	CheckRadioButton( IDC_RADIO_COMMAND, IDC_RADIO_SMOOTH, IDC_RADIO_SMOOTH );
void CMapEditorView::OnButtonSmooth() 
{
	// 07-05-15 by shkim, 다듬기
	m_nCommand = 10;
	UpdateData(FALSE);
}

void CMapEditorView::OnSelchangeListTile() 
{
	int num = m_ctrlTileList.GetCurSel();
	m_nTileTextype = num;
	// TODO: Add your control notification handler code here
	
}

void CMapEditorView::OnButtonCameramoveLeft() 
{
	// TODO: Add your control notification handler code here
	if(m_bCamDirType < 2)
		m_bCamDirType++;
	else
		m_bCamDirType = 0;
	D3DXVECTOR3 vDir,vUp;
	D3DXMATRIX matTemp;
	vUp = D3DXVECTOR3(1,0,0);
	vDir = D3DXVECTOR3(0,-1,0);
	D3DXMatrixRotationAxis( &matTemp, &vDir, (3.14f/2.0f)*m_bCamDirType);
	D3DXVec3TransformCoord( &vUp, &vUp, &matTemp );
	m_pCamera->SetViewParams(m_pCamera->GetEyePt(),m_pCamera->GetEyePt() + vDir,vUp);
}

#define ACOS(fVal)									(((fVal) > 1.0f) ? acos(1.0f) : acos(fVal))
void CMapEditorView::OnButtonCameramoveRight() 
{
	// TODO: Add your control notification handler code here
//	if(m_bCamDirType > 1)
//		m_bCamDirType--;
//	else
//		m_bCamDirType = 3;
//	D3DXVECTOR3 vDir,vUp;
//	D3DXMATRIX matTemp;
//	vUp = D3DXVECTOR3(1,0,0);
//	vDir = D3DXVECTOR3(0,-1,0);
//	D3DXMatrixRotationAxis( &matTemp, &vDir, (3.14f/2.0f)*m_bCamDirType);
//	D3DXVec3TransformCoord( &vUp, &vUp, &matTemp );
//	m_pCamera->SetViewParams(m_pCamera->GetEyePt(),m_pCamera->GetEyePt() + vDir,vUp);
	D3DXVECTOR3 vEye, vLookAt, vUp;
	D3DXVECTOR3 vtNewDst, vCross;
	D3DXMATRIXA16 matRot;
	float fAngle = m_pCamera->GetTotalAngelX();
	double dRadian = 0.0f;

	vEye = m_pCamera->GetEyePt();
	vLookAt = m_pCamera->GetLookatPt();
	vUp = m_pCamera->GetUpVec();
	
	// 각도 수정
	fAngle = (-0.4f - fAngle) / 0.004f;
	m_pCamera->RotationLocal3X(fAngle);

	// 내 위치 수정
	vtNewDst = vEye - vLookAt;
	vtNewDst.y = 0.0f;

	D3DXVec3Normalize(&vtNewDst, &vtNewDst);
	D3DXVec3Cross(&vCross, &D3DXVECTOR3(0,0,1), &vtNewDst);
	float dot = D3DXVec3Dot(&D3DXVECTOR3(0,0,1), &vtNewDst);
	if(1.0f > dot)
	{
		if(0.0f < vCross.y)
		{
			//오른쪽 회전  
			dRadian -= ACOS(dot);
		}
		else	
		{
			// 왼쪽 회전
			dRadian += ACOS(dot);
		}
	
		m_pCamera->RotationLocal3Y(dRadian / 0.004f);
	}
//	vEye.x = 0.0f;
//	m_pCamera->SetViewParams(vEye, vLookAt, vUp);

}

void CMapEditorView::OnChangeEditUpdownValue() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
}

void CMapEditorView::OnChangeEditFlatSize() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
}

void CMapEditorView::OnSelchangeComboContorlSize() 
{
	// 07-05-13 by shkim, 기본 브러쉬 사이즈를 콤보박스에서 수정될때 마다 적용 된다.
	int DefaultSize = 2;
	m_nControlSizeType = m_comboControlSizeType.GetCurSel();
	m_nBrushSize = m_nControlSizeType + DefaultSize;
//	m_nBrushSize = ( m_nControlSizeType + 1 ) * DefaultSize; // 나중에 써

}

void CMapEditorView::OnSelchangeComboObjectSelect() 
{
	// TODO: Add your control notification handler code here
	m_dwObjectType = m_comboObjectSelect.GetCurSel();	
//	CString str;
//	m_comboObjectSelect.GetLBText(m_dwObjectType,str);
//	m_nObjectNum = atoi(str);
}

void CMapEditorView::OnRadioObject() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 3;	
	UpdateData();
}

void CMapEditorView::OnChangeEditObjectCreatecont() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	if(m_editObjectNumber>100)
		MessageBox("Please input a number less than or equal to 100.");
}

void CMapEditorView::OnChangeEditObjectDelete() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	if(m_editObjectDelete>100)
		MessageBox("Please input a number from 1 to 100.");
	
}

void CMapEditorView::OnRadioObjectDelete() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 4;	
	UpdateData();
	
}

void CMapEditorView::OnRadioWater() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 5;	
	UpdateData();
	
}
/*
void CMapEditorView::OnButtonNewobject() 
{
	// TODO: Add your control notification handler code here
	CInsertObjectDlg dlg;
	if(dlg.DoModal() == IDOK)
	{
	}
	
}
*/
void CMapEditorView::CheckMove()
{
	// 07-05-09 by shkim, 주석만 추가.
	// 이 함수가 하는 일은 매프레임시 화면에 보여 주는 지형이 32*32 인지를
	// 체크 해 주고 지형을 마우스로 드레그 해서 움직이면 32* 32 만큼 그려 준다.
	
	D3DXVECTOR3 vLookat,vVel;
	D3DXVec3Normalize( &vVel, &m_pCamera->GetViewDir() );
//	vLookat = m_pCamera->GetEyePt() + 16*40.0f*vVel;
	vLookat = m_pCamera->GetLookatPt();
	SPRITEVERTEX* v;
	int xi,zi,i,j;
	xi = (int)(vLookat.x/40.0f);
	zi = (int)(vLookat.z/40.0f);
	if(m_pBackground)
	{
		if(!(m_nOldLookX==xi && m_nOldLookZ==zi))
		{
			m_nOldLookX = xi;
			m_nOldLookZ = zi;
/*			for(i=0;i<32;i++)
			{
				for(j=0;j<32;j++)
				{
					if(m_nOldLookX-16+i >= 0 && m_nOldLookX-16+i+1 <= m_pBackground->m_sXSize && m_nOldLookZ-16+j >= 0 && m_nOldLookZ-16+j+1 <= m_pBackground->m_sYSize)
					{
						m_pBackground->m_pVBRender[i*32+j]->Lock( 0, 0, (BYTE**)&v, 0 );
						v[0].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j)].pos;
						v[0].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j)].nor;
						v[0].tu = 0.0f;v[0].tv = 0.0f;
						v[1].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j+1)].pos;
						v[1].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j+1)].nor;
						v[1].tu = 0.0f;v[1].tv = 1.0f;
						v[2].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j+1)].pos;
						v[2].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j+1)].nor;
						v[2].tu = 1.0f;v[2].tv = 1.0f;
						v[3].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j)].pos;
						v[3].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j)].nor;
						v[3].tu = 0.0f;v[3].tv = 0.0f;
						v[4].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j+1)].pos;
						v[4].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j+1)].nor;
						v[4].tu = 1.0f;v[4].tv = 1.0f;
						v[5].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j)].pos;
						v[5].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-16+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-16+j)].nor;
						v[5].tu = 1.0f;v[5].tv = 0.0f;
						m_pBackground->m_pVBRender[i*32+j]->Unlock();
					}
				}
			}
*/			for(i=0;i<64;i++)
			{
				for(j=0;j<64;j++)
				{
					if(m_nOldLookX-32+i >= 0 && m_nOldLookX-32+i+1 <= m_pBackground->m_sXSize && m_nOldLookZ-32+j >= 0 && m_nOldLookZ-32+j+1 <= m_pBackground->m_sYSize)
					{
						m_pBackground->m_pVBRender[i*64+j]->Lock( 0, 0, (BYTE**)&v, 0 );

						v[0].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j)].pos;
						v[0].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j)].nor;
						v[0].tu = 0.0f;
						v[0].tv = 0.0f;

						v[1].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j+1)].pos;
						v[1].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j+1)].nor;
						v[1].tu = 0.0f;
						v[1].tv = 1.0f;

						v[2].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j+1)].pos;
						v[2].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j+1)].nor;
						v[2].tu = 1.0f;
						v[2].tv = 1.0f;

						v[3].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j)].pos;
						v[3].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j)].nor;
						v[3].tu = 0.0f;
						v[3].tv = 0.0f;

						v[4].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j+1)].pos;
						v[4].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j+1)].nor;
						v[4].tu = 1.0f;
						v[4].tv = 1.0f;

						v[5].p = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j)].pos;
						v[5].n = m_pBackground->m_pTileVertexArray[(m_nOldLookX-32+i+1)*(m_pBackground->m_sYSize+1)+(m_nOldLookZ-32+j)].nor;
						v[5].tu = 1.0f;
						v[5].tv = 0.0f;

						if(m_pBackground->m_pBackTexture)
						{
							v[0].tv = 1.0f - ((float)(m_nOldLookZ-32+j))/((float)m_pBackground->m_sYSize);
							v[0].tu = ((float)(m_nOldLookX-32+i))/((float)m_pBackground->m_sXSize);
							v[1].tv = 1.0f - ((float)(m_nOldLookZ-32+j+1))/((float)m_pBackground->m_sYSize);
							v[1].tu = ((float)(m_nOldLookX-32+i))/((float)m_pBackground->m_sXSize);
							v[2].tv = 1.0f - ((float)(m_nOldLookZ-32+j+1))/((float)m_pBackground->m_sYSize);
							v[2].tu = ((float)(m_nOldLookX-32+i+1))/((float)m_pBackground->m_sXSize);
							v[3].tv = 1.0f - ((float)(m_nOldLookZ-32+j))/((float)m_pBackground->m_sYSize);
							v[3].tu = ((float)(m_nOldLookX-32+i))/((float)m_pBackground->m_sXSize);
							v[4].tv = 1.0f - ((float)(m_nOldLookZ-32+j+1))/((float)m_pBackground->m_sYSize);
							v[4].tu = ((float)(m_nOldLookX-32+i+1))/((float)m_pBackground->m_sXSize);
							v[5].tv = 1.0f - ((float)(m_nOldLookZ-32+j))/((float)m_pBackground->m_sYSize);
							v[5].tu = ((float)(m_nOldLookX-32+i+1))/((float)m_pBackground->m_sXSize);

						}

						m_pBackground->m_pVBRender[i*64+j]->Unlock();
					}
				}
			}
		}
	}
}


void CMapEditorView::OnChangeEditWater() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	if(m_editWater>200)
		MessageBox("Please enter a number less than or equal to 200.");

}

void CMapEditorView::OnReleasedcaptureSliderObjectDir(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	D3DXMATRIX matTemp;
	D3DXVECTOR3 vUp = D3DXVECTOR3(0,1,0);
	D3DXVECTOR3 vVel = D3DXVECTOR3(0,0,1);
	int nPos = m_sliderObjectDir.GetPos();
	D3DXMatrixRotationAxis( &matTemp, &vUp, 3.14f*2.0f*nPos/1000.0f);
	D3DXVec3TransformCoord( &m_vObjectVel, &vVel, &matTemp );
	UpdateData(FALSE);
	
	*pResult = 0;
}

int CMapEditorView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CFormView::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	// TODO: Add your specialized creation code here
	
	return 0;
}

BOOL CMapEditorView::PreTranslateMessage(MSG* pMsg) 
{
	// TODO: Add your specialized code here and/or call the base class

//	MsgProc( pMsg->hwnd, pMsg->message, pMsg->wParam, pMsg->lParam );
	switch(pMsg->message)
	{
	case WM_KEYDOWN:
		{
			// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
			float moveSpeed = 1.0f;
			if((GetAsyncKeyState(VK_LCONTROL) & 0x8000) > 0)
			{
				moveSpeed = 0.1f;
			}
			// end by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.

			// 11-03-21 by jhAhn, Del키 사용 가능
			if (pMsg->wParam == 46)
			{
				m_dlgAllList.OnKeyButtonDelete();
			}
			//end 11-03-21 by jhAhn, Del키 사용 가능
			if(pMsg->wParam == 107)// || pMsg->wParam == 187)//'+'
			{// 위
				m_pCamera->SetLookAtY(80.0f*moveSpeed);// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
			}
			else if(pMsg->wParam == 109)// || pMsg->wParam == 189)//'-'
			{// 아래
				m_pCamera->SetLookAtY(-80.0f*moveSpeed);// by dhkwon 100913 CTRL키 누르면 카메라 이동속도 1/10로 느려짐.
			}
			// 07-05-04 by shkim, 지형 범위 조절
			if( pMsg->wParam == 219 )// '['
			{
				KeyProcess( pMsg->wParam );
			}

			if( pMsg->wParam == 221 )// ']'
			{
				KeyProcess( pMsg->wParam );
			}			

			if( pMsg->wParam == 17 ) // Ctrl
			{
				m_bCtrl = TRUE;
				KeyProcess( pMsg->wParam );			
			}
			// 07-05-04 by shkim, 지형 범위 조절 추가 끝

			if( pMsg->wParam == 32 ) // 07-05-04 by shkim, space bar
			{
				m_bCheckBrush = !m_bCheckBrush;

				// 07-05-04 by shkim, 픽킹 위치와 브러쉬를 보여주기를 체크
				m_pBackground->BrushCheck( m_bCheckBrush );
			}

//			if(m_nCommand == 6)
//			{
//				if(pMsg->wParam == 87)//38)'W'
//				{// 위
//					m_pCamera->MoveLocalZ(80);
//					return TRUE;
//				}
//				else if(pMsg->wParam == 83)//'S')//40)
//				{// 아래
//					m_pCamera->MoveLocalZ(-80);
//					return TRUE;
//				}
//				else if(pMsg->wParam == 65)//'A'
//				{
//					m_pCamera->MoveLocalX(80);
//					return TRUE;
//				}
//				else if(pMsg->wParam == 68)//'D'
//				{
//					m_pCamera->MoveLocalX(-80);
//					return TRUE;
//				}
//			}
//			else
			{
				if(m_bCheckObject && m_dlgObjectSet && m_dlgObjectSet.m_checkMoveObject && m_dlgObjectSet.m_pObject)
				{
					D3DXVECTOR3 vSide, vVel;
					vSide = m_pCamera->GetCross();
					vSide.y = 0;
					D3DXVec3Normalize(&vSide,&vSide);
					vVel = D3DXVECTOR3(0,1,0);
					D3DXVec3Cross(&vVel,&vVel,&vSide);
					vVel.y = 0.0f;
					D3DXVec3Normalize(&vVel,&vVel);
					if(pMsg->wParam == 37)
					{// 좌
						m_dlgObjectSet.m_pObject->m_vPos += m_dlgObjectSet.m_editMoveObject*vSide;
						m_dlgObjectSet.ObjectSelect(m_dlgObjectSet.m_pObject);
						return TRUE;
					}
					else if(pMsg->wParam == 38)
					{// 위
						m_dlgObjectSet.m_pObject->m_vPos += m_dlgObjectSet.m_editMoveObject*vVel;
						m_dlgObjectSet.ObjectSelect(m_dlgObjectSet.m_pObject);
						return TRUE;
					}
					else if(pMsg->wParam == 39)
					{// 우
						m_dlgObjectSet.m_pObject->m_vPos -= m_dlgObjectSet.m_editMoveObject*vSide;
						m_dlgObjectSet.ObjectSelect(m_dlgObjectSet.m_pObject);
						return TRUE;
					}
					else if(pMsg->wParam == 40)
					{// 아래
						m_dlgObjectSet.m_pObject->m_vPos -= m_dlgObjectSet.m_editMoveObject*vVel;
						m_dlgObjectSet.ObjectSelect(m_dlgObjectSet.m_pObject);
						return TRUE;
					}
					else if(pMsg->wParam == 33)
					{// 우
						m_dlgObjectSet.m_pObject->m_vPos.y += m_dlgObjectSet.m_editMoveObject;
						m_dlgObjectSet.ObjectSelect(m_dlgObjectSet.m_pObject);
						return TRUE;
					}
					else if(pMsg->wParam == 34)
					{// 아래
						m_dlgObjectSet.m_pObject->m_vPos.y -= m_dlgObjectSet.m_editMoveObject;
						m_dlgObjectSet.ObjectSelect(m_dlgObjectSet.m_pObject);
						return TRUE;
					}
				}
			}
		} // KEYDOWN end
		break;

		case WM_KEYUP:
		{
			if( pMsg->wParam == 17 )
			{
				m_bCtrl = FALSE;
			//	KeyProcess( pMsg->wParam ); // 07-05-04 by shkim, ctrl 올라감
			}

//			if( GetKeyState( VK_CONTROL ) > 0 )
//			{
//				m_bCtrl = FALSE;

//				OutputDebugString( " 컨트롤 키가 올라 갔다. \n" );
//			}
		}
		break;
	}

	return CFormView::PreTranslateMessage(pMsg);
}

void CMapEditorView::KeyProcess( int nKey )
{
	// 07-05-03 by shkim, nkey로 키 메시지를 받아서 각각의 기능을 한다.
	
	int nDefultSize = 2;
	int nTotal = m_comboControlSizeType.GetCount();
	m_nComboCtrlSizeType = m_comboControlSizeType.GetCurSel();

	switch( nKey )
	{
		case CTRL:
		{
		}
		break;

		case GREATE_GARO_LEFT:
		{
			if( m_nComboCtrlSizeType == 0 )
			{
				m_nComboCtrlSizeType = 0;
				m_comboControlSizeType.SetCurSel( m_nComboCtrlSizeType );
				m_nControlSizeType = m_nComboCtrlSizeType; // Terrain용
			//	m_nBrushSize = (m_nControlSizeType + 1) * nDefultSize; // 기본 브러쉬 값
				m_nBrushSize = nDefultSize; // 기본 브러쉬 값
				return;
			}

			m_nComboCtrlSizeType--;
			m_nBrushSize--;
			m_comboControlSizeType.SetCurSel( m_nComboCtrlSizeType );
			m_nControlSizeType = m_nComboCtrlSizeType; // Terrain용	
		}
		break;

		case GREATE_GARO_RIGHT:
		{
			if( m_nComboCtrlSizeType == (nTotal - 1) )
			{
				m_nComboCtrlSizeType = nTotal - 1;
				m_comboControlSizeType.SetCurSel( m_nComboCtrlSizeType );
				m_nControlSizeType = m_nComboCtrlSizeType; // Terrain용
				m_nBrushSize = 4; // 최대 브러쉬 값
				return;
			}

			m_nComboCtrlSizeType++;
			m_nBrushSize++;
			m_comboControlSizeType.SetCurSel( m_nComboCtrlSizeType );
			m_nControlSizeType = m_nComboCtrlSizeType; // Terrain용
		}
		break;
	}
}

BOOL CMapEditorView::DestroyWindow() 
{
	// TODO: Add your specialized code here and/or call the base class
	

	return CFormView::DestroyWindow();
}

void CMapEditorView::OnDestroy() 
{
	if(m_pWorkspace)
	{
		int re = AfxMessageBox( "Do you want to save the entire final data?",MB_YESNO);
		if( re == IDYES )
		{
			OnSaveProject();
		}
	}
	CFormView::OnDestroy();
	
	Cleanup3DEnvironment();
	DestroyMenu( ::GetMenu(GetSafeHwnd()) );
	
	// TODO: Add your message handler code here
}

void CMapEditorView::OnEventSet() 
{
	// TODO: Add your command handler code here
	m_bCheckEventSet = !m_bCheckEventSet;
	if(m_bCheckEventSet)
	 	m_dlgEventSet.ShowWindow(SW_SHOW);
	else
		m_dlgEventSet.ShowWindow(SW_HIDE);
}

void CMapEditorView::OnUpdateEventSet(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
}

void CMapEditorView::OnWorkspaceView() 
{
	// TODO: Add your command handler code here
	m_bCheckWorkspaceView = !m_bCheckWorkspaceView;
	if(m_bCheckWorkspaceView)
	{
		m_dlgWorkspace.ShowWindow(SW_SHOW);
		m_dlgWorkspace.UpdateWorkspace();
	}
	else
	{
		m_dlgWorkspace.ShowWindow(SW_HIDE);
	}
	
}

void CMapEditorView::OnUpdateWorkspaceView(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
	
}

void CMapEditorView::OnNewWorkspace() 
{
	// TODO: Add your command handler code here
	if(m_pWorkspace)
	{
		int re = AfxMessageBox( "Save changes made to this workspace?",MB_YESNOCANCEL);
		if( re == IDYES )
		{
			if(m_pBackground)
			{
				// Project를 저장한다.
				SaveProject();
				// Map File을 저장한다.
				SaveMapFile();

			}
			// Workspace 저장한다.
			SaveWorkspace();
		}
		else if(re == IDNO)
			;//지나간다.
		else if(re == IDCANCEL)
			return;
		SAFE_DELETE( m_pWorkspace );
	}
	if(m_pBackground)
	{
		m_pBackground->InvalidateDeviceObjects();
		m_pBackground->DeleteDeviceObjects();
		SAFE_DELETE( m_pBackground );
		// Effect(App의) 을 지운다.
		CAtumNode* pEffect = (CAtumNode *)m_pEffectList->m_pChild;
		while(pEffect)
		{
			pEffect->m_bUsing = FALSE;
			pEffect = pEffect->m_pNext;
		}
		m_pEffectList->Tick();
		m_listEffectInfo.clear();
		int i;
		int n = m_dlgEffect.m_listEffect.GetCount();
		for(i=0;i < n;i++)
		   m_dlgEffect.m_listEffect.DeleteString( n-i-1 );
		
		list<D3DLIGHT8*>::iterator itLight = m_listLightInfo.begin();
		while( itLight != m_listLightInfo.end() )
		{
			SAFE_DELETE( (*itLight) );
			itLight++;
		}
		m_listLightInfo.clear();
		m_nUseLightNum = USED_LIGHT_NUM;
		n = m_dlgLightList.m_listLight.GetCount();
		for(i=0;i < n;i++)
		   m_dlgLightList.m_listLight.DeleteString( n-i-1 );
	}
	if(m_pMiniMap)
	{
		m_pMiniMap->InvalidateDeviceObjects();
		m_pMiniMap->DeleteDeviceObjects();
		SAFE_DELETE( m_pMiniMap );
	}

	CNewWorkspace dlg;
	if(dlg.DoModal()==IDOK && !dlg.m_strWorkspaceName.IsEmpty())
	{
		m_pWorkspace = new WORKSPACE;
		strcpy(m_pWorkspace->workspaceName,(LPCTSTR)dlg.m_strWorkspaceName);
		m_pWorkspace->numberOfProject = 0;
		m_listProjectInfo.clear();
		_chdir(m_strCurrentDir);
		_mkdir(m_pWorkspace->workspaceName);
		m_pBackground = NULL;
	}
	if(m_bCheckWorkspaceView)
		m_dlgWorkspace.UpdateWorkspace();
}

void CMapEditorView::OnNewProject() 
{
	// TODO: Add your command handler code here
	if(m_pBackground)
	{
		int re = AfxMessageBox( "Save changes made to this project?",MB_YESNOCANCEL);
		if( re == IDYES )
		{
			// Project를 저장한다.
			SaveProject();
			// Map File을 저장한다.
			SaveMapFile();
			// Worksapce를 저장한다.
			SaveWorkspace();
		}
		else if(re == IDNO)
			;//지나간다.
		else if(re == IDCANCEL)
			return;
		m_pBackground->InvalidateDeviceObjects();
		m_pBackground->DeleteDeviceObjects();
		SAFE_DELETE( m_pBackground );
		// Effect(App의) 을 지운다.
		CAtumNode* pEffect = (CAtumNode *)m_pEffectList->m_pChild;
		while(pEffect)
		{
			pEffect->m_bUsing = FALSE;
			pEffect = pEffect->m_pNext;
		}
		m_pEffectList->Tick();
		m_listEffectInfo.clear();
		int i;
		int n = m_dlgEffect.m_listEffect.GetCount();
		for(i=0;i < n;i++)
		   m_dlgEffect.m_listEffect.DeleteString( n-i-1 );

		list<D3DLIGHT8*>::iterator itLight = m_listLightInfo.begin();
		while( itLight != m_listLightInfo.end() )
		{
			SAFE_DELETE( (*itLight) );
			itLight++;
		}
		m_listLightInfo.clear();
		m_nUseLightNum = USED_LIGHT_NUM;
		n = m_dlgLightList.m_listLight.GetCount();
		for(i=0;i < n;i++)
		   m_dlgLightList.m_listLight.DeleteString( n-i-1 );

		if(m_pMiniMap)
		{
			m_pMiniMap->InvalidateDeviceObjects();
			m_pMiniMap->DeleteDeviceObjects();
			SAFE_DELETE( m_pMiniMap );
		}
	}
	if(m_pWorkspace)
	{
		PROJECTINFO project;
		CNewProjectDlg dlg;
		if(dlg.DoModal()==IDOK && !dlg.m_editMapName.IsEmpty())
		{
			project.m_useTileSetIndex = dlg.m_editTileSetIndex;
			strcpy(project.m_strProjectName, (LPCTSTR)dlg.m_editMapName );
			strcpy(project.m_strFieldIP, (LPCTSTR)dlg.m_editFieldIP );
			project.m_sFieldPort = dlg.m_editFieldPort;
			project.m_sFieldPortUDP = dlg.m_editFieldPortUDP;
			strcpy(project.m_strNPCIP, (LPCTSTR)dlg.m_editNPCIP );
			project.m_sNPCPort = dlg.m_editNPCPort;
			project.m_sNPCPortUDP = dlg.m_editNPCPortUDP;
			project.m_sXSize = dlg.m_editXSize;
			project.m_sYSize = dlg.m_editYSize;
			project.m_fHeightMax = dlg.m_editHeightMax;
			project.m_fHeightMin = dlg.m_editHeightMin;
			project.m_fWaterHeight = dlg.m_editWaterHeight;
			project.m_fAmbientB1 = 1.0f;
			project.m_fAmbientG1 = 1.0f;
			project.m_fAmbientR1 = 1.0f;
			project.m_fDiffuseB1 = 1.0f;
			project.m_fDiffuseG1 = 1.0f;
			project.m_fDiffuseR1 = 1.0f;
			project.m_fAmbientB2 = 0.0f;
			project.m_fAmbientG2 = 0.0f;
			project.m_fAmbientR2 = 0.0f;
			project.m_fDiffuseB2 = 0.0f;
			project.m_fDiffuseG2 = 0.0f;
			project.m_fDiffuseR2 = 0.0f;
			m_dlgLightSet.SetData(project);
			// 디렉토리 생성
			_chdir(m_strCurrentDir);
			char strpath[256];
			wsprintf(strpath,".\\%s\\%s",m_pWorkspace->workspaceName,project.m_strProjectName);
			_mkdir(strpath);
			m_pBackground = new CBackground(project.m_sXSize,project.m_sYSize);
			memcpy( &m_pBackground->m_projectInfo, &project, sizeof(PROJECTINFO) );
			m_listProjectInfo.push_back(project);
			m_pWorkspace->numberOfProject++;

			m_pBackground->InitDeviceObjects();
			m_pBackground->RestoreDeviceObjects();
			InitMapData();

			POINT start,end;
			start.x = 0; start.y = 0;
			end.x = project.m_sXSize; end.y = project.m_sYSize; 
			m_pMiniMap = new CMiniMap(project.m_sXSize,project.m_sYSize);
			m_pMiniMap->Create( "minimap.tga",start,end);
			m_pMiniMap->SetRect(0,0,project.m_sXSize, project.m_sYSize);
			m_pMiniMap->InitDeviceObjects();
			m_pMiniMap->RestoreDeviceObjects();


			//////////////////////////////////////////////////////////////////////////////////////////////////////////////
			int i,j;
			m_dlgLightSet.SetData(m_pBackground->m_projectInfo);
					
					m_pBackground->m_pHeightMap = new float[m_pBackground->m_projectInfo.m_sXSize *  m_pBackground->m_projectInfo.m_sYSize];
					
					float fMin = m_pBackground->m_pTileVertexArray[0].pos.y;// ROAM  최대,최소 높이 계산 by dhkwon 2011.4.4
					float fMax = m_pBackground->m_pTileVertexArray[0].pos.y;
					
					for(i=0;i<m_pBackground->m_projectInfo.m_sXSize;i++)
					{
						for(int j=0;j<m_pBackground->m_projectInfo.m_sYSize;j++)
						{
							m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j] = m_pBackground->m_pTileVertexArray[j*(m_pBackground->m_projectInfo.m_sXSize+1)+i].pos.y;
							if(fMin > m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j] ) fMin = m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j];	// ROAM  최대,최소 높이 계산 by dhkwon 2011.4.4
							if(fMax < m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j] ) fMax = m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j];
						}	
					}
						
					float fMaxHeight = fMax - fMin;// ROAM  최대,최소 높이 계산 by dhkwon 2011.4.4
					Patch::m_fMaxHeight = fMaxHeight;
					Patch:: m_fMin = fMin;
					Patch:: m_fMax = fMax;									
					m_pBackground->m_pTerrain->Init(m_pBackground->m_pHeightMap, m_pBackground->m_projectInfo.m_fHeightMax, m_pBackground->m_projectInfo.m_sXSize, m_pBackground->m_projectInfo.m_sYSize);
					if(m_pBackground->m_pTerrain)
					{
						TriangleTreeNode::Init(MAX_TRIANGLE_NODES); 
						Patch::pvert=new CUSTOMVERTEX[WJ_VERTEXBUFFERSIZE];
						m_pBackground->m_pTerrain->Reset();
						//reset the triangle node pool
						TriangleTreeNode::Reset();	
					}
			//////////////////////////////////////////////////////////////////////////////////////////////////////////////
		}
		if(m_bCheckWorkspaceView)
			m_dlgWorkspace.UpdateWorkspace();
	}
	else
	{
		AfxMessageBox( "No workspace selected.",MB_OK);
	}
}

void CMapEditorView::OnOpenProjectSub(CString str) 
{
	if(m_pBackground)
	{
		int re = AfxMessageBox( "Save changes made to this project?",MB_YESNOCANCEL);

		if( re == IDYES )
		{
			// Project를 저장한다.
			SaveProject();
			// Map File을 저장한다.
			SaveMapFile();
			// Worksapce를 저장한다.
			SaveWorkspace();
		}
		else if(re == IDNO)
		{
			;//지나간다.
		}
		else if(re == IDCANCEL)
		{
			return;
	}
	}

	if(m_pWorkspace)
	{
		// 같은 이름의 Project가 현재 workspace에 존재할 경우 불러온다.
		list<PROJECTINFO>::iterator it = m_listProjectInfo.begin();

		int i = 0;
		for(i=0;i<m_pWorkspace->numberOfProject;i++)
		{
			CString strProject,strMapFile;
			PROJECTINFO project;

			//strProject
			CString tempstr = _T("");
			tempstr = (*it).m_strProjectName;

			if(0==strcmp((*it).m_strProjectName,str))
			{
				project = OpenProject(str);
				if(m_pBackground)
				{
					m_pBackground->InvalidateDeviceObjects();
					m_pBackground->DeleteDeviceObjects();

					SAFE_DELETE( m_pBackground );

					// Effect(App의) 을 지운다.
					CAtumNode* pEffect = (CAtumNode *)m_pEffectList->m_pChild;

					while(pEffect)
					{
						pEffect->m_bUsing = FALSE;
						pEffect = pEffect->m_pNext;
					}

					m_pEffectList->Tick();
					m_listEffectInfo.clear();

					int i = 0;
					int n = m_dlgEffect.m_listEffect.GetCount();

					for(i=0;i < n;i++)
					{
					   m_dlgEffect.m_listEffect.DeleteString( n-i-1 );
					}

					list<D3DLIGHT8*>::iterator itLight = m_listLightInfo.begin();

					while( itLight != m_listLightInfo.end() )
					{
						SAFE_DELETE( (*itLight) );
						itLight++;
					}

					m_listLightInfo.clear();
					m_nUseLightNum = USED_LIGHT_NUM;
					n = m_dlgLightList.m_listLight.GetCount();

					for(i=0;i < n;i++)
					{
					   m_dlgLightList.m_listLight.DeleteString( n-i-1 );
				}
				}

				if(m_pMiniMap)
				{
					m_pMiniMap->InvalidateDeviceObjects();
					m_pMiniMap->DeleteDeviceObjects();
					SAFE_DELETE( m_pMiniMap );
				}

				project.m_useTileSetIndex = (*it).m_useTileSetIndex;

				strcpy(project.m_strFieldIP,(*it).m_strFieldIP);

				project.m_sFieldPort = (*it).m_sFieldPort;
				project.m_sFieldPortUDP = (*it).m_sFieldPortUDP;

				strcpy(project.m_strNPCIP,(*it).m_strNPCIP);

				project.m_sNPCPort = (*it).m_sNPCPort;
				project.m_sNPCPort = (*it).m_sNPCPortUDP;

				project.m_sXSize = (*it).m_sXSize;
				project.m_sYSize = (*it).m_sYSize;

				project.m_fHeightMax = (*it).m_fHeightMax;
				project.m_fHeightMin = (*it).m_fHeightMin;

				project.m_fWaterHeight = (*it).m_fWaterHeight;

				
				

				m_pBackground = new CBackground(project.m_sXSize,project.m_sYSize);
				memcpy( &m_pBackground->m_projectInfo, &project, sizeof(PROJECTINFO) );

				m_pBackground->InitDeviceObjects();
				m_pBackground->RestoreDeviceObjects();

				InitMapData();

				POINT start,end;

				start.x = 0; start.y = 0;

				end.x = project.m_sXSize; end.y = project.m_sYSize; 

				m_pMiniMap = new CMiniMap(project.m_sXSize,project.m_sYSize);
				m_pMiniMap->Create( "minimap.tga",start,end);
				m_pMiniMap->SetRect(0,0,project.m_sXSize, project.m_sYSize);

				m_pMiniMap->InitDeviceObjects();
				m_pMiniMap->RestoreDeviceObjects();

				m_dlgObjectSet.m_pObject = NULL; // 07-05-02 by shkim, 버그로 죽는 현상 해결

				OpenMapData((*it).m_strProjectName);

				m_dlgLightSet.SetData(m_pBackground->m_projectInfo);

				m_pBackground->m_pHeightMap = new float[m_pBackground->m_projectInfo.m_sXSize *  m_pBackground->m_projectInfo.m_sYSize];
									//jhahn 문제 부분
									
				float fMin = m_pBackground->m_pTileVertexArray[0].pos.y;// ROAM  최대,최소 높이 계산 by dhkwon 2011.4.4
				float fMax = m_pBackground->m_pTileVertexArray[0].pos.y;
					
				for(i=0;i<m_pBackground->m_projectInfo.m_sXSize;i++)
					for(int j=0;j<m_pBackground->m_projectInfo.m_sYSize;j++)
					{
						m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j] = m_pBackground->m_pTileVertexArray[j*(m_pBackground->m_projectInfo.m_sXSize+1)+i].pos.y;
						if(fMin > m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j] ) fMin = m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j];	// ROAM  최대,최소 높이 계산 by dhkwon 2011.4.4
						if(fMax < m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j] ) fMax = m_pBackground->m_pHeightMap[i*m_pBackground->m_projectInfo.m_sXSize+j];
					}	
					
				float fMaxHeight = fMax - fMin;// ROAM  최대,최소 높이 계산 by dhkwon 2011.4.4
				Patch::m_fMaxHeight = fMaxHeight;
				Patch:: m_fMin = fMin;
				Patch:: m_fMax = fMax;
				m_pBackground->m_pTerrain->Init(m_pBackground->m_pHeightMap, m_pBackground->m_projectInfo.m_fHeightMax, m_pBackground->m_projectInfo.m_sXSize, m_pBackground->m_projectInfo.m_sYSize);
				if(m_pBackground->m_pTerrain)
				{
					TriangleTreeNode::Init(MAX_TRIANGLE_NODES); 
					Patch::pvert=new CUSTOMVERTEX[WJ_VERTEXBUFFERSIZE];
					m_pBackground->m_pTerrain->Reset();
					//reset the triangle node pool
					TriangleTreeNode::Reset();	
				}

					
										
//				m_pTerrain->Init(m_strTerrainMap);


//				m_dlgLightSet.m_editDiffuseB = m_pBackground->m_projectInfo.m_fDiffuseB;
//				m_dlgLightSet.m_editDiffuseG = m_pBackground->m_projectInfo.m_fDiffuseG;
//				m_dlgLightSet.m_editDiffuseR = m_pBackground->m_projectInfo.m_fDiffuseR;
//				m_dlgLightSet.m_editAmbientB = m_pBackground->m_projectInfo.m_fAmbientB;
//				m_dlgLightSet.m_editAmbientG = m_pBackground->m_projectInfo.m_fAmbientG;
//				m_dlgLightSet.m_editAmbientR = m_pBackground->m_projectInfo.m_fAmbientR;
//				m_dlgLightSet.m_bChangeLight = FALSE;

				return;
			}

			it++;
				
		}

		int re = AfxMessageBox( "Are you sure you want to add to the current project workspace?",MB_YESNO);

		if( re == IDYES )
		{
			PROJECTINFO project;
			CString strMapFile;

			project = OpenProject(str);

			if(m_pBackground)
			{
				m_pBackground->InvalidateDeviceObjects();
				m_pBackground->DeleteDeviceObjects();

				SAFE_DELETE( m_pBackground );

				// Effect(App의) 을 지운다.
				CAtumNode* pEffect = (CAtumNode *)m_pEffectList->m_pChild;

				while(pEffect)
				{
					pEffect->m_bUsing = FALSE;
					pEffect = pEffect->m_pNext;
				}

				m_pEffectList->Tick();
				m_listEffectInfo.clear();

				int i;
				int n = m_dlgEffect.m_listEffect.GetCount();

				for(i=0;i < n;i++)
				{
				   m_dlgEffect.m_listEffect.DeleteString( n-i-1 );
				}

				list<D3DLIGHT8*>::iterator itLight = m_listLightInfo.begin();

				while( itLight != m_listLightInfo.end() )
				{
					SAFE_DELETE( (*itLight) );
					itLight++;
				}

				m_listLightInfo.clear();
				m_nUseLightNum = USED_LIGHT_NUM;

				n = m_dlgLightList.m_listLight.GetCount();

				for(i=0;i < n;i++)
				{
				   m_dlgLightList.m_listLight.DeleteString( n-i-1 );
			}
			}


		
			m_pBackground = new CBackground(project.m_sXSize,project.m_sYSize);

			m_pBackground->InitDeviceObjects();
			m_pBackground->RestoreDeviceObjects();

			memcpy( &m_pBackground->m_projectInfo, &project, sizeof(PROJECTINFO) );

			m_listProjectInfo.push_back(project);
			m_pWorkspace->numberOfProject++;

			InitMapData();

			POINT start,end;

			start.x = 0; start.y = 0;

			end.x = project.m_sXSize; end.y = project.m_sYSize; 

			m_pMiniMap = new CMiniMap(project.m_sXSize,project.m_sYSize);

			m_pMiniMap->Create( "minimap.tga",start,end);
			m_pMiniMap->SetRect(0,0,project.m_sXSize, project.m_sYSize);

			m_pMiniMap->InitDeviceObjects();
			m_pMiniMap->RestoreDeviceObjects();

			m_dlgObjectSet.m_pObject = NULL; // 07-05-02 by shkim, 버그로 죽는 현상 해결

			OpenMapData(project.m_strProjectName);


		}
		else if(re == IDNO)
		{
			return;
		}
	} 
	else 
	{
		AfxMessageBox("Workspace is not open.");
	}

	if(m_bCheckWorkspaceView)
	{
		m_dlgWorkspace.UpdateWorkspace();
	}
}
void CMapEditorView::OnOpenProject() 
{
	// TODO: Add your command handler code here
	if(m_pWorkspace)
	{
		// 프로젝트 파일 불러오기
		CFileDialog dlg(TRUE,"poj",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT , "Project Files (*.poj)|*.poj", NULL);
		if(dlg.DoModal() == IDOK)
		{
			POSITION pos = dlg.GetStartPosition();
			const char* pdest;
			CString str;
			while(pos)
			{
				CString strPath = dlg.GetNextPathName( pos );

				pdest = strrchr( (LPCTSTR)strPath, '\\' );
				str = pdest+1;
			}
			int len = str.GetLength();
			str.Delete(len-4, 4);
			OnOpenProjectSub(str);
		}
	}
	else
	{
		AfxMessageBox( "No workspace selected.",MB_OK);
	}
}

void CMapEditorView::OnOpenWorkspace() 
{
	// TODO: Add your command handler code here
	if(m_pWorkspace)
	{
		int re = AfxMessageBox( "Save changes made to this workspace?",MB_YESNOCANCEL);
		if( re == IDYES )
		{
			if(m_pBackground)
			{
				// Project를 저장한다.
				SaveProject();
				// Map File을 저장한다.
				SaveMapFile();
			}
			// Workspace 저장한다.
			SaveWorkspace();
		}
		else if(re == IDNO)
			;//지나간다.
		else if(re == IDCANCEL)
			return;
	}
	CFileDialog dlg(TRUE,"wok",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT , "Project Files (*.wok)|*.wok||", NULL);
	if(dlg.DoModal() == IDOK)
	{
		SAFE_DELETE( m_pWorkspace );
		if(m_pBackground)
		{
			m_pBackground->InvalidateDeviceObjects();
			m_pBackground->DeleteDeviceObjects();
			SAFE_DELETE( m_pBackground );
			// Effect(App의) 을 지운다.
			CAtumNode* pEffect = (CAtumNode *)m_pEffectList->m_pChild;
			while(pEffect)
			{
				pEffect->m_bUsing = FALSE;
				pEffect = pEffect->m_pNext;
			}
			m_pEffectList->Tick();
			m_listEffectInfo.clear();
			int i;
			int n = m_dlgEffect.m_listEffect.GetCount();
			for(i=0;i < n;i++)
			   m_dlgEffect.m_listEffect.DeleteString( n-i-1 );

			list<D3DLIGHT8*>::iterator itLight = m_listLightInfo.begin();
			while( itLight != m_listLightInfo.end() )
			{
				SAFE_DELETE( (*itLight) );
				itLight++;
			}
			m_listLightInfo.clear();
			m_nUseLightNum = USED_LIGHT_NUM;
			n = m_dlgLightList.m_listLight.GetCount();
			for(i=0;i < n;i++)
			   m_dlgLightList.m_listLight.DeleteString( n-i-1 );
		}
		if(m_pMiniMap)
		{
			m_pMiniMap->InvalidateDeviceObjects();
			m_pMiniMap->DeleteDeviceObjects();
			SAFE_DELETE( m_pMiniMap );
		}

		POSITION pos = dlg.GetStartPosition();
		const char* pdest;
		CString str;
		while(pos)
		{
			CString strPath = dlg.GetNextPathName( pos );

			pdest = strrchr( (LPCTSTR)strPath, '\\' );
			str = pdest+1;
		}
		m_pWorkspace = new WORKSPACE;
		OpenWorkspace(str);
	}
	if(m_bCheckWorkspaceView)
		m_dlgWorkspace.UpdateWorkspace();
}

void CMapEditorView::OnSaveProject() 
{
	// TODO: Add your command handler code here
	if(m_pWorkspace)
	{
		if(m_pBackground)
		{
			// Project를 저장한다.
			SaveProject();
			// Map File을 저장한다.
			SaveMapFile();
		}
		// Workspace 저장한다.
		SaveWorkspace();
	}
}

void CMapEditorView::SaveWorkspace()
{
	///////////////// Workspace Info //////////////////////
	CFile MakeWorkspace;
	int i;//,j;
	CFileHeader Workspaceheader;
	Workspaceheader.m_dwFileType = _WORKSPACE;
	CString str;
	//////////// Workspace 내의 Project 들의 Info /////////
	char buf[512];	
	memset(buf, 0x00, 512);
	_chdir(m_strCurrentDir);
	str.Format(".\\%s\\%s.txt_n",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
	CFile textdata;
	textdata.Open(str,CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate);
	_chdir(m_strCurrentDir);
	str.Format(".\\%s\\%s.wok_n",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
	MakeWorkspace.Open(str, CFile::modeCreate | CFile::modeWrite );
	MakeWorkspace.Write(&Workspaceheader,sizeof(Workspaceheader));
	MakeWorkspace.Seek(20,CFile::begin);
	MakeWorkspace.Write(m_pWorkspace,sizeof(WORKSPACE));
	list<PROJECTINFO>::iterator it = m_listProjectInfo.begin();
	for(i=0;i<m_pWorkspace->numberOfProject;i++)
	{
		wsprintf( buf, "%40s\t%16s\t%4d\t%4d\t%16s\t%4d\t%4d\t%3d\t%3d\t%d\t%d\t%d\r\n",
			      it->m_strProjectName,
				  it->m_strFieldIP,
				  (int)it->m_sFieldPort,
				  (int)it->m_sFieldPortUDP,
				  it->m_strNPCIP,
				  (int)it->m_sNPCPort,
				  (int)it->m_sNPCPortUDP,
				  (int)it->m_sXSize,
				  (int)it->m_sYSize,
				  (int)it->m_fHeightMax,
				  (int)it->m_fHeightMin,
				  (int)it->m_fWaterHeight );

		textdata.Write(buf, strlen(buf));

		MakeWorkspace.Write(&(*it),sizeof(PROJECTINFO));
		it++;
	}
	MakeWorkspace.Close();
	textdata.Close();
	_chdir(m_strCurrentDir);
	CString strNewFileName,strOldFileName;

	str.Format(".\\%s\\%s.txt_n",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
	strOldFileName.Format(".\\%s\\%s.txt_o",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
	strNewFileName.Format(".\\%s\\%s.txt",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);

	CFileFind finder;
	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);

	str.Format(".\\%s\\%s.wok_n",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
	strOldFileName.Format(".\\%s\\%s.wok_o",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
	strNewFileName.Format(".\\%s\\%s.wok",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);

	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);
}

void CMapEditorView::SaveProject()
{
	char str[256];
	CFile MakeProject;
	CFileHeader Projectheader;
	Projectheader.m_dwFileType = _PROJECTINFO;
	_chdir(m_strCurrentDir);
	wsprintf(str,".\\%s\\%s\\%s.poj_n",m_pWorkspace->workspaceName,
		m_pBackground->m_projectInfo.m_strProjectName,
		m_pBackground->m_projectInfo.m_strProjectName);
	if(MakeProject.Open(str, CFile::modeCreate | CFile::modeWrite )==FALSE)
	{
		AfxMessageBox("Save error");
		return;
	}
	MakeProject.Write(&Projectheader,sizeof(Projectheader));
	MakeProject.Seek(20,CFile::begin);
	MakeProject.Write(&m_pBackground->m_projectInfo,sizeof(PROJECTINFO));
	MakeProject.Close();
	CString strNewFileName,strOldFileName;
//	str.Format(".\\%s\\%s\\%s.poj_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strOldFileName.Format(".\\%s\\%s\\%s.poj_o",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strNewFileName.Format(".\\%s\\%s\\%s.poj",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	CFileFind finder;
	if(finder.FindFile(strOldFileName))
		CFile::Remove(strOldFileName);
	if(finder.FindFile(strNewFileName))
		CFile::Rename(strNewFileName,strOldFileName);
	CFile::Rename(str,strNewFileName);

	list<PROJECTINFO>::iterator it = m_listProjectInfo.begin();
	while(1)
	{
		if(it==m_listProjectInfo.end())
			break;
		int re = strcmp(it->m_strProjectName, m_pBackground->m_projectInfo.m_strProjectName);
		if(re == 0)
		{
			it->m_useTileSetIndex = m_pBackground->m_projectInfo.m_useTileSetIndex;
			it->m_sFieldPort = m_pBackground->m_projectInfo.m_sFieldPort;
			it->m_sFieldPortUDP = m_pBackground->m_projectInfo.m_sFieldPortUDP;
			it->m_sNPCPort = m_pBackground->m_projectInfo.m_sNPCPort;
			it->m_sNPCPortUDP = m_pBackground->m_projectInfo.m_sNPCPortUDP;
			strcpy(it->m_strFieldIP,m_pBackground->m_projectInfo.m_strFieldIP);
			strcpy(it->m_strNPCIP, m_pBackground->m_projectInfo.m_strNPCIP);
			strcpy(it->m_strProjectName, m_pBackground->m_projectInfo.m_strProjectName);
			it->m_sXSize = m_pBackground->m_projectInfo.m_sXSize;
			it->m_sYSize = m_pBackground->m_projectInfo.m_sYSize;
			it->m_fHeightMax = m_pBackground->m_projectInfo.m_fHeightMax;
			it->m_fHeightMin = m_pBackground->m_projectInfo.m_fHeightMin;
			it->m_fWaterHeight = m_pBackground->m_projectInfo.m_fWaterHeight;
			it->m_fDiffuseR1 = m_pBackground->m_projectInfo.m_fDiffuseR1;
			it->m_fDiffuseG1 = m_pBackground->m_projectInfo.m_fDiffuseG1;
			it->m_fDiffuseB1 = m_pBackground->m_projectInfo.m_fDiffuseB1;
			it->m_fAmbientR1 = m_pBackground->m_projectInfo.m_fAmbientR1;
			it->m_fAmbientG1 = m_pBackground->m_projectInfo.m_fAmbientG1;
			it->m_fAmbientB1 = m_pBackground->m_projectInfo.m_fAmbientB1;
			it->m_fDiffuseR2 = m_pBackground->m_projectInfo.m_fDiffuseR2;
			it->m_fDiffuseG2 = m_pBackground->m_projectInfo.m_fDiffuseG2;
			it->m_fDiffuseB2 = m_pBackground->m_projectInfo.m_fDiffuseB2;
			it->m_fAmbientR2 = m_pBackground->m_projectInfo.m_fAmbientR2;
			it->m_fAmbientG2 = m_pBackground->m_projectInfo.m_fAmbientG2;
			it->m_fAmbientB2 = m_pBackground->m_projectInfo.m_fAmbientB2;
			break;
		}
		else 
			it++;
	}
}

void CMapEditorView::SaveMapFile()
{
	if(!m_pBackground)
		return;
	///////////////////////// Map Editor Data (*.mbd) ///////////////////////////
	CFileFind finder;
	int i,j;
	// 블럭 단위정점 
	CFile BVFile;
	CString strBVFile;
	CString str,str2,strNewFileName,strOldFileName;

	_chdir(m_strCurrentDir);

	strBVFile.Format( ".\\%s\\%s\\%s.mbd_n",
		              m_pWorkspace->workspaceName,
		              m_pBackground->m_projectInfo.m_strProjectName,
		              m_pBackground->m_projectInfo.m_strProjectName );

	if(BVFile.Open(strBVFile,CFile::modeCreate | CFile::modeReadWrite))
	{
//		VERTEXINFO vertex;
		BVFile.Seek(20,CFile::begin);

		for( i = 0 ; i < ( 2 * m_pBackground->m_projectInfo.m_sXSize + 1 )
			  * ( 2 * m_pBackground->m_projectInfo.m_sYSize + 1 ) ; i++ )
		{
			BVFile.Write(&m_pBackground->m_pBlockVertexArray[i],sizeof(VERTEXINFO));
		}

		BVFile.Close();

		str.Format( ".\\%s\\%s\\%s.mbd_n",
			         m_pWorkspace->workspaceName,
					 m_pBackground->m_projectInfo.m_strProjectName,
					 m_pBackground->m_projectInfo.m_strProjectName );
		strOldFileName.Format( ".\\%s\\%s\\%s.mbd_o",
			                    m_pWorkspace->workspaceName,
								m_pBackground->m_projectInfo.m_strProjectName,
								m_pBackground->m_projectInfo.m_strProjectName );
		strNewFileName.Format( ".\\%s\\%s\\%s.mbd",
			                   m_pWorkspace->workspaceName,
							   m_pBackground->m_projectInfo.m_strProjectName,
							   m_pBackground->m_projectInfo.m_strProjectName );

		if(finder.FindFile(strOldFileName))
			CFile::Remove(strOldFileName);

		if(finder.FindFile(strNewFileName))
			CFile::Rename(strNewFileName,strOldFileName);

		CFile::Rename(str,strNewFileName);
	}

	///////////////////////// Map Data (*.m) -Mapeditor 용///////////////////////////
	_chdir(m_strCurrentDir);
	str.Format( ".\\%s\\%s\\%s.m_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );

	CFile MakeFile;
	CFileHeader header;

	header.m_dwFileType = _MAP;

	MakeFile.Open(str, CFile::modeCreate | CFile::modeWrite );

	MakeFile.Write(&header,sizeof(header));

	MakeFile.Seek(20,CFile::begin);

	m_info.m_fTileSize = m_pBackground->m_fTileSize;
	m_info.m_nVertexNumber = (m_pBackground->m_sXSize+1)*(m_pBackground->m_sYSize+1);
	m_info.m_nTileInfoNumber = (m_pBackground->m_sXSize)*(m_pBackground->m_sYSize);
	m_info.m_nObjectNumber = m_pBackground->m_nObjectNumber;

	MakeFile.Write(&m_info,sizeof(m_info));

	for(i=0;i<m_info.m_nVertexNumber;i++)
	{
		MakeFile.Write(&m_pBackground->m_pTileVertexArray[i],sizeof(VERTEXINFO));
	}

	for(i=0;i<m_info.m_nTileInfoNumber;i++)
	{
		MakeFile.Write(&m_pBackground->m_pTileInfo[i],sizeof(TILEINFO));
	}

	OBJECTINFO objInfo;

	map<INT,CAtumNode *>::iterator it = m_pBackground->m_mapObjectData.begin();

	if(m_info.m_nObjectNumber>0)
	{
		while(it != m_pBackground->m_mapObjectData.end())
		{
			if(it->second)
			{
				CObjectChild * pNode = (CObjectChild *)it->second->m_pChild;

				while(pNode)
				{
					objInfo.m_dwObjType = pNode->m_dwPartType;
					objInfo.bRenderType = pNode->m_bRenderType;
					objInfo.bCheckTick = pNode->m_bCheckTick;
					objInfo.vPos = pNode->m_vPos;

					D3DXVec3Normalize(&objInfo.vVel,&pNode->m_vVel);
					D3DXVec3Normalize(&objInfo.vUp,&pNode->m_vUp);

					MakeFile.Write(&objInfo,sizeof(OBJECTINFO));
					pNode = (CObjectChild *)pNode->m_pNext;
				}
			}

			it++;
		}
	}

	MakeFile.Close();

	str.Format( ".\\%s\\%s\\%s.m_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );
	strOldFileName.Format( ".\\%s\\%s\\%s.m_o",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );
	strNewFileName.Format( ".\\%s\\%s\\%s.m",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );

	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);

	///////////////////////// Map Object Data (*.mo) -Mapeditor 용///////////////////////////

	_chdir(m_strCurrentDir);

	str.Format( ".\\%s\\%s\\%s.mo_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );

	MakeFile.Open(str, CFile::modeCreate | CFile::modeWrite );

	if(m_info.m_nObjectNumber>0)
	{
		it = m_pBackground->m_mapObjectData.begin();

		while(it != m_pBackground->m_mapObjectData.end())
		{
			if(it->second)
			{
				CObjectChild * pNode = (CObjectChild *)it->second->m_pChild;
				while(pNode)
				{
					MakeFile.Write(&pNode->m_info,sizeof(MAPOBJECTINFODETAIL));
					pNode = (CObjectChild *)pNode->m_pNext;
				}
			}

			it++;
		}
	}

	MakeFile.Close();

	str.Format(".\\%s\\%s\\%s.mo_n",
		       m_pWorkspace->workspaceName,
			   m_pBackground->m_projectInfo.m_strProjectName,
			   m_pBackground->m_projectInfo.m_strProjectName );
	strOldFileName.Format( ".\\%s\\%s\\%s.mo_o",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );
	strNewFileName.Format( ".\\%s\\%s\\%s.mo",
		                   m_pWorkspace->workspaceName,
		                   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );

	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);

	///////////////////////// Map Client Data (*.mc) -Client 용///////////////////////////
	_chdir(m_strCurrentDir);

	str.Format( ".\\%s\\%s\\%s.mc_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );
	MakeFile.Open(str, CFile::modeCreate | CFile::modeWrite );

	MakeFile.Seek(20,CFile::begin);
	MakeFile.Write(&m_info,sizeof(m_info));

	for(i=0;i<m_info.m_nVertexNumber;i++)
	{
		MakeFile.Write(&m_pBackground->m_pTileVertexArray[i],sizeof(VERTEXINFO));
	}

	TILEINFOCLIENT tileInfo;
	for(i=0;i<m_info.m_nTileInfoNumber;i++)
	{
		tileInfo.bMove = m_pBackground->m_pEventInfo[i].m_bMove;
		tileInfo.useTexNumber = m_pBackground->m_pTileInfo[i].useTexNumber;
		tileInfo.waterType = m_pBackground->m_pTileInfo[i].waterType;
		tileInfo.waterHeight = m_pBackground->m_pTileInfo[i].waterHeight;
		tileInfo.waterTexNumber = m_pBackground->m_pTileInfo[i].waterTexNumber;
		tileInfo.bEnableLand = m_pBackground->m_pEventInfo[i].m_bEnableLand;
		tileInfo.bEnvetType = m_pBackground->m_pEventInfo[i].m_bEnvetType;

		MakeFile.Write(&tileInfo,sizeof(TILEINFOCLIENT));
	}

	int nObjCont = 0;

	if(m_info.m_nObjectNumber>0)
	{
		it = m_pBackground->m_mapObjectData.begin();

		while(it != m_pBackground->m_mapObjectData.end())
		{
			if(it->second)
			{
				CObjectChild * pNode = (CObjectChild *)it->second->m_pChild;

				while(pNode)
				{
					OBJECTINFOCLIENT objectInfo;
					memset(&objectInfo,0x00,sizeof(OBJECTINFOCLIENT));

//					objectInfo.bCheckTick = pNode->m_bCheckTick;
//					objectInfo.bRenderType = pNode->m_bRenderType;

					objectInfo.dwObjType = pNode->m_nObjectNum;
					objectInfo.nCount = nObjCont++;
					objectInfo.vPos = pNode->m_vPos;

					D3DXVec3Normalize(&objectInfo.vUp,&pNode->m_vUp);
					D3DXVec3Normalize(&objectInfo.vVel,&pNode->m_vVel);

					objectInfo.dwMonsterUniqueNumber = pNode->m_info.dwMonsterUniqueNumber;
					objectInfo.bObjectTexIndex = pNode->m_info.bObjectTexIndex;
					objectInfo.nObjectSrcIndex = pNode->m_info.nObjectSrcIndex;
					objectInfo.bBodyCondition = pNode->m_info.bBodyCondition;

					objectInfo.bIsEvent = pNode->m_info.bIsEvent;
					objectInfo.bEventType = pNode->m_info.bEventType;
					objectInfo.sEventIndexFrom = pNode->m_info.sEventIndexFrom;
					objectInfo.sEventIndexTo = pNode->m_info.sEventIndexTo;
					objectInfo.sEventIndex3 = pNode->m_info.sEventIndex3;

//					strcpy(objectInfo.strEventParam,pNode->m_info.strEventParam);

					memset(objectInfo.strEventParam, 0x00, sizeof(objectInfo.strEventParam));
					strncpy( objectInfo.strEventParam,
						     pNode->m_info.strEventParam, strlen( pNode->m_info.strEventParam ) );

					MakeFile.Write(&objectInfo,sizeof(OBJECTINFOCLIENT));
					pNode = (CObjectChild *)pNode->m_pNext;
				}
			}

			it++;
		}
	}

	MakeFile.Close();

	str.Format( ".\\%s\\%s\\%s.mc_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );
	strOldFileName.Format( ".\\%s\\%s\\%s.mc_o",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );
	strNewFileName.Format( ".\\%s\\%s\\%s.mc",
		                   m_pWorkspace->workspaceName,
		                   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );

	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);

	///////////////////////// Map Server Data (*.ms) -Server 용///////////////////////////
	MapInfoServer mapInfoServer;
	mapInfoServer.m_nVertexNumber = m_info.m_nVertexNumber;
	mapInfoServer.m_nObjectNumber = m_info.m_nObjectNumber;

	_chdir(m_strCurrentDir);

	str.Format( ".\\%s\\%s\\%s.ms_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );

	MakeFile.Open(str, CFile::modeCreate | CFile::modeWrite );

	MakeFile.Seek(20,CFile::begin);

	MakeFile.Write(&mapInfoServer,sizeof(MapInfoServer));

	for(i=0;i<m_info.m_nVertexNumber;i++)
	{
		MakeFile.Write(&m_pBackground->m_pTileVertexArray[i].pos.y,sizeof(float));
	}

	if(m_info.m_nObjectNumber>0)
	{
		it = m_pBackground->m_mapObjectData.begin();

		while(it != m_pBackground->m_mapObjectData.end())
		{
			if(it->second)
			{
				CObjectChild * pNode = (CObjectChild *)it->second->m_pChild;

				while(pNode)
				{
					OBJECTINFOSERVER objInfoserver;

					memset(&objInfoserver,0x00,sizeof(OBJECTINFOSERVER));

					objInfoserver.dwObjType = pNode->m_nObjectNum;
					objInfoserver.vPos = pNode->m_vPos;

					D3DXVec3Normalize(&objInfoserver.vUp,&pNode->m_vUp);

					objInfoserver.bIsEvent = pNode->m_info.bIsEvent;
					objInfoserver.bEventType = pNode->m_info.bEventType;
					objInfoserver.sEventIndexFrom = pNode->m_info.sEventIndexFrom;
					objInfoserver.sEventIndexTo = pNode->m_info.sEventIndexTo;
					objInfoserver.sEventIndex3 = pNode->m_info.sEventIndex3;

					memset(objInfoserver.strEventParam, 0x00, sizeof(objInfoserver.strEventParam));

					strncpy( objInfoserver.strEventParam,
						     pNode->m_info.strEventParam,
							 strlen( pNode->m_info.strEventParam ) );
					MakeFile.Write(&objInfoserver,sizeof(OBJECTINFOSERVER));
					pNode = (CObjectChild *)pNode->m_pNext;
				}
			}

			it++;
		}
	}

	MakeFile.Close();

	str.Format( ".\\%s\\%s\\%s.ms_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );
	strOldFileName.Format( ".\\%s\\%s\\%s.ms_o",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );
	strNewFileName.Format( ".\\%s\\%s\\%s.ms",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );

	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);

	///////////////////////// Map Server Data (*.sma) Map Edit Data (*.mma) ///////////////////////////
	///////////////////////// Map Server Data (*.sma2) Map Edit Data (*.mma2) /////////////////////////// -> 몬스터의 종류별 타입 들어감(0~4 보스,대형,중형,소형)

	_chdir(m_strCurrentDir);

	str.Format( ".\\%s\\%s\\%s.sma2_n", 
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );
	str2.Format( ".\\%s\\%s\\%s.mma2_n",
		         m_pWorkspace->workspaceName,
				 m_pBackground->m_projectInfo.m_strProjectName,
				 m_pBackground->m_projectInfo.m_strProjectName );

	CFile MakeSmaFile,MakeMmaFile;

	CFileHeader Smaheader;

	Smaheader.m_dwFileType = _SMA;

	MakeSmaFile.Open(str, CFile::modeCreate | CFile::modeWrite );
	MakeMmaFile.Open(str2, CFile::modeCreate | CFile::modeWrite );

	MakeSmaFile.Write(&Smaheader,sizeof(Smaheader));
	MakeMmaFile.Write(&Smaheader,sizeof(Smaheader));

	MakeSmaFile.Seek(20,CFile::begin);
	MakeMmaFile.Seek(20,CFile::begin);

	for(i=0;i<m_pBackground->m_sXSize;i++)
	{
		for(j=0;j<m_pBackground->m_sYSize;j++)
		{
			byte bCheckHeight = 0;
			EVENTINFO eventInfo;

			eventInfo = m_pBackground->m_pEventInfo[i*m_pBackground->m_sYSize+j];

			if( m_pBackground->m_pTileVertexArray[ i * ( m_pBackground->m_sYSize + 1 ) + j ].pos.y
				 > m_pBackground->m_projectInfo.m_fHeightMax )
			{
				bCheckHeight++;
			}

			if( m_pBackground->m_pTileVertexArray[ ( i + 1 ) * ( m_pBackground->m_sYSize + 1 ) + j ].pos.y
				 > m_pBackground->m_projectInfo.m_fHeightMax )
			{
				bCheckHeight++;
			}

			if( m_pBackground->m_pTileVertexArray[ i * ( m_pBackground->m_sYSize + 1 ) + j + 1 ].pos.y
				 > m_pBackground->m_projectInfo.m_fHeightMax )
			{
				bCheckHeight++;
			}

			if( m_pBackground->m_pTileVertexArray[ ( i + 1 ) * ( m_pBackground->m_sYSize + 1 ) + j + 1 ].pos.y 
				 > m_pBackground->m_projectInfo.m_fHeightMax )
			{
				bCheckHeight++;
			}

			if(bCheckHeight > 1)
			{
				eventInfo.m_bMove = 1;
			}

			MakeSmaFile.Write(&eventInfo,sizeof(EVENTINFO));
			MakeMmaFile.Write( &m_pBackground->m_pEventInfo[ i * m_pBackground->m_sYSize + j ],
				               sizeof( EVENTINFO ) );
		}
	}
	MakeSmaFile.Write(&m_pBackground->m_nMonsterNumber,sizeof(int));
	MakeMmaFile.Write(&m_pBackground->m_nMonsterNumber,sizeof(int));

	list<MONSTERINFO2>::iterator it2 = m_pBackground->m_listMonsterInfo.begin();

	for(i=0;i<m_pBackground->m_nMonsterNumber;i++)
	{
		// .sma
		if((*it2).nMonType > 0)
		{
			MakeSmaFile.Write(&(*it2),sizeof(MONSTERINFO2));
			MakeMmaFile.Write(&(*it2),sizeof(MONSTERINFO2));
		}

		it2++;
	}

	MakeSmaFile.Close();
	MakeMmaFile.Close();

	str.Format( ".\\%s\\%s\\%s.sma2_n",
		        m_pWorkspace->workspaceName,
				m_pBackground->m_projectInfo.m_strProjectName,
				m_pBackground->m_projectInfo.m_strProjectName );
	strOldFileName.Format( ".\\%s\\%s\\%s.sma2_o",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );
	strNewFileName.Format( ".\\%s\\%s\\%s.sma",
		                   m_pWorkspace->workspaceName,
						   m_pBackground->m_projectInfo.m_strProjectName,
						   m_pBackground->m_projectInfo.m_strProjectName );
	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);

	str.Format(".\\%s\\%s\\%s.mma2_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strOldFileName.Format(".\\%s\\%s\\%s.mma2_o",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strNewFileName.Format(".\\%s\\%s\\%s.mma2",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);

	if(finder.FindFile(strOldFileName))
	{
		CFile::Remove(strOldFileName);
	}

	if(finder.FindFile(strNewFileName))
	{
		CFile::Rename(strNewFileName,strOldFileName);
	}

	CFile::Rename(str,strNewFileName);
	///////////////////////// Map Client Data (*.omd) ///////////////////////////
	CFile MakeOmdFile;
	int objCont = 0;
	int monCont = 0;
/*	int objCont2 = 0;
	BOOL * setObjectType;
	BOOL * setObjectType2;
	setObjectType = new BOOL[m_nObjectNormalCont];
	setObjectType2 = new BOOL[m_nObjectBlockCont];
	int *objType;
	int *objType2;
	objType = new int[m_nObjectNormalCont];
	objType2 = new int[m_nObjectBlockCont];
	for(i=0;i<m_nObjectNormalCont;i++)
	{
		setObjectType[i] = FALSE;
		objType[i] = -1;
	}
	for(i=0;i<m_nObjectBlockCont;i++)
	{
		setObjectType2[i] = FALSE;
		objType2[i] = -1;
	}

	BOOL setMonsterType[MONSTER_NUM];
	int monType[MONSTER_NUM];
	for(i=0;i<MONSTER_NUM;i++)
	{
		setMonsterType[i] = FALSE;
		monType[i] = -1;
	}
*/
	CString omdStr;
	omdStr.Format(".\\%s\\%s\\%s.omd_n",
		          m_pWorkspace->workspaceName,
				  m_pBackground->m_projectInfo.m_strProjectName,
				  m_pBackground->m_projectInfo.m_strProjectName);

	CFileHeader Omdheader;
	int temp;

	list<int> listTemp1;
	list<int>::iterator itTemp1 = listTemp1.begin();

	if(m_info.m_nObjectNumber>0)
	{
		it = m_pBackground->m_mapObjectData.begin();
		while(it != m_pBackground->m_mapObjectData.end())
		{
			if(it->second)
			{
				CObjectChild * pNode = (CObjectChild *)it->second->m_pChild;
				while(pNode)
				{
					bool bSet = FALSE;
					
					while(itTemp1 != listTemp1.end())
					{
						if((*itTemp1) == pNode->m_nObjectNum)
						{
							bSet = TRUE;
							break;
						}
						itTemp1++;
					}
					if(!bSet)
					{
						if(pNode->m_nObjectNum > 0)
						{
							listTemp1.push_back(pNode->m_nObjectNum);
							objCont++;
						}
					}
					pNode = (CObjectChild *)pNode->m_pNext;
				}
			}
			it++;
		}
	}

	list<int> listTemp2;
	list<int>::iterator itTemp2 = listTemp2.begin();

	it2 = m_pBackground->m_listMonsterInfo.begin();
	for(i=0;i<m_pBackground->m_nMonsterNumber;i++)
	{
		bool bSet = FALSE;	
		while(itTemp2 != listTemp2.end())
		{
			if((*itTemp2) == (*it2).nMonType)
			{
				bSet = TRUE;
				break;
			}
			itTemp2++;
		}
		if(!bSet)
		{
			if((*it2).nMonType > 0)
			{
				listTemp2.push_back((*it2).nMonType);
				monCont++;
			}
		}
		
		it2++;
	}

	MakeOmdFile.Open(omdStr, CFile::modeCreate | CFile::modeWrite );
	MakeOmdFile.Seek(20,CFile::begin);
	MakeOmdFile.Write(&objCont,sizeof(int));
	
	itTemp1 = listTemp1.begin();

	while(itTemp1 != listTemp1.end())
	{
		if((*itTemp1) > 0)
			MakeOmdFile.Write(&(*itTemp1),sizeof(int));
		itTemp1++;
	}

	listTemp1.clear();
	MakeOmdFile.Write(&monCont,sizeof(int));
	itTemp2 = listTemp2.begin();
	while(itTemp2 != listTemp2.end())
	{
		if((*itTemp2) > 0)
			MakeOmdFile.Write(&(*itTemp2),sizeof(int));
		itTemp2++;
	}
	listTemp2.clear();

	temp = MakeOmdFile.GetLength();
	DWORD length = MakeOmdFile.SeekToEnd();
	MakeOmdFile.Close();
	str.Format(".\\%s\\%s\\%s.omd_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strOldFileName.Format(".\\%s\\%s\\%s.omd_o",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strNewFileName.Format(".\\%s\\%s\\%s.omd",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	if(finder.FindFile(strOldFileName))
		CFile::Remove(strOldFileName);
	if(finder.FindFile(strNewFileName))
		CFile::Rename(strNewFileName,strOldFileName);
	CFile::Rename(str,strNewFileName);

//	SAFE_DELETE_ARRAY(setObjectType);
//	SAFE_DELETE_ARRAY(objType);
//	SAFE_DELETE_ARRAY(setObjectType2);
//	SAFE_DELETE_ARRAY(objType2);
	///////////////////////// Map Client Data (*.mud) ///////////////////////////
	CFile TexDataFile;
	int usetex;
	char strpath[256];
	_chdir(m_strCurrentDir);
	wsprintf(strpath,".\\Tile\\%d\\Texdata.mtd",m_pBackground->m_projectInfo.m_useTileSetIndex);
	if(TexDataFile.Open(strpath, CFile::modeRead))
	{
		TexDataFile.Seek(20,CFile::begin);
		TexDataFile.Read(&usetex,sizeof(int));
		TexDataFile.Close();
	}
	bool bUseTex[MAX_TEXTILE_NUM];
	for(i = 0 ; i < MAX_TEXTILE_NUM ; i++)
	{
		bUseTex[i] = FALSE;
	}
	for(i=0;i<m_pBackground->m_sXSize;i++)
	{
		for(j=0;j<m_pBackground->m_sYSize;j++)
		{
			bUseTex[m_pBackground->m_pTileInfo[i*m_pBackground->m_sYSize + j].useTexNumber] = TRUE;
		}
	}
	CString mudStr;
	CFile UseTexDataFile;
	int cont = 0;
	_chdir(m_strCurrentDir);
	mudStr.Format(".\\%s\\%s\\%s.mud_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	UseTexDataFile.Open(mudStr, CFile::modeCreate | CFile::modeWrite );
	UseTexDataFile.Seek(24,CFile::begin);
	for(i=0;i<MAX_TEXTILE_NUM;i++)
	{
		if(bUseTex[i])
		{
			cont++;
			UseTexDataFile.Write(&i,sizeof(int));
		}
	}
	UseTexDataFile.Seek(20,CFile::begin);
	UseTexDataFile.Write(&cont,sizeof(int));
	UseTexDataFile.Close();
	str.Format(".\\%s\\%s\\%s.mud_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strOldFileName.Format(".\\%s\\%s\\%s.mud_o",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	strNewFileName.Format(".\\%s\\%s\\%s.mud",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	if(finder.FindFile(strOldFileName))
		CFile::Remove(strOldFileName);
	if(finder.FindFile(strNewFileName))
		CFile::Rename(strNewFileName,strOldFileName);
	CFile::Rename(str,strNewFileName);

	if(m_dlgEffect)// && m_dlgEffect.m_listEffect.GetCount())
	{
		///////////////////////// Map Data (*.Efm)-맵에디터용///////////////////////////
		_chdir(m_strCurrentDir);
		str.Format(".\\%s\\%s\\%s.efm_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		CFile MakeEffectFile;
		int nEffCont = m_dlgEffect.m_listEffect.GetCount();
		MakeEffectFile.Open(str, CFile::modeCreate | CFile::modeWrite );
		MakeEffectFile.Seek(20,CFile::begin);
		MakeEffectFile.Write(&nEffCont,sizeof(nEffCont));
		list<EFFECTINFO>::iterator itEff = m_listEffectInfo.begin();
		while(itEff != m_listEffectInfo.end())
		{
			itEff->fCheckTime = itEff->fReTime;
			MakeEffectFile.Write(&(*itEff),sizeof(EFFECTINFO));
			itEff++;
		}
		MakeEffectFile.Close();
		str.Format(".\\%s\\%s\\%s.efm_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		strOldFileName.Format(".\\%s\\%s\\%s.efm_o",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		strNewFileName.Format(".\\%s\\%s\\%s.efm",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		if(finder.FindFile(strOldFileName))
			CFile::Remove(strOldFileName);
		if(finder.FindFile(strNewFileName))
			CFile::Rename(strNewFileName,strOldFileName);
		CFile::Rename(str,strNewFileName);
		///////////////////////// Map Data (*.Efc)-클라이언트용///////////////////////////
		_chdir(m_strCurrentDir);
		str.Format(".\\%s\\%s\\%s.efc_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		CFile MakeEffectFile2;
		MakeEffectFile2.Open(str, CFile::modeCreate | CFile::modeWrite );
		MakeEffectFile2.Seek(20,CFile::begin);
		MakeEffectFile2.Write(&nEffCont,sizeof(nEffCont));
		itEff = m_listEffectInfo.begin();
		while(itEff != m_listEffectInfo.end())
		{
			EFFECTINFOCLIENT eff;
			eff.bLoop = itEff->bLoop;
			eff.bRegion = itEff->bRegion;
			eff.fReTime = itEff->fReTime;
			eff.nType = itEff->nType;
			eff.vPos = itEff->vPos;
			MakeEffectFile2.Write(&eff,sizeof(EFFECTINFOCLIENT));
			itEff++;
		}
		MakeEffectFile2.Close();
		str.Format(".\\%s\\%s\\%s.efc_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		strOldFileName.Format(".\\%s\\%s\\%s.efc_o",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		strNewFileName.Format(".\\%s\\%s\\%s.efc",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		if(finder.FindFile(strOldFileName))
			CFile::Remove(strOldFileName);
		if(finder.FindFile(strNewFileName))
			CFile::Rename(strNewFileName,strOldFileName);
		CFile::Rename(str,strNewFileName);
	}
	if(m_dlgLightList)// && m_dlgLightList.m_listLight.GetCount())
	{
		///////////////////////// Map Data (*.Ltm)-맵에디터-클라이언트 용///////////////////////////
		_chdir(m_strCurrentDir);
		str.Format(".\\%s\\%s\\%s.ltm_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		CFile MakeLightFile;
		int nLightCont = m_dlgLightList.m_listLight.GetCount();
		MakeLightFile.Open(str, CFile::modeCreate | CFile::modeWrite );
		MakeLightFile.Seek(20,CFile::begin);
		MakeLightFile.Write(&nLightCont,sizeof(nLightCont));
		list<D3DLIGHT8*>::iterator itLight = m_listLightInfo.begin();
		while(itLight != m_listLightInfo.end())
		{
			MakeLightFile.Write((*itLight),sizeof(D3DLIGHT8));
			itLight++;
		}
		MakeLightFile.Close();
		str.Format(".\\%s\\%s\\%s.ltm_n",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		strOldFileName.Format(".\\%s\\%s\\%s.ltm_o",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		strNewFileName.Format(".\\%s\\%s\\%s.ltm",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		if(finder.FindFile(strOldFileName))
			CFile::Remove(strOldFileName);
		if(finder.FindFile(strNewFileName))
			CFile::Rename(strNewFileName,strOldFileName);
		CFile::Rename(str,strNewFileName);
	}
}

void CMapEditorView::OpenWorkspace(CString str)
{
	int i;
	PROJECTINFO project;
	CFile ReadMapFile;
	CFileHeader header;
	if(ReadMapFile.Open(str,CFile::modeRead))
	{
		int temp = ReadMapFile.GetLength();
		ReadMapFile.Read(&header,sizeof(header));
		if(header.m_dwFileType!=_WORKSPACE)
		{
			MessageBox("Not a valid workspace file.");
			return ;
		}
		ReadMapFile.Seek(20,CFile::begin);
		ReadMapFile.Read(m_pWorkspace,sizeof(WORKSPACE));
		int cont = 0;
		if(temp < sizeof(PROJECTINFO)*m_pWorkspace->numberOfProject + 20 + sizeof(WORKSPACE))
		{
			for(i=0;i<m_pWorkspace->numberOfProject;i++)
			{
				memset(&project,0x00,sizeof(PROJECTINFO));
				ReadMapFile.Read(&project,sizeof(PROJECTINFOOLD));
				if(project.m_useTileSetIndex >= 0 && project.m_sXSize > 0 && project.m_sYSize > 0)
				{
					cont++;
					m_listProjectInfo.push_back(project);
				}
			}
		}
		else
		{
			for(i=0;i<m_pWorkspace->numberOfProject;i++)
			{
				ReadMapFile.Read(&project,sizeof(PROJECTINFO));
				if(project.m_useTileSetIndex >= 0 && project.m_sXSize > 0 && project.m_sYSize > 0)
				{
					cont++;
					m_listProjectInfo.push_back(project);
				}
			}
		}
		ReadMapFile.Close();
		m_pWorkspace->numberOfProject = cont;
	}
}

PROJECTINFO CMapEditorView::OpenProject(CString str)
{
	PROJECTINFO project;
	memset(&project,0x00,sizeof(PROJECTINFO));
	char strpath[256];
	wsprintf(strpath,".\\%s\\%s\\%s.poj",m_pWorkspace->workspaceName,str,str);
	CFile ReadMapFile;
	CFileHeader header;
	_chdir(m_strCurrentDir);
	if(ReadMapFile.Open(strpath,CFile::modeRead))
	{
		int temp = ReadMapFile.GetLength();
		ReadMapFile.Read(&header,sizeof(header));
		if(header.m_dwFileType != _PROJECTINFO)

		{
			MessageBox("Not a valid project file.");
			return project;
		}
		ReadMapFile.Seek(20,CFile::begin);
		if(temp < sizeof(PROJECTINFO) + 20)
		{
			memset(&project,0x00,sizeof(PROJECTINFO));
			ReadMapFile.Read(&project,sizeof(PROJECTINFOOLD));
		}
		else
			ReadMapFile.Read(&project,sizeof(PROJECTINFO));
		ReadMapFile.Close();
		m_dlgLightSet.SetData(project);
	}
	m_editWaterHeight = project.m_fWaterHeight;
	UpdateData(FALSE);
	strcpy(project.m_strProjectName ,str);
	return project;
}

void CMapEditorView::OpenMapData(CString str)
{
	CString strMapName;
	strMapName.Format("Map Editor - %s", str);
	CFrameWnd* pMainWnd = GetParentFrame();
	pMainWnd->SetWindowText(strMapName);
	///////////////////////// Map Client Data (*.m) ///////////////////////////
	CString strMapFile,strSmaFile,strBVFile;
	_chdir(m_strCurrentDir);
	strMapFile.Format(".\\%s\\%s\\%s.m",m_pWorkspace->workspaceName,str,m_pBackground->m_projectInfo.m_strProjectName);
	CFile ReadMapFile;
	CFileHeader header;
	int i,j;
	if(ReadMapFile.Open(strMapFile,CFile::modeRead))
	{
		ReadMapFile.Read(&header,sizeof(header));
		if(header.m_dwFileType!=_MAP)
		{
			MessageBox("Not a valid map file.");
			return;
		}
		ReadMapFile.Seek(20,CFile::begin);
		ReadMapFile.Read(&m_info,sizeof(m_info));
		if(m_pObjectInfo)
			SAFE_DELETE_ARRAY( m_pObjectInfo );
		if(m_pObjectInfoDetail)
			SAFE_DELETE_ARRAY( m_pObjectInfoDetail );
		
		for(i=0;i<m_info.m_nVertexNumber;i++)
		{
			// 타일 단위 정점 셋팅
			VERTEXINFO vertex;

			ReadMapFile.Read(&vertex,sizeof(VERTEXINFO));
//			if(vertex.pos.y > 1000.0f || vertex.pos.y < -1000.0f)
//				m_pBackground->m_pTileVertexArray[i].pos.y = 0.0f;
//			else 
				m_pBackground->m_pTileVertexArray[i].pos.y = vertex.pos.y;

				// 07-05-08 by shkim, 저장되어 있던 높이 값을 임시 변수에 넣는다.
				m_pBackground->m_pvTempVecArr[i].y = m_pBackground->m_pTileVertexArray[i].pos.y;

			m_pBackground->m_pTileVertexArray[i].nor = vertex.nor;
		}

		// 블럭 단위 정점 셋팅 (.mbd)
		CFile BVFile;
		_chdir(m_strCurrentDir);

		strBVFile.Format(".\\%s\\%s\\%s.mbd",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		if(BVFile.Open(strBVFile,CFile::modeRead))
		{
//			VERTEXINFO vertex;
			BVFile.Seek(20,CFile::begin);
			for(i=0;i<(2*m_pBackground->m_projectInfo.m_sXSize+1)*(2*m_pBackground->m_projectInfo.m_sYSize+1);i++)
			{
				BVFile.Read(&m_pBackground->m_pBlockVertexArray[i],sizeof(VERTEXINFO));
			}
/*			for(i=0;i<(2*m_pBackground->m_projectInfo.m_sXSize)*(2*m_pBackground->m_projectInfo.m_sYSize);i++)
			{
				BVFile.Read(&m_pBackground->m_pBlockData[i],sizeof(BLOCKDATA));
			}
*/			BVFile.Close();
		}
		else
		{
			for(i=0;i<m_info.m_nVertexNumber;i++)
			{
				if(i<m_info.m_nVertexNumber-m_pBackground->m_sYSize-1)
				{
					if(i%(m_pBackground->m_sYSize+1) != m_pBackground->m_sYSize)
					{
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))].pos.y 
							= m_pBackground->m_pTileVertexArray[i].pos.y;
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))+1].pos.y 
							= (m_pBackground->m_pTileVertexArray[i].pos.y+m_pBackground->m_pTileVertexArray[i+1].pos.y)/2.0f;
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))+2*m_pBackground->m_sYSize+1].pos.y 
							= (m_pBackground->m_pTileVertexArray[i].pos.y+m_pBackground->m_pTileVertexArray[i+m_pBackground->m_sYSize+1].pos.y)/2.0f;
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))+2*m_pBackground->m_sYSize+1+1].pos.y 
							= (m_pBackground->m_pTileVertexArray[i].pos.y+m_pBackground->m_pTileVertexArray[i+1+m_pBackground->m_sYSize+1].pos.y)/2.0f;
					}
					else
					{
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))].pos.y 
							= m_pBackground->m_pTileVertexArray[i].pos.y;
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))+2*m_pBackground->m_sYSize+1].pos.y 
							= (m_pBackground->m_pTileVertexArray[i].pos.y+m_pBackground->m_pTileVertexArray[i+m_pBackground->m_sYSize+1].pos.y)/2.0f;
					}
				}
				else
				{
					if(i%(m_pBackground->m_sYSize+1) != m_pBackground->m_sYSize)
					{
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))].pos.y 
							= m_pBackground->m_pTileVertexArray[i].pos.y;
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))+1].pos.y 
							= (m_pBackground->m_pTileVertexArray[i].pos.y+m_pBackground->m_pTileVertexArray[i+1].pos.y)/2.0f;
					}
					else
					{
						m_pBackground->m_pBlockVertexArray[(i/(m_pBackground->m_sYSize+1))*2*(2*m_pBackground->m_sYSize+1) + 2*(i%(m_pBackground->m_sYSize+1))].pos.y 
							= m_pBackground->m_pTileVertexArray[i].pos.y;
					}
				}
			}
			for(i=0;i<(2*m_pBackground->m_projectInfo.m_sXSize)*(2*m_pBackground->m_projectInfo.m_sYSize);i++)
			{
				float fHeight;
				int x,z;
				x = i/(2*m_pBackground->m_projectInfo.m_sXSize);
				z = i%(2*m_pBackground->m_projectInfo.m_sXSize);
				fHeight = m_pBackground->m_pBlockVertexArray[x*(2*m_pBackground->m_projectInfo.m_sXSize+1) + z].pos.y;
				if(fHeight > m_pBackground->m_pBlockVertexArray[x*(2*m_pBackground->m_projectInfo.m_sXSize+1) + z+1].pos.y)
					fHeight = m_pBackground->m_pBlockVertexArray[x*(2*m_pBackground->m_projectInfo.m_sXSize+1) + z+1].pos.y;
				if(fHeight > m_pBackground->m_pBlockVertexArray[(x+1)*(2*m_pBackground->m_projectInfo.m_sXSize+1) + z].pos.y)
					fHeight = m_pBackground->m_pBlockVertexArray[(x+1)*(2*m_pBackground->m_projectInfo.m_sXSize+1) + z].pos.y;
				if(fHeight > m_pBackground->m_pBlockVertexArray[(x+1)*(2*m_pBackground->m_projectInfo.m_sXSize+1) + z+1].pos.y)
					fHeight = m_pBackground->m_pBlockVertexArray[(x+1)*(2*m_pBackground->m_projectInfo.m_sXSize+1) + z+1].pos.y;
				m_pBackground->m_pBlockData[i].fGroundHeight = fHeight;
				m_pBackground->m_pBlockData[i].fBlockHeight = fHeight;
				m_pBackground->m_pBlockData[i].nUseBlockCount = 0;
			}
		}
		for(i=0;i<m_info.m_nTileInfoNumber;i++)
			ReadMapFile.Read(&m_pBackground->m_pTileInfo[i],sizeof(TILEINFO));

		if(m_info.m_nObjectNumber > 0)
			m_pObjectInfo = new OBJECTINFO[m_info.m_nObjectNumber];
		 
		for(i=0;i<m_info.m_nObjectNumber ;i++)
			ReadMapFile.Read(&m_pObjectInfo[i],sizeof(OBJECTINFO));

		if(m_info.m_nObjectNumber > 0)
			m_pObjectInfoDetail = new MAPOBJECTINFODETAIL[m_info.m_nObjectNumber];

		//// (.mo) ////
		CString strObjFile;
		CFile ObjFile;

		strObjFile.Format(".\\%s\\%s\\%s.mo",m_pWorkspace->workspaceName,str,m_pBackground->m_projectInfo.m_strProjectName);

		DBGOUT("MAP : OPEN : OBJ [count:%d]\n",m_info.m_nObjectNumber);

		if(ObjFile.Open(strObjFile,CFile::modeRead))
		{
			for(i=0;i<m_info.m_nObjectNumber ;i++)
			{
				ObjFile.Read(&m_pObjectInfoDetail[i],sizeof(MAPOBJECTINFODETAIL));
			}

			ObjFile.Close();
		}
		else
		{
			for(i=0;i<m_info.m_nObjectNumber ;i++)
				memset(&m_pObjectInfoDetail[i],0x00,sizeof(MAPOBJECTINFODETAIL));
		}

		ReadMapFile.Close();
	}



	m_pBackground->ReInitMap(&m_info);
	///////////////////////// Map Editer Data (*.mma) ///////////////////////////
	// *.mma2 가 있으면 불러오고 없으면 다음
	// mma 가 있으면 불러오고 없으면 sma 를 불러온다.
	m_dlgMonsterSet.ClearMonsterData();

	_chdir(m_strCurrentDir);

	CString strMma2File;
	CFile Mma2File;
	strMma2File.Format(".\\%s\\%s\\%s.mma2",m_pWorkspace->workspaceName,str,m_pBackground->m_projectInfo.m_strProjectName);

	strSmaFile.Format(".\\%s\\%s\\%s.mma",m_pWorkspace->workspaceName,str,m_pBackground->m_projectInfo.m_strProjectName);
	CFile ReadSmaFile;
	CFileHeader Smaheader;

	
	if(Mma2File.Open(strMma2File,CFile::modeRead))
	{
		Mma2File.Read(&Smaheader,sizeof(Smaheader));
		if(Smaheader.m_dwFileType!=_SMA)
		{
			MessageBox("Not a valid map (sma) file.");
			return;
		}
		Mma2File.Seek(20,CFile::begin);
		for(i=0;i<m_pBackground->m_sXSize;i++)
		{
			for(j=0;j<m_pBackground->m_sYSize;j++)
			{
				Mma2File.Read(&m_pBackground->m_pEventInfo[i*m_pBackground->m_sYSize+j],sizeof(EVENTINFO));
			}
		}
		Mma2File.Read(&m_pBackground->m_nMonsterNumber,sizeof(int));
		MONSTERINFO2 monsterInfo;
		for(i=0;i<m_pBackground->m_nMonsterNumber;i++)
		{
			Mma2File.Read(&monsterInfo,sizeof(MONSTERINFO2));
			m_pBackground->m_listMonsterInfo.push_back(monsterInfo);
			m_dlgMonsterSet.UpdateMonster(monsterInfo.strRegionName);
			m_pBackground->UpdateMonsterRegion(monsterInfo.sStartx,monsterInfo.sStartz,monsterInfo.sEndx,monsterInfo.sEndz,TRUE);
		}
		Mma2File.Close();
	}
	else if(ReadSmaFile.Open(strSmaFile,CFile::modeRead))
	{
		ReadSmaFile.Read(&Smaheader,sizeof(Smaheader));
		if(Smaheader.m_dwFileType!=_SMA)
		{
			MessageBox("Not a valid map (sma) file.");
			return;
		}
		ReadSmaFile.Seek(20,CFile::begin);
		for(i=0;i<m_pBackground->m_sXSize;i++)
		{
			for(j=0;j<m_pBackground->m_sYSize;j++)
			{
				ReadSmaFile.Read(&m_pBackground->m_pEventInfo[i*m_pBackground->m_sYSize+j],sizeof(EVENTINFO));
			}
		}
		ReadSmaFile.Read(&m_pBackground->m_nMonsterNumber,sizeof(int));
		MONSTERINFO monsterInfo;
		MONSTERINFO2 monsterInfo2;
		for(i=0;i<m_pBackground->m_nMonsterNumber;i++)
		{
			ReadSmaFile.Read(&monsterInfo,sizeof(MONSTERINFO));
			strcpy(monsterInfo2.strRegionName,monsterInfo.strRegionName);
			monsterInfo2.nMonType = monsterInfo.nMonType;
			monsterInfo2.sStartx = monsterInfo.sStartx;
			monsterInfo2.sStartz = monsterInfo.sStartz;
			monsterInfo2.sEndx = monsterInfo.sEndx;
			monsterInfo2.sEndz = monsterInfo.sEndz;
			monsterInfo2.sMaxMon = monsterInfo.sMaxMon;
			monsterInfo2.sResNum = monsterInfo.sResNum;
			monsterInfo2.sResTime = monsterInfo.sResTime;
			monsterInfo2.bMonType = 3;		// 0:Boss 1:Formation 2:Medium 3:Small
			m_pBackground->m_listMonsterInfo.push_back(monsterInfo2);
			m_dlgMonsterSet.UpdateMonster(monsterInfo2.strRegionName);
			m_pBackground->UpdateMonsterRegion(monsterInfo2.sStartx,monsterInfo2.sStartz,monsterInfo2.sEndx,monsterInfo2.sEndz,TRUE);
		}
		ReadSmaFile.Close();
	}
	else
	{
		strSmaFile.Format(".\\%s\\%s\\%s.sma",m_pWorkspace->workspaceName,str,m_pBackground->m_projectInfo.m_strProjectName);
		if(ReadSmaFile.Open(strSmaFile,CFile::modeRead))
		{
			ReadSmaFile.Read(&Smaheader,sizeof(Smaheader));
			if(Smaheader.m_dwFileType!=_SMA)
			{
				MessageBox("Not a valid map (sma) file.");
				return;
			}
			ReadSmaFile.Seek(20,CFile::begin);
			for(i=0;i<m_pBackground->m_sXSize;i++)
			{
				for(j=0;j<m_pBackground->m_sYSize;j++)
				{
					ReadSmaFile.Read(&m_pBackground->m_pEventInfo[i*m_pBackground->m_sYSize+j],sizeof(EVENTINFO));
				}
			}
			ReadSmaFile.Read(&m_pBackground->m_nMonsterNumber,sizeof(int));
//			MONSTERINFO monsterInfo;
			MONSTERINFO2 monsterInfo2;
			for(i=0;i<m_pBackground->m_nMonsterNumber;i++)
			{
//				ReadSmaFile.Read(&monsterInfo,sizeof(MONSTERINFO));
//				strcpy(monsterInfo2.strRegionName,monsterInfo.strRegionName);
//				monsterInfo2.nMonType = monsterInfo.nMonType;
//				monsterInfo2.sStartx = monsterInfo.sStartx;
//				monsterInfo2.sStartz = monsterInfo.sStartz;
//				monsterInfo2.sEndx = monsterInfo.sEndx;
//				monsterInfo2.sEndz = monsterInfo.sEndz;
//				monsterInfo2.sMaxMon = monsterInfo.sMaxMon;
//				monsterInfo2.sResNum = monsterInfo.sResNum;
//				monsterInfo2.sResTime = monsterInfo.sResTime;
//				monsterInfo2.bMonType = 3;		// 0:보스 1:대형 2:중형 3:소형
				ReadSmaFile.Read(&monsterInfo2,sizeof(MONSTERINFO2));				
				m_pBackground->m_listMonsterInfo.push_back(monsterInfo2);
				m_dlgMonsterSet.UpdateMonster(monsterInfo2.strRegionName);
				m_pBackground->UpdateMonsterRegion(monsterInfo2.sStartx,monsterInfo2.sStartz,monsterInfo2.sEndx,monsterInfo2.sEndz,TRUE);
			}
			ReadSmaFile.Close();
		}
	}
	// Event 정보에 물관련 정보가 잘못되는 경우 다시 셋팅하여 불러온다
	for(i=0;i<m_info.m_nTileInfoNumber;i++)
		m_pBackground->m_pEventInfo[i].m_dwWaterType = m_pBackground->m_pTileInfo[i].waterType;

	///////////////////////// Map Data (*.Efm)-맵에디터용///////////////////////////
	if(m_dlgEffect && m_dlgEffect.m_listEffect)
	{
		int n = m_dlgEffect.m_listEffect.GetCount();
		for(i=0;i < n;i++)
		   m_dlgEffect.m_listEffect.DeleteString( n-i-1 );
		_chdir(m_strCurrentDir);
		str.Format(".\\%s\\%s\\%s.efm",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
		CFile ReadEffectFile;
		int nEffCont;
		if(ReadEffectFile.Open(str, CFile::modeRead ))
		{
			ReadEffectFile.Seek(20,CFile::begin);
			ReadEffectFile.Read(&nEffCont,sizeof(int));
			for(i=0;i<nEffCont;i++)
			{
				EFFECTINFO eff;
				ReadEffectFile.Read(&eff,sizeof(EFFECTINFO));
				m_listEffectInfo.push_back(eff);
				m_dlgEffect.m_listEffect.AddString(eff.strEffectName);
			}
			ReadEffectFile.Close();
		}
	}
	else
	{
		AfxMessageBox("No Effect Dlg.",MB_OK);
	}
	///////////////////////// Map Data (*.Ltm)-맵에디터-클라이언트 용///////////////////////////
	_chdir(m_strCurrentDir);
	str.Format(".\\%s\\%s\\%s.ltm",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	CFile ReadLightFile;
	int nLightCont;
	if(ReadLightFile.Open(str, CFile::modeRead ))
	{
		ReadLightFile.Seek(20,CFile::begin);
		ReadLightFile.Read(&nLightCont,sizeof(int));
		m_nUseLightNum = nLightCont + USED_LIGHT_NUM;
		for(i=0;i<nLightCont;i++)
		{
			D3DLIGHT8 *light = new D3DLIGHT8;
			ReadLightFile.Read(light,sizeof(D3DLIGHT8));
			m_listLightInfo.push_back(light);
			char buf[256];
			sprintf(buf,"Library updated [%d] first.",i+1);
			m_dlgLightList.m_listLight.AddString(buf);
		}
		ReadLightFile.Close();
	}
	SetLightAll();

	// 카메라 높이 셋팅하기
//	D3DXVECTOR3 vEye,vLookat,vUp,vDir;
//	float fDist,a,b;
//	vDir = D3DXVECTOR3(0,-1,0);
//	vEye = m_pCamera->GetEyePt();
//	vLookat = m_pCamera->GetViewDir();
//	vUp = m_pCamera->GetUpVec();
//	int nCamX = (int)(vEye.x/m_pBackground->m_projectInfo.m_sXSize);
//	int nCamZ = (int)(vEye.z/m_pBackground->m_projectInfo.m_sYSize);
//	if(nCamX < 0)
//	{
//		nCamX = 0;
//		vEye.x = m_pBackground->m_projectInfo.m_sXSize*0.5f;
//	}
//	if(nCamX >= m_pBackground->m_projectInfo.m_sXSize)
//	{
//		nCamX = m_pBackground->m_projectInfo.m_sXSize - 1;
//		vEye.x = (nCamX*m_pBackground->m_projectInfo.m_sXSize - 1) - m_pBackground->m_projectInfo.m_sXSize*0.5f;
//	}
//	if(nCamZ < 0)
//	{
//		nCamZ = 0;
//		vEye.z = m_pBackground->m_projectInfo.m_sYSize*0.5f;
//	}
//	if(nCamZ >= m_pBackground->m_projectInfo.m_sYSize)
//	{
//		nCamZ = m_pBackground->m_projectInfo.m_sYSize - 1;
//		vEye.z = (nCamX*m_pBackground->m_projectInfo.m_sYSize - 1) - m_pBackground->m_projectInfo.m_sYSize*0.5f;
//	}
//
//	if(m_pBackground->IntersectTriangle(vEye,vDir,m_pBackground->m_pTileVertexArray[nCamX*(m_pBackground->m_sYSize+1)+nCamZ].pos,
//		m_pBackground->m_pTileVertexArray[nCamX*(m_pBackground->m_sYSize+1)+(nCamZ+1)].pos,m_pBackground->m_pTileVertexArray[(nCamX+1)*(m_pBackground->m_sYSize+1)+(nCamZ+1)].pos,
//		&fDist, &a, &b ))
//	{
//		vEye = vEye + vDir*fDist;
//	}
//	else if(m_pBackground->IntersectTriangle(vEye,vDir,m_pBackground->m_pTileVertexArray[nCamX*(m_pBackground->m_sYSize+1)+nCamZ].pos,
//		m_pBackground->m_pTileVertexArray[(nCamX+1)*(m_pBackground->m_sYSize+1)+(nCamZ+1)].pos,m_pBackground->m_pTileVertexArray[(nCamX+1)*(m_pBackground->m_sYSize+1)+nCamZ].pos,
//		&fDist, &a, &b ))
//	{
//		vEye = vEye + vDir*fDist;
//	}
//	vEye -= vDir*300.0f; 
//	m_pCamera->SetViewParams(vEye,vEye + vLookat,vUp);

	m_pCamera->InitCam();
	D3DXVECTOR3 vEye,vLookat,vUp,vDir;
	vEye = m_pCamera->GetEyePt();
	vLookat = m_pCamera->GetLookatPt();
	vUp = m_pCamera->GetUpVec();
	vLookat.y = m_pBackground->m_pTileVertexArray[0].pos.y;
	vEye.y += m_pBackground->m_pTileVertexArray[0].pos.y;
	m_pCamera->SetViewParams(vEye, vLookat,vUp);
}


void CMapEditorView::OnSelchangeListTilebase() 
{
	// TODO: Add your control notification handler code here
	int re = AfxMessageBox("Do you want to set a new base file?\n(Data will be initialized.)",MB_YESNO);
	if(re==IDYES)
	{
		int num = m_ctrlBaseTileList.GetCurSel();
		m_nBaseTileTextype = num;
		m_pBackground->SetBaseTile(num);
	}
	else if(re==IDNO)
	{
		return;
	}
}

void CMapEditorView::OnCameraSet() 
{
	// TODO: Add your command handler code here
/*	while(1)
	{
		D3DXVECTOR3 vDirect = m_vLookat - m_vEye;
		D3DXVec3Normalize(&vDirect, &vDirect);
//		zDelta /= WHEEL_DELTA/24;
		if(m_vEye.y<108.0f)
		{
			m_vEye -= (vDirect);
			m_pCamera->SetViewParams(m_vEye,m_vLookat,m_vUp);
		}
		else if(m_vEye.y>112.0f)
		{
			m_vEye += (vDirect);
			m_pCamera->SetViewParams(m_vEye,m_vLookat,m_vUp);
		}
		else 
		{
			break;
		}
	}
	m_pCamera->SetViewParams(m_vEye,m_vLookat,m_vUp);
*/
}

void CMapEditorView::OnFlyingView() 
{
	// TODO: Add your command handler code here
	m_bFlyingViewMax = !m_bFlyingViewMax;	
}

void CMapEditorView::OnUpdateFlyingView(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
	
}

void CMapEditorView::OnMinimapView() 
{
	// TODO: Add your command handler code here
	m_bCheckMiniMapView = !m_bCheckMiniMapView;
}

void CMapEditorView::OnUpdateMinimapView(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
	
}


void CMapEditorView::OnCheckObjectalpha() 
{
	// TODO: Add your control notification handler code here
	m_checkAlphaBlending = !m_checkAlphaBlending;
}


void CMapEditorView::OnButtonInserttile2() 
{
	// TODO: Add your control notification handler code here
	CInsertTileDlg2	dlg;
	if(dlg.DoModal()==IDOK)
	{
	}
}

void CMapEditorView::OnButtonObject() 
{
	// TODO: Add your command handler code here
	m_bCheckObject = !m_bCheckObject;
	if(m_bCheckObject)
	{
		m_dlgObjectSet.ShowWindow(SW_SHOW);
	}
	else
	{
		m_dlgObjectSet.SetRenderState();
		m_dlgObjectSet.m_pObject = NULL;
				
		m_dlgObjectSet.ShowWindow(SW_HIDE);
	}

}

void CMapEditorView::OnUpdateButtonObject(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
	
}

void CMapEditorView::OnButtonMonster() 
{
	// TODO: Add your command handler code here
	m_bCheckMonsterSet = !m_bCheckMonsterSet;
	if(m_bCheckMonsterSet)
		m_dlgMonsterSet.ShowWindow(SW_SHOW);
	else
	{
		m_dlgMonsterSet.ShowWindow(SW_HIDE);
	}
	
}

void CMapEditorView::OnUpdateButtonMonster(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
}

void CMapEditorView::OnButtonTileSetInsert() 
{
	// TODO: Add your control notification handler code here
	CNewTileSetDlg	dlg;
	if(dlg.DoModal()==IDOK)
	{
		// Tile Set File 로딩
		int usetileset;
		CFile tileSetFile;
		char strpath[256];
		_chdir(m_strCurrentDir);
		wsprintf(strpath,"TileSet");
		TileSetInfo tileset;
		if(tileSetFile.Open(strpath, CFile::modeReadWrite))
		{
			tileSetFile.Seek(20,CFile::begin);
			tileSetFile.Read(&usetileset,sizeof(int));
			usetileset++;
			tileSetFile.Seek(20,CFile::begin);
			tileSetFile.Write(&usetileset,sizeof(int));
			tileSetFile.Seek(sizeof(tileset)*(usetileset-1),CFile::current);
			tileset.index = usetileset-1;
			strcpy(tileset.TileSetName,dlg.m_strTileSetName);
			tileSetFile.Write(&tileset,sizeof(tileset));
			tileSetFile.Close();
		}
		m_comboTileSet.AddString(tileset.TileSetName);
		wsprintf(strpath,"%s\\Tile",m_strCurrentDir);
		_chdir(strpath);
		wsprintf(strpath,"%d",usetileset-1);
		_mkdir(strpath);
	}
}

void CMapEditorView::OnSelchangeComboTileset() 
{
	// TODO: Add your control notification handler code here
	int nOldUseTileset = m_nUseTileset;
	m_nUseTileset = m_comboTileSet.GetCurSel();
	if(m_pWorkspace && m_pBackground)
	{
		int re = AfxMessageBox("Do you want to make a new Tile Set?\n(Data will be initialized.)",MB_YESNO);
		if(re==IDYES)
		{
//			int num = m_comboTileSet.GetCurSel();
			m_pBackground->m_projectInfo.m_useTileSetIndex = m_nUseTileset;
			memset(m_pBackground->m_pTileInfo, 0x00, sizeof(TILEINFO)*m_pBackground->m_sXSize*m_pBackground->m_sYSize);
			int i,j;
			for(i=0;i<m_pBackground->m_sXSize*m_pBackground->m_sYSize;i++)
			{
				m_pBackground->m_pTileInfo[i].texTileDirect1=-1;
				m_pBackground->m_pTileInfo[i].texTileDirect2=-1;
				m_pBackground->m_pTileInfo[i].texTileDirect3=-1;
				m_pBackground->m_pTileInfo[i].texTileDirect4=-1;
				m_pBackground->m_pTileInfo[i].useTexNumber = 0;
				m_pBackground->m_pTileInfo[i].useBaseTexNumber = -1;
				m_pBackground->m_pTileInfo[i].ranTexNumber = -1;
				m_pBackground->m_pTileInfo[i].waterType = 0;
				m_pBackground->m_pTileInfo[i].useTexNumber = -1;
				m_pBackground->m_pTileInfo[i].waterHeight = -1;
				m_pBackground->m_pTileInfo[i].bBaseTile = TRUE;

				m_pBackground->m_pEventInfo[i].m_dwWaterType = 0;
			}
			for(i=0;i<MAX_TEXTILE_NUM;i++)
			{
				wsprintf(m_pBackground->m_pTexFileInfo[i].name, "");
				m_pBackground->m_pTexFileInfo[i].texTileDirect1=-1;
				m_pBackground->m_pTexFileInfo[i].texTileDirect2=-1;
				m_pBackground->m_pTexFileInfo[i].texTileDirect3=-1;
				m_pBackground->m_pTexFileInfo[i].texTileDirect4=-1;
			}
			for( i=0; i<MAX_BASETILE_NUM; i++)
				for(j=0;j<MAX_BASETILERANDOM_NUM;j++)
					SAFE_RELEASE( m_pBackground->m_pTileTexture[i][j] );
			for(i=0; i<MAX_TEXTILE_NUM; i++)
				SAFE_RELEASE( m_pBackground->m_pCreateTexture[i] );
//			for(i=0; i<32*32; i++)
//				SAFE_RELEASE( m_pBackground->m_pVBRender[i] );
			for(i=0; i<64*64; i++)
				SAFE_RELEASE( m_pBackground->m_pVBRender[i] );
			// test tile
//			for(i=0;i<32;i++)
			for(i=0;i<64;i++)
			{
//				for(j=0;j<32;j++)
				for(j=0;j<64;j++)
				{
					if( FAILED( g_pD3dDev->CreateVertexBuffer( 6 * sizeof(SPRITEVERTEX),
//						0, D3DFVF_SPRITEVERTEX, D3DPOOL_MANAGED, &m_pBackground->m_pVBRender[i*32+j] ) ) )
						0, D3DFVF_SPRITEVERTEX, D3DPOOL_MANAGED, &m_pBackground->m_pVBRender[i*64+j] ) ) )
						return ;
				}
			}
			m_pBackground->m_nTexUseNumber = 0;
			m_pBackground->m_nCreateTexNumber = 0;
			m_pBackground->m_ninsertTileFileCont = 0;
			InitMapData();

		}
		else if(re==IDNO)
		{
			m_nUseTileset = nOldUseTileset;
			m_comboTileSet.SetCurSel(m_nUseTileset);
			return;
		}
	}
}


LRESULT CMapEditorView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	if(m_bCheckObject && m_dlgObjectSet && m_dlgObjectSet.m_bMoveRotation && m_dlgObjectSet.m_pObject)
	{
		m_ArcBall.m_matRotation._21 = m_dlgObjectSet.m_pObject->m_vUp.x;
		m_ArcBall.m_matRotation._22 = m_dlgObjectSet.m_pObject->m_vUp.y;
		m_ArcBall.m_matRotation._23 = m_dlgObjectSet.m_pObject->m_vUp.z;
		m_ArcBall.m_matRotation._31 = m_dlgObjectSet.m_pObject->m_vVel.x;
		m_ArcBall.m_matRotation._32 = m_dlgObjectSet.m_pObject->m_vVel.y;
		m_ArcBall.m_matRotation._33 = m_dlgObjectSet.m_pObject->m_vVel.z;
		m_ArcBall.m_matTranslation._41 = m_dlgObjectSet.m_pObject->m_vPos.x;
		m_ArcBall.m_matTranslation._42 = m_dlgObjectSet.m_pObject->m_vPos.y;
		m_ArcBall.m_matTranslation._43 = m_dlgObjectSet.m_pObject->m_vPos.z;
		m_ArcBall.HandleMouseMessages( CD3DApplication::m_hWnd, message, wParam, lParam );
		
		ObjectMoveRotation();
	}
	
	return CFormView::WindowProc(message, wParam, lParam);
}

void CMapEditorView::ObjectMoveRotation()
{
	if(m_dlgObjectSet.m_pObject)
	{
		D3DXMATRIX mat;
		mat = *m_ArcBall.GetRotationMatrix();
 		m_dlgObjectSet.m_pObject->m_vUp.x = mat._21;
		m_dlgObjectSet.m_pObject->m_vUp.y = mat._22;
		m_dlgObjectSet.m_pObject->m_vUp.z = mat._23;
		m_dlgObjectSet.m_pObject->m_vVel.x = mat._31;
		m_dlgObjectSet.m_pObject->m_vVel.y = mat._32;
		m_dlgObjectSet.m_pObject->m_vVel.z = mat._33;
		mat = *m_ArcBall.GetTranslationMatrix();
		m_dlgObjectSet.m_pObject->m_vPos.x = mat._41;
//		m_dlgObjectSet.m_pObject->m_vPos.y = mat._42;
		m_dlgObjectSet.m_pObject->m_vPos.z = mat._43;
	}
}

void CMapEditorView::OnButtonPicture() 
{
	// TODO: Add your command handler code here
	if(m_pBackground)
	{
		m_pBackground->SaveMiniMap();
	}
}

void CMapEditorView::OnUpdateButtonPicture(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
//	pCmdUI->Enable(TRUE);
//	pCmdUI->SetCheck(FALSE);
	
}
// by dhkwon, 100727 기능 삭제
void CMapEditorView::OnButtonLoaddata() 
{
	// TODO: Add your command handler code here
	AfxMessageBox("Feature is currently not being used.",MB_OK);
/*
	if(m_pBackground)
	{
		CFileDialog dlg(TRUE,"tga",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT , "tga Files (*.tga)|*.tga||", NULL);
		if(dlg.DoModal() == IDOK)
		{
			POSITION pos = dlg.GetStartPosition();
			char* pdest;
			CString str;
			while(pos)
			{
				CString strPath = dlg.GetNextPathName( pos );

				pdest = strrchr( (LPCTSTR)strPath, '\\' );
				str = pdest+1;
			}
			m_pBackground->SetHeightData(str);
		}
	}
	else
	{
		AfxMessageBox("열려있는 프로젝트가 없습니다.",MB_OK);
	}
	*/
}

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


void CMapEditorView::OnButtonLoaddata256() 
{
	// TODO: Add your command handler code here
	CSetHeightDlg * pDlg = new CSetHeightDlg();
	if(pDlg->DoModal()==IDOK)
	{
		if(m_pBackground)
		{
			CFileDialog dlg(TRUE,"tga",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT , "tga Files (*.tga)|*.tga||", NULL);
			if(dlg.DoModal() == IDOK)
			{
// by dhkwon 100727 하이트맵 디렉토리를 자유롭게 변경 가능.
//				POSITION pos = dlg.GetStartPosition();
//				char* pdest;
//				CString str;
//				while(pos)
//				{
//					CString strPath = dlg.GetNextPathName( pos );

//					pdest = strrchr( (LPCTSTR)strPath, '\\' );
//					str = pdest+1;
//				}
				CString strPath = dlg.GetPathName();
// end by dhkwon 100727 하이트맵 디렉토리를 자유롭게 변경 가능.
				m_pBackground->SetHeightData(strPath,pDlg->m_editBaseHeight,pDlg->m_editMaxHeight);
				m_editHeightMax = pDlg->m_editBaseHeight + pDlg->m_editMaxHeight;
				m_editHeightMin = pDlg->m_editBaseHeight;
				UpdateData();
			}
		}
		else
		{
			AfxMessageBox("No project is currently open.",MB_OK);
		}
	}
	delete pDlg;

}

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

void CMapEditorView::OnCheckTilesetPoint() 
{
	// TODO: Add your control notification handler code here
	m_checkTilesetPoint = TRUE;
	m_checkTilesetRegion = FALSE;
	UpdateData(FALSE);	
}

void CMapEditorView::OnCheckTilesetRegion() 
{
	// TODO: Add your control notification handler code here
	m_checkTilesetPoint = FALSE;
	m_checkTilesetRegion = TRUE;
	UpdateData(FALSE);	
}


void CMapEditorView::OnChangeEditWaterHeight() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	m_pBackground->m_projectInfo.m_fWaterHeight = m_editWaterHeight;
}

void CMapEditorView::OnButtonDeletetile() 
{
	// TODO: Add your control notification handler code here
/*
	CFile ReadFile, WriteFile;
	CString strName,str;
	char strpath1[256];
	char strpath2[256];
	int num = m_nTileTextype;
	int usetile,i,j;
	char tilename[20];

	m_ctrlTileList.GetText(num,strName);
	str.Format("선택된 타일(%s)을 삭제하시겠습니까?",strName);
  	int re = AfxMessageBox(str,MB_YESNO);

	if(re==IDYES)
	{
		// Mapdata.trd 파일 갱신
		m_ctrlTileList.DeleteString(m_nTileTextype);
		_chdir(m_strCurrentDir);
		wsprintf(strpath1,".\\Tile\\%d\\Mapdata.trd",m_pBackground->m_projectInfo.m_useTileSetIndex);
		if(ReadFile.Open(strpath1,CFile::modeRead))
		{
			_chdir(m_strCurrentDir);
			wsprintf(strpath2,".\\Tile\\%d\\Temp.trd",m_pBackground->m_projectInfo.m_useTileSetIndex);
			if(WriteFile.Open(strpath2,CFile::modeCreate | CFile::modeWrite))
			{
				ReadFile.Seek(20,CFile::begin);
				ReadFile.Read(&usetile,sizeof(int));
				usetile--;
				WriteFile.Seek(20,CFile::begin);
				WriteFile.Write(&usetile,sizeof(int));
				for(i=0;i<usetile+1;i++)
				{
					if(i!=m_nTileTextype)
					{
						ReadFile.Read(&tilename,sizeof(char)*20);
						WriteFile.Write(&tilename,sizeof(char)*20);
						for(j=0;j<MAX_BASETILERANDOM_NUM;j++)
						{
							ReadFile.Read(&tilename,sizeof(char)*20);
							WriteFile.Write(&tilename,sizeof(char)*20);
						}
					}
				}
			}
		}
		ReadFile.Close();
		CFile::Remove( strpath1 );				// 기존 파일 삭제
		WriteFile.Close();
		CFile::Rename( strpath2, strpath1 );	// 새 파일 이름을 기존이름으로 교체

		// m_pTileTexture 의 갱신
		for(i=0; i<MAX_BASETILE_NUM; i++)
		{
			for(j=0;j<MAX_BASETILERANDOM_NUM;j++)
			{
				SAFE_RELEASE( m_pBackground->m_pTileTexture[i][j] );
			}
		}
		m_pBackground->m_nTexUseNumber = 0;
		m_pBackground->m_ninsertTileFileCont = 0;
		_chdir(m_strCurrentDir);
		wsprintf(strpath1,".\\Tile\\%d\\Mapdata.trd",m_pBackground->m_projectInfo.m_useTileSetIndex);
		if(ReadFile.Open(strpath1,CFile::modeRead))
		{
			ReadFile.Seek(20,CFile::begin);
			ReadFile.Read(&usetile,sizeof(int));
			for(i=0;i<usetile;i++)
			{
				ReadFile.Read(&tilename,sizeof(char)*20);
				for(int j=0;j<MAX_BASETILERANDOM_NUM;j++)
				{
					ReadFile.Read(&tilename,sizeof(char)*20);
					_chdir(m_strCurrentDir);
					wsprintf(strpath2,".\\Res-Tile\\%s",tilename);
					m_pBackground->InsertTile(strpath2);
				}
			}
			ReadFile.Close();
		}
		// 지형을 렌더링 하기 위해 생성한 m_pCreateTexture의 갱신

	}
*/
}
void CMapEditorView::OnButtonUpdatetile() 
{
	// TODO: Add your control notification handler code here
	CString strName,str;
//	char strpath[256];
//	char buf[256];
	int i,j;
	m_ctrlTileList.GetText(m_nTileTextype,strName);
	str.Format("The selected file (% s) Would you like to update?",strName);
  	int re = AfxMessageBox(str,MB_YESNO);
	if(re==IDYES)
	{
  		re = AfxMessageBox("This takes some time to complete. Are you sure?",MB_YESNO);
		if(re==IDYES)
		{
			// 기본 베이스에 등록된 파일이 업데이트 되었을 수도 있으니 먼저 기본 타일부터 갱신한다음 생성된 파일을 갱신한다.
			CFile TileFile;
			char strpath[256];
			char filename[20];
			_chdir(m_strCurrentDir);
			wsprintf(strpath,".\\Tile\\%d\\Mapdata.trd",m_pBackground->m_projectInfo.m_useTileSetIndex);
			if(TileFile.Open(strpath, CFile::modeRead))
			{
				TileFile.Seek(20 + 4 + 23*m_nTileTextype*20 + 20,CFile::begin);	// 20 : 헤더, 4 : 타일셋에 쓰인 타일종류수, 22*m_nTileTextype*20 : 몇번째 타일인지, 20 : 대표명
				for(i=0;i<22;i++)
				{
					TileFile.Read(filename,sizeof(char)*20);
					_chdir(m_strCurrentDir);
					wsprintf(strpath,".\\Res-Tile\\%s",filename);
					SAFE_RELEASE(m_pBackground->m_pTileTexture[m_nTileTextype][i]);
					D3DUtil_CreateTexture( g_pD3dDev, strpath, &m_pBackground->m_pTileTexture[m_nTileTextype][i] ); 
				}
				TileFile.Close();
			}
			// 기본 베이스에 등록된 파일을 업데이트 했으니 생성된 파일을 업데이트한다.
			for(i=0;i<m_pBackground->m_nCreateTexNumber;i++)
			{
				BYTE bUpdate = 0;
				if(m_pBackground->m_pTexFileInfo[i].texTileDirect1 == m_nTileTextype)
					bUpdate++;
				if(m_pBackground->m_pTexFileInfo[i].texTileDirect2 == m_nTileTextype)
					bUpdate++;
				if(m_pBackground->m_pTexFileInfo[i].texTileDirect3 == m_nTileTextype)
					bUpdate++;
				if(m_pBackground->m_pTexFileInfo[i].texTileDirect4 == m_nTileTextype)
					bUpdate++;
				if(bUpdate)
				{
					// 업데이트 하기 위해 베이스 타일로 셋팅
					D3DLOCKED_RECT d3dlr,d3dlr1;
//					int k = rand()%10;
					int k = rand()%BASETILE_CENTER_NUM;
					if(bUpdate == 4 && m_pBackground->m_pTexFileInfo[i].texTileDirect1 == m_nBaseTileTextype)
						k = m_pBackground->m_pTexFileInfo[i].ranTexNumber;
					m_pBackground->m_pCreateTexture[i]->LockRect( 0, &d3dlr, 0, 0 );
					m_pBackground->m_pTileTexture[m_nBaseTileTextype][k]->LockRect( 0, &d3dlr1, 0, 0 );
					DWORD* pDstRow = (DWORD*)d3dlr.pBits;
					DWORD* pDstRow1 = (DWORD*)d3dlr1.pBits;
					DWORD* pDst16,*pSrc1;
					pDst16 = (DWORD*)pDstRow;
					pSrc1 = (DWORD*)pDstRow1;
					for(int y=0; y < 128; y++ )
					{
						for(int x=0; x < 128; x++ )
						{
							*pDst16 = (DWORD)((*pSrc1));
							pSrc1++;
							pDst16++;
						}
					}
					m_pBackground->m_pTileTexture[m_nBaseTileTextype][k]->UnlockRect(0);
					m_pBackground->m_pCreateTexture[i]->UnlockRect(0);
					// 4 귀퉁이에 셋팅된 타일을 검색하여 생성해 나간다.					
					for(j=0;j<m_pBackground->m_nTexUseNumber+1;j++)
					{
						if(m_pBackground->m_pTexFileInfo[i].texTileDirect1 == j && m_pBackground->m_pTexFileInfo[i].texTileDirect1 != m_nBaseTileTextype)
						{
							CreateChangeTexture(i,j);
						}
						else if(m_pBackground->m_pTexFileInfo[i].texTileDirect2 == j && m_pBackground->m_pTexFileInfo[i].texTileDirect2 != m_nBaseTileTextype)
						{
							CreateChangeTexture(i,j);
						}
						else if(m_pBackground->m_pTexFileInfo[i].texTileDirect3 == j && m_pBackground->m_pTexFileInfo[i].texTileDirect3 != m_nBaseTileTextype)
						{
							CreateChangeTexture(i,j);
						}
						else if(m_pBackground->m_pTexFileInfo[i].texTileDirect4 == j && m_pBackground->m_pTexFileInfo[i].texTileDirect4 != m_nBaseTileTextype)
						{
							CreateChangeTexture(i,j);
						}
					}
				}
			}
		}
	}
}

void CMapEditorView::CreateChangeTexture(int num, int nTargetIndex)
{
	int d[4];
	d[0] = m_pBackground->m_pTexFileInfo[num].texTileDirect1;
	d[1] = m_pBackground->m_pTexFileInfo[num].texTileDirect2;
	d[2] = m_pBackground->m_pTexFileInfo[num].texTileDirect3;
	d[3] = m_pBackground->m_pTexFileInfo[num].texTileDirect4;

	int type,tileType,tileType2 = 0;
	if(d[0] == nTargetIndex)
		type = 0;
	else if(d[1] == nTargetIndex)
		type = 1;
	else if(d[2] == nTargetIndex)
		type = 2;
	else if(d[3] == nTargetIndex)
		type = 3;

	switch(type)
	{
		case 0:
		{
			if(d[0]==d[1])
			{
				if(d[1]==d[2])
				{
					if(d[2]==d[3])
					{
						tileType = m_pBackground->m_pTexFileInfo[num].ranTexNumber;
					}
					else
					{
						tileType = BASETILE_CENTER_NUM + 9;
					}
				}
				else
				{
					if(d[0]==d[3])
					{
						tileType = BASETILE_CENTER_NUM + 8;
					}
					else
					{
						tileType = BASETILE_CENTER_NUM + 4;
					}
				}
			}
			else
			{
				if(d[0]==d[3])
				{
					if(d[3]==d[2])
					{
						tileType = BASETILE_CENTER_NUM + 11;
					}
					else
					{
						tileType = BASETILE_CENTER_NUM + 7;
					}
				}
				else
				{
					tileType = BASETILE_CENTER_NUM + 0;
					if(d[0]==d[2])
					{
						tileType2 = BASETILE_CENTER_NUM + 2;
					}
				}
			}
			break;
		}
		case 1:
		{
			if(d[1]==d[2])
			{
				if(d[2]==d[3])
				{
					tileType = BASETILE_CENTER_NUM + 10;
				}
				else
				{
					tileType = BASETILE_CENTER_NUM + 5;
				}
			}
			else
			{
				tileType = BASETILE_CENTER_NUM + 1;
				if(d[1] == d[3])
				{
					tileType2 = BASETILE_CENTER_NUM + 3;
				}
			}
			break;
		}
		case 2:
		{
			if(d[2]==d[3])
			{
				tileType = BASETILE_CENTER_NUM + 6;
			}
			else
			{
				tileType = BASETILE_CENTER_NUM + 2;
			}
			break;
		}
		case 3:
		{
			tileType = BASETILE_CENTER_NUM + 3;
			break;
		}
	}

    D3DLOCKED_RECT d3dlr,d3dlr1,d3dlr2;

	m_pBackground->m_pCreateTexture[num]->LockRect( 0, &d3dlr, 0, 0 );
	m_pBackground->m_pTileTexture[nTargetIndex][tileType]->LockRect( 0, &d3dlr1, 0, 0 );
	if(tileType2 !=0 )
		m_pBackground->m_pTileTexture[nTargetIndex][tileType2]->LockRect( 0, &d3dlr2, 0, 0 );

	DWORD* pDstRow = (DWORD*)d3dlr.pBits;
	DWORD* pDstRow1 = (DWORD*)d3dlr1.pBits;
	DWORD* pDstRow2;
	if(tileType2 !=0 )
		pDstRow2 = (DWORD*)d3dlr2.pBits;

	DWORD* pDst16,*pSrc1,*pSrc2;
	DWORD bAlpha; // 4-bit measure of pixel intensity
	BYTE bRed1,bGreen1, bBlue1;
	BYTE bRed2,bGreen2, bBlue2;

	pDst16 = (DWORD*)pDstRow;
	pSrc1 = (DWORD*)pDstRow1;
	if(tileType2 !=0 )
		pSrc2 = (DWORD*)pDstRow2;

	for(int y=0; y < 128; y++ )
	{
		for(int x=0; x < 128; x++ )
		{
			bAlpha =  (DWORD)((*pSrc1)  >> 24);
			if(bAlpha == 255)
			{
				*pDst16 = (DWORD)((*pSrc1));
			}
			else if(bAlpha > 0)
			{
				bRed2 = (BYTE)(*pSrc1  >> 16);
				bGreen2 = (BYTE)(*pSrc1  >> 8);
				bBlue2 = (BYTE)(*pSrc1);
				bRed2 = bRed2 * bAlpha / 255;
				bGreen2 = bGreen2 * bAlpha / 255;
				bBlue2 = bBlue2 * bAlpha / 255;

				bRed1 = (BYTE)(*pDst16  >> 16);
				bGreen1 = (BYTE)(*pDst16  >> 8);
				bBlue1 = (BYTE)(*pDst16);
				bRed1 = bRed1 * (255-bAlpha) / 255;
				bGreen1 = bGreen1 * (255-bAlpha) / 255;
				bBlue1 = bBlue1 * (255-bAlpha) / 255;

				*pDst16 = D3DCOLOR_ARGB(0x00,bRed1,bGreen1,bBlue1) + D3DCOLOR_ARGB(0xFF,bRed2,bGreen2,bBlue2);
			}
			if(tileType2 !=0 )
			{
				bAlpha =  (DWORD)((*pSrc2)  >> 24);
				if(bAlpha == 255)
				{
					*pDst16 = (DWORD)((*pSrc2));
				}
				else if(bAlpha > 0)
				{
					bRed2 = (BYTE)(*pSrc2  >> 16);
					bGreen2 = (BYTE)(*pSrc2  >> 8);
					bBlue2 = (BYTE)(*pSrc2);
					bRed2 = bRed2 * bAlpha / 255;
					bGreen2 = bGreen2 * bAlpha / 255;
					bBlue2 = bBlue2 * bAlpha / 255;

					bRed1 = (BYTE)(*pDst16  >> 16);
					bGreen1 = (BYTE)(*pDst16  >> 8);
					bBlue1 = (BYTE)(*pDst16);
					bRed1 = bRed1 * (255-bAlpha) / 255;
					bGreen1 = bGreen1 * (255-bAlpha) / 255;
					bBlue1 = bBlue1 * (255-bAlpha) / 255;

					*pDst16 = D3DCOLOR_ARGB(0x00,bRed1,bGreen1,bBlue1) + D3DCOLOR_ARGB(0xFF,bRed2,bGreen2,bBlue2);
				}
			}
			pSrc1++;
			if(tileType2 !=0 )
				pSrc2++;
			pDst16++;
		}
	}
	// Done updating texture, so clean up used objects
	if(tileType2 !=0 )
		m_pBackground->m_pTileTexture[nTargetIndex][tileType2]->UnlockRect(0);
	m_pBackground->m_pTileTexture[nTargetIndex][tileType]->UnlockRect(0);
	m_pBackground->m_pCreateTexture[num]->UnlockRect(0);

	char buf[256];
	wsprintf(buf,"05%06d",num);
	strcpy(m_pBackground->m_pTexFileInfo[num].name,buf);
	char strpathtexture[256];
	_chdir(m_strCurrentDir);
	wsprintf(strpathtexture,".\\Tile\\%d\\128\\%s.bmp",m_pBackground->m_projectInfo.m_useTileSetIndex,buf);
	HRESULT hr;
//	CFile::Remove(strpathtexture);
	hr = D3DXSaveTextureToFile(strpathtexture,D3DXIFF_BMP,m_pBackground->m_pCreateTexture[num],NULL);
	if(hr)
		int kkkk = 0;
}

void CMapEditorView::OnButtonSetlight() 
{
	// TODO: Add your command handler code here
	m_bCheckLightSet = !m_bCheckLightSet;
	if(m_bCheckLightSet)
	 	m_dlgLightSet.ShowWindow(SW_SHOW);
	else
		m_dlgLightSet.ShowWindow(SW_HIDE);
}

void CMapEditorView::OnUpdateButtonSetlight(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
}

void CMapEditorView::OnChangeEditHeightmax() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnChangeEditHeightmin() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnButtonFlightmin() 
{
	// TODO: Add your command handler code here
	m_bFlyingViewMin = !m_bFlyingViewMin;	
	
}

void CMapEditorView::OnUpdateButtonFlightmin(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
}

void CMapEditorView::OnButtonObjectturnright() 
{
	// TODO: Add your control notification handler code here
	m_bObjectDir++;
	if(m_bObjectDir==4)
		m_bObjectDir = 0;
}

void CMapEditorView::OnButtonObjectturnleft() 
{
	// TODO: Add your control notification handler code here
	if(m_bObjectDir==0)
		m_bObjectDir = 3;
	else
		m_bObjectDir--;
}

void CMapEditorView::OnButtonTilesetDelete() 
{
	// TODO: Add your control notification handler code here
	if(m_pWorkspace && !m_pBackground)
	{
		int re = AfxMessageBox("Selected Tile Set (including generated files) will be erased. Are you sure you wish to continue?",MB_YESNO);
		if(re == IDYES)
		{
			int re2 = AfxMessageBox("All the projects selected from a group of three tiles will be removed. Do you wish to continue?",MB_YESNO);
			if(re2 == IDYES)
			{
				int i,cont = 0;
				WORKSPACE workspaceinfo;
				CString strWorkspacename, strNewFilename;//, strTemp;
				_chdir(m_strCurrentDir);
				strWorkspacename.Format(".\\%s\\%s.wok",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
				strNewFilename.Format(".\\%s\\%s.tmp",m_pWorkspace->workspaceName,m_pWorkspace->workspaceName);
				PROJECTINFO project;
				CFile ReadFile,WriteFile;
				CFileHeader header;
				header.m_dwFileType = _WORKSPACE;
				if(ReadFile.Open(strWorkspacename,CFile::modeRead) && WriteFile.Open(strNewFilename,CFile::modeCreate|CFile::modeWrite))
				{
					WriteFile.Write(&header,sizeof(header));
					ReadFile.Seek(20+sizeof(WORKSPACE),CFile::begin);
					WriteFile.Seek(20+sizeof(WORKSPACE),CFile::begin);
					for(i=0;i<m_pWorkspace->numberOfProject;i++)
					{
						ReadFile.Read(&project,sizeof(PROJECTINFO));
						if(project.m_useTileSetIndex > m_nUseTileset)
						{
							project.m_useTileSetIndex--;
							WriteFile.Write(&project,sizeof(PROJECTINFO));
							char str[256];
							CFile MakeProject;
							CFileHeader Projectheader;
							Projectheader.m_dwFileType = _PROJECTINFO;
							_chdir(m_strCurrentDir);
							wsprintf(str,".\\%s\\%s\\%s.poj",m_pWorkspace->workspaceName,project.m_strProjectName,project.m_strProjectName);
							if(MakeProject.Open(str,CFile::modeReadWrite ))
							{
								MakeProject.Write(&Projectheader,sizeof(Projectheader));
								MakeProject.Seek(20,CFile::begin);
								MakeProject.Write(&project,sizeof(PROJECTINFO));
								MakeProject.Close();
							}
							cont++;
						}
						else if(project.m_useTileSetIndex == m_nUseTileset)
						{
							// 현재 프로젝트 삭제
							;
						}
						else
						{
							WriteFile.Write(&project,sizeof(PROJECTINFO));
							cont++;
						}
					}
					strcpy(workspaceinfo.workspaceName,m_pWorkspace->workspaceName);
					workspaceinfo.numberOfProject = cont;
					WriteFile.Seek(20,CFile::begin);
					WriteFile.Write(&workspaceinfo,sizeof(WORKSPACE));
					WriteFile.Close();
					ReadFile.Read(&project,sizeof(PROJECTINFO));
					ReadFile.Close();
					CFileFind finder;
					if(finder.FindFile(strWorkspacename))
						CFile::Remove(strWorkspacename);
//					CFile::Remove(strWorkspacename);
					CFile::Rename(strNewFilename,strWorkspacename);
				}
				// TileSet File Update
				CString strOldTileSet, strNewTileSet;
				TileSetInfo tileset;
				int usetileset;
				_chdir(m_strCurrentDir);
				strOldTileSet.Format("TileSet");
				strNewTileSet.Format("TileSet.tmp");
				if(ReadFile.Open(strOldTileSet,CFile::modeRead) && WriteFile.Open(strNewTileSet,CFile::modeCreate|CFile::modeWrite))
				{
					ReadFile.Seek(20,CFile::begin);
					ReadFile.Read(&usetileset,sizeof(int));
					usetileset--;
					WriteFile.Seek(20,CFile::begin);
					WriteFile.Write(&usetileset,sizeof(int));
					for(i=0;i<usetileset+1;i++)
					{
						ReadFile.Read(&tileset,sizeof(TileSetInfo));
						if(i != m_nUseTileset)
							WriteFile.Write(&tileset,sizeof(TileSetInfo));
					}
					ReadFile.Close();
					WriteFile.Close();
					CFile::Remove(strOldTileSet);
					CFile::Rename(strNewTileSet,strOldTileSet);
				}
				// Delete TileSet
				CString strDir,stroldfiledir,strnewfiledir,strTemp;
				strDir.Format(".\\Tile\\%d",m_nUseTileset);
				_chdir(m_strCurrentDir);
				_chdir(strDir);
				WIN32_FIND_DATA FindFileData;
				HANDLE hFind;
				hFind = FindFirstFile("*", &FindFileData);
				while(hFind)
				{
					DeleteFile(FindFileData.cFileName);
					BOOL bCheck = FindNextFile(hFind, &FindFileData);
					if(!bCheck)
					{
						FindClose(hFind);
						break;
					}
				}
				// TileSet Sort(FileMove)
				for(i=0;i<usetileset-m_nUseTileset;i++)
				{
					_chdir(m_strCurrentDir);
					stroldfiledir.Format(".\\Tile\\%d",m_nUseTileset+1+i);
					_chdir(stroldfiledir);
					hFind = FindFirstFile("*",&FindFileData);
					while(hFind)
					{
						strnewfiledir.Format(".\\Tile\\%d\\%s",m_nUseTileset+i,FindFileData.cFileName);
						_chdir(m_strCurrentDir);
						strTemp.Format("%s\\%s",stroldfiledir,FindFileData.cFileName);
						BOOL b = MoveFile(strTemp,strnewfiledir);
						_chdir(stroldfiledir);
						BOOL bCheck = FindNextFile(hFind,&FindFileData);
						if(!bCheck)
						{
							FindClose(hFind);
							break;
						}
					}
				}
				// TileSet Last Directory Delete
				_chdir(m_strCurrentDir);
				strDir.Format(".\\Tile\\%d",usetileset);
				RemoveDirectory(strDir);
				// ComboBox Update
				m_comboTileSet.DeleteString(m_nUseTileset);
				m_nUseTileset = 0;
				m_comboTileSet.SetCurSel(m_nUseTileset);
				SAFE_DELETE( m_pWorkspace );
				m_pWorkspace = new WORKSPACE;
				m_listProjectInfo.clear(); 
				OpenWorkspace(strWorkspacename);
			}
		}
	}
}

void CMapEditorView::OnSelchangeComboTilesetscale() 
{
	// TODO: Add your control notification handler code here
	m_nTileSetScaleType = m_comboTileSetScale.GetCurSel();
}

void CMapEditorView::OnChangeEditObjectBlockcont() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnChangeEditObjectNormalcont() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnButtonObjectUpdate() 
{
	// TODO: Add your control notification handler code here
	m_nObjectNormalCont = m_editObjectNormalCont;
	m_nObjectBlockCont = m_editObjectBlockCont;
	UpdateData(FALSE);
	UpdateData(TRUE);

	_chdir(m_strCurrentDir);
	CFile WriteFile;
	if(WriteFile.Open("Object",CFile::modeCreate|CFile::modeWrite))
	{
		WriteFile.Seek(20,CFile::begin);
		WriteFile.Write(&m_nObjectNormalCont,sizeof(INT));
		WriteFile.Write(&m_nObjectBlockCont,sizeof(INT));
		WriteFile.Close();

		if(m_pObject)
		{
			m_pObject->InvalidateDeviceObjects();
			m_pObject->DeleteDeviceObjects();
			SAFE_DELETE(m_pObject);
		}

		int n = m_comboObjectSelect.GetCount();
		
		for(int i=0;i<n;i++)
		{
			m_comboObjectSelect.DeleteString(0);
		}

		m_pObject = new CObjectRender();

		m_pObject->InitDeviceObjects(); // 디바이스 초기화 와 메쉬를 로드를 한다.
		m_pObject->RestoreDeviceObjects();
	}
	else
	{
		AfxMessageBox("Object information file creation failed.",MB_OK);
	}
}

void CMapEditorView::OnCheckObjectnormal() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnButtonObjectReset() 
{
	// TODO: Add your command handler code here
	m_bEdit = !m_bEdit;
	if(m_bEdit)
	 	m_dlgEdit.ShowWindow(SW_SHOW);
	else
		m_dlgEdit.ShowWindow(SW_HIDE);
	
}

void CMapEditorView::OnUpdateButtonObjectReset(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
	
}


void CMapEditorView::OnRadioCamera() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 6;	
	UpdateData();
	
}

void CMapEditorView::OnRadioDefault() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 8;	
	UpdateData();
	
}

// iCoordW가 0보다 클경우 스크린 안쪽에 있으며, 좌표는 iCoordX, iCoordY가 된다.
void CMapEditorView::CalcObjectSourceScreenCoords(	D3DXVECTOR3 vObjPos, 
										int iScreenWidth, int iScreenHeight,
										int &iCoordX, int &iCoordY, int &iCoordW)
{
	D3DXMATRIX matWorld, matView, matConcat, matViewportScale;
	D3DXVECTOR4 vResult;
	matViewportScale = D3DXMATRIX(iScreenWidth/2.0f, 0, 0, 0,
									0, -iScreenHeight/2.0f, 0, 0,
									0, 0, 1, 0,	
									iScreenWidth/2.0f, iScreenHeight/2.0f, 0, 1);
	matView = m_pCamera->GetViewMatrix();
	D3DXMatrixIdentity(&matWorld); // no need for a world xform
	matConcat = matWorld;
	matConcat *= matView;
	matConcat *= m_pCamera->GetProjMatrix();
	matConcat *= matViewportScale;
	D3DXVec3Transform(&vResult, &vObjPos, &matConcat);
	iCoordX = (int)(vResult.x/vResult.w);
	iCoordY = (int)(vResult.y/vResult.w);
	iCoordW = (int)vResult.w;
}

void CMapEditorView::OnCheckFog() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnButtonEffect() 
{
	// TODO: Add your command handler code here
	// TODO: Add your command handler code here
	m_bEffect = !m_bEffect;
	if(m_bEffect)
	 	m_dlgEffect.ShowWindow(SW_SHOW);
	else
		m_dlgEffect.ShowWindow(SW_HIDE);
	
}

void CMapEditorView::OnUpdateButtonEffect(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
}

void CMapEditorView::OnRadioEffect() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 7;	
	UpdateData();
}

void CMapEditorView::OnButtonSetlight2() 
{
	// TODO: Add your command handler code here
	m_bCheckLightSet2 = !m_bCheckLightSet2;
	if(m_bCheckLightSet2)
	 	m_dlgLightList.ShowWindow(SW_SHOW);
	else
		m_dlgLightList.ShowWindow(SW_HIDE);
}

void CMapEditorView::OnUpdateButtonSetlight2(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
}

void CMapEditorView::OnRadioLight() 
{
	// TODO: Add your control notification handler code here
	m_nCommand = 8;	
	UpdateData();
}

void CMapEditorView::OnCheckObjectallrender() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnCheckLand() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnButtonAlllist() 
{
	// TODO: Add your command handler code here
	m_bAllList = !m_bAllList;
	if(m_bAllList)
	 	m_dlgAllList.ShowWindow(SW_SHOW);
	else
		m_dlgAllList.ShowWindow(SW_HIDE);
	
}

void CMapEditorView::OnUpdateButtonAlllist(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);	
//	pCmdUI->SetCheck(FALSE);
	
}


void CMapEditorView::ResetObjectList()
{
	int i;
	int n = m_dlgAllList.m_ListObject.GetCount();
	for(i=0;i < n;i++)
		m_dlgAllList.m_ListObject.DeleteString(n-i-1);

	int cont = 0;
	map<INT, CAtumNode *>::iterator it = m_pBackground->m_mapObjectData.begin();

	while(it != m_pBackground->m_mapObjectData.end())
	{
//		CAtumNode * pNode = it->second;
		CObjectChild * pObj = (CObjectChild *)it->second->m_pChild;
		while(pObj)
		{
			char buf[256];
//			wsprintf(buf,"%d 번째 : %d",cont++,pObj->m_nObjectNum);
			// by dhkwon, 20100708, ListBox에 ItemData 세팅 및 에디트 박스 소팅 
			if(pObj->m_info.bEventType == 0)
			{
				wsprintf(buf, "%d", pObj->m_nObjectNum, GetEventType(pObj->m_info.bEventType));
				if(pObj->m_info.bIsEvent != FALSE)
				{
					wsprintf(buf, "turn off event check of %s", buf);
					DbgOut(buf);
				}
			}
			else
			{
				wsprintf(buf, "%d(%s)", pObj->m_nObjectNum, GetEventType(pObj->m_info.bEventType));
				if(pObj->m_info.bIsEvent != TRUE)
				{
					wsprintf(buf, "turn on event check of %s", buf);
					DbgOut(buf);
				}
			}
			int index = m_dlgAllList.m_ListObject.AddString(buf);
			if( LB_ERR == index || LB_ERRSPACE == index )
			{
				ASSERT(FALSE);
				AfxMessageBox("Critical error(MapEditorView.cpp Line:5376). Please notify the developer.");
				return;
			}
			m_dlgAllList.m_ListObject.SetItemDataPtr( index, (void*)pObj );
			// by dhkwon, 20100708, ListBox에 ItemData 세팅 및 에디트 박스 소팅 
			pObj = (CObjectChild *)pObj->m_pNext;

			//m_nObjTotalCoun++;
		}
		it++;
	}
}

void CMapEditorView::OnCheckObjectallnotrender() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
}

void CMapEditorView::OnButtonLoadObject() 
{
	CLoadObjectDlg *pDlg = new CLoadObjectDlg;
	if ( pDlg->DoModal() == IDOK )
	{
		D3DXMATRIX mat;
		D3DXMatrixIdentity( &mat );
		CSkinnedMesh * pMesh = new CSkinnedMesh;
		pMesh->InitDeviceObjects();
		char szFilename[256];
		wsprintf( szFilename, "%s", pDlg->m_szFileName );
		pMesh->LoadMeshHierarchy( szFilename );
		pMesh->SetWorldMatrix( mat );
		pMesh->Tick( 0.0f );
		pMesh->LoadMatrix();
//		pMesh->LoadObject( szFilename );
		for ( int nCount = 0;nCount < pMesh->m_nObjectCount;nCount++ )
		{
			SetObject( pMesh->m_infoObject[nCount].mObjectMatrix, pMesh->m_infoObject[nCount].szObjectName );
		}
		pMesh->DeleteDeviceObjects();
		SAFE_DELETE( pMesh );
	}
	delete pDlg;
	pDlg = NULL;
}

void CMapEditorView::OnUpdateButtonLoadObject(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	pCmdUI->Enable(TRUE);
//	pCmdUI->SetCheck(FALSE);
}

struct VERTEX
{
	D3DXVECTOR3 vPos;
	D3DXVECTOR3 vNor;
	FLOAT	tu ;
	FLOAT	tv; 
};

struct MYINDEX
{
	DWORD _0,_1,_2;
};

#define D3DFVF_VERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)

void CMapEditorView::OnButtonSaveX() 
{

/*	
	HRESULT hr;
	_chdir(m_strCurrentDir);
	CFile cfXFile;
	char szFilename[256];
	char szFilename2[256];
	wsprintf(szFilename,".\\%s\\%s\\%s.x",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);
	wsprintf(szFilename2,".\\%s\\%s\\%s2.x",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);

	VERTEX* VBuffer = NULL;
	short* IBuffer = NULL;
	DWORD* MBuffer = NULL;
	LPD3DXMESH pSysMesh;
	LPD3DXMESH pOptiMesh;
	LPD3DXMESH pMesh;
	int nSize = m_pBackground->m_projectInfo.m_sXSize / 4;
	DWORD nTriangleNum = nSize * nSize * 2;
	DWORD nVertexNum = (nSize + 1) * (nSize + 1);
	hr = D3DXCreateMeshFVF(nTriangleNum, nVertexNum, D3DXMESH_DYNAMIC  ,D3DFVF_VERTEX,
						m_pd3dDevice, &pSysMesh);


	VERTEX *pVertex = new VERTEX[nVertexNum];
	int i,j;
	for ( i = 0;i < nSize + 1;i++ )
	{
		for ( j = 0;j < nSize + 1;j++ )
		{
			pVertex[i*nSize + j].vPos = m_pBackground->m_pTileVertexArray[i * (m_pBackground->m_projectInfo.m_sYSize + 1) + j].pos;
			pVertex[i*nSize + j].vNor = m_pBackground->m_pTileVertexArray[i * (m_pBackground->m_projectInfo.m_sYSize + 1) + j].nor;
		}
	}
	pSysMesh->LockVertexBuffer(D3DLOCK_DISCARD  , (BYTE**)&VBuffer);
	memcpy(VBuffer, pVertex, nVertexNum * sizeof(VERTEX) );
	pSysMesh->UnlockVertexBuffer();

	MYINDEX idx;
	MYINDEX *pIdx = new MYINDEX[nTriangleNum];

	for ( i = 0;i < nSize;i++ )
	{
		for ( j = 0;j < nSize;j++ )
		{
			idx._0 = i * (nSize + 1) + j;
			idx._1 = i * (nSize + 1) + j + 1;
			idx._2 = (i + 1) * (nSize + 1) + j + 1;
			pIdx[2 * (i * nSize + j)] = idx;

			idx._0 = i * (nSize + 1) + j;
			idx._1 = (i + 1) * (nSize + 1) + j + 1;
			idx._2 = (i + 1) * (nSize + 1) + j;
			pIdx[2 * (i * nSize + j) + 1] = idx;
		}
	}
	pSysMesh->LockIndexBuffer(D3DLOCK_DISCARD ,(BYTE**)&IBuffer);
	memcpy(IBuffer, pIdx, sizeof(MYINDEX)*nTriangleNum );
	pSysMesh->UnlockIndexBuffer();

	DWORD *pMaterial = new DWORD[nTriangleNum];

	for( int kkk = 0;kkk < nTriangleNum;kkk++ )
	{
		pMaterial[kkk] = 0x00000000;
	}
//	memset(pMaterial,0x00,sizeof(DWORD)*nTriangleNum);

	pSysMesh->LockAttributeBuffer(D3DLOCK_DISCARD, &MBuffer);
	memcpy(MBuffer, pMaterial, sizeof(DWORD)*nTriangleNum);
	pSysMesh->UnlockAttributeBuffer();


	LPD3DXBUFFER pAdjacencyBuffer;
	D3DXCreateBuffer(nTriangleNum*3*sizeof(DWORD), &pAdjacencyBuffer);
	hr = pSysMesh->GenerateAdjacency(0.0f, (DWORD*)pAdjacencyBuffer->GetBufferPointer());

	DWORD mmmm = pAdjacencyBuffer->GetBufferSize();

	D3DXWELDEPSILONS Epsilons;
	memset(&Epsilons, 0, sizeof(D3DXWELDEPSILONS));
	D3DXWeldVertices( pSysMesh, &Epsilons, (DWORD*)pAdjacencyBuffer->GetBufferPointer(), 
                                            NULL, NULL, NULL );

	
	pSysMesh->Optimize( D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE ,
								 (DWORD*)pAdjacencyBuffer->GetBufferPointer(),
								 NULL, NULL, NULL, &pOptiMesh);

	pOptiMesh->CloneMeshFVF( D3DXMESH_MANAGED | D3DXMESH_VB_SHARE, D3DFVF_VERTEX,
										  m_pd3dDevice, &pMesh );



	D3DXMATERIAL material;
	memset( &material, 0x00, sizeof(D3DXMATERIAL) );
	material.MatD3D.Ambient.r = 1.0f;
	material.MatD3D.Ambient.g = 1.0f;
	material.MatD3D.Ambient.b = 1.0f;
	material.MatD3D.Diffuse.r = 1.0f;
	material.MatD3D.Diffuse.g = 1.0f;
	material.MatD3D.Diffuse.b = 1.0f;
	material.pTextureFilename = "map.tga";
//	D3DXSaveMeshToX(szFilename,pMesh,(DWORD*)pAdjacencyBuffer->GetBufferPointer(),&material,1,DXFILEFORMAT_TEXT);
	D3DXSaveMeshToX(szFilename2,pMesh,(DWORD*)pAdjacencyBuffer->GetBufferPointer(),NULL,0,DXFILEFORMAT_TEXT);
	
	pAdjacencyBuffer->Release();
	pSysMesh->Release();
	pOptiMesh->Release();

	SAFE_DELETE_ARRAY( pVertex );
	SAFE_DELETE_ARRAY( pIdx );
	SAFE_DELETE_ARRAY( pMaterial );
*/		

	if( !m_pBackground )
	{
		AfxMessageBox( "No project is currently open." ,MB_OK );
		return;
	}
	// by dhkwon, 2010.0715 X파일 저장 방식: 새로운 X파일 저장 방식
	SaveXFile(m_pBackground->m_projectInfo.m_sXSize,0,0);  

/*
	// by dhkwon, 2010.0715 X파일 저장 방식: 분할 저장 방식, 예전 방식
	if(m_pBackground->m_projectInfo.m_sXSize == 512) 
	{
		int nCheckSize = m_pBackground->m_projectInfo.m_sXSize / 8;

		for ( int i = 0;i < 8;i++)
		{
			for ( int j = 0;j < 8;j++)
			{
				SaveXFileOld(nCheckSize,i,j);  
			}
		}
	}
	else
	// 2005.6.13 by dhkwon, 사이즈가 384인 경우 6x6으로 X파일 생성(맵의 사이드 오브젝트 뽑기 위함)
	if(m_pBackground->m_projectInfo.m_sXSize == 384) 
	{
		int nCheckSize = m_pBackground->m_projectInfo.m_sXSize / 6;

		for ( int i = 0;i < 6;i++)
		{
			for ( int j = 0;j < 6;j++)
			{
				SaveXFileOld(nCheckSize,i,j);  
			}
		}
	}
	else
	{
		int nCheckSize = m_pBackground->m_projectInfo.m_sXSize / 4;

		for ( int i = 0;i < 4;i++)
		{
			for ( int j = 0;j < 4;j++)
			{
				SaveXFileOld(nCheckSize,i,j);  
			}
		}
	}
*/
}

void CMapEditorView::SaveXFileOld(int nSize, int x, int z)
{
	HRESULT hr;
	_chdir(m_strCurrentDir);
	char szFilename[256];
//	char szFilename2[256];
	wsprintf(szFilename,".\\%s\\%s\\%s_%d%d.x",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName,x,z);

	VERTEX* VBuffer = NULL;
	short* IBuffer = NULL;
	DWORD* MBuffer = NULL;
	LPD3DXMESH pSysMesh;
//	int nSize = 64;//m_pBackground->m_projectInfo.m_sXSize;
	DWORD nTriangleNum = nSize * nSize * 2;
	DWORD nVertexNum = nTriangleNum * 3;
	hr = D3DXCreateMeshFVF(nTriangleNum, nVertexNum, D3DXMESH_MANAGED|D3DXMESH_32BIT, D3DFVF_VERTEX,
						m_pd3dDevice, &pSysMesh);
	if(hr == E_OUTOFMEMORY)
	{
		ASSERT(FALSE);
	}
	if(hr == D3DERR_INVALIDCALL)
	{
		ASSERT(FALSE);
	}

	VERTEX *pVertex = new VERTEX[nVertexNum];
	int i,j;
	for ( i = 0;i < nSize;i++ )
	{
		for ( j = 0;j < nSize;j++ )
		{
			pVertex[i*nSize*6 + j*6 + 0].vPos = m_pBackground->m_pTileVertexArray[(i + nSize * x) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)].pos;
			pVertex[i*nSize*6 + j*6 + 0].vNor = m_pBackground->m_pTileVertexArray[(i + nSize * x) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)].nor;
			pVertex[i*nSize*6 + j*6 + 0].tu = 0;
			pVertex[i*nSize*6 + j*6 + 0].tv = 0;

			pVertex[i*nSize*6 + j*6 + 1].vPos = m_pBackground->m_pTileVertexArray[(i + nSize * x) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)+1].pos;
			pVertex[i*nSize*6 + j*6 + 1].vNor = m_pBackground->m_pTileVertexArray[(i + nSize * x) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)+1].nor;
			pVertex[i*nSize*6 + j*6 + 1].tu = 1;
			pVertex[i*nSize*6 + j*6 + 1].tv = 0;

			pVertex[i*nSize*6 + j*6 + 2].vPos = m_pBackground->m_pTileVertexArray[((i + nSize * x)+1) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)+1].pos;
			pVertex[i*nSize*6 + j*6 + 2].vNor = m_pBackground->m_pTileVertexArray[((i + nSize * x)+1) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)+1].nor;
			pVertex[i*nSize*6 + j*6 + 2].tu = 1;
			pVertex[i*nSize*6 + j*6 + 2].tv = 1;

			pVertex[i*nSize*6 + j*6 + 3].vPos = m_pBackground->m_pTileVertexArray[(i + nSize * x) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)].pos;
			pVertex[i*nSize*6 + j*6 + 3].vNor = m_pBackground->m_pTileVertexArray[(i + nSize * x) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)].nor;
			pVertex[i*nSize*6 + j*6 + 3].tu = 0;
			pVertex[i*nSize*6 + j*6 + 3].tv = 0;

			pVertex[i*nSize*6 + j*6 + 4].vPos = m_pBackground->m_pTileVertexArray[((i + nSize * x)+1) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)+1].pos;
			pVertex[i*nSize*6 + j*6 + 4].vNor = m_pBackground->m_pTileVertexArray[((i + nSize * x)+1) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)+1].nor;
			pVertex[i*nSize*6 + j*6 + 4].tu = 1;
			pVertex[i*nSize*6 + j*6 + 4].tv = 1;

			pVertex[i*nSize*6 + j*6 + 5].vPos = m_pBackground->m_pTileVertexArray[((i + nSize * x)+1) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)].pos;
			pVertex[i*nSize*6 + j*6 + 5].vNor = m_pBackground->m_pTileVertexArray[((i + nSize * x)+1) * (m_pBackground->m_projectInfo.m_sYSize + 1) + (j + nSize * z)].nor;
			pVertex[i*nSize*6 + j*6 + 5].tu = 0;
			pVertex[i*nSize*6 + j*6 + 5].tv = 1;
		}
	}
	pSysMesh->LockVertexBuffer(0  , (BYTE**)&VBuffer);
	memcpy(VBuffer, pVertex, nVertexNum * sizeof(VERTEX) );
	pSysMesh->UnlockVertexBuffer();

	MYINDEX *pIdx = new MYINDEX[nTriangleNum];

	for ( i = 0;i < nSize;i++ )
	{
		for ( j = 0;j < nSize;j++ )
		{
			pIdx[2 * (i * nSize + j)]._0 = i * (nSize*6) + j*6;
			pIdx[2 * (i * nSize + j)]._1 = i * (nSize*6) + j*6 + 1;
			pIdx[2 * (i * nSize + j)]._2 = i * (nSize*6) + j*6 + 2;

			pIdx[2 * (i * nSize + j) + 1]._0 = i * (nSize*6) + j*6 + 3;
			pIdx[2 * (i * nSize + j) + 1]._1 = i * (nSize*6) + j*6 + 4;
			pIdx[2 * (i * nSize + j) + 1]._2 = i * (nSize*6) + j*6 + 5;
		}
	}
	pSysMesh->LockIndexBuffer(0 ,(BYTE**)&IBuffer);
	memcpy(IBuffer, pIdx, sizeof(MYINDEX)*nTriangleNum );
	pSysMesh->UnlockIndexBuffer();

	DWORD *pMaterial = new DWORD[nTriangleNum];

	for( int kkk = 0;kkk < nTriangleNum;kkk++ )
	{
		pMaterial[kkk] = 0x00000000;
	}
//	memset(pMaterial,0x00,sizeof(DWORD)*nTriangleNum);

	pSysMesh->LockAttributeBuffer(0, &MBuffer);
	memcpy(MBuffer, pMaterial, sizeof(DWORD)*nTriangleNum);
	pSysMesh->UnlockAttributeBuffer();
	LPD3DXBUFFER pAdjacencyBuffer;
	hr = D3DXCreateBuffer(pSysMesh->GetNumFaces()*3*sizeof(DWORD), &pAdjacencyBuffer);
	if( E_OUTOFMEMORY == hr )
	{
		ASSERT(FALSE);
	}
	ASSERT(pSysMesh->GetNumFaces()*3*sizeof(DWORD) == pAdjacencyBuffer->GetBufferSize());
//	D3DXCreateBuffer(nTriangleNum*3, &pAdjacencyBuffer);
	DWORD* pAdjBuffer = (DWORD*)pAdjacencyBuffer->GetBufferPointer();
	hr = pSysMesh->GenerateAdjacency(0.0f, pAdjBuffer );//(DWORD*)pAdjacencyBuffer->GetBufferPointer());
	D3DXMATERIAL material;
	memset( &material, 0x00, sizeof(D3DXMATERIAL) );
	material.MatD3D.Ambient.r = 1.0f;
	material.MatD3D.Ambient.g = 1.0f;
	material.MatD3D.Ambient.b = 1.0f;
	material.MatD3D.Diffuse.r = 1.0f;
	material.MatD3D.Diffuse.g = 1.0f;
	material.MatD3D.Diffuse.b = 1.0f;
	material.pTextureFilename = "map.tga";
	D3DXSaveMeshToX(szFilename,pSysMesh,(DWORD*)pAdjacencyBuffer->GetBufferPointer(),&material,1,DXFILEFORMAT_TEXT);
//	D3DXSaveMeshToX(szFilename,pSysMesh,NULL,&material,1,DXFILEFORMAT_TEXT);
	
	pAdjacencyBuffer->Release();
	pSysMesh->Release();

	SAFE_DELETE_ARRAY( pVertex );
	SAFE_DELETE_ARRAY( pIdx );
	SAFE_DELETE_ARRAY( pMaterial );

}
// by dhkwon, 2010.0715 X파일 저장 방식: 새로운 X파일 저장 방식, big size 파일도 저장 가능하다.
void CMapEditorView::SaveXFile(int nSize, int x, int z)
{
	HRESULT hr;
	_chdir(m_strCurrentDir);
	char szFilename[256];
//	char szFilename2[256];
	wsprintf(szFilename,".\\%s\\%s\\%s.x",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,m_pBackground->m_projectInfo.m_strProjectName);

	VERTEX* VBuffer = NULL;
	short* IBuffer = NULL;
	DWORD* MBuffer = NULL;
	LPD3DXMESH pSysMesh;
	int nVertexSize = nSize+1;
	DWORD nTriangleNum = nSize * nSize * 2;
	DWORD nVertexNum = nVertexSize * nVertexSize;
	hr = D3DXCreateMeshFVF(nTriangleNum, nVertexNum, D3DXMESH_MANAGED|D3DXMESH_32BIT, 
		D3DFVF_VERTEX,m_pd3dDevice, &pSysMesh);
	if(hr == E_OUTOFMEMORY)
	{
		ASSERT(FALSE);
	}
	if(hr == D3DERR_INVALIDCALL)
	{
		ASSERT(FALSE);
	}

	VERTEX *pVertex = new VERTEX[nVertexNum];
	int i,j;
	for ( i = 0;i < nVertexSize;i++ ) // x
	{
		for ( j = 0;j < nVertexSize;j++ ) // y
		{
			pVertex[i*nVertexSize + j].vPos = m_pBackground->m_pTileVertexArray[i*nVertexSize + j].pos;
			pVertex[i*nVertexSize + j].vNor = m_pBackground->m_pTileVertexArray[i*nVertexSize + j].nor;
			pVertex[i*nVertexSize + j].tu = 0;
			pVertex[i*nVertexSize + j].tv = 0;

		}
	}


	pSysMesh->LockVertexBuffer(0  , (BYTE**)&VBuffer);
	memcpy(VBuffer, pVertex, nVertexNum * sizeof(VERTEX) );
	pSysMesh->UnlockVertexBuffer();

	MYINDEX *pIdx = new MYINDEX[nTriangleNum];

	for ( i = 0;i < nSize;i++ )
	{
		for ( j = 0;j < nSize;j++ )
		{
			pIdx[2 * (i * nSize + j)]._0 = i*nVertexSize + j;
			pIdx[2 * (i * nSize + j)]._1 = i*nVertexSize + j+1;
			pIdx[2 * (i * nSize + j)]._2 = (i+1)*nVertexSize + j+1;

			pIdx[2 * (i * nSize + j) + 1]._0 = i*nVertexSize + j;
			pIdx[2 * (i * nSize + j) + 1]._1 = (i+1)*nVertexSize + j+1;
			pIdx[2 * (i * nSize + j) + 1]._2 = (i+1)*nVertexSize + j;
		}
	}
	pSysMesh->LockIndexBuffer(0 ,(BYTE**)&IBuffer);
	memcpy(IBuffer, pIdx, sizeof(MYINDEX)*nTriangleNum );
	pSysMesh->UnlockIndexBuffer();

	DWORD *pMaterial = new DWORD[nTriangleNum];

	for( int kkk = 0;kkk < nTriangleNum;kkk++ )
	{
		pMaterial[kkk] = 0x00000000;
	}
//	memset(pMaterial,0x00,sizeof(DWORD)*nTriangleNum);

	pSysMesh->LockAttributeBuffer(0, &MBuffer);
	memcpy(MBuffer, pMaterial, sizeof(DWORD)*nTriangleNum);
	pSysMesh->UnlockAttributeBuffer();
	LPD3DXBUFFER pAdjacencyBuffer;
	int nTemp = pSysMesh->GetNumFaces();
	nTemp = sizeof(DWORD);
	nTemp = pSysMesh->GetNumFaces()*3*sizeof(DWORD);
	hr = D3DXCreateBuffer(pSysMesh->GetNumFaces()*3*sizeof(DWORD), &pAdjacencyBuffer);
	if( E_OUTOFMEMORY == hr )
	{
		ASSERT(FALSE);
	}
	ASSERT(pSysMesh->GetNumFaces()*3*sizeof(DWORD) == pAdjacencyBuffer->GetBufferSize());
//	D3DXCreateBuffer(nTriangleNum*3, &pAdjacencyBuffer);
	DWORD* pAdjBuffer = (DWORD*)pAdjacencyBuffer->GetBufferPointer();
	hr = pSysMesh->GenerateAdjacency(0.0f, pAdjBuffer );//(DWORD*)pAdjacencyBuffer->GetBufferPointer());
	D3DXMATERIAL material;
	memset( &material, 0x00, sizeof(D3DXMATERIAL) );
	material.MatD3D.Ambient.r = 1.0f;
	material.MatD3D.Ambient.g = 1.0f;
	material.MatD3D.Ambient.b = 1.0f;
	material.MatD3D.Diffuse.r = 1.0f;
	material.MatD3D.Diffuse.g = 1.0f;
	material.MatD3D.Diffuse.b = 1.0f;
	material.pTextureFilename = "map.tga";
	D3DXSaveMeshToX(szFilename,pSysMesh,(DWORD*)pAdjacencyBuffer->GetBufferPointer(),&material,1,DXFILEFORMAT_TEXT);
//	D3DXSaveMeshToX(szFilename,pSysMesh,NULL,&material,1,DXFILEFORMAT_TEXT);
	
	pAdjacencyBuffer->Release();
	pSysMesh->Release();

	SAFE_DELETE_ARRAY( pVertex );
	SAFE_DELETE_ARRAY( pIdx );
	SAFE_DELETE_ARRAY( pMaterial );

}
void CMapEditorView::OnUpdateButtonSaveX(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(TRUE);
	
}

void CMapEditorView::OnButtonMap() 
{
	if ( !m_pBackground )
	{
		AfxMessageBox( "No project is currently open.", MB_OK );
		return;
	}
	CMapTileSaveDlg * pDlg = new CMapTileSaveDlg;

	if ( pDlg->DoModal() == IDOK )
	{
		switch ( pDlg->m_bySizeType )
		{
		case 0:
			{
				_chdir(m_strCurrentDir);
				char szFilename[256];
				if ( m_pBackground )
				{
					int nSize = m_pBackground->m_projectInfo.m_sXSize;
					int nNum;
					if ( nSize % 4)
					{
						nNum = nSize / 4 + 1;
					}
					else
					{
						nNum = nSize / 4;
					}
					char buf[256];
					LPDIRECT3DTEXTURE8 tempTexDest = NULL;
					LPDIRECT3DTEXTURE8 tempTexSrc = NULL;
					D3DLOCKED_RECT d3dlrDest, d3dlrSrc;
					DWORD* pDst,*pSrc;
					wsprintf( buf, "mappicture512.tga" );
					D3DUtil_CreateTexture( g_pD3dDev,buf, &tempTexDest );
					char bufDirName[256];
					wsprintf( bufDirName,".\\%s\\%s\\map",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName );
					_mkdir( bufDirName );
					for ( int x = 0;x < nNum;x++ )
					{
						for ( int y = 0;y < nNum;y++ )
						{
							tempTexDest->LockRect( 0, &d3dlrDest, 0, 0 );
							DWORD* pDestRow = (DWORD*)d3dlrDest.pBits;
							wsprintf(szFilename,".\\%s\\%s\\map\\map_%02d_%02d.bmp",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,x,y);
							for ( int i = 0;i < 4;i++ )
							{
								for ( int j = 0;j < 4;j++ )
								{
									if ( 4 * y + j < nSize && 4 * x + i < nSize )
									{
										pDst = (DWORD*)pDestRow;
										pDst += (128 * i) * 512 + j * 128;
										int nTileNum = (4 * x + i) * nSize + 4 * y + j;
										int nUseTileNum = m_pBackground->m_pTileInfo[nTileNum].useTexNumber;
										tempTexSrc = m_pBackground->m_pCreateTexture[nUseTileNum];
										tempTexSrc->LockRect( 0, &d3dlrSrc, 0, 0 );
										DWORD* pSrcRow = (DWORD*)d3dlrSrc.pBits;
										pSrc = (DWORD*)pSrcRow;
										for ( int nTexX = 0;nTexX < 128;nTexX++ )
										{
											for ( int nTexY = 0;nTexY < 128;nTexY++ )
											{
												*pDst = (DWORD)(*pSrc);
												pSrc++;
												pDst += 512;
											}
											pDst = (DWORD*)pDestRow;
											pDst += (128 * i) * 512 + j * 128;
											pDst += nTexX + 1;
										}
										tempTexSrc->UnlockRect(0);
									}
								}
							}
							tempTexDest->UnlockRect(0);
							if( FAILED(D3DXSaveTextureToFile(szFilename,D3DXIFF_BMP,tempTexDest,NULL)))
							{
								AfxMessageBox("Map texture creation failed.");
							}
						}
					}
					SAFE_RELEASE( tempTexDest );
				}
			}
			break;
		case 1:
			{
			}
			break;
		case 2:
			{
				_chdir(m_strCurrentDir);
				char szFilename[256];
				if ( m_pBackground )
				{
					int nSize = m_pBackground->m_projectInfo.m_sXSize;
					int nNum;
					int x, y, i, j;
					char buf[256];
					if ( nSize % 16)
					{
						nNum = nSize / 16 + 1;
					}
					else
					{
						nNum = nSize / 16;
					}
					LPDIRECT3DTEXTURE8 tempTexDest = NULL;
					LPDIRECT3DTEXTURE8 tempTexSrc = NULL;
					D3DLOCKED_RECT d3dlrDest, d3dlrSrc;
					DWORD* pDst,*pSrc;
					wsprintf( buf, "mappicture512.tga" );
					D3DUtil_CreateTexture( g_pD3dDev,buf, &tempTexDest );
					char bufDirName[256];
					wsprintf( bufDirName,".\\%s\\%s\\map",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName );
					_mkdir( bufDirName );
					for ( x = 0;x < nNum;x++ )
					{
						for ( y = 0;y < nNum;y++ )
						{
							tempTexDest->LockRect( 0, &d3dlrDest, 0, 0 );
							DWORD* pDestRow = (DWORD*)d3dlrDest.pBits;
							wsprintf(szFilename,".\\%s\\%s\\map\\map_%02d_%02d.bmp",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,x,y);
							for ( i = 0;i < 16;i++ )
							{
								for ( j = 0;j < 16;j++ )
								{
									if ( 16 * y + j < nSize && 16 * x + i < nSize )
									{
										pDst = (DWORD*)pDestRow;
										pDst += (32 * i) * 512 + j * 32;
										int nTileNum = (16 * x + i) * nSize + 16 * y + j;
										int nUseTileNum = m_pBackground->m_pTileInfo[nTileNum].useTexNumber;
										char bufTex[256];
										wsprintf( bufTex, 
											".\\Tile\\%d\\32\\05%06d.bmp",
											m_pBackground->m_projectInfo.m_useTileSetIndex,
											nUseTileNum );
										D3DUtil_CreateTexture( g_pD3dDev,bufTex, &tempTexSrc );
										tempTexSrc->LockRect( 0, &d3dlrSrc, 0, 0 );
										DWORD* pSrcRow = (DWORD*)d3dlrSrc.pBits;
										pSrc = (DWORD*)pSrcRow;
										for ( int nTexX = 0;nTexX < 32;nTexX++ )
										{
											for ( int nTexY = 0;nTexY < 32;nTexY++ )
											{
												*pDst = (DWORD)(*pSrc);
												pSrc++;
												pDst += 512;
											}
											pDst = (DWORD*)pDestRow;
											pDst += (32 * i) * 512 + j * 32;
											pDst += nTexX + 1;
										}
										tempTexSrc->UnlockRect(0);
										SAFE_RELEASE( tempTexSrc );
									}
								}
							}
							tempTexDest->UnlockRect(0);
							// 512로 생성된 맵을 64(1/4)맵으로 사이즈를 줄이자
							LPDIRECT3DTEXTURE8 texTemp;
							texTemp = ResizeTexture(tempTexDest, 512);
							texTemp = ResizeTexture(texTemp, 256);
							texTemp = ResizeTexture(texTemp, 128);

							if( FAILED(D3DXSaveTextureToFile(szFilename,D3DXIFF_BMP,texTemp,NULL)))
							{
								AfxMessageBox("Map texture creation failed.");
							}
						}
					}
					SAFE_RELEASE( tempTexDest );

					
					
					LPDIRECT3DTEXTURE8 TexOri = NULL;
					LPDIRECT3DTEXTURE8 TexOriSrc = NULL;
					D3DLOCKED_RECT d3dlrOri, d3dlrOriSrc;
					wsprintf( buf, "mappicture512.tga" );
					D3DUtil_CreateTexture( g_pD3dDev,buf, &TexOri );
					nSize = nNum;
					if ( nSize % 8)
					{
						nNum = nSize / 8 + 1;
					}
					else
					{
						nNum = nSize / 8;
					}
					for ( x = 0;x < nNum;x++ )
					{
						for ( y = 0;y < nNum;y++ )
						{
							TexOri->LockRect( 0, &d3dlrOri, 0, 0 );
							DWORD* pOriRow = (DWORD*)d3dlrOri.pBits;
							wsprintf(szFilename,".\\%s\\%s\\map\\MAPFINAL_%2d_%2d.bmp",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName,x,y);
							for ( i = 0;i < 8;i++ )
							{
								for ( j = 0;j < 8;j++ )
								{
									if ( 8 * y + j < nSize && 8 * x + i < nSize )
									{
										DWORD* pOri = (DWORD*)pOriRow;
										pOri += (64 * i) * 512 + j * 64;
										char bufTex[256];
										wsprintf( bufTex, 
											".\\%s\\%s\\map\\map_%02d_%02d.bmp",
											m_pWorkspace->workspaceName,
											m_pBackground->m_projectInfo.m_strProjectName,
											(x * 8 + i),
											(y * 8 + j) );
										D3DUtil_CreateTexture( g_pD3dDev,bufTex, &TexOriSrc );
										TexOriSrc->LockRect( 0, &d3dlrOriSrc, 0, 0 );
										DWORD* pOriRowSrc = (DWORD*)d3dlrOriSrc.pBits;
										DWORD* pOriSrc = (DWORD*)pOriRowSrc;
										for ( int nTexX = 0;nTexX < 64;nTexX++ )
										{
											for ( int nTexY = 0;nTexY < 64;nTexY++ )
											{
												*pOri = (DWORD)(*pOriSrc);
												pOriSrc++;
												pOri++;
//												pOri += 512;
											}
											pOri = (DWORD*)pOriRow;
											pOri += (64 * i) * 512 + j * 64;
//											pOri += nTexX + 1;
											pOri += (nTexX + 1) * 512;
										}
										TexOriSrc->UnlockRect(0);
										SAFE_RELEASE( TexOriSrc );
									}
								}
							}
							TexOri->UnlockRect(0);
							if( FAILED(D3DXSaveTextureToFile(szFilename,D3DXIFF_BMP,TexOri,NULL)))
							{
								AfxMessageBox("Map texture creation failed.");
							}
						}
					}
				}
				
			}
			break;
		}
	}

	delete pDlg;
	pDlg = NULL;
}

void CMapEditorView::OnUpdateButtonMap(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(TRUE);
}

void CMapEditorView::OnButtonLightView() 
{
	m_bShowLight = !m_bShowLight;
}

void CMapEditorView::OnUpdateButtonLightView(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(TRUE);
	pCmdUI->SetCheck(FALSE);
}

void CMapEditorView::SetObject(D3DXMATRIX mat, char *szFilename)
{
	D3DXVECTOR3 vPos;//, vVel, vUp;
	vPos.x = fabs(mat._41);
	vPos.y = fabs(mat._42);
	vPos.z = fabs(mat._43);

/*
	vVel.x = mat._31;
	vVel.y = mat._32;
	vVel.z = mat._33;

	vUp.x = mat._21;
	vUp.y = mat._22;
	vUp.z = mat._23;


	vVel.x = mat._21;
	vVel.y = mat._22;
	vVel.z = mat._23;

	
	vUp.x = mat._31;
	vUp.y = mat._32;
	vUp.z = mat._33;
*/

	int nObjType = atoi( szFilename );
	CObjectChild * pObject = new CObjectChild( vPos, D3DXVECTOR3(1,0,0), D3DXVECTOR3(0,1,0), (nObjType - 3000000) / 100 );
//	pObject->SetObjectMatrix( mat );
	char buf[256];
	sprintf(buf, "Object name : %s, Pos[%.2f, %.2f, %.2f]\n", szFilename, vPos.x, vPos.y, vPos.z );
	DBGOUT(buf);
	if ( !pObject->m_bUsing )
	{
		delete pObject;
	}
	else
	{
		m_pBackground->InsertObject(pObject);
		ResetObjectList();
	}
	m_pBackground->m_nObjectNumber++;

}


LPDIRECT3DTEXTURE8 CMapEditorView::ResizeTexture(LPDIRECT3DTEXTURE8 pTexture, int nSize)
{
	D3DLOCKED_RECT d3dlr,d3dlr1;
	LPDIRECT3DTEXTURE8 tempTex;
	BYTE bRed,bGreen, bBlue;
	DWORD bR,bG,bB;
	char buf[128];
	wsprintf(buf,"mappicture%d.tga", nSize / 2);
	D3DUtil_CreateTexture( g_pD3dDev,buf, &tempTex ) ;
	tempTex->LockRect( 0, &d3dlr, 0, 0 );
	pTexture->LockRect( 0, &d3dlr1, 0, 0 );
	DWORD* pDstRow = (DWORD*)d3dlr.pBits;
	DWORD* pDstRow1 = (DWORD*)d3dlr1.pBits;
	DWORD* pDst,*pSrc;
	pDst = (DWORD*)pDstRow;
	pSrc = (DWORD*)pDstRow1;
	int x,y;
	for(x=0; x < nSize / 2; x++ )
	{
		for(y=0; y < nSize/ 2; y++ )
		{
			pSrc = (DWORD*)pDstRow1;
			pSrc += nSize*2*x + y*2;
			bR = (BYTE)(*pSrc  >> 16);
			bG = (BYTE)(*pSrc  >> 8);
			bB = (BYTE)(*pSrc);
			pSrc++;
			bR += (BYTE)(*pSrc  >> 16);
			bG += (BYTE)(*pSrc  >> 8);
			bB += (BYTE)(*pSrc);
			pSrc += nSize - 1;
			bR += (BYTE)(*pSrc  >> 16);
			bG += (BYTE)(*pSrc  >> 8);
			bB += (BYTE)(*pSrc);
			pSrc++;
			bR += (BYTE)(*pSrc  >> 16);
			bG += (BYTE)(*pSrc  >> 8);
			bB += (BYTE)(*pSrc);

			bRed = bR/4;
			bGreen = bG/4;
			bBlue = bB/4;
			
			*pDst = D3DCOLOR_ARGB(0xFF,bRed,bGreen,bBlue);
			pDst++;
		}
	}
	tempTex->UnlockRect( 0 );
	pTexture->UnlockRect( 0 );
	return tempTex;
}

void CMapEditorView::OnButtonSetBackTexture() 
{
	// TODO: Add your command handler code here
	CFileDialog dlg(TRUE,"jpg|dds",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT , "dds/jpg Files (*.dds, *.jpg)|*.dds;*.jpg||", NULL);
	if(dlg.DoModal() == IDOK)
	{
		CString strPath = dlg.GetPathName();
		if(strPath.IsEmpty()==TRUE)
		{
			return;
		}
		if( m_pBackground->SetAllTexture(strPath) == TRUE )
		{
			m_pBackground->Restore();
		}
	}
}

void CMapEditorView::OnChangeEditWaterType() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData();	
}
#include "TextureGenerator.h"
#define PATCH_SIZE 64
#define PATCH_COUNT 8 //탑건 팀 사이즈 크기

void CMapEditorView::OnButtonGenerateBackTexture() 
{
	// TODO: Add your command handler code here
	if ( m_pBackground == NULL ) return;
	if(m_pBackground->m_pBackTexture == NULL) return;


	int nXCount = m_pBackground->m_projectInfo.m_sXSize/PATCH_SIZE;
	int nYCount = m_pBackground->m_projectInfo.m_sYSize/PATCH_SIZE;
	char strPath[MAX_PATH];
	_chdir(m_strCurrentDir);
	wsprintf( strPath,".\\%s\\%s\\texture",m_pWorkspace->workspaceName,m_pBackground->m_projectInfo.m_strProjectName );
	_mkdir( strPath );
	CTextureGenerator gen;
	gen.GenerateDevideAndMirrorTexture(g_pD3dDev, m_pBackground->m_pBackTexture, nXCount, nYCount, strPath);
}

void CMapEditorView::OnChangeEditRed() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here

	UpdateData(TRUE);
	if (m_dwBackRed > 255) m_dwBackRed = 255;

	
}

void CMapEditorView::OnChangeEditGreen() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	if (m_dwBackGreen > 255) m_dwBackGreen = 255;

	
}

void CMapEditorView::OnChangeEditBlue() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	if (m_dwBackBlue > 255) m_dwBackBlue = 255;

	
}

void CMapEditorView::OnCheckRoamland() 
{
	// TODO: Add your control notification handler code here	
	UpdateData();
	
}
