//-----------------------------------【Direct3D_Render( )函数】-------------------------------
//	描述:使用Direct3D进行渲染
//--------------------------------------------------------------------------------------------------
void Direct3D_Render(HWND hwnd)
{
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之一】:清屏操作
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_XRGB(50, 100, 250), 1.0f, 0);


	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之二】:开始绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->BeginScene();                     // 开始绘制
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之三】:正式绘制
	//--------------------------------------------------------------------------------------

	g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_matWorld);

	for (DWORD i = 0; i < g_dwNumMtrls; i++)
	{
		g_pd3dDevice->SetMaterial(&g_pMaterials[i]);
		g_pd3dDevice->SetTexture(0, g_pTextures[i]);
		g_pMesh->DrawSubset(i);
	}

	D3DXMATRIX matWorld;
	D3DXMatrixTranslation(&matWorld, 0.0f, 0.0f, 0.0f);
	g_pd3dDevice->SetTransform(D3DTS_WORLD, &matWorld);
	g_pd3dDevice->SetTexture(0, g_pTexture);
	g_pd3dDevice->SetStreamSource(0, g_pVertexBuffer, 0, sizeof(CUSTOMVERTEX));
	g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
	g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);

	D3DXMATRIX TransMatrix, RotMatrix, FinalMatrix;
	D3DXMatrixRotationX(&RotMatrix, -D3DX_PI * 0.5f);
	g_pd3dDevice->SetMaterial(&g_MaterialCylinder);
	for (int i = 0; i < 6; i++)
	{
		D3DXMatrixTranslation(&TransMatrix, -100.0f, 0.0f, -150.0f + (i * 75.0f));
		FinalMatrix = RotMatrix * TransMatrix;
		g_pd3dDevice->SetTransform(D3DTS_WORLD, &FinalMatrix);
		g_cylinder->DrawSubset(0);

		D3DXMatrixTranslation(&TransMatrix, 100.0f, 0.0f, -150.0f + (i * 75.0f));
		FinalMatrix = RotMatrix * TransMatrix;
		g_pd3dDevice->SetTransform(D3DTS_WORLD, &FinalMatrix);
		g_cylinder->DrawSubset(0);
	}

	HelpText_Render(hwnd);


	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之四】:结束绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->EndScene();                       // 结束绘制
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之五】:显示翻转
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Present(NULL, NULL, NULL, NULL);  // 翻转与显示
}
//*************************************************************************************************************
void Render(float alpha, float elapsedtime)
{
	D3DXMATRIX view, proj;
	D3DXMATRIX inv, vp, tmp;
	D3DXMATRIX lightview, lightproj, lightvp;

	D3DXVECTOR2 orient = cameraangle.smooth(alpha);
	D3DXVECTOR4 lightpos(0, 0, -5, 0);
	D3DXVECTOR3 look(0, 0.5f, 0), up(0, 1, 0);
	D3DXVECTOR3 eye(0, 0, -5.2f);
	D3DXVECTOR4 clipplanes(0, 0, 0, 0);
	D3DXVECTOR4 texelsize(1.0f / SHADOWMAP_SIZE, 1.0f / SHADOWMAP_SIZE, 0, 0);

	// setup camera
	D3DXMatrixRotationYawPitchRoll(&tmp, orient.x, orient.y, 0);
	D3DXVec3TransformCoord(&eye, &eye, &tmp);

	D3DXMatrixLookAtLH(&view, &eye, &look, &up);
	D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI / 4, (float)screenwidth / (float)screenheight, 0.1f, 20);
	D3DXMatrixMultiply(&vp, &view, &proj);

	// setup light
	orient = lightangle.smooth(alpha);
	look = D3DXVECTOR3(0, 0, 0);

	D3DXMatrixRotationYawPitchRoll(&tmp, orient.x, orient.y, 0);
	D3DXVec4Transform(&lightpos, &lightpos, &tmp);

	D3DXMatrixLookAtLH(&lightview, (D3DXVECTOR3*)&lightpos, &look, &up);
	DXFitToBox(lightproj, clipplanes, lightview, scenebb);
	D3DXMatrixMultiply(&lightvp, &lightview, &lightproj);

	if( SUCCEEDED(device->BeginScene()) )
	{
		switch( shadowtech )
		{
		case 0:
			RenderWithPCF(vp, eye, lightview, lightproj, lightpos, clipplanes, D3DXVECTOR4(0, 0, 0, 0));
			break;

		case 1:
			RenderWithPCF(vp, eye, lightview, lightproj, lightpos, clipplanes, texelsize);
			break;

		case 2:
			RenderWithIrregularPCF(vp, eye, lightview, lightproj, lightpos, clipplanes, texelsize);
			break;

		case 3:
			RenderWithVariance(vp, eye, lightview, lightproj, lightpos, clipplanes);
			break;

		case 4:
			RenderWithConvolution(vp, eye, lightview, lightproj, lightpos, clipplanes);
			break;

		case 5:
			RenderWithExponential(vp, eye, lightview, lightproj, lightpos, clipplanes);
			break;

		case 6:
			RenderWithExponentialVariance(vp, eye, lightview, lightproj, lightpos, clipplanes);
			break;

		case 7:
			RenderWithPCSS(vp, eye, lightview, lightproj, lightpos, clipplanes, texelsize);
			break;

		default:
			device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0);
			break;
		}

		// render text
		device->SetFVF(D3DFVF_XYZRHW|D3DFVF_TEX1);
		device->SetRenderState(D3DRS_ZENABLE, FALSE);
		device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
		device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
		device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

		device->SetTexture(0, text);
		device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, textvertices, 6 * sizeof(float));

		device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
		device->SetRenderState(D3DRS_ZENABLE, TRUE);

		device->EndScene();
	}

	device->Present(NULL, NULL, NULL, NULL);
}
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
VOID Render()
{
    // Clear the backbuffer and the zbuffer
    g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
                         D3DCOLOR_XRGB( 0, 0, 255 ), 1.0f, 0 );

    // Begin the scene
    if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
    {
		SetupCameraMatrices();
		SetupLights((timeGetTime() / 1000) % 2);

		SetupCylinderMatrices();
		
		int TextureIndex = (timeGetTime() / 1000) % 2;

		g_pd3dDevice->SetTexture(0, g_pTexture[TextureIndex]);
		g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
		g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
		g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
		g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);

#ifdef SHOW_HOW_TO_USE_TCI
		D3DXMATRIXA16 mTextureTransform;
		D3DXMATRIXA16 mProj;
		D3DXMATRIXA16 mTrans;
		D3DXMATRIXA16 mScale;

		g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &mProj);
		D3DXMatrixTranslation(&mTrans, 0.5f, 0.5f, 0.0f);
		D3DXMatrixScaling(&mScale, 0.5f, -0.5f, 1.0f);
		mTextureTransform = mProj * mScale * mTrans;

		g_pd3dDevice->SetTransform(D3DTS_TEXTURE0, &mTextureTransform);
		g_pd3dDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT4 | D3DTTFF_PROJECTED);
		g_pd3dDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
#endif

		g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
		g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
		g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2 * 50 - 2);

        // Meshes are divided into subsets, one for each material. Render them in
        // a loop
		for (int loop = 0; loop < MESH_COUNT; ++loop)
		{
			// Setup the world, view, and projection matrices
			SetupMeshesMatrices(loop);

			for (DWORD i = 0; i < g_dwNumMaterials[loop]; i++)
			{
				// Set the material and texture for this subset
				g_pd3dDevice->SetMaterial(&g_pMeshMaterials[loop][i]);
				g_pd3dDevice->SetTexture(0, g_pMeshTextures[loop][i]);

				// Draw the mesh subset
				g_pMesh[loop]->DrawSubset(0);
			}
		}
		
        
        // End the scene
        g_pd3dDevice->EndScene();
    }

    // Present the backbuffer contents to the display
    g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
Example #4
0
// `使用Direct3D9來繪圖`
void RenderFrameDX9(void)
{
	LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9();

	Matrix4x4 light_projection_matrix;
	Matrix4x4 light_view_matrix;

	Matrix4x4 view_matrix = g_Control.GetViewMatrix();
	Matrix4x4 world_matrix = g_Control.GetObjectMatrix();

	// `開始下繪圖指令`
	device->BeginScene(); 

	// `把剪影畫在動態貼圖中`
	if(1)
	{
		//! 设置临时framebuffer
		LPDIRECT3DSURFACE9 pFrameBufferBackup, pDepthBufferBackup;
		device->GetRenderTarget(0, &pFrameBufferBackup); 
		pFrameBufferBackup->Release();
		device->GetDepthStencilSurface(&pDepthBufferBackup); 
		pDepthBufferBackup->Release();

		LPDIRECT3DSURFACE9 pSurface;
		g_pTexture->GetSurfaceLevel(0, &pSurface); 

		device->SetRenderTarget(0, pSurface);
		device->SetDepthStencilSurface(g_pDepthStencil);

		device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(255, 255, 255, 255), 1.0f, 0);

		Vector4 vLightPos = g_Light.m_Position;
		Vector4 vLightUp(0.0f, 1.0f, 0.0f);
		Vector4 vLightLookat(0.0f, 0.0f, 0.0f);
		// `把鏡頭放在光源的`
		light_projection_matrix = GutMatrixPerspectiveRH_DirectX(60.0f, 1.0f, 0.1f, 100.0f);
		light_view_matrix = GutMatrixLookAtRH(vLightPos, vLightLookat, vLightUp);
		// `設定轉換矩陣`
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *)&light_projection_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *)&light_view_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *)&world_matrix);

		D3DCOLORVALUE zero = {0.0f, 0.0f, 0.0f, 1.0f};

		sModelMaterial_DX9 material;
		material.m_Material.Ambient = zero;
		material.m_Material.Emissive = zero;
		material.m_Material.Diffuse = zero;
		material.m_Material.Specular = zero;
		material.m_bCullFace = false;

		material.Submit();

		device->SetRenderState(D3DRS_LIGHTING, 0);

		g_Model_DX9.Render(0);

		pSurface->Release();
		device->SetRenderTarget(0, pFrameBufferBackup);
		device->SetDepthStencilSurface(pDepthBufferBackup);
	}

	// `把上一個步驟的結果當成貼圖來使用`
	{
		// `消除畫面`
		device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0, 0, 150, 255), 1.0f, 0);
		// `設定轉換矩陣`
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &world_matrix);


#define DRAW_TEAPORT_FIRST 1

		//! 画茶壶
		if (DRAW_TEAPORT_FIRST)
		{
			SetupLightingDX9();
			g_Model_DX9.Render();
		}

		//! 设置矩形的纹理
		sModelMaterial_DX9 material;
		material.m_pTextures[0] = g_pTexture;
		material.Submit();

		Matrix4x4 inv_view_matrix = view_matrix;
		inv_view_matrix.FastInvert();

		Matrix4x4 uv_offset_matrix;
		uv_offset_matrix.Identity();
		uv_offset_matrix.Scale(0.5f, -0.5f, 0.5f);
		uv_offset_matrix[3].Set(0.5f, 0.5f, 0.5f, 1.0f);

		Matrix4x4 texture_matrix = inv_view_matrix * light_view_matrix * light_projection_matrix * uv_offset_matrix;
		Matrix4x4 indent_matrix = Matrix4x4::IdentityMatrix();

		device->SetTransform(D3DTS_TEXTURE0, (D3DMATRIX *) &texture_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &indent_matrix);

		device->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
		device->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT4 |  D3DTTFF_PROJECTED );
		device->SetRenderState(D3DRS_LIGHTING, FALSE);
		// `畫出矩形`
		device->SetFVF(D3DFVF_XYZ);
		device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Quad, sizeof(Vertex_VT));

		//! 关闭纹理矩阵
		device->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);

		if (!DRAW_TEAPORT_FIRST)
		{
			//SetupLightingDX9();
			device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &world_matrix);
			g_Model_DX9.Render();
		}


	}
	// `宣告所有的繪圖指令都下完了`
	device->EndScene(); 
	// `把背景backbuffer的畫面呈現出來`
	device->Present( NULL, NULL, NULL, NULL );
}
VOID Render()
{
	g_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0);

	if (SUCCEEDED(g_pD3DDevice->BeginScene()))
	{
		SetupLights();

		SetupMatrices();

		if (15 < (g_tick % 31))
		{
			g_pD3DDevice->SetTexture(0, g_pTexture0);
		}
		else
		{
			g_pD3DDevice->SetTexture(0, g_pTexture1);
		}
		g_pD3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
		g_pD3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
		g_pD3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
		g_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
		

		g_pD3DDevice->SetStreamSource(0, g_pVertexBuffer0, 0, sizeof(CUSTOMVERTEX));
		g_pD3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
		g_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2 * 50 - 2);

		g_pD3DDevice->SetStreamSource(0, g_pVertexBuffer1, 0, sizeof(CUSTOMVERTEX));
		g_pD3DDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
		g_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2 * 50 - 2);



		//tiger 1
		D3DXMATRIXA16 matFirstTiger, matTrans, matRotate;
		//D3DXMatrixIdentity(&matFirstTiger);

		//g_pD3DDevice->GetTransform(D3DTS_WORLD, &matFirstTiger);
		D3DXMatrixTranslation(&matTrans, -3.f, -1.5f, -1.6f);		
		D3DXMatrixRotationY(&matRotate, timeGetTime() / 1000.0f);
		D3DXMatrixMultiply(&matFirstTiger, &matRotate, &matTrans);
		g_pD3DDevice->SetTransform(D3DTS_WORLD, &matFirstTiger);

		
		for (DWORD i = 0; i < g_dwNumMaterials; ++i)
		{
			g_pD3DDevice->SetMaterial(&g_pMeshMaterials0[i]);
			g_pD3DDevice->SetTexture(0, g_pMeshTextures0[i]);

			g_pMesh0->DrawSubset(i);
		}


		//tiger 2
		D3DXMATRIXA16 matSecondTiger;
		D3DXMatrixIdentity(&matSecondTiger);
		D3DXMatrixIdentity(&matTrans);
		D3DXMatrixIdentity(&matRotate);

		g_pD3DDevice->GetTransform(D3DTS_WORLD, &matSecondTiger);
		D3DXMatrixTranslation(&matTrans, 3.f, -1.5f, -1.6f);
		D3DXMatrixRotationY(&matRotate, -(timeGetTime() / 1000.0f));
		D3DXMatrixMultiply(&matSecondTiger, &matRotate, &matTrans);
		g_pD3DDevice->SetTransform(D3DTS_WORLD, &matSecondTiger);

		for (DWORD i = 0; i < g_dwNumMaterials; ++i)
		{
			g_pD3DDevice->SetMaterial(&g_pMeshMaterials0[i]);
			g_pD3DDevice->SetTexture(0, g_pMeshTextures0[i]);

			g_pMesh0->DrawSubset(i);
		}

		g_pD3DDevice->EndScene();
	}

	g_pD3DDevice->Present(NULL, NULL, NULL, NULL);
	g_tick++;
}
Example #6
0
//-----------------------------------【Direct3D_Render( )函数】-------------------------------
//	描述:使用Direct3D进行渲染
//--------------------------------------------------------------------------------------------------
void Direct3D_Render(HWND hwnd)
{

	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之一】:清屏操作
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(100, 100, 100), 1.0f, 0);

	//定义一个矩形,用于获取主窗口矩形
	RECT formatRect;
	GetClientRect(hwnd, &formatRect);

	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之二】:开始绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->BeginScene();                     // 开始绘制

	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之三】:正式绘制,利用顶点缓存绘制图形
	//--------------------------------------------------------------------------------------

	g_pd3dDevice->SetStreamSource(0, g_pVertexBuffer, 0, sizeof(CUSTOMVERTEX));//把包含的几何体信息的顶点缓存和渲染流水线相关联
	g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);//指定我们使用的灵活顶点格式的宏名称
	g_pd3dDevice->SetIndices(g_pIndexBuffer);//设置索引缓存
	//--------------------------------------------------------------------------------------
	// 【纹理绘制四步曲之四】:纹理的启用
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->SetTexture(0, g_pTexture);  //启用纹理

	g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 24, 0, 12);//利用索引缓存配合顶点缓存绘制图形

	//在窗口右上角处,显示每秒帧数
	int charCount = swprintf_s(g_strFPS, 20, _T("FPS:%0.3f"), Get_FPS());
	g_pTextFPS->DrawText(NULL, g_strFPS, charCount, &formatRect, DT_TOP | DT_RIGHT, D3DCOLOR_RGBA(0, 239, 136, 255));

	//显示显卡类型名
	g_pTextAdaperName->DrawText(NULL, g_strAdapterName, -1, &formatRect,
		DT_TOP | DT_LEFT, D3DXCOLOR(1.0f, 0.5f, 0.0f, 1.0f));

	// 输出绘制信息
	formatRect.top = 30;
	static wchar_t strInfo[256] = { 0 };
	swprintf_s(strInfo, -1, L"模型坐标: (%.2f, %.2f, %.2f)", g_matWorld._41, g_matWorld._42, g_matWorld._43);
	g_pTextHelper->DrawText(NULL, strInfo, -1, &formatRect, DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(135, 239, 136, 255));

	// 输出帮助信息
	formatRect.left = 0, formatRect.top = 380;
	g_pTextInfor->DrawText(NULL, L"控制说明:", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(235, 123, 230, 255));
	formatRect.top += 35;
	g_pTextHelper->DrawText(NULL, L"    按住鼠标左键并拖动:平移模型", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255, 200, 0, 255));
	formatRect.top += 25;
	g_pTextHelper->DrawText(NULL, L"    按住鼠标右键并拖动:旋转模型", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255, 200, 0, 255));
	formatRect.top += 25;
	g_pTextHelper->DrawText(NULL, L"    滑动鼠标滚轮:拉伸模型", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255, 200, 0, 255));
	formatRect.top += 25;
	g_pTextHelper->DrawText(NULL, L"    W、S、A、D键:平移模型 ", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255, 200, 0, 255));
	formatRect.top += 25;
	g_pTextHelper->DrawText(NULL, L"    上、下、左、右方向键:旋转模型 ", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255, 200, 0, 255));
	formatRect.top += 25;
	g_pTextHelper->DrawText(NULL, L"    键盘上1,2数字键:在两种填充模式之间切换 ", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255, 200, 0, 255));
	formatRect.top += 25;
	g_pTextHelper->DrawText(NULL, L"    ESC键 : 退出程序", -1, &formatRect,
		DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255, 200, 0, 255));


	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之四】:结束绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->EndScene();                       // 结束绘制
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之五】:显示翻转
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Present(NULL, NULL, NULL, NULL);  // 翻转与显示

}
Example #7
0
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void MainLoop()
{
	for(;;)
	{ 
		MSG msg;
		if (PeekMessage (&msg,NULL,0,0,PM_NOREMOVE)) 
		{
			if( msg.message == WM_QUIT )
			{
				return ;
			}
			GetMessage (&msg,NULL,0,0);
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			// サーバーの更新を行う。
			g_server->Update();

			if( g_timer % 120 == 0 )
			{
				// エフェクトの停止
				g_manager->StopEffect( g_handle );

				// エフェクトの再生
				g_handle = g_manager->Play( g_effect, 0, 0, 0 );
			}

			// エフェクトの移動処理を行う。
			g_manager->AddLocation( g_handle, ::Effekseer::Vector3D( 0.2f, 0.0f, 0.0f ) );

			// エフェクトの更新処理を行う。
			g_manager->Update();
			
			
			g_d3d_device->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );
			g_d3d_device->BeginScene();

			// エフェクトの描画開始処理を行う。
			g_renderer->BeginRendering();

			// エフェクトの描画を行う。
			g_manager->Draw();

			// エフェクトの描画終了処理を行う。
			g_renderer->EndRendering();

			g_d3d_device->EndScene();

			g_timer++;

			{
				HRESULT hr;
				hr = g_d3d_device->Present( NULL, NULL, NULL, NULL );

				// デバイスロスト処理
				switch ( hr )
				{
					// デバイスロスト
					case D3DERR_DEVICELOST:
					while ( FAILED( hr = g_d3d_device->TestCooperativeLevel() ) )
					{
						switch ( hr )
						{
							// デバイスロスト
							case D3DERR_DEVICELOST:
								::SleepEx( 1000, true );
								break;

							// デバイスロスト:リセット可
							case D3DERR_DEVICENOTRESET:
								
								// デバイスロストの処理を行う前に実行する
								g_renderer->OnLostDevice();

								D3DPRESENT_PARAMETERS d3dp;
								ZeroMemory(&d3dp, sizeof(d3dp));
								d3dp.BackBufferWidth = g_window_width;
								d3dp.BackBufferHeight = g_window_height;
								d3dp.BackBufferFormat = D3DFMT_X8R8G8B8;
								d3dp.BackBufferCount = 1;      
								d3dp.SwapEffect = D3DSWAPEFFECT_DISCARD;
								d3dp.Windowed = TRUE;
								d3dp.hDeviceWindow = g_window_handle;
								d3dp.EnableAutoDepthStencil = TRUE;
								d3dp.AutoDepthStencilFormat = D3DFMT_D16;

								g_d3d_device->Reset( &d3dp );

								// デバイスロストの処理の後に実行する
								g_renderer->OnResetDevice();

								break;
						}
					}
					break;
				}
			}
		}
	}
}
Example #8
0
void Game()
{
	build_display_array();

	if(g_pDevice == NULL) return;

	g_pDevice->SetRenderState(D3DRS_FILLMODE, 
						(g_bShowWireFrm)?D3DFILL_WIREFRAME:D3DFILL_SOLID);
	 
	g_pDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0);	

	SetupCam();


	for (int i=0;i<100;++i)
		for (int j=0;j<100;++j) {
			int index = (i * 100 + j) * 6;
			int count = g_pBox[i][j].bSelect;
			int intensity;
			if (count == 0) intensity = 0;
			else if (count == 1) intensity = 127;
			else {
				intensity = min(255, 127 + count*16);
			}
			intensity = 255 - intensity;
			int color = D3DCOLOR_ARGB(255, intensity, intensity, 255);
			g_pVerticesList[index++].color = color;
			g_pVerticesList[index++].color = color;
			g_pVerticesList[index++].color = color;
			g_pVerticesList[index++].color = color;
			g_pVerticesList[index++].color = color;
			g_pVerticesList[index++].color = color;
		}

	//'장면(Scene) 그리기' 시작
	if(SUCCEEDED(g_pDevice->BeginScene()))	
	{	
		g_pDevice->SetFVF(D3DFVF_CUSTOMVERTEX);


	//버퍼 채우기.
	VOID*	pVertices;
	
	if(FAILED(g_pVB->Lock(0, sizeof(g_pVerticesList), (void**)&pVertices, 0 )))
	{
		printf("버텍스버퍼 Locking 오류!!\n");
		return;
	}
	
	memcpy(pVertices, g_pVerticesList, sizeof(g_pVerticesList));

	g_pVB->Unlock();
		g_pDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
		D3DXMATRIX mTrans;
		D3DXMatrixIdentity(&mTrans);
		g_pDevice->SetTransform(D3DTS_WORLD, &mTrans);
		g_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 6 * 100 * 100);
		g_pDevice->EndScene();
	}
	g_pDevice->Present(NULL, NULL, NULL, NULL);

}
//-----------------------------------【Direct3D_Render( )函数】-------------------------------
//	描述:使用Direct3D进行渲染
//--------------------------------------------------------------------------------------------------
void Direct3D_Render(HWND hwnd)
{
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之一】:清屏操作
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

	//定义一个矩形,用于获取主窗口矩形
	RECT formatRect;
	GetClientRect(hwnd, &formatRect);
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之二】:开始绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->BeginScene();                     // 开始绘制

	Matrix_Set();//调用封装了四大变换的函数,对Direct3D世界变换,取景变换,投影变换,视口变换进行设置

	// 获取键盘消息并给予设置相应的填充模式
	if (::GetAsyncKeyState(0x31) & 0x8000f)         // 若数字键1被按下,进行实体填充
		g_pd3dDevice->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID);	
	if (::GetAsyncKeyState(0x32) & 0x8000f)         // 若数字键2被按下,进行线框填充
		g_pd3dDevice->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);

	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之三】:正式绘制,利用顶点缓存绘制图形
	//--------------------------------------------------------------------------------------

	D3DXMatrixRotationY(&R, ::timeGetTime() / 1440.0f);  //设置公转的矩阵

	// 进行立方体的绘制
	D3DXMatrixTranslation(&g_WorldMatrix[0], 3.0f, -3.0f, 0.0f);
	g_WorldMatrix[0]  =  g_WorldMatrix[0]*R; 
	g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[0]);
	g_cube->DrawSubset(0);

	//进行茶壶的绘制
	D3DXMatrixTranslation(&g_WorldMatrix[1], -3.0f, -3.0f, 0.0f);
	g_WorldMatrix[1]  =  g_WorldMatrix[1]*R; 
	g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[1]);	
	g_teapot->DrawSubset(0);

	// 进行圆环的绘制
	D3DXMatrixTranslation(&g_WorldMatrix[2], 3.0f, 3.0f, 0.0f);
	g_WorldMatrix[2]  =  g_WorldMatrix[2]*R; 
	g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[2]);	
	g_torus->DrawSubset(0);

	// 进行球面体的绘制
	D3DXMatrixTranslation(&g_WorldMatrix[3], -3.0f, 3.0f, 0.0f);
	g_WorldMatrix[3]  =  g_WorldMatrix[3]*R; 
	g_pd3dDevice->SetTransform(D3DTS_WORLD, &g_WorldMatrix[3]);
	g_sphere->DrawSubset(0);

	//在窗口右上角处,显示每秒帧数
	int charCount = swprintf_s(g_strFPS, 20, _T("FPS:%0.3f"), Get_FPS() );
	g_pFont->DrawText(NULL, g_strFPS, charCount , &formatRect, DT_TOP | DT_RIGHT, D3DCOLOR_XRGB(255,39,136));

	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之四】:结束绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->EndScene();                       // 结束绘制
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之五】:显示翻转
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Present(NULL, NULL, NULL, NULL);  // 翻转与显示
}
Example #10
0
void Render(float alpha, float elapsedtime)
{
	static float time = 0;
	LPDIRECT3DSURFACE9 backbuffer = 0;

	D3DXMATRIX		view, proj, viewproj;
	D3DXMATRIX		world, inv;

	D3DXVECTOR4		texelsize;
	D3DXVECTOR4		lightpos(-600, 350, 1000, 1);
	D3DXVECTOR4		refllight;
	D3DXVECTOR3		eye(0, 0, -5.0f);
	D3DXVECTOR3		look(0, 1.2f, 0);
	D3DXVECTOR3		refleye, refllook;
	D3DXVECTOR3		up(0, 1, 0);
	D3DXVECTOR2		orient	= cameraangle.smooth(alpha);

	D3DXMatrixRotationYawPitchRoll(&view, orient.x, orient.y, 0);
	D3DXVec3TransformCoord(&eye, &eye, &view);
	
	eye.y += 1.2f;

	D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI / 2, (float)screenwidth / (float)screenheight, 0.1f, 30);

	time += elapsedtime;

	if( SUCCEEDED(device->BeginScene()) )
	{
		device->GetRenderTarget(0, &backbuffer);

		// STEP 1: render reflection texture
		device->SetRenderTarget(0, reflectsurf);
		device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0);

		D3DXPLANE plane(0, 1, 0, 1);

		refleye = eye - 2 * D3DXPlaneDotCoord(&plane, &eye) * (D3DXVECTOR3&)plane;
		refllook = look - 2 * D3DXPlaneDotCoord(&plane, &look) * (D3DXVECTOR3&)plane;

		refllight = lightpos - 2 * D3DXPlaneDot(&plane, &lightpos) * (D3DXVECTOR4&)plane;
		refllight.w = 1;

		D3DXMatrixLookAtLH(&view, &refleye, &refllook, &up);
		D3DXMatrixMultiply(&viewproj, &view, &proj);

		D3DXMatrixInverse(&inv, 0, &viewproj);
		D3DXMatrixTranspose(&inv, &inv);
		D3DXPlaneTransform(&plane, &plane, &inv);

		device->SetClipPlane(0, &plane.a);

		RenderScene(viewproj, refleye, refllight, true);

		// STEP 2: render scene (later used for refraction)
		D3DXMatrixLookAtLH(&view, &eye, &look, &up);
		D3DXMatrixMultiply(&viewproj, &view, &proj);

		device->SetRenderTarget(0, refractsurf);
		device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0);

		RenderScene(viewproj, eye, lightpos, false);

		// render water surface into alpha channel for masking
		device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA);

		D3DXMatrixTranslation(&world, 0, -1, 0);

		device->SetTransform(D3DTS_WORLD, &world);
		device->SetTransform(D3DTS_VIEW, &view);
		device->SetTransform(D3DTS_PROJECTION, &proj);

		waterplane->DrawSubset(0, DXObject::Opaque);

		device->SetRenderState(D3DRS_COLORWRITEENABLE, 0x0f);

		// STEP 3: light shafts
		quadvertices[6] = quadvertices[24] = quadvertices[30]	= (float)screenwidth - 0.5f;
		quadvertices[13] = quadvertices[19] = quadvertices[31]	= (float)screenheight - 0.5f;

		RenderLightShafts(view, proj, eye, lightpos);

		// STEP 4: gamma correct
		device->SetRenderTarget(0, sceneldrsurf);

		device->SetRenderState(D3DRS_ZENABLE, FALSE);
		device->SetVertexDeclaration(quaddecl);

		bloom->SetTechnique("gammacorrect");
		bloom->Begin(0, 0);
		bloom->BeginPass(0);
		{
			device->SetTexture(0, refraction);
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		bloom->EndPass();
		bloom->End();

		device->SetRenderState(D3DRS_ZENABLE, TRUE);

		// STEP 5: water surface
		device->SetRenderState(D3DRS_SRGBWRITEENABLE, TRUE);

		D3DXMatrixTranslation(&world, 0, -1, 0);
		D3DXMatrixIdentity(&inv);

		water->SetMatrix("matViewProj", &viewproj);
		water->SetMatrix("matWorld", &world);
		water->SetMatrix("matWorldInv", &inv);
		water->SetVector("eyePos", (D3DXVECTOR4*)&eye);
		water->SetVector("lightPos", &lightpos);
		water->SetVector("lightColor", &lightcolor);
		water->SetFloat("time", time);

		water->Begin(0, 0);
		water->BeginPass(0);
		{
			device->SetTexture(0, refraction);
			device->SetTexture(1, reflection);
			device->SetTexture(2, waves);

			waterplane->DrawSubset(0, DXObject::Opaque);
		}
		water->EndPass();
		water->End();

		device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);

		// STEP 6: downsample & blur
		quadvertices[6] = quadvertices[24] = quadvertices[30]	= (float)screenwidth * 0.5f - 0.5f;
		quadvertices[13] = quadvertices[19] = quadvertices[31]	= (float)screenheight * 0.5f - 0.5f;

		device->SetRenderTarget(0, bloomsurf1);
		device->SetRenderState(D3DRS_ZENABLE, FALSE);
		device->SetVertexDeclaration(quaddecl);

		texelsize.x = 1.0f / screenwidth;
		texelsize.y = 1.0f / screenheight;

		bloom->SetTechnique("downsample");
		bloom->SetVector("texelSize", &texelsize);

		bloom->Begin(0, 0);
		bloom->BeginPass(0);
		{
			device->SetTexture(0, sceneldr);
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		bloom->EndPass();
		bloom->End();

		device->SetRenderTarget(0, bloomsurf2);

		texelsize.x = 2.0f / screenwidth;
		texelsize.y = 2.0f / screenheight;

		bloom->SetTechnique("blur");
		bloom->SetVector("texelSize", &texelsize);

		bloom->Begin(0, 0);
		bloom->BeginPass(0);
		{
			device->SetTexture(0, bloomtex1);
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		bloom->EndPass();
		bloom->End();

		// STEP 7: add light shafts
		quadvertices[6] = quadvertices[24] = quadvertices[30]	= (float)screenwidth - 0.5f;
		quadvertices[13] = quadvertices[19] = quadvertices[31]	= (float)screenheight - 0.5f;

		device->SetRenderTarget(0, backbuffer);

		godray->SetTechnique("final");
		godray->Begin(0, 0);
		godray->BeginPass(0);
		{
			device->SetTexture(0, sceneldr);
			device->SetTexture(1, occluders);
			device->SetTexture(2, bloomtex2);

			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		godray->EndPass();
		godray->End();

		backbuffer->Release();

		device->SetRenderState(D3DRS_ZENABLE, TRUE);
		device->EndScene();
	}

	device->Present(NULL, NULL, NULL, NULL);
}
Example #11
0
// 使用DirectX 9來繪圖
void RenderFrameDX9(void)
{
	LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9();
	Matrix4x4 view_matrix = g_Control.GetViewMatrix();
	Matrix4x4 world_matrix = g_Control.GetObjectMatrix();
	Matrix4x4 ident_matrix; ident_matrix.Identity();
	device->BeginScene(); 
	// 消除畫面
	device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_RGBA(30, 30, 30, 255), 1.0f, 0);
	// light position & orientation
	Vector4 light_pos(5.0f, 0.0f, 5.0f);
	Vector4 light_lookat(0.0f, 0.0f, 0.0f);
	Vector4 light_up(0.0f, 1.0f, 0.0f);
	// light matrix
	Matrix4x4 light_view = GutMatrixLookAtRH(light_pos, light_lookat, light_up);
	Matrix4x4 light_world_view = world_matrix * light_view;
	Matrix4x4 shadow_matrix;
	// 建立shadow volume
	if ( g_bDirectionalLight )
	{
		g_ShadowVolume.BuildShadowVolume_DirectionalLight(light_world_view, 20.0f, true);
		shadow_matrix = light_view;
		shadow_matrix.FastInvert();
	}
	else
	{
		g_ShadowVolume.BuildShadowVolume_PointLight(light_pos, world_matrix, 20.0f, true);
		shadow_matrix.Identity();
	}
	// 畫出空間中的茶壼
	{
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &world_matrix);

		g_Model_DX9.Render();
	}
	// 畫出墻壁
	{
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &ident_matrix);

		sModelMaterial_DX9 material;

		material.m_Material.Diffuse.r = 0.0f;
		material.m_Material.Diffuse.g = 0.0f;
		material.m_Material.Diffuse.b = 1.0f;
		material.m_Material.Diffuse.a = 1.0f;

		material.Submit();

		device->SetFVF(D3DFVF_XYZ);
		device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Quad, sizeof(Vertex_VT));
	}
	device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
	device->SetRenderState(D3DRS_STENCILENABLE, TRUE);
	device->SetRenderState(D3DRS_STENCILREF, 0x01);
	device->SetRenderState(D3DRS_STENCILMASK, 0xff);
	// 在Stencil Buffer上標示出陰影區域
	{
		sModelMaterial_DX9 material;
		material.m_bCullFace = false;
		material.Submit();
		// 套用矩陣
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &shadow_matrix);
		// 設定頂點資料格式
		device->SetFVF(D3DFVF_XYZ);

		device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
		// cw stencil setting
		device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
		device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_INCR);
		// ccw stencil setting
		device->SetRenderState(D3DRS_CCW_STENCILFUNC, D3DCMP_ALWAYS);
		device->SetRenderState(D3DRS_CCW_STENCILZFAIL, D3DSTENCILOP_DECR);
		// disable color write
		device->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
		// 畫出Shadow Volume
		device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, g_ShadowVolume.m_iNumShadowVolumeFaces, g_ShadowVolume.m_pShadowVolume, sizeof(Vector4));
		// 恢復更新framebuffer
		device->SetRenderState(D3DRS_COLORWRITEENABLE, 0xff);
		device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
		device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP);
		device->SetRenderState(D3DRS_CCW_STENCILZFAIL, D3DSTENCILOP_KEEP);
	}
	// 畫出陰影
	{
		sModelMaterial_DX9 material;
		material.m_bCullFace = false;
		material.Submit();

		device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
		device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2);
		// 套用矩陣
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &ident_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &ident_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &ident_matrix);
		// 只更新stencil buffer上值為1的像素
		device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL);
		device->SetRenderState(D3DRS_STENCILREF, 0x01);
		// 使用黑色再畫一次墻壁
		device->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_RGBA(0, 0, 0,255) );
		device->SetFVF(D3DFVF_XYZ);
		device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_FullScreenQuad, sizeof(Vertex_VT));
	}
	device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
	// 觀察shadow volume, 除錯用.
	if ( g_bDrawShadowVolume )
	{
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &shadow_matrix);

		sModelMaterial_DX9 material;
		material.m_bCullFace = false;
		material.Submit();

		device->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_RGBA(255, 255, 255, 255) );
		device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
		device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, g_ShadowVolume.m_iNumShadowVolumeFaces, g_ShadowVolume.m_pShadowVolume, sizeof(Vector4));
		device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
	}
	// 恢復更新zbuffer
	device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
	// 把顏色來源還原為 diffuse * texture
	device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
	device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
	device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
	// 宣告所有的繪圖指令都下完了
	device->EndScene(); 
	// 把背景backbuffer的畫面呈現出來
	device->Present( NULL, NULL, NULL, NULL );
}
Example #12
0
//*************************************************************************************************************
void Render(float alpha, float elapsedtime)
{
	LPDIRECT3DSURFACE9 oldtarget = NULL;

	D3DXMATRIX		vp, inv, tmp1, tmp2;
	D3DXVECTOR3		axis(0, 1, 0);
	D3DXVECTOR3		eye(0, 0, -5);
	D3DXVECTOR3		look(0, 0, 0);
	D3DXVECTOR3		up(0, 1, 0);

	D3DXVECTOR2		cangle	= cameraangle.smooth(alpha);
	D3DXVECTOR2		oangle	= objectangle.smooth(alpha);
	float			expo	= exposure.smooth(alpha);

	D3DXMatrixRotationYawPitchRoll(&world, cangle.x, cangle.y, 0);
	D3DXVec3TransformCoord(&eye, &eye, &world);

	D3DXMatrixLookAtLH(&view, &eye, &look, &up);
	D3DXMatrixMultiply(&vp, &view, &proj);
	D3DXMatrixInverse(&inv, NULL, &view);

	memcpy(&eye, inv.m[3], 3 * sizeof(float));

	if( mesh == mesh1 )
	{
		// skullocc
		D3DXMatrixScaling(&world, 0.4f, 0.4f, 0.4f);
		world._42 = -1.5f;
	}
	else if( mesh == mesh2 )
	{
		// knot
		D3DXMatrixScaling(&world, 0.8f, 0.8f, 0.8f);
	}
	else
	{
		// teapot
		D3DXMatrixScaling(&world, 1.5f, 1.5f, 1.5f);
	}

	D3DXMatrixRotationYawPitchRoll(&tmp1, oangle.x, oangle.y, 0);
	D3DXMatrixMultiply(&world, &world, &tmp1);
	D3DXMatrixInverse(&inv, NULL, &world);

	fresnel->SetVector("eyePos", (D3DXVECTOR4*)&eye);
	fresnel->SetMatrix("matWorld", &world);
	fresnel->SetMatrix("matWorldInv", &inv);
	fresnel->SetMatrix("matViewProj", &vp);

	D3DXMatrixScaling(&world, 20, 20, 20);
	skyeffect->SetMatrix("matWorld", &world);

	D3DXMatrixIdentity(&world);
	skyeffect->SetMatrix("matWorldSky", &world);
	skyeffect->SetMatrix("matViewProj", &vp);

	memcpy(tmpvert, quadvertices, 36 * sizeof(float));

	if( SUCCEEDED(device->BeginScene()) )
	{
		device->SetRenderState(D3DRS_SRGBWRITEENABLE, false);
		device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
		device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);

		// STEP 1: render sky
		device->GetRenderTarget(0, &oldtarget);

		if( firstframe )
		{
			device->SetRenderTarget(0, aftersurfaces[0]);
			device->Clear(0, NULL, D3DCLEAR_TARGET, 0, 1.0f, 0);

			device->SetRenderTarget(0, aftersurfaces[1]);
			device->Clear(0, NULL, D3DCLEAR_TARGET, 0, 1.0f, 0);

			device->SetRenderTarget(0, avglumsurfaces[4]);
			device->Clear(0, NULL, D3DCLEAR_TARGET, 0x11111111, 1.0f, 0);

			device->SetRenderTarget(0, avglumsurfaces[5]);
			device->Clear(0, NULL, D3DCLEAR_TARGET, 0x11111111, 1.0f, 0);

			firstframe = false;
		}

		device->SetRenderTarget(0, scenesurface);
		device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0);
		device->SetRenderState(D3DRS_ZENABLE, FALSE);

		device->SetTexture(0, skytexture);

		skyeffect->Begin(NULL, 0);
		skyeffect->BeginPass(0);
		{
			skymesh->DrawSubset(0);
		}
		skyeffect->EndPass();
		skyeffect->End();
		
		device->SetRenderState(D3DRS_ZENABLE, TRUE);

		// STEP 2: render object
		device->SetTexture(0, texture);
		device->SetTexture(1, fresneltexture);
		device->SetTexture(2, skytexture);
		device->SetTexture(3, roughspecular);

		fresnel->Begin(NULL, 0);
		fresnel->BeginPass(0);
		{
			mesh->DrawSubset(0);
		}
		fresnel->EndPass();
		fresnel->End();

		device->SetVertexDeclaration(vertexdecl);

		// STEP 3: measure average luminance
		MeasureLuminance();

		// STEP 4: adapt luminance to eye
		AdaptLuminance(elapsedtime);

		// STEP 5: bright pass
		BrightPass();

		// STEP 6: downsample bright pass texture
		DownSample();

		// STEP 7: blur downsampled textures
		Blur();

		// STEP 8: ghost
		LensFlare();

		// STEP 9: star
		Star();

		// STEP 10: final combine
		hdreffect->SetTechnique("final");
		hdreffect->SetFloat("targetluminance", targetluminance);

		device->SetRenderTarget(0, oldtarget);
		device->SetTexture(0, scenetarget);			// scene
		device->SetTexture(1, blurtargets[0]);		// blur
		device->SetTexture(2, blurtargets[1]);		// star
		device->SetTexture(3, ghosttargets[0]);		// ghost
		device->SetTexture(4, afterimages[1 - afterimagetex]);

		device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
		device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
		device->SetRenderState(D3DRS_SRGBWRITEENABLE, true);

		oldtarget->Release();

		hdreffect->Begin(NULL, 0);
		hdreffect->BeginPass(0);
		{
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, sizeof(D3DXVECTOR4) + sizeof(D3DXVECTOR2));
		}
		hdreffect->EndPass();
		hdreffect->End();

		if( drawhelp )
		{
			// render text
			device->SetFVF(D3DFVF_XYZRHW|D3DFVF_TEX1);
			device->SetRenderState(D3DRS_ZENABLE, FALSE);
			device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
			device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
			device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

			device->SetTexture(0, text);
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, textvertices, 6 * sizeof(float));

			device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
			device->SetRenderState(D3DRS_ZENABLE, TRUE);
		}

		// clean up
		device->SetTexture(1, NULL);
		device->SetTexture(2, NULL);
		device->SetTexture(3, NULL);
		device->SetTexture(4, NULL);
		device->SetTexture(5, NULL);

		device->EndScene();
	}

	device->Present(NULL, NULL, NULL, NULL);
}
Example #13
0
//랜더
void Render(int timeDelta)
{
	//화면 청소
	if (SUCCEEDED(g_pDevice->Clear( 
		0,			//청소할 영역의 D3DRECT 배열 갯수		( 전체 클리어 0 )
		NULL,		//청소할 영역의 D3DRECT 배열 포인터		( 전체 클리어 NULL )
		D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL,	//청소될 버퍼 플레그 ( D3DCLEAR_TARGET 컬러버퍼, D3DCLEAR_ZBUFFER 깊이버퍼, D3DCLEAR_STENCIL 스텐실버퍼
		D3DCOLOR_XRGB(150, 150, 150),			//컬러버퍼를 청소하고 채워질 색상( 0xAARRGGBB )
		1.0f,				//깊이버퍼를 청소할값 ( 0 ~ 1 0 이 카메라에서 제일가까운 1 이 카메라에서 제일 먼 )
		0					//스텐실 버퍼를 채울값
		)))
	{
		//화면 청소가 성공적으로 이루어 졌다면... 랜더링 시작
		g_pDevice->BeginScene();

		//fps출력
		static WORD frameCnt = 0;
		static DWORD ntimeDelay = 0;
		static float fps = 0.f;
				
		frameCnt++;
		ntimeDelay += timeDelta;
		if( ntimeDelay >= 1000 )
		{	
			fps = (float)frameCnt;
			frameCnt = 0;
			ntimeDelay -= ntimeDelay;
		}		
		string outputFps = format( "%0.3f", fps );
		RECT rc;
		SetRect( &rc, 150, 100, 0, 0 );  //다이렉트 생성할때의 화면 크기의 좌표로 적용됨
		global->font->DrawTextA( NULL,   //A : 아스키코드
//			"global->font->DrawText", 
			outputFps.c_str(),
			-1, 
			&rc, 
			DT_NOCLIP,  //다 출력하겠다라는 의미(화면 크기 연연하지 않겠다인듯??)
			D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f) );
				

		//쿼터니언 응용	
		/*
		Quaternion quat;
		quat.SetRotationArc(Vector3(0,1,0),Vector3(0,0,1));  //첫번째 인자방향 기준으로 두번째 인자 방향으로
		Matrix44 qt = quat.GetMatrix();
		*/
		static float ftheta = 0.f;
		ftheta += 0.0005f;
		const float fradian = ftheta / MATH_PI;
		if( ftheta >= 360.f )
			ftheta = 0.f;
		Matrix44 mat;
		mat.SetTranslate(Vector3(5, sin(fradian) * 10.f, -490));  //sin(fradian) : 각도에 따른 +-변화  //10.f 곱하기는 범위
//		Matrix44 m = global->localTm * mat;
//		g_pDevice->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&m);  //마우스 회전 잠금
		g_pDevice->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&mat);
		global->mesh3DText->DrawSubset( 0 );
				
		Vector3 mainPos(-10, 0, -490);
		Vector3 targetLook = mat.GetPosition() - mainPos;  //대상물체와 메인물체와의 거리 판단
		targetLook.Normalize();
		Quaternion quat;
//		mainPos.Normalize();
//		quat.SetRotationArc(mainPos, targetLook);   //첫번째 인자를 물체의 위치로 하니 회전하는 방향이 생각과는 다르게 표현된다...역시 고정된 방향이어야 되나보다...
		quat.SetRotationArc(Vector3(1,0,0), targetLook);  //양의 x축방향으로 대상물체를 바라본다
		Matrix44 qm = quat.GetMatrix();
		mat.SetTranslate(mainPos);
		qm *= mat;
		g_pDevice->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&qm);
		global->mesh3DText->DrawSubset( 0 );
		
		//랜더링 끝
		g_pDevice->EndScene();
		//랜더링이 끝났으면 랜더링된 내용 화면으로 전송
		g_pDevice->Present( NULL, NULL, NULL, NULL );
	}
}
Example #14
0
File: main.cpp Project: mxt819/H405
//=============================================================================
//	エントリー関数
//=============================================================================
int APIENTRY WinMain(HINSTANCE _instanceHandle ,HINSTANCE _instanceHandlePrev, LPSTR _cmdLine, int _cmdShow)
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	UNREFERENCED_PARAMETER(_instanceHandlePrev);
	UNREFERENCED_PARAMETER(_cmdLine);

	DWORD execLastTime;
	DWORD LastTimeFPS;
	DWORD currentTime;
	DWORD flameCount;

	WNDCLASSEX wcex =
	{
		sizeof(WNDCLASSEX),
		CS_CLASSDC,
		WndProc,
		0,
		0,
		_instanceHandle,
		NULL,
		LoadCursor(NULL, IDC_ARROW),
		(HBRUSH)(COLOR_WINDOW + 1),
		NULL,
		CLASS_NAME,
		NULL
	};

	HWND windowHandle;
	MSG msg;
	
	//	ウィンドウクラスの登録
	RegisterClassEx(&wcex);

	//	ウィンドウの作成
	windowHandle = CreateWindowEx(0,
								  CLASS_NAME,
								  WINDOW_NAME,
								  WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME,
								  CW_USEDEFAULT,
								  CW_USEDEFAULT,
								  static_cast<int>(SCREEN_WIDTH + GetSystemMetrics(SM_CXDLGFRAME) * 2),
								  static_cast<int>(SCREEN_HEIGHT + GetSystemMetrics(SM_CXDLGFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION)),
								  NULL,
								  NULL,
								  _instanceHandle,
								  NULL);

	//	フレームカウント初期化
	timeBeginPeriod(1);	//	分解能を設定
	execLastTime = LastTimeFPS = timeGetTime();
	currentTime = flameCount = 0;

	//	ウインドウの表示(初期化処理の後に呼ばないと駄目)
	ShowWindow(windowHandle, _cmdShow);
	UpdateWindow(windowHandle);


#ifndef _DEBUG
	LoadLibraryA("WiiYourself.dll");
#else
	LoadLibraryA("WiiYourself_debug.dll");
#endif



	LPDIRECT3D9 direct3D;	//	Direct3D9用デバイス
	LPDIRECT3DDEVICE9 device;	//	_deviceオブジェクト(描画に必要)
	D3DDISPLAYMODE displayMode;
	D3DPRESENT_PARAMETERS presentParameter;

	//	Direct3Dオブジェクトの作成
	direct3D = Direct3DCreate9(D3D_SDK_VERSION);
	direct3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode);

	//	デバイスのプレゼンテーションパラメータの設定
	//--------------------------------------------------------------------
	//	ワークをゼロクリア
	ZeroMemory(&presentParameter, sizeof(presentParameter));

	//	バックバッファの数をセット
	presentParameter.BackBufferCount = 1;

	//ゲーム画面サイズ
	presentParameter.BackBufferWidth = static_cast<int>SCREEN_WIDTH;
	presentParameter.BackBufferHeight = static_cast<int>SCREEN_HEIGHT;

	//	バックバッファフォーマットはディスプレイモードに合わせて使う
	presentParameter.BackBufferFormat = displayMode.Format;

	//	映像信号に同期してフリップする
	presentParameter.SwapEffect = D3DSWAPEFFECT_DISCARD;

	//	ウィンドウモード
	presentParameter.Windowed = TRUE;

	//	デプスバッファ(Zバッファ)とステンシルバッファを作成
	presentParameter.EnableAutoDepthStencil = TRUE;

	//	デプスバッファの利用方法
	//	D3DFMT_D16		デプスバッファのみを16bitとして扱う
	//	D3DFMT_D24S8	デプスバッファを24bit ステンシルバッファを8bitとして扱う
	presentParameter.AutoDepthStencilFormat = D3DFMT_D24S8;

	//	ウィンドウモード
	presentParameter.FullScreen_RefreshRateInHz = 0;
	presentParameter.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	//--------------------------------------------------------------------

	direct3D->CreateDevice(D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		windowHandle,
		D3DCREATE_HARDWARE_VERTEXPROCESSING,
		&presentParameter,
		&device);




	CDebug* debug = new CDebug();
	debug->Init(device);

	CKeyboard* keyboard = new CKeyboard();
	keyboard->Init(_instanceHandle, windowHandle);

	CMouse* mouse = new CMouse();
	mouse->Init(_instanceHandle, windowHandle);

	CWiiController* wiiController = new CWiiController();


	//	メッセージループ
	for (;;)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (msg.message == WM_QUIT)
			{
				//	PostQuitMessage()が呼ばれたらループ終了
				break;
			}
			else
			{
				//	メッセージの翻訳とディスパッチ
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
		else
		{
			currentTime = timeGetTime();
			if ((currentTime - LastTimeFPS) >= 500)
			{
				#ifdef _DEBUG
					countFPS = flameCount * 1000 / (currentTime - LastTimeFPS);
				#endif

				LastTimeFPS = currentTime;
				flameCount = 0;
			}

			if ((currentTime - execLastTime) >= (1000 / 60))
			{
				execLastTime = currentTime ;


				keyboard->Update();
				mouse->Update();
				wiiController->update();


				{
					//	本体
					{
						debug->SetDebug("本体の加速度X [%f]\n", wiiController->getAccelerationX());
						debug->SetDebug("本体の加速度Y [%f]\n", wiiController->getAccelerationY());
						debug->SetDebug("本体の加速度Z [%f]\n", wiiController->getAccelerationZ());

						debug->SetDebug("本体の回転角X [%f]\n", wiiController->getRotX());
						debug->SetDebug("本体の回転角Y [%f]\n", wiiController->getRotY());
						debug->SetDebug("本体の回転角Z [%f]\n", wiiController->getRotZ());

						debug->SetDebug("本体の回転角の変異X [%f]\n", wiiController->getChangeRotX());
						debug->SetDebug("本体の回転角の変異Y [%f]\n", wiiController->getChangeRotY());
						debug->SetDebug("本体の回転角の変異Z [%f]\n", wiiController->getChangeRotZ());

						debug->SetDebug("本体の角速度X [%f]\n", wiiController->getRotSpeedX());
						debug->SetDebug("本体の角速度Y [%f]\n", wiiController->getRotSpeedY());
						debug->SetDebug("本体の角速度Z [%f]\n", wiiController->getRotSpeedZ());
					}

					//	ヌンチャク
					{
						debug->SetDebug("ヌンチャクの加速度X [%f]\n", wiiController->getAccelerationNX());
						debug->SetDebug("ヌンチャクの加速度Y [%f]\n", wiiController->getAccelerationNY());
						debug->SetDebug("ヌンチャクの加速度Z [%f]\n", wiiController->getAccelerationNZ());

						debug->SetDebug("ヌンチャクの回転角X [%f]\n", wiiController->getRotNX());
						debug->SetDebug("ヌンチャクの回転角Y [%f]\n", wiiController->getRotNY());
						debug->SetDebug("ヌンチャクの回転角Z [%f]\n", wiiController->getRotNZ());

						debug->SetDebug("ヌンチャクの位置X [%f]\n", wiiController->getJoystick().x);
						debug->SetDebug("ヌンチャクの位置Y [%f]\n", wiiController->getJoystick().y);
					}

					//	赤外線
					{
						debug->SetDebug("赤外線X [%f]\n", wiiController->getIR().x);
						debug->SetDebug("赤外線Y [%f]\n", wiiController->getIR().y);
					}

					debug->SetDebug("バッテリー残量[%d%]\n", wiiController->battery());

					debug->SetDebug("モーションPlusの接続状態[%d]\n", wiiController->getMotionConnect());

					/*if (wiiController->getTrigger(WC_A))
						wiiController->rumble(true);

					if (wiiController->getTrigger(WC_B))
						wiiController->rumble(false);

					if (wiiController->getTrigger(WC_UP))
						wiiController->rumble((unsigned int)1000);*/

					//	Aボタン
					{
						if (wiiController->getPress(WC_A))
							debug->SetDebug("A [ON]\n");
						else
							debug->SetDebug("A [OFF]\n");
					}

					//	Bボタン
					{
						if (wiiController->getPress(WC_B))
							debug->SetDebug("B [ON]\n");
						else
							debug->SetDebug("B [OFF]\n");
					}

					//	Cボタン
					{
						if (wiiController->getPress(WC_C))
							debug->SetDebug("C [ON]\n");
						else
							debug->SetDebug("C [OFF]\n");
					}

					//	Zボタン
					{
						if (wiiController->getPress(WC_Z))
							debug->SetDebug("Z [ON]\n");
						else
							debug->SetDebug("Z [OFF]\n");
					}

					//	↑ボタン
					{
						if (wiiController->getPress(WC_UP))
							debug->SetDebug("UP [ON]\n");
						else
							debug->SetDebug("UP [OFF]\n");
					}

					//	↓ボタン
					{
						if (wiiController->getPress(WC_DOWN))
							debug->SetDebug("DOWN [ON]\n");
						else
							debug->SetDebug("DOWN [OFF]\n");
					}

					//	←ボタン
					{
						if (wiiController->getPress(WC_LEFT))
							debug->SetDebug("LEFT [ON]\n");
						else
							debug->SetDebug("LEFT [OFF]\n");
					}

					//	→ボタン
					{
						if (wiiController->getPress(WC_RIGHT))
							debug->SetDebug("RIGHT [ON]\n");
						else
							debug->SetDebug("RIGHT [OFF]\n");
					}

					//	-ボタン
					{
						if (wiiController->getPress(WC_MINUS))
							debug->SetDebug("MINUS [ON]\n");
						else
							debug->SetDebug("MINUS [OFF]\n");

						if(wiiController->getTrigger(WC_MINUS))
							wiiController->rotSpeedCalibration();
					}

					//	+ボタン
					{
						if (wiiController->getPress(WC_PLUS))
							debug->SetDebug("PLUS [ON]\n");
						else
							debug->SetDebug("PLUS [OFF]\n");

						if(wiiController->getTrigger(WC_PLUS))
							wiiController->rotReset();
					}

					//	1ボタン
					{
						if (wiiController->getPress(WC_ONE))
							debug->SetDebug("ONE [ON]\n");
						else
							debug->SetDebug("ONE [OFF]\n");
					}

					//	2ボタン
					{
						if (wiiController->getPress(WC_TWO))
							debug->SetDebug("TWO [ON]\n");
						else
							debug->SetDebug("TWO [OFF]\n");
					}

					//	HOMEボタン
					{
						if (wiiController->getPress(WC_HOME))
							debug->SetDebug("HOME [ON]\n");
						else
							debug->SetDebug("HOME [OFF]\n");
					}
				}

				//	バックバッファ&Zバッファのクリア
				device->Clear(0,
					NULL,
					(D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER),
					D3DCOLOR_RGBA(255, 255, 255, 255),
					1.0f,
					0);

				//	Direct3Dによる描画の開始
				if (SUCCEEDED(device->BeginScene()))
				{
					CDebug::Draw();

					//	Direct3Dによる描画の終了
					device->EndScene();
				}

				//	バックバッファとフロントバッファの入れ替える
				device->Present(NULL, NULL, NULL, NULL);

				flameCount++;
			}
		}
	}

	SAFE_DELETE(wiiController);
	SAFE_DELETE(keyboard);
	SAFE_DELETE(mouse);
	SAFE_DELETE(debug);

	//	ウィンドウクラスの登録を解除
	UnregisterClass(CLASS_NAME, wcex.hInstance);

	timeEndPeriod(1);	//	分解能を戻す

	return static_cast<int>(msg.wParam);
}
Example #15
0
BOOL FSEndScene( void )
{
	return lpD3DDevice->EndScene() == D3D_OK;
}
Example #16
0
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
VOID Render(HWND hWnd)
{
	// Clear the backbuffer and the zbuffer
	g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 
		D3DCOLOR_XRGB(40,40,40), 1.0f, 0 );


	g_pd3dDevice->BeginScene();



	g_pd3dDevice->SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL );
	SetupMatrices();

	// Set up the vertex shader constants

	D3DXMATRIX mat;
	D3DXMATRIX mat1;
	D3DXMatrixMultiply( &mat, &g_matWorld, &g_matView );
	D3DXMatrixTranspose( &mat1, &mat );

	D3DXMatrixMultiply( &mat, &mat, &g_matProj );
	D3DXMatrixTranspose( &mat, &mat );

	// send the world matrix to the shader into constant register 0 (actually 0 to 3 due to the size of a matrix)
	g_pd3dDevice->SetVertexShaderConstantF(0, (float*)&mat,  4);


	// send the camera position to constant register 4
	float	fCamera[3] = { cameraPos.x , cameraPos.y , cameraPos.z };
	g_pd3dDevice->SetVertexShaderConstantF(4, (float*)fCamera,1);

	// send the light position into constant register 5
	float	fLightPosition[3] = { lightPos.x , lightPos.y , lightPos.z };
	g_pd3dDevice->SetVertexShaderConstantF(5, (float*)fLightPosition,1);

	// send the light 2  position into constant register 6
	float	fLightPosition2[3] = { -5.0f , 0.0f , 2.0f };
	g_pd3dDevice->SetVertexShaderConstantF(6, (float*)fLightPosition2,1);

	// send the light 3 position into constant register 7
	float	fLightPosition3[3] = { 0.0f , 5.0f , -2.0f };
	g_pd3dDevice->SetVertexShaderConstantF(7, (float*)fLightPosition3,1);

	// send the diffuse color into constant register 8
	float	diffuseColor[4] = { 0.90f, 0.90f, 0.90f, 1.0f };
	g_pd3dDevice->SetVertexShaderConstantF(8, (float*)diffuseColor, 1);

	// send the diffuse color 2 into constant register 9
	float	diffuseColor2[4] = { 0.95f, 0.20f, 0.10f, 1.0f };
	g_pd3dDevice->SetVertexShaderConstantF(9, (float*)diffuseColor2, 1);

	// send the diffuse color 3  into constant register 10
	float	diffuseColor3[4] = { 0.10f, 0.20f, 0.95f, 1.0f };
	g_pd3dDevice->SetVertexShaderConstantF(10, (float*)diffuseColor3, 1);

	// send the ambient colour into constant register 11
	float	fAmbient[4] = {0.1f, 0.1f, 0.1f, 1.0f};
	g_pd3dDevice->SetVertexShaderConstantF(11, (float*)fAmbient,1);

	// send the specular lighting colour into constant register 12
	float	fSpecularLight[4] = {1.0f, 1.0f, 1.0f, 1.0f};
	g_pd3dDevice->SetVertexShaderConstantF(12, (float*)fSpecularLight,1);

	// send the reflection constant to constant register 13
	float	fReflection = 10.0f;
	g_pd3dDevice->SetVertexShaderConstantF(13,&fReflection,1);

	// send the separation line to constant register 14
	float	separationLine = 0.0f;
	g_pd3dDevice->SetVertexShaderConstantF(14,&separationLine,1);

	// send ambient material to the constant register 15
	float	ambientMaterial[4] = { 0.25f , 0.25f , 0.25f , 1.0f};
	g_pd3dDevice->SetVertexShaderConstantF(15,(float*)ambientMaterial,1);

	// send diffuse material one to constant register 16
	float	diffuseMaterial1[4] = { 0.75f , 0.60f , 0.40f , 1.0f};
	g_pd3dDevice->SetVertexShaderConstantF(16,(float*)diffuseMaterial1,1);

	// send diffuse material two to constant register 17
	float	diffuseMaterial2[4] = { 0.95f , 0.20f , 0.1f , 1.0f };
	g_pd3dDevice->SetVertexShaderConstantF(17,(float*)diffuseMaterial2,1);

	// send specular material to the constant register 18
	float	specularMaterial[4] = { 1.0f , 1.0f , 1.0f , 1.0f};
	g_pd3dDevice->SetVertexShaderConstantF(18,(float*)specularMaterial,1);



	//   Render the vertex buffer contents 
	g_pd3dDevice->SetFVF(D3DFVF_D3DVERTEX );
	g_pd3dDevice->SetStreamSource( 0, g_pMeshVB, 0, sizeof(D3DVERTEX) );
	g_pd3dDevice->SetIndices( g_pMeshIB);
	g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
	g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
	g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
	g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_MODULATE );
	g_pd3dDevice->SetTexture( 0, g_pTexture ); 

	switch ( currentShader )  // activate the appropiate vertex shader
	{
		case 1:	g_pd3dDevice->SetVertexShader( g_pVertexShader); break;
		case 2:	g_pd3dDevice->SetVertexShader( g_pVertexShader2); break;
		case 3:	g_pd3dDevice->SetVertexShader( g_pVertexShader3); g_pd3dDevice->SetTexture( 0, g_pTexture2 );break;
		case 4:	g_pd3dDevice->SetVertexShader( g_pVertexShader4); break;
		case 5:	g_pd3dDevice->SetVertexShader( g_pVertexShader5); g_pd3dDevice->SetTexture( 0, marbleTexture ); break;
		case 6:	g_pd3dDevice->SetVertexShader( g_pVertexShader6); g_pd3dDevice->SetTexture( 0, backgroundTexture );break;
	};


	g_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,0,
		0, g_dwNumVertices,
		0, g_dwNumFaces );

	// End the scene.
	g_pd3dDevice->EndScene();

	// Present the backbuffer contents to the display
	g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
Example #17
0
// 使用DirectX 9來繪圖
void RenderFrameDX9(void)
{
	LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9();
	Vector4 vPlane(0.0f, 0.0f, 1.0f, -g_mirror_z);

	// 開始下繪圖指令
	device->BeginScene(); 

	{
		LPDIRECT3DSURFACE9 pFrameBufferBackup, pDepthBufferBackup;
		device->GetRenderTarget(0, &pFrameBufferBackup); pFrameBufferBackup->Release();
		device->GetDepthStencilSurface(&pDepthBufferBackup); pDepthBufferBackup->Release();

		LPDIRECT3DSURFACE9 pSurface;
		g_pTexture->GetSurfaceLevel(0, &pSurface); 

		device->SetRenderTarget(0, pSurface);
		device->SetDepthStencilSurface(g_pDepthStencil);

		device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0, 0, 200, 255), 1.0f, 0);

		RenderModelDX9(true, &vPlane);

		pSurface->Release();
		device->SetRenderTarget(0, pFrameBufferBackup);
		device->SetDepthStencilSurface(pDepthBufferBackup);
	}

	// 把上一個步驟的結果當成貼圖來使用
	{
		// 消除畫面
		device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0, 0, 150, 255), 1.0f, 0);

		RenderModelDX9(false, NULL);

		Matrix4x4 identMat; identMat.Identity();
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &identMat);

		sModelMaterial_DX9 material;
		material.m_pTextures[0] = g_pTexture;
		material.Submit();

		device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
		device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
		device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);

		device->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
		device->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
		device->SetSamplerState(1, D3DSAMP_MIPFILTER, D3DTEXF_NONE);

		Matrix4x4 uv_offset_matrix;
		uv_offset_matrix.Scale_Replace(0.5f, -0.5f, 1.0f);
		uv_offset_matrix[3].Set(0.5f, 0.5f, 0.5f, 1.0f);

		Matrix4x4 inv_view_matrix = g_Control.GetViewMatrix();
		inv_view_matrix.FastInvert();

		Matrix4x4 texture_matrix = inv_view_matrix * g_mirror_view_matrix * g_projection_matrix * uv_offset_matrix;

		device->SetTransform(D3DTS_TEXTURE0, (D3DMATRIX *) &texture_matrix);
		device->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
		// D3DTTFF_PROJECTED告知direct3d裝置texcoord需要除以w
		device->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT4|D3DTTFF_PROJECTED);
		float v[12];
		for ( int i=0; i<4; i++ )
		{
			g_Quad[i].m_Position.StoreXYZ(&v[i*3]);
		}
		// 畫出矩形
		device->SetFVF(D3DFVF_XYZ);
		//device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Quad, sizeof(Vertex_V));
		device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, 12);

	}

	// 宣告所有的繪圖指令都下完了
	device->EndScene(); 

	// 把背景backbuffer的畫面呈現出來
	device->Present( NULL, NULL, NULL, NULL );
}
Example #18
0
// 使用DirectX 9來繪圖
void RenderFrameDX9(void)
{
	DWORD FogColor = D3DCOLOR_RGBA(128, 128, 128, 255);

	LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9();

	device->BeginScene(); 
	// 消除畫面
	device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, FogColor, 1.0f, 0);
	// 設定轉換矩陣
	Matrix4x4 view_matrix = g_Control.GetViewMatrix();
	Matrix4x4 object_matrix = g_Control.GetObjectMatrix();

	device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix);
	device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix);
	device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &object_matrix);
	// 設定霧
	device->SetRenderState(D3DRS_FOGENABLE, TRUE);
	device->SetRenderState(D3DRS_FOGCOLOR, FogColor);

	switch(g_iFogMode)
	{
	case 0:
		device->SetRenderState(D3DRS_FOGENABLE, FALSE);
		break;
	case 1:
		{
			// 隨距離線性變濃的霧
			float fStart = 0.0f;
			float fEnd = 10.0f;
			device->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR);
			device->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&fStart));
			device->SetRenderState(D3DRS_FOGEND, *(DWORD *)(&fEnd));
			// 計算公式為
			// (fog_end - distance_to_camera) / (fog_end - fog_start)
			break;
		}
	case 2:
		{
			// `套用指數函式來變化的霧 `
			float fFogDensity = 0.5f;
			device->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_EXP);
			device->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)&fFogDensity);
			// 計算公式為
			// power(e, -(fog_density * distance_to_camera))
			break;
		}
	case 3:
		{
			// `套用指數函式來變化的霧 `
			float fFogDensity = 0.5f;
			device->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_EXP2);
			device->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)&fFogDensity);
			// 計算公式為
			// power(e, -(fog_density * distance_to_camera)^2)
			break;
		}
	}
	// 畫出模型
	g_Model_DX9.Render();
	// 宣告所有的繪圖指令都下完了
	device->EndScene(); 
	// 把背景backbuffer的畫面呈現出來
	device->Present( NULL, NULL, NULL, NULL );
}
Example #19
0
 /* =============== */
 virtual void leave ()
 {
     m_devcs->EndScene();
 }
Example #20
0
VOID Render()
{
	static __int64 _lastFrameTime, currTime, cps;
	static float _deltaT;

	static D3DXMATRIX t;
	D3DXMatrixTranslation(&ObjectAllign, 0.0f, 0.0f, 0);
	D3DXMatrixRotationYawPitchRoll(&t, 0, 0, D3DX_PI);
	D3DXMatrixMultiply(&ObjectAllign, &ObjectAllign, &t);


	pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 
					  D3DCOLOR_XRGB(100,100,255), 1.0f, 0x0);


	if( SUCCEEDED( pD3DDevice->BeginScene() ) ) ///////////////////////////////////////////////////
	{
		pD3DDevice->SetVertexShader(NULL);

		// Set properties
		g_dist_tolerance = GetTolerance(fabs(Position.z));
		for(int l = 0; l < LAYER_NUM; ++l)
		{
			for(size_t i = 0; i < g_layers[l].Components().size(); ++i)
			{
				g_layers[l].Components()[i]->SetProperty(VG::PP_DEFAULT_JOINT, g_joint_style);
				g_layers[l].Components()[i]->SetProperty(VG::PP_DEFAULT_ENDING, g_ending_style);
				g_layers[l].Components()[i]->DistanceTolerance() = g_dist_tolerance;
			}
		}


		// Calculate paths
		size_t triangles = 0;
		for(int l = 0; l < LAYER_NUM; ++l)
		{
			g_layers[l].Recalculate();
			triangles += g_layers[l].TriangleCount();
		}

		// Draw layers
		D3DXMATRIX m;
		D3DXMatrixRotationYawPitchRoll(&m, CameraRotation.y, CameraRotation.x, CameraRotation.z);
		D3DXMatrixMultiply(&m, &ObjectAllign, &m);
		pD3DDevice->SetTransform(D3DTS_WORLD, &m);

		for(int l = 0; l < LAYER_NUM; ++l)
		{
			g_layers[l].Draw(pD3DDevice);
		}


		// FPS
		wchar_t buf[1000];
		RECT rect = {0, 0, iWidth, iHeight};
		swprintf(buf, 1000, L"FPS: %d \nSec: %f \nTriangles: %d \nDistance: %f \nTolerance: %f", 
			int(1.0f / _deltaT), 
			_deltaT, 
			triangles,
			fabs(Position.z),
			g_dist_tolerance);
		g_font->DrawText(NULL, buf, -1, &rect, DT_TOP | DT_LEFT, 0xff80ff80);
		
		pD3DDevice->EndScene();//////////////////////////////////////////////////////////
	}

	pD3DDevice->Present(NULL, NULL, NULL, NULL);

	BOOL ok = QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
	assert(ok);
	ok = QueryPerformanceFrequency((LARGE_INTEGER*)&cps);
	assert(ok);

	_deltaT = float(currTime - _lastFrameTime) / cps;
	_lastFrameTime = currTime;
}
Example #21
0
// 使用Direct3D9來繪圖
void RenderFrameDX9(void)
{
	LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9();
	// `消除畫面`
	device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1.0f, 0);
	// `開始下繪圖指令`
	device->BeginScene(); 
	// `設定矩陣`
	Matrix4x4 view_matrix = g_Control.GetViewMatrix();
	Matrix4x4 object_matrix = g_Control.GetObjectMatrix();
	device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix);
	device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &object_matrix);
	// `設定資料格式`
	device->SetFVF(D3DFVF_XYZ|D3DFVF_TEX1); 
	// `套用貼圖`
	device->SetTexture(0, g_pTexture);

	device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
	device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);

	switch(g_iFilterMode)
	{
	case 1: // linear filtering
		// `貼圖被放大時, 取最接近4個點來內插.`
		device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
		// `貼圖被縮小時, 取最接近4個點來平均.`
		device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
		// `不使用Mipmap`
		device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
		break;
	case 2: // bilinear filtering
		// `貼圖被放大時, 取最接近4個點來內插.`
		device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
		// `貼圖被縮小時, 取最接近4個點來平均.`
		device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
		// `取最接近大小的圖層`
		device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
		break;
	case 3: // trilinear filtering
		// `貼圖被放大時, 取最接近4個點來內插.`
		device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
		// `貼圖被縮小時, 取最接近4個點來平均.`
		device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
		// `取最接近大小的兩個圖層, 然後再內插.`
		device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
		break;
	case 4: // anisotropic filtering
		// `會根據縮放的長寬比例來取用貼圖, 不固定是取哪幾個圖.`
		device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
		device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC);
		device->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, 8);
		// `取最接近大小的兩個圖層, 然後再內插.`
		device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
		break;
	}
	// `畫出矩形`
	device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Quad, sizeof(Vertex_VT));
	// `宣告所有的繪圖指令都下完了`
	device->EndScene(); 
	// `把背景backbuffer的畫面呈現出來`
	device->Present( NULL, NULL, NULL, NULL );
}
Example #22
0
	void EndGraphics() {
		device->EndScene();
		device->Present(0, 0, 0, 0);
	}
Example #23
0
///////////////////////////////////////////////////////////////////////
///
/// Generate a shadow map of the scene
///
void VCND3D9EffectCore::GenerateShadowMap()
{
	GPU_PROFILE_BLOCK_NAME( VCNTXT("Shadow Map") );

	HRESULT hr = S_FALSE;
	
	// Notify that we have start to render shadow map
	mGeneratingShadowMap = true;

	VCND3D9* renderer = static_cast<VCND3D9*>(VCNRenderCore::GetInstance());
	LPDIRECT3DDEVICE9 device = renderer->GetD3DDevice();

	// Keep track of the previous back buffer
	CComPtr<IDirect3DSurface9> d3dBackBuffer;
	hr = device->GetRenderTarget(0, &d3dBackBuffer);

	// Set shadow map surface and start rendering of scene using the shadow map effect
	CComPtr<IDirect3DSurface9> shadowMapSurface;
	hr = mShadowMapTexture->GetSurfaceLevel(0, &shadowMapSurface);
	VCN_ASSERT( SUCCEEDED(hr) );

	hr = device->SetRenderTarget(0, shadowMapSurface);
	VCN_ASSERT( SUCCEEDED(hr) );

	// Set the map viewport
	D3DSURFACE_DESC d3dSurfaceDesc;
	shadowMapSurface->GetDesc( &d3dSurfaceDesc );
	VCNRenderCore::GetInstance()->SetViewport(d3dSurfaceDesc.Width, d3dSurfaceDesc.Height);

	// Clear the shadow map for what's coming
	device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0, 1.0f, 0);

	// Start rendering to the map
	hr = device->BeginScene();
	VCN_ASSERT( SUCCEEDED(hr) );  
	
	device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN);
	device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
	device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
	device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO);

	// Backup current view settings
	const Matrix4 oldView = VCNXformCore::GetInstance()->GetViewMatrix();
	const Matrix4 oldProj = VCNXformCore::GetInstance()->GetProjectionMatrix();
	const VCNProjectionType oldProjType = VCNXformCore::GetInstance()->GetProjectionType();
	
	// Set the view as the light view when generating the shadow map.
	VCNLight* shadowLightSource = VCNLightingCore::GetInstance()->GetLight(0);
	const Matrix4 lightProj = shadowLightSource->GetProjectionMatrix();
	const Matrix4 lightView = shadowLightSource->GetViewMatrix();
	
	VCNXformCore::GetInstance()->SetViewLookAt( lightView );
	VCNXformCore::GetInstance()->SetProjectionMatrix( lightProj );
	
	// Draw scene
	// TODO: Generate map for each light
	VCNNodeCore::GetInstance()->GetRootNode()->Render();

	// Restore view
	VCNXformCore::GetInstance()->SetProjectionType( oldProjType, oldProj );
	VCNXformCore::GetInstance()->SetViewLookAt( oldView );

	// Restore color writes
	device->SetRenderState(D3DRS_COLORWRITEENABLE, 
		D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE);

	hr = device->EndScene();
	VCN_ASSERT( SUCCEEDED(hr) );

	// Set shadow map texture for effects that needs it
	// TODO: Effects that need the shadow map should pull it from the effect core shadow maps pool
	mEffectMap[eidLitTextured]->Cast<VCND3D9_LitTexturedFX>()->SetShadowMapTexture( mShadowMapTexture );
	mEffectMap[eidSkinned]->Cast<VCND3D9_LitTexturedSkinnedFX>()->SetShadowMapTexture( mShadowMapTexture );
	mEffectMap[eidTerrain]->Cast<VCND3D9_TerrainFX>()->SetShadowMapTexture( mShadowMapTexture );

	// Restore back buffer
	device->SetRenderTarget(0, d3dBackBuffer);

	// Restore back buffer viewport
	VCNRenderCore::GetInstance()->RestoreFullViewport();

	// We are done generating shadow map
	mGeneratingShadowMap = false;
}
VOID Render()
{
	g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
		D3DCOLOR_XRGB( 0, 0, 255 ), 1.0f, 0 );

	// Begin the scene
	if ( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
	{
		// Setup the world, view, and projection matrices
		SetupCylinderMatrices();

		// Setup the Lights and materials
		SetupLightEnvironment();

		// swtich Light every one second
		if ( HeartBeatOneSecond() )
		{
			SetupLights1();
			LoadBananaTexture();
		}
		else
		{
			SetUpLights2();
			LoadStoneTexture();
		}

		g_pd3dDevice->SetTexture( 0, g_pTexture );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );

		// Render the vertex buffer contents
		g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
		g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
		g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 * 50 - 2 );

		// setup Tiger matrix
		SetupTigerMatrices();

		// draw Tiger
		if ( SUCCEEDED( LoadMesh() ) )
		{
			for ( DWORD i = 0; i < g_dwNumMaterials; ++i )
			{
				g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );
				g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );

				g_pMesh->DrawSubset( i );
			}
		}

		// setup Tiger 2 matrix
		SetupTigerSecondMatrices();

		if ( SUCCEEDED( LoadSecondMesh() ) )
		{
			for ( DWORD i = 0; i < g_dwNumMaterialsSecond; ++i )
			{
				g_pd3dDevice->SetMaterial( &g_pMeshMaterialsSecond[i] );
				g_pd3dDevice->SetTexture( 0, g_pMeshTexturesSecond[i] );

				g_pMeshSecond->DrawSubset( i );
			}
		}

		// End the scene
		g_pd3dDevice->EndScene();
	}

	// Present the backbuffer contents to the display
	g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
VOID Render(float timeDelta)
{
	SetupMatrix() ;

	// Clear the back-buffer to a RED color
	g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );

	static float totalTime = 0.0f ;


	// Begin the scene
	if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
	{
		// build rotation matrix
		for (int i = 0; i < 4; i++)
		{
			totalTime += timeDelta ; // angle
			D3DXMATRIX matRotation ;

			if(i == 0) // rotate teapot by Z
				D3DXMatrixRotationZ(&matRotation, totalTime) ;
			else if (i == 1) // rotate sphere by Y
			{
				D3DXMatrixRotationY(&matRotation, totalTime) ;

			}
			else if(i == 2) // rotate Cylinder by X
			{
				D3DXMatrixRotationX(&matRotation, totalTime) ;
			}
			else // rotate torus by axis = (1.0f, 1.0f, 1.0f)
				D3DXMatrixRotationAxis(&matRotation, &D3DXVECTOR3(1.0f, 1.0f, 1.0f), totalTime) ;

			// move object to origin
			D3DXMatrixTranslation(&matWorld[i], 0.0f, 0.0f, 0.0f) ;

			// rotate
			D3DXMatrixMultiply(&matWorld[i], &matWorld[i], &matRotation) ;
		}

		// Move object back to its original position
		D3DXMATRIX world[4];
		D3DXMatrixTranslation(&world[0], -2.0f, 0.0f, 0.0f) ;
		D3DXMatrixTranslation(&world[1], 2.0f, 0.0f, 0.0f) ;
		D3DXMatrixTranslation(&world[2], 0.0f, 2.0f, 0.0f) ;
		D3DXMatrixTranslation(&world[3], 0.0f, -2.0f, 0.0f) ;

		// multiply with world matrix to get the final transform matrix and apply it
		for (int i = 0; i < 4; i++)
		{
			matWorld[i] *= world[i] ;

			g_pd3dDevice->SetTransform(D3DTS_WORLD, &matWorld[i]) ;
			g_pMeshes[i]->DrawSubset(0) ;

		}

		// End the scene
		g_pd3dDevice->EndScene();
	}

	// Present the back-buffer contents to the display
	g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
Example #26
0
HRESULT KGraphicsEngine::Render()
{
	HRESULT hr = S_OK;
	
	if(!g_hRenderWnd)
		return FALSE;

	if(TRUE!=::GetWindowRect(g_hRenderWnd,&m_RenderWindowRect))
	{
		//MessageBox(g_hBaseWnd,"不知道该渲染到什么地方","Error!",0);

		return FALSE;
	}

	if (m_lpCurScene!=NULL) 
		m_lpCurScene->FrameMove();

	g_cGraphicsTool.SetCurScene(m_lpCurScene);
	
	RECT ScrRect;
	ScrRect.left = 0;
	ScrRect.right = m_RenderWindowRect.right - m_RenderWindowRect.left;
	ScrRect.top = 0;
	ScrRect.bottom = m_RenderWindowRect.bottom - m_RenderWindowRect.top;

	D3DVIEWPORT9 ViewPort;
	ViewPort.X = m_RenderWindowRect.left;
	ViewPort.Y = m_RenderWindowRect.top;
	ViewPort.Width  = ScrRect.right;
	ViewPort.Height = ScrRect.bottom;
	ViewPort.MinZ = 0;
	ViewPort.MaxZ = 1.0f;
	g_pd3dDevice->SetViewport(&ViewPort);
	
	LPDIRECT3DSURFACE9 lpSurface = NULL;
	LPDIRECT3DSURFACE9 lpSurfaceSave = NULL;
	
	if (m_bUseMotionBlur)
	{	
		if (m_BufferTextureID)
		{
			g_pd3dDevice->GetRenderTarget(0,&lpSurfaceSave);
			lpSurfaceSave->Release();
			
			LPTEXTURE pTexture = NULL;
			if (FAILED(g_cTextureTable.GetTexture(&pTexture,m_BufferTextureID)))
			{
				return E_FAIL;
			}
			
			if (FAILED(hr = pTexture->m_lpTexture->GetSurfaceLevel(0,&lpSurface)))
				return hr;
			
			lpSurface->Release();
			g_pd3dDevice->SetRenderTarget(0,lpSurface);
		}
	}


	m_cCamera.zFar = 1000000;
	if (!m_bWindowed)
	{
		m_cCamera.Aspect = m_DisplayMode.Width*1.0f/m_DisplayMode.Height;
	}
	m_cCamera.SetCamera();

	if (m_lpCurScene!=NULL) 
		m_lpCurScene->SetLighting();

	g_pd3dDevice->BeginScene();
	g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
		0xFF606060, 1.0f, 0 );

	if (m_lpCurScene!=NULL) 
		m_lpCurScene->Render();
	
	
	//////////////////////////////////////////////////////////////////////////
	/*D3DXVECTOR3 V = D3DXVECTOR3(400*sinf(timeGetTime()*0.001f) ,
		                 100,
		                 400*cosf(timeGetTime()*0.001f) -2000 );
	g_cGraphicsTool.DrawLine(&(V+D3DXVECTOR3(0,35,0)),&(V+D3DXVECTOR3(0,-35,0)),0xffffffff,0xffff0000); 
	g_cGraphicsTool.DrawLine(&(V+D3DXVECTOR3(35,0,0)),&(V+D3DXVECTOR3(-35,0,0)),0xffffffff,0xffff0000); 
	g_cGraphicsTool.DrawLine(&(V+D3DXVECTOR3(0,0,35)),&(V+D3DXVECTOR3(0,0,-35)),0xffffffff,0xffff0000); */
	g_pd3dDevice->EndScene();

	if (m_bUseMotionBlur)
	{
		if (m_BufferTextureID)
		{
			g_pd3dDevice->SetRenderState(D3DRS_FOGENABLE,FALSE);

			g_pd3dDevice->SetRenderTarget(0,lpSurfaceSave);

			Render2SmallerTexture();
			
			g_pd3dDevice->BeginScene();
			g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
				0x00000000, 1.0f, 0 );

			D3DXVECTOR2 A(0,0),C((float)m_DisplayMode.Width,(float)m_DisplayMode.Height);
			float K = 3;

			D3DXVECTOR2 T1(5,5);
			D3DXVECTOR2 T2(-3,3);

			
			//g_cTextureTable.SetTexture(0,m_BufferTextureID);
			g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE ,FALSE);
			g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
			g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
			g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);
			
			
			//g_cGraphicsTool.DrawScreenRectNormal(&A,&C,0.0f,0x90FFFFFF,0x90FFFFFF,0x90FFFFFF,0x90FFFFFF);
			
			g_cGraphicsTool.DrawScreenRect(&A,&C,0.0f,0xFFFFFFFF,m_BufferTextureID);

			g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
			g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
			g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_ONE);

			if (m_lpCurScene!=NULL) 
			{
				g_cGraphicsTool.DrawScreenRect(&(A-T1),&(C),0.0f,m_lpCurScene->m_Glow.m_AddColor,m_SmallerTextureID);
			}
			/*g_cGraphicsTool.DrawScreenRect(&(A-T1),&(C-T1),0.0f,0xFF808080,m_BufferTextureID);
			g_cGraphicsTool.DrawScreenRect(&(A+T1),&(C+T1),0.0f,0xFF808080,m_BufferTextureID);
			g_cGraphicsTool.DrawScreenRect(&(A-T2),&(C-T2),0.0f,0xFF808080,m_BufferTextureID);
			g_cGraphicsTool.DrawScreenRect(&(A+T2),&(C+T2),0.0f,0xFF808080,m_BufferTextureID);*/
			//g_cGraphicsTool.DrawScreenRectDp3(&A,&C,0.0f,0xFF8F8F8F,m_BufferTextureID);
			g_pd3dDevice->EndScene();
			
		}
	}

	if (m_bWindowed)
	{
		//只将backbuffer中的一个区域提交到窗口上
		if(g_hRenderWnd)
		{
			g_pd3dDevice->Present( &m_RenderWindowRect,NULL, g_hRenderWnd, NULL );
		}
		else
		{
			MessageBox(g_hBaseWnd,"不知道该渲染到什么地方","Error!",0);
		}
	}
	else
	{
		g_pd3dDevice->Present( NULL, NULL, g_hRenderWnd, NULL );
	}

	g_dwRenderCount++;
	return TRUE;
}
VOID Render()
{
	if ( NULL == g_pd3dDevice )
	{
		return;
	}

	g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
						 D3DCOLOR_XRGB( 30, 10, 10 ), 1.0f, 0 );

	if ( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
	{
		SetupLights();

		SetupMatrices();

		if ( g_Tick )
		{
			g_pd3dDevice->SetTexture( 0, g_pTexture1 );
		}
		else
		{
			g_pd3dDevice->SetTexture( 0, g_pTexture2 );
		}

		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );

#ifdef SHOW_HOW_TO_USE_TCI
		D3DXMATRIXA16 mTextureTransform;
		D3DXMATRIXA16 mProj;
		D3DXMATRIXA16 mTrans;
		D3DXMATRIXA16 mScale;

		g_pd3dDevice->GetTransform( D3DTS_PROJECTION , &mProj );
		D3DXMatrixTranslation( &mTrans , 0.5f , 0.5f , 0.0f );
		D3DXMatrixScaling( &mScale , 0.5f , -0.5f , 1.0f );
		mTextureTransform = mProj * mScale * mTrans;

		g_pd3dDevice->SetTransform( D3DTS_TEXTURE0 , &mTextureTransform );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT4 | D3DTTFF_PROJECTED );
		g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION );
#endif
		g_pd3dDevice->SetStreamSource( 0, g_pVB1, 0, sizeof( CUSTOMVERTEX ) );
		g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
		g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 * 50 - 2 );

		if ( g_Tick )
		{
			g_pd3dDevice->SetTexture( 0, g_pTexture2 );
		}
		else
		{
			g_pd3dDevice->SetTexture( 0, g_pTexture1 );
		}

		g_pd3dDevice->SetStreamSource( 0, g_pVB2, 0, sizeof( CUSTOMVERTEX ) );
		g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
		g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 * 50 - 2 );

		float scale = sinf( static_cast<float>( D3DX_PI * timeGetTime() / 1000 ) ) * 0.8f;
		D3DXMATRIXA16 thisMatrix, prevMatrix;

		g_pd3dDevice->GetTransform( D3DTS_WORLD, &prevMatrix );

		D3DXMATRIXA16 matFirstTiger, matTrans, matRotate;

		D3DXMatrixRotationY( &matRotate, timeGetTime() / 1000.0f );
		D3DXMatrixTranslation( &matTrans, -3.f, 2.0f, 5.0f );
		D3DXMatrixMultiply( &matFirstTiger, &matRotate, &matTrans );
		g_pd3dDevice->SetTransform( D3DTS_WORLD, &matFirstTiger );

		for ( DWORD i = 0; i < g_dwNumMaterials; ++i )
		{
			g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );
			g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );
			g_pMesh->DrawSubset( i );
		}

		g_pd3dDevice->SetTransform( D3DTS_WORLD, &prevMatrix );

		D3DXMatrixTranslation( &thisMatrix, 3.0f, 2.0f, 5.0f );
		g_pd3dDevice->MultiplyTransform( D3DTS_WORLD, &thisMatrix );
		D3DXMatrixScaling( &thisMatrix, -scale + 1.0f, 1.0f, 1.0f );
		g_pd3dDevice->MultiplyTransform( D3DTS_WORLD, &thisMatrix );

		for ( DWORD i = 0; i < g_dwNumMaterials; ++i )
		{
			g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );
			g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );
			g_pMesh->DrawSubset( i );
		}

		g_pd3dDevice->EndScene();
	}

	g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
//-----------------------------------【Direct3D_Render( )函数】-------------------------------
//	描述:使用Direct3D进行渲染
//--------------------------------------------------------------------------------------------------
void Direct3D_Render(HWND hwnd)
{

	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之一】:清屏操作
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(100, 100, 100), 1.0f, 0);

	//定义一个矩形,用于获取主窗口矩形
	RECT formatRect;
	GetClientRect(hwnd, &formatRect);
	
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之二】:开始绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->BeginScene();                     // 开始绘制

	// 绘制网格
	for (DWORD i = 0; i < g_dwNumMtrls; i++)
	{
		g_pd3dDevice->SetMaterial(&g_pMaterials[i]);
		g_pd3dDevice->SetTexture(0, g_pTextures[i]);
		g_pMesh->DrawSubset(i);
	}

			//在窗口右上角处,显示每秒帧数
			int charCount = swprintf_s(g_strFPS, 20, _T("FPS:%0.3f"), Get_FPS() );
			g_pTextFPS->DrawText(NULL, g_strFPS, charCount , &formatRect, DT_TOP | DT_RIGHT, D3DCOLOR_RGBA(0,239,136,255));

			//显示显卡类型名
			g_pTextAdaperName->DrawText(NULL,g_strAdapterName, -1, &formatRect, 
				DT_TOP | DT_LEFT, D3DXCOLOR(1.0f, 0.5f, 0.0f, 1.0f));

			// 输出绘制信息
			 formatRect.top = 30;
			static wchar_t strInfo[256] = {0};
			swprintf_s(strInfo,-1, L"模型坐标: (%.2f, %.2f, %.2f)", g_matWorld._41, g_matWorld._42, g_matWorld._43);
			g_pTextHelper->DrawText(NULL, strInfo, -1, &formatRect, DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(135,239,136,255));

			// 输出帮助信息
			formatRect.left = 0,formatRect.top = 380;
			g_pTextInfor->DrawText(NULL, L"控制说明:", -1, &formatRect, 
				DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(235,123,230,255));
			formatRect.top += 35;
			g_pTextHelper->DrawText(NULL, L"    按住鼠标左键并拖动:平移模型", -1, &formatRect, 
				DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255,200,0,255));
			formatRect.top += 25;
			g_pTextHelper->DrawText(NULL, L"    按住鼠标右键并拖动:旋转模型", -1, &formatRect, 
				DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255,200,0,255));
			formatRect.top += 25;
			g_pTextHelper->DrawText(NULL, L"    滑动鼠标滚轮:拉伸模型", -1, &formatRect, 
				DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255,200,0,255));
			formatRect.top += 25;
			g_pTextHelper->DrawText(NULL, L"    W、S、A、D键:平移模型 ", -1, &formatRect, 
				DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255,200,0,255));
			formatRect.top += 25;
			g_pTextHelper->DrawText(NULL, L"    上、下、左、右方向键:旋转模型 ", -1, &formatRect, 
				DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255,200,0,255));
			formatRect.top += 25;
			g_pTextHelper->DrawText(NULL, L"    ESC键 : 退出程序", -1, &formatRect, 
				DT_SINGLELINE | DT_NOCLIP | DT_LEFT, D3DCOLOR_RGBA(255,200,0,255));

	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之四】:结束绘制
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->EndScene();                       // 结束绘制
	//--------------------------------------------------------------------------------------
	// 【Direct3D渲染五步曲之五】:显示翻转
	//--------------------------------------------------------------------------------------
	g_pd3dDevice->Present(NULL, NULL, NULL, NULL);  // 翻转与显示
	 
}
Example #29
0
//*************************************************************************************************************
void Render(float alpha, float elapsedtime)
{
	static float time = 0;

	D3DXMATRIX		view, proj, vp;
	D3DXMATRIX		world;
	D3DXMATRIX		inv;

	D3DXVECTOR4		amblight(0.2f, 0.2f, 0.2f, 1);
	D3DXVECTOR4		intensity(0.8f, 0.8f, 0.8f, 1);
	D3DXVECTOR4		zero(0, 0, 0, 1);

	D3DXVECTOR3		lightpos(0, 0, -10);
	D3DXVECTOR3		eye(0, 0, -5.2f);
	D3DXVECTOR3		look(0, 0.5f, 0);
	D3DXVECTOR3		up(0, 1, 0);
	D3DXVECTOR3		p1, p2;
	D3DXVECTOR2		orient	= cameraangle.smooth(alpha);
	D3DXVECTOR2		light	= lightangle.smooth(alpha);

	time += elapsedtime;

	// setup light
	D3DXMatrixRotationYawPitchRoll(&view, light.x, light.y, 0);
	D3DXVec3TransformCoord(&lightpos, &lightpos, &view);

	// TODO: no need to calculate every frame
	for( int i = 0; i < NUM_OBJECTS; ++i )
	{
		FindSilhouette(objects[i], (D3DXVECTOR3&)lightpos);
		ExtrudeSilhouette(objects[i], (D3DXVECTOR3&)lightpos);
	}

	// setup camera
	D3DXMatrixRotationYawPitchRoll(&view, orient.x, orient.y, 0);
	D3DXVec3TransformCoord(&eye, &eye, &view);

	D3DXMatrixLookAtLH(&view, &eye, &look, &up);
	D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI / 4, (float)screenwidth / (float)screenheight, 0.1f, 20);

	// put far plane to infinity
	proj._33 = 1;
	proj._43 = -0.1f;

	D3DXMatrixMultiply(&vp, &view, &proj);
	D3DXMatrixScaling(&world, 5, 0.1f, 5);

	// specular effect uniforms
	specular->SetMatrix("matViewProj", &vp);
	specular->SetVector("eyePos", (D3DXVECTOR4*)&eye);
	specular->SetVector("lightPos", (D3DXVECTOR4*)&lightpos);
	specular->SetVector("ambient", &zero); // it's a f**k-up
	specular->SetVector("lightColor", &intensity); // lazy to tonemap
	
	ambient->SetMatrix("matViewProj", &vp);
	ambient->SetVector("ambient", &amblight);

	if( SUCCEEDED(device->BeginScene()) )
	{
		device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, 0xff6694ed, 1.0f, 0);

		// STEP 1: z pass
		ambient->SetTechnique("ambientlight");
		ambient->SetMatrix("matViewProj", &vp);

		DrawScene(ambient);

		// STEP 2: draw shadow with depth fail method
		device->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
		device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);

		device->SetRenderState(D3DRS_STENCILENABLE, TRUE);
		device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
		device->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
		device->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP);
		device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_INCR);
		device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);

		extrude->SetTechnique("extrude");
		extrude->SetMatrix("matViewProj", &vp);

		extrude->Begin(0, 0);
		extrude->BeginPass(0);
		{
			for( int i = 0; i < NUM_OBJECTS; ++i )
				DrawShadowVolume(objects[i]);

			device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_DECR);
			device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);

			for( int i = 0; i < NUM_OBJECTS; ++i )
				DrawShadowVolume(objects[i]);
		}
		extrude->EndPass();
		extrude->End();

		device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_ALPHA);

		// STEP 3: multipass lighting
		device->SetRenderState(D3DRS_ZENABLE, TRUE);
		device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
		device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
		device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
		device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

		device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP);
		device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_GREATER);
		device->SetRenderState(D3DRS_STENCILREF, 1);

		DrawScene(specular);

		device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
		device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
		device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);

		if( drawsilhouette )
		{
			amblight = D3DXVECTOR4(1, 1, 0, 0.5f);

			// reuse whatever we can...
			extrude->SetVector("ambient", &amblight);
			extrude->Begin(0, 0);
			extrude->BeginPass(0);

			device->SetVertexDeclaration(shadowdecl);

			for( int i = 0; i < NUM_OBJECTS; ++i )
			{
				const ShadowCaster& caster = objects[i];
				D3DXVECTOR4* verts = (D3DXVECTOR4*)malloc(caster.silhouette.size() * 2 * sizeof(D3DXVECTOR4));

				for( size_t j = 0; j < caster.silhouette.size(); ++j )
				{
					const Edge& e = caster.silhouette[j];

					verts[j * 2 + 0] = D3DXVECTOR4(e.v1, 1);
					verts[j * 2 + 1] = D3DXVECTOR4(e.v2, 1);
				}

				extrude->SetMatrix("matWorld", &caster.world);
				extrude->CommitChanges();

				device->DrawPrimitiveUP(D3DPT_LINELIST, caster.silhouette.size(), verts, sizeof(D3DXVECTOR4));
				free(verts);
			}

			extrude->EndPass();
			extrude->End();
			extrude->SetVector("ambient", &zero);
		}

		if( drawvolume )
		{
			device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
			device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
			device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

			amblight = D3DXVECTOR4(1, 1, 0, 0.5f);

			extrude->SetVector("ambient", &amblight);
			extrude->Begin(0, 0);
			extrude->BeginPass(0);

			for( int i = 0; i < NUM_OBJECTS; ++i )
				DrawShadowVolume(objects[i]);

			extrude->EndPass();
			extrude->End();
			extrude->SetVector("ambient", &zero);

			device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
		}

		// render text
		device->SetFVF(D3DFVF_XYZRHW|D3DFVF_TEX1);
		device->SetRenderState(D3DRS_ZENABLE, FALSE);
		device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
		device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
		device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

		device->SetTexture(0, text);
		device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, textvertices, 6 * sizeof(float));

		device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
		device->SetRenderState(D3DRS_ZENABLE, TRUE);

		device->SetTexture(0, 0);
		device->EndScene();
	}

	device->Present(NULL, NULL, NULL, NULL);
}
Example #30
0
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	// Initialize comctl
	CoInitializeEx(NULL, COINIT_MULTITHREADED);

	static const wchar_t *class_name = L"ImGui Example";

	// Create application window
	HINSTANCE instance = GetModuleHandle(NULL);
	HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1));
	WNDCLASSEX wc = {sizeof(WNDCLASSEX),
	                 CS_CLASSDC,
	                 WndProc,
	                 0L,
	                 0L,
	                 instance,
	                 icon,
	                 NULL,
	                 NULL,
	                 NULL,
	                 class_name,
	                 NULL};
	RegisterClassEx(&wc);
	HWND hwnd =
	    CreateWindow(class_name, _T("Open Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
	                 CW_USEDEFAULT, 1280, 800, NULL, NULL, wc.hInstance, NULL);

	DragAcceptFiles(hwnd, true);

	// Initialize Direct3D
	LPDIRECT3D9 pD3D;
	if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) {
		UnregisterClass(class_name, wc.hInstance);
		MessageBox(hwnd, L"Failed to initialise Direct3D", NULL, 0);
		return 0;
	}
	ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
	g_d3dpp.Windowed = TRUE;
	g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	g_d3dpp.EnableAutoDepthStencil = TRUE;
	g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
	g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;

	// Create the D3DDevice
	if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
	                       D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) {
		pD3D->Release();
		UnregisterClass(class_name, wc.hInstance);
		MessageBox(hwnd, L"Failed to create Direct3D device", NULL, 0);
		return 0;
	}

	// Setup ImGui binding
	ImGui_ImplDX9_Init(hwnd, g_pd3dDevice);

	ImGuiIO &io = ImGui::GetIO();
	io.IniFilename = NULL; // Disable imgui.ini

	// Load Fonts
	for (auto name : {"Liberation Sans", "DejaVu Sans", "Arial",
	                  ""}) { // Empty string = use system default font
		ImFontConfig font_cfg{};
		font_cfg.FontDataOwnedByAtlas = false;
		const std::vector<char> ttf = load_font(name);
		if (!ttf.empty()) {
			io.Fonts->AddFontFromMemoryTTF(
			    const_cast<void *>(reinterpret_cast<const void *>(ttf.data())), ttf.size(), 20.0f,
			    &font_cfg);
			break;
		}
	}
	io.Fonts->AddFontDefault(); // ImGui fallback font
#if 0
	// Get current flag
	int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

	// Turn on leak-checking bit.
	tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;

	// Set flag to the new value.
	_CrtSetDbgFlag(tmpFlag);
#endif
	BoardView app{};

	bool show_test_window = true;
	bool show_another_window = false;
	ImVec4 clear_col = ImColor(20, 20, 30);

	// Main loop
	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	ShowWindow(hwnd, SW_SHOWDEFAULT);
	UpdateWindow(hwnd);
	while (msg.message != WM_QUIT) {
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			continue;
		}
		ImGui_ImplDX9_NewFrame();

		if (msg.message == WM_DROPFILES) {

			HDROP hDrop = (HDROP)msg.wParam;
			TCHAR *lpszFile = new TCHAR[MAX_PATH];
			UINT uFile = 0;

			uFile = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, NULL);

			if (uFile > 1) {
				app.ShowError("Multiple files not supported");
			} else {
				lpszFile[0] = '\0';
				if (DragQueryFile(hDrop, 0, lpszFile, MAX_PATH)) {
					char *fileAsChar = new char[MAX_PATH];
					wcstombs_s(NULL, fileAsChar, MAX_PATH, lpszFile, wcslen(lpszFile) + 1);
					app.OpenFile(fileAsChar);
				}
			}

			DragFinish(hDrop);
		}

#if 0
		// 1. Show a simple window
		// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window
		// automatically called "Debug"
		{
			static float f = 0.0f;
			ImGui::Text("Hello, world!");
			ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
			ImGui::ColorEdit3("clear color", (float *)&clear_col);
			if (ImGui::Button("Test Window"))
				show_test_window ^= 1;
			if (ImGui::Button("Another Window"))
				show_another_window ^= 1;
			ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
			            1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
		}

		// 2. Show another simple window, this time using an explicit Begin/End pair
		if (show_another_window) {
			ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
			ImGui::Begin("Another Window", &show_another_window);
			ImGui::Text("Hello");
			ImGui::End();
		}

#endif
#if 0
		// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
		if (show_test_window) {
			ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
			ImGui::ShowTestWindow(&show_test_window);
		}
#endif
		app.Update();
		if (app.m_wantsQuit) {
			PostMessage(hwnd, WM_QUIT, 0, 0);
		}

		if (app.m_wantsTitleChange) {
			app.m_wantsTitleChange = false;

			TCHAR title[MAX_PATH + 100];
			TCHAR filename[MAX_PATH + 10];

			// Convert character encoding if required, and format the window title
			mbstowcs_s(NULL, filename, _countof(filename), app.m_lastFileOpenName,
			           strlen(app.m_lastFileOpenName));
			_stprintf_s(title, _countof(title), L"%s - Open Board Viewer", filename);

			SetWindowText(hwnd, title);
		}

		// Rendering
		g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
		g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
		g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
		D3DCOLOR clear_col_dx =
		    D3DCOLOR_RGBA((int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f),
		                  (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f));
		g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
		if (g_pd3dDevice->BeginScene() >= 0) {
			ImGui::Render();
			g_pd3dDevice->EndScene();
		}
		g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
	}

	ImGui_ImplDX9_Shutdown();
	if (g_pd3dDevice)
		g_pd3dDevice->Release();
	if (pD3D)
		pD3D->Release();
	UnregisterClass(class_name, wc.hInstance);

	DragAcceptFiles(hwnd, false);

	return 0;
}