// cylinderX.cpp : 定义应用程序的入口点。
//

#include "stdafx.h"
#include "cylinderX.h"
#include "D3DEnvClass.h"
#define MAX_LOADSTRING 100


// 自定义顶点结构体
typedef struct tagCUSTOMVERTEX{
	D3DXVECTOR3 position; // The position of the vertex.
	D3DCOLOR    color;    // The color
}CUSTOMVERTEX;

// 自定义顶点格式
#define D3DFVF_CUSTOMVERTEX  D3DFVF_XYZ|D3DFVF_DIFFUSE

// 全局变量:
HINSTANCE hInst;								// 当前实例
TCHAR szTitle[MAX_LOADSTRING];					// 标题栏文本
TCHAR szWindowClass[MAX_LOADSTRING];			// 主窗口类名

// 全局变量，D3D环境对象
CZFXD3DEnv g_d3dEnv;
IDirect3DVertexBuffer9* g_pVB;          //Vertex Buffer, 
IDirect3DIndexBuffer9* g_pIB;          //Index Buffer, 

BOOL CreateVertexBuf( IDirect3DVertexBuffer9* & g_pVB);
BOOL CreateIndexBuf( IDirect3DIndexBuffer9* & g_pIB);
void SetupMatrices();

// 此代码模块中包含的函数的前向声明:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: 在此放置代码。
	MSG msg;
	HACCEL hAccelTable;

	// 初始化全局字符串
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_CYLINDERX, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// 执行应用程序初始化:
	if (!InitInstance (hInstance, nCmdShow)) 
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_CYLINDERX);

	// 主消息循环:
	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}



//
//  函数: MyRegisterClass()
//
//  目的: 注册窗口类。
//
//  注释: 
//
//    仅当希望在已添加到 Windows 95 的
//    “RegisterClassEx”函数之前此代码与 Win32 系统兼容时，
//    才需要此函数及其用法。调用此函数
//    十分重要，这样应用程序就可以获得关联的
//   “格式正确的”小图标。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, (LPCTSTR)IDI_CYLINDERX);
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= (LPCTSTR)IDC_CYLINDERX;
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

	return RegisterClassEx(&wcex);
}

//
//   函数: InitInstance(HANDLE, int)
//
//   目的: 保存实例句柄并创建主窗口
//
//   注释: 
//
//        在此函数中，我们在全局变量中保存实例句柄并
//        创建和显示主程序窗口。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // 将实例句柄存储在全局变量中

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   if(FAILED(g_d3dEnv.InitD3D(TRUE, hWnd)))
	   return FALSE;

   if( !CreateVertexBuf(g_pVB))
	{
		MessageBox(NULL, "Create Vertex Buffer Failed", "Textures.exe", MB_OK);
		return FALSE;
	}

	if( !CreateIndexBuf(g_pIB))
	{
		MessageBox(NULL, "Create Index Buffer Failed", "Textures.exe", MB_OK);
		return FALSE;
	}

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  函数: WndProc(HWND, unsigned, WORD, LONG)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND	- 处理应用程序菜单
//  WM_PAINT	- 绘制主窗口
//  WM_DESTROY	- 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
//	PAINTSTRUCT ps;
//	HDC hdc;

	switch (message) 
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam); 
		wmEvent = HIWORD(wParam); 
		// 分析菜单选择:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		//hdc = BeginPaint(hWnd, &ps);
		// TODO: 在此添加任意绘图代码...
		//EndPaint(hWnd, &ps);
		// 确信设备未丢失，如果丢失，函数会完成重置设备功能
		g_d3dEnv.MakeSureNotLost();
		// 清除屏幕
		g_d3dEnv.m_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0,0,0,0), 1.0f, 0 );
		// 开始渲染
		g_d3dEnv.m_pd3dDevice->BeginScene();
		// 在此渲染你要呈现的场景
		// .....
		// 设置变换矩阵
		SetupMatrices();
		// 设置渲染状态
		g_d3dEnv.m_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
		g_d3dEnv.m_pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
		g_d3dEnv.m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
		g_d3dEnv.m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );

		g_d3dEnv.m_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
		g_d3dEnv.m_pd3dDevice->SetIndices(g_pIB);
		g_d3dEnv.m_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
		g_d3dEnv.m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
                    0,                  // BaseVertexIndex
                    0,                  // MinIndex
                   102,                  // NumVertices
                    0,                  // StartIndex
                    196);                // PrimitiveCount

		g_d3dEnv.m_pd3dDevice->EndScene();
		// 将后台缓冲的数据搬到屏幕
		g_d3dEnv.m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		g_pVB->Release();
		g_pIB->Release();
		g_d3dEnv.Release();
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// “关于”框的消息处理程序。
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_INITDIALOG:
		return TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) 
		{
			EndDialog(hDlg, LOWORD(wParam));
			return TRUE;
		}
		break;
	}
	return FALSE;
}


//102 Vertices created.........
BOOL CreateVertexBuf(IDirect3DVertexBuffer9* & g_pVB)
{
	CUSTOMVERTEX pVertices[102];
	ZeroMemory( pVertices, 102*sizeof( CUSTOMVERTEX ) );

	for(int i=0;i<50;i++)
	{
		FLOAT alpha = (2*D3DX_PI*i)/49;
		pVertices[2*i].position   =  D3DXVECTOR3( sinf(alpha), 1.0f, cosf(alpha));
		pVertices[2*i].color      =  0x88ffffff;
		pVertices[2*i+1].position =  D3DXVECTOR3( sinf(alpha),-1.0f, cosf(alpha));
		pVertices[2*i+1].color      =  0x88ffffff;
	}
	pVertices[100].position   =  D3DXVECTOR3(0, 1.0f, 0);
	pVertices[100].color      =  0x88ffffff;
	pVertices[101].position =  D3DXVECTOR3(0,-1.0f, 0);
	pVertices[101].color      =  0x88ffffff;

	if( FAILED(g_d3dEnv.m_pd3dDevice->CreateVertexBuffer( 102*sizeof(CUSTOMVERTEX), 0, D3DFVF_CUSTOMVERTEX
		, D3DPOOL_DEFAULT, &g_pVB, NULL)))
		return FALSE;
	void* pData;
	g_pVB->Lock(0, 102*sizeof(CUSTOMVERTEX), (void**)&pData, 0);
	memcpy(pData, pVertices, 102*sizeof(CUSTOMVERTEX));
	g_pVB->Unlock();
	return TRUE;
}

BOOL CreateIndexBuf( IDirect3DIndexBuffer9* & g_pIB)
{
	WORD pIndices[588];
	int i = 0;
	for(int j=0;j<98;j++)
	{
		pIndices[i] = j;
		i++;
		pIndices[i] = j+1;
		i++;
		pIndices[i] = j+2;
		i++;
	}
	for(int j=0;j<98;j+=2)
	{
		pIndices[i] = 100;
		i++;
		pIndices[i] = j;
		i++;
		pIndices[i] = j+2;
		i++;
	}
	for(int j=0;j<98;j+=2)
	{
		pIndices[i] = 101;
		i++;
		pIndices[i] = j+1;
		i++;
		pIndices[i] = j+3;
		i++;
	}
	if( FAILED( g_d3dEnv.m_pd3dDevice->CreateIndexBuffer( 588*sizeof(WORD),
           D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, 
	       &g_pIB, NULL ) ) )
		return false;
	void* pData;
	g_pIB->Lock(0,588*sizeof(WORD), (void**)&pData, 0);
	memcpy(pData, pIndices, 588*sizeof(WORD));
	g_pIB->Unlock();
	return TRUE;
}

void SetupMatrices()
{
	// Set up world matrix
	D3DXMATRIX matWorld;
	D3DXMatrixIdentity( &matWorld );
	g_d3dEnv.m_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

	// Set up our view matrix. A view matrix can be defined given an eye point,
	// a point to lookat, and a direction for which way is up. Here, we set the
	// eye five units back along the z-axis and up three units, look at the
	// origin, and define "up" to be in the y-direction.
	D3DXVECTOR3 vEyePt( 0.0f, 2.0f,-4.0f );
	D3DXVECTOR3 vLookatPt( 0.0f, 0.0f, 0.0f );
	D3DXVECTOR3 vUpVec( 0.0f, 1.0f, 0.0f );
	D3DXMATRIX matView;
	D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );
	g_d3dEnv.m_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

	// For the projection matrix, we set up a perspective transform (which
	// transforms geometry from 3D view space to 2D viewport space, with
	// a perspective divide making objects smaller in the distance). To build
	// a perpsective transform, we need the field of view (1/4 pi is common),
	// the aspect ratio, and the near and far clipping planes (which define at
	// what distances geometry should be no longer be rendered).
	D3DXMATRIX matProj;
	D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 20.0f );
	g_d3dEnv.m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
}