Esempio n. 1
0
	//Set up the world, view, and projection transform matrices.
	void Graphics::SetupMatrices()
	{
		if(!CurrentCamera)
			return;  //^? I'm putting this here to stop the game from crashing when there is no camera...
							 // it's not that we shouldn't crash when there is no camera... obviously thats a hint that
							 // something is horrendously wrong. It's just annoying.

		//Set the position of the camera.
		float cameraX = CurrentCamera->transform->Position.x;
		float cameraY = CurrentCamera->transform->Position.y;
		float cameraH = -10.0f;

		//The eye point is the location of the viewer (center of the screen, 10 units away).
		Vec3 eyePoint( cameraX, cameraY, cameraH );
		//The look-at point is where the viewer is looking (center of the screen).
		Vec3 lookAtPoint( cameraX, cameraY, 0.0f );
		//The up vector defines which way is up (the y-direction).
		Vec3 upVector( 0.0f, 1.0f, 0.0f );
		//Create a left-handed view matrix.
		Mat4 matView;
		D3DXMatrixLookAtLH(&matView, &eyePoint, &lookAtPoint, &upVector);
		//Store the view matrix
		ViewMatrix = matView;
		//Create an orthogonal left-handed projection matrix.
		//This will transform everything to the view port with no perspective.
		//The near and far clipping plains are still needed, but not as important.
		Mat4 matProj;
		D3DXMatrixOrthoLH(&matProj, SurfaceSize.x , SurfaceSize.y , 1.0f, 100.0f);
		//Store the projection matrix;
		ProjMatrix = matProj;

		//Store the view projection matrix
		ViewProjMatrix = ViewMatrix * ProjMatrix;
	}
//--------------------------------------------------------------------------------------
// Updates the position and velocity of the entity associated to this movement manager
// using the accumulated sum of all forces impacting the entity.
// Param1: The time in seconds passed since the last frame.
// Param2: The maximal speed of the entity.
// Param3: The maximal size of the accumulated forces.
// Param4: The handicap to use if the entity is currently being handicapped.
//--------------------------------------------------------------------------------------
void EntityMovementManager::UpdatePosition(float deltaTime, float maxSpeed, float maxForce, float handicap)
{
	// Truncate steering force to not be greater than the maximal allowed force
	float magnitude = 0.0f;
	XMStoreFloat(&magnitude, XMVector2Length(XMLoadFloat2(&m_steeringForce)));

	if(magnitude > maxForce)
	{
		// Truncate the vector to be of the magnitude corresponding to the maximal allowed force
		XMStoreFloat2(&m_steeringForce, XMVector2Normalize(XMLoadFloat2(&m_steeringForce)) * maxForce);
	}

	// Calculate the new velocity for the entity
	XMFLOAT2 newVelocity;
	XMStoreFloat2(&newVelocity, XMLoadFloat2(&m_velocity) + XMLoadFloat2(&m_steeringForce));

	// Truncate the velocity if it is greater than the maximally allowed velocity for the entity
	XMStoreFloat(&magnitude, XMVector2Length(XMLoadFloat2(&newVelocity)));

	if(magnitude > maxSpeed)
	{
		// Truncate the vector to be of the magnitude corresponding to the maximal allowed velocity
		XMStoreFloat2(&newVelocity, XMVector2Normalize(XMLoadFloat2(&newVelocity)) * maxSpeed);
	}

	// Set the new velocity and position on the entity

	m_velocity = newVelocity;
		
	XMFLOAT2 newPosition;

	if(m_pEntity->IsHandicapped())
	{
		XMStoreFloat2(&newPosition, XMLoadFloat2(&m_pEntity->GetPosition()) + XMLoadFloat2(&newVelocity) * deltaTime * handicap);
	}else
	{
		XMStoreFloat2(&newPosition, XMLoadFloat2(&m_pEntity->GetPosition()) + XMLoadFloat2(&newVelocity) * deltaTime);
	}

	m_pEntity->SetPosition(newPosition);
	m_pEntity->UpdateColliderPosition(newPosition);

	// Update the rotation to make the entity face the direction, in which it is moving
	if(!(newVelocity.x == 0.0f && newVelocity.y == 0.0f))
	{
		XMFLOAT2 lookAtPoint(0.0f, 0.0f);
		XMStoreFloat2(&lookAtPoint, XMLoadFloat2(&m_pEntity->GetPosition()) + XMLoadFloat2(&newVelocity));
		LookAt(lookAtPoint);
	}

	// Reset the steering force for the next frame
	m_steeringForce.x = 0.0f;
	m_steeringForce.y = 0.0f;
}
void
ColladaNode::handleLookAt(domLookat *lookat)
{
    if(lookat == NULL)
        return;
	
    domNodeRef        node   = getDOMElementAs<domNode>();
    Pnt3f eyePosition(lookat->getValue()[0],lookat->getValue()[1],lookat->getValue()[2]), 
          lookAtPoint(lookat->getValue()[3],lookat->getValue()[4],lookat->getValue()[5]);
    Vec3f upDirection(lookat->getValue()[7],lookat->getValue()[8],lookat->getValue()[9]);

    if(getGlobal()->getOptions()->getFlattenNodeXForms())
    {
        LookAtTransformationElementUnrecPtr LookAtElement = LookAtTransformationElement::create();
        LookAtElement->setEyePosition(eyePosition);
        LookAtElement->setLookAtPosition(lookAtPoint);
        LookAtElement->setUpDirection(upDirection);
        setName(LookAtElement, lookat->getSid());

        appendStackedXForm(LookAtElement, node);
    }
    else
    {

        TransformUnrecPtr xform = Transform::create();
	    NodeUnrecPtr      xformN = makeNodeFor(xform);

        Matrix lookAtMatrix;
        MatrixLookAt(lookAtMatrix,eyePosition, lookAtPoint, upDirection);

	    xform->setMatrix(lookAtMatrix);

	     if(getGlobal()->getOptions()->getCreateNameAttachments() == true && 
           node->getName()                                       != NULL   )
        {
            std::string nodeName = node->getName();

            if(lookat->getSid() != NULL && 
			    getGlobal()->getOptions()->getFlattenNodeXForms() == false)
            {
                nodeName.append("."                );
                nodeName.append(lookat->getSid());
            }

            setName(xformN, nodeName);
        }

        appendXForm(xformN);
    }
}
//////////////////////////////////////////////////////////////////////////
// 행렬 세팅
//
// World, View, Projection
//////////////////////////////////////////////////////////////////////////
VOID SetupMatrices()
{
	// World
	D3DXMATRIXA16 worldMatrix;
	
	// float 연산의 정밀도를 위해서 1000으로 나머지 연산
	UINT  time = timeGetTime() % 1000;
	
	// 1초마다 한바퀴씩(2 * pi) 회전 할 각도
	FLOAT angle = time * ( 2.0f * D3DX_PI ) / 1000.0f;
	
	// Y축 기준으로 회전하는 행렬 생성
	D3DXMatrixRotationY( &worldMatrix, angle );
	
	// 생성한 회전 행렬을 World 행렬로 디바이스에 설정
	g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldMatrix );
	

	//////////////////////////////////////////////////////////////////////////
	// View 행렬을 정의하기 위해서 세가지 값이 필요하다.
	// 원점, 시점, 업벡터
	//////////////////////////////////////////////////////////////////////////
	
	// 1. 눈의 위치			( 0, 3.0, -5)
	D3DXVECTOR3 eyePoint( 0.0f, 3.0f, -5.0f );
	
	// 2. 눈이 바라보는 위치	( 0, 0, 0 )
	D3DXVECTOR3 lookAtPoint( 0.0f, 0.0f, 0.0f );
	
	// 3. 업벡터				( 0, 1, 0 )
	D3DXVECTOR3 upVector( 0.0f, 1.0f, 0.0f );
	
	D3DXMATRIXA16 viewMatrix;
	// 1, 2, 3의 값으로 View 행렬 생성
	D3DXMatrixLookAtLH( &viewMatrix, &eyePoint, &lookAtPoint, &upVector );
	
	// 생성한 View 행렬을 디바이스에 설정
	g_pd3dDevice->SetTransform( D3DTS_VIEW, &viewMatrix );
	
	// Projection 행렬을 정의하기 위해서는 시야각(FOV=Field Of View)과 종횡비(aspect ratio), 클리핑 평면 값이 필요하다.
	D3DXMATRIXA16 projMatrix;

	/// matProj   : 값이 설정될 행렬
	/// D3DX_PI/4 : FOV(D3DX_PI/4 = 45도)
	/// 1.0f      : 종횡비
	/// 1.0f      : 근접 클리핑 평면(near clipping plane)
	/// 100.0f    : 원거리 클리핑 평면(far clipping plane)
	D3DXMatrixPerspectiveFovLH(

		// 행렬을 얻어올 변수
		&projMatrix,

		// FOV(D3DX_PI/4 = 45도)
		D3DX_PI / 4,
		
		// 종횡비 1:1
		1.0f,
		
		// Near Plane
		1.0f,
		
		// Far Plane
		100.0f
		
		);

	// 생성한 Projection 행렬을 디바이스에 설정
	g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &projMatrix );
}
// Handle OnCreation events
//-----------------------------------------------------------------------------
void MySample::Create()
{    
    CPUTAssetLibrary *pAssetLibrary = CPUTAssetLibrary::GetAssetLibrary();

    gLightDir.normalize();

    // TODO: read from cmd line, using these as defaults
    //pAssetLibrary->SetMediaDirectoryName(    _L("Media"));

    CPUTGuiControllerDX11 *pGUI = CPUTGetGuiController();

    // create some controls
	CPUTButton     *pButton = NULL;
    pGUI->CreateButton(_L("Fullscreen"), ID_FULLSCREEN_BUTTON, ID_MAIN_PANEL, &pButton);
	pGUI->CreateDropdown( L"Rasterizer Technique: SCALAR", ID_RASTERIZE_TYPE, ID_MAIN_PANEL, &mpTypeDropDown);
    mpTypeDropDown->AddSelectionItem( L"Rasterizer Technique: SSE" );
   	mpTypeDropDown->SetSelectedItem(mSOCType + 1);
   
	wchar_t string[CPUT_MAX_STRING_LENGTH];
    pGUI->CreateText(    _L("Occluders                                              \t"), ID_OCCLUDERS, ID_MAIN_PANEL, &mpOccludersText);
	
	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Models: \t%d"), mNumOccluders);
	pGUI->CreateText(string, ID_NUM_OCCLUDERS, ID_MAIN_PANEL, &mpNumOccludersText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tDepth rasterized models: %d"), mNumOccludersR2DB);
	pGUI->CreateText(string, ID_NUM_OCCLUDERS_RASTERIZED_TO_DB, ID_MAIN_PANEL, &mpOccludersR2DBText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t\t%f"), mNumOccluderTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDER_TRIS, ID_MAIN_PANEL, &mpOccluderTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tDepth rasterized tris: \t%f"), mNumOccluderRasterizedTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDER_RASTERIZED_TRIS, ID_MAIN_PANEL, &mpOccluderRasterizedTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tDepth raterizer time: \t%f"), mRasterizeTime);
	pGUI->CreateText(string, ID_RASTERIZE_TIME, ID_MAIN_PANEL, &mpRasterizeTimeText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Occluder Size Threshold: %0.4f"), mOccluderSizeThreshold);
	pGUI->CreateSlider(string, ID_OCCLUDER_SIZE, ID_MAIN_PANEL, &mpOccluderSizeSlider);
	mpOccluderSizeSlider->SetScale(0, 5.0, 51);
	mpOccluderSizeSlider->SetValue(mOccluderSizeThreshold);
	mpOccluderSizeSlider->SetTickDrawing(false);
    
	pGUI->CreateText(_L("Occludees                                              \t"), ID_OCCLUDEES, ID_MAIN_PANEL, &mpOccludeesText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Models: \t%d"), mNumOccludees);
	pGUI->CreateText(string, ID_NUM_OCCLUDEES, ID_MAIN_PANEL, &mpNumOccludeesText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tModels culled: \t%d"), mNumCulled);
	pGUI->CreateText(string, ID_NUM_CULLED, ID_MAIN_PANEL, &mpCulledText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tModels visible: \t%d"), mNumVisible);
	pGUI->CreateText(string, ID_NUM_VISIBLE, ID_MAIN_PANEL, &mpVisibleText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t%d"), (int)mNumOccludeeTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDEE_TRIS, ID_MAIN_PANEL, &mpOccludeeTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tCulled Triangles: \t%d"), (int)mNumOccludeeCulledTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDEE_CULLED_TRIS, ID_MAIN_PANEL, &mpCulledTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tVisible Triangles: \t%d"), (int)mNumOccludeeVisibleTris);
	pGUI->CreateText(string, ID_NUM_OCCLUDEE_VISIBLE_TRIS, ID_MAIN_PANEL, &mpVisibleTrisText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tVisible Triangles: \t%0.2f ms"), mDepthTestTime);
	pGUI->CreateText(string, ID_DEPTHTEST_TIME, ID_MAIN_PANEL, &mpDepthTestTimeText);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Occludee Size Threshold: %0.4f"), mOccludeeSizeThreshold);
	pGUI->CreateSlider(string, ID_OCCLUDEE_SIZE, ID_MAIN_PANEL, &mpOccludeeSizeSlider);
	mpOccludeeSizeSlider->SetScale(0, 0.1f, 41);
	mpOccludeeSizeSlider->SetValue(mOccludeeSizeThreshold);
	mpOccludeeSizeSlider->SetTickDrawing(false);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Total Cull time: %0.2f"), mTotalCullTime);
	pGUI->CreateText(string, ID_TOTAL_CULL_TIME, ID_MAIN_PANEL, &mpTotalCullTimeText);

	pGUI->CreateCheckbox(_L("Depth Test Culling"),  ID_ENABLE_CULLING, ID_MAIN_PANEL, &mpCullingCheckBox);
	pGUI->CreateCheckbox(_L("Frustum Culling"),  ID_ENABLE_FCULLING, ID_MAIN_PANEL, &mpFCullingCheckBox);
	pGUI->CreateCheckbox(_L("View Depth Buffer"),  ID_DEPTH_BUFFER_VISIBLE, ID_MAIN_PANEL, &mpDBCheckBox);
	pGUI->CreateCheckbox(_L("View Bounding Box"),  ID_BOUNDING_BOX_VISIBLE, ID_MAIN_PANEL, &mpBBCheckBox);
	pGUI->CreateCheckbox(_L("Multi Tasking"), ID_ENABLE_TASKS, ID_MAIN_PANEL, &mpTasksCheckBox);
	pGUI->CreateCheckbox(_L("Vsync"), ID_VSYNC_ON_OFF, ID_MAIN_PANEL, &mpVsyncCheckBox);
	pGUI->CreateCheckbox(_L("Pipeline"), ID_PIPELINE, ID_MAIN_PANEL, &mpPipelineCheckBox);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Number of draw calls: \t%d"), mNumDrawCalls);
	pGUI->CreateText(string, ID_NUM_DRAW_CALLS, ID_MAIN_PANEL, &mpDrawCallsText),
	
	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Depth Test Tasks: \t\t%d"), mNumDepthTestTasks);
    pGUI->CreateSlider(string, ID_DEPTH_TEST_TASKS, ID_MAIN_PANEL, &mpDepthTestTaskSlider);
	mpDepthTestTaskSlider->SetScale(1, (float)NUM_DT_TASKS, 11);
	mpDepthTestTaskSlider->SetValue((float)mNumDepthTestTasks);
	mpDepthTestTaskSlider->SetTickDrawing(false);
	mpAABB->SetDepthTestTasks(mNumDepthTestTasks);

    //
    // Create Static text
    //
    pGUI->CreateText( _L("F1 for Help"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("[Escape] to quit application"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("A,S,D,F - move camera position"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("Q - camera position up"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("E - camera position down"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
    pGUI->CreateText( _L("mouse + right click - camera look location"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);
	pGUI->CreateText( _L("size thresholds : computed using screen space metris"), ID_IGNORE_CONTROL_ID, ID_SECONDARY_PANEL);

    pGUI->SetActivePanel(ID_MAIN_PANEL);
    pGUI->DrawFPS(true);

    // Add our programatic (and global) material parameters
    CPUTMaterial::mGlobalProperties.AddValue( _L("cbPerFrameValues"), _L("$cbPerFrameValues") );
    CPUTMaterial::mGlobalProperties.AddValue( _L("cbPerModelValues"), _L("$cbPerModelValues") );
    CPUTMaterial::mGlobalProperties.AddValue( _L("_Shadow"), _L("$shadow_depth") );

	// Creating a render target to view the CPU rasterized depth buffer
	mpCPUDepthBuf[0] = new char[SCREENW*SCREENH*4];
	mpCPUDepthBuf[1] = new char[SCREENW*SCREENH*4];
	mpGPUDepthBuf    = new char[SCREENW*SCREENH*4];

	CD3D11_TEXTURE2D_DESC cpuRenderTargetDescSSE
	(
		DXGI_FORMAT_R8G8B8A8_UNORM,
        SCREENW * 2, // TODO: round up to full tile sizes
        SCREENH / 2,
        1, // Array Size
        1, // MIP Levels
		D3D11_BIND_SHADER_RESOURCE,
        D3D11_USAGE_DEFAULT,
		0
    );
	HRESULT hr;
	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescSSE, NULL, &mpCPURenderTargetSSE[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescSSE, NULL, &mpCPURenderTargetSSE[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetSSE[0], NULL, &mpCPUSRVSSE[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetSSE[1], NULL, &mpCPUSRVSSE[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	// Corresponding texture object
	CPUTTextureDX11 *pDummyTex0 = new CPUTTextureDX11;
	pDummyTex0->SetTextureAndShaderResourceView(mpCPURenderTargetSSE[0], mpCPUSRVSSE[0]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_SSE"), pDummyTex0 );
	SAFE_RELEASE(pDummyTex0);

	CPUTTextureDX11 *pDummyTex1 = new CPUTTextureDX11;
	pDummyTex1->SetTextureAndShaderResourceView(mpCPURenderTargetSSE[1], mpCPUSRVSSE[1]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_SSE"), pDummyTex1 );
	SAFE_RELEASE(pDummyTex1);

	CD3D11_TEXTURE2D_DESC cpuRenderTargetDescScalar
	(
		DXGI_FORMAT_R8G8B8A8_UNORM,
        SCREENW, // TODO: round up to full tile sizes
        SCREENH,
        1, // Array Size
        1, // MIP Levels
		D3D11_BIND_SHADER_RESOURCE,
        D3D11_USAGE_DEFAULT,
		0
    );
	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescScalar, NULL, &mpCPURenderTargetScalar[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateTexture2D(&cpuRenderTargetDescScalar, NULL, &mpCPURenderTargetScalar[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating render target."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetScalar[0], NULL, &mpCPUSRVScalar[0]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	hr = mpD3dDevice->CreateShaderResourceView(mpCPURenderTargetScalar[1], NULL, &mpCPUSRVScalar[1]);
	ASSERT(SUCCEEDED(hr), _L("Failed creating shader resource view."));

	// Corresponding texture object
	CPUTTextureDX11 *pDummyTex2 = new CPUTTextureDX11;
	pDummyTex2->SetTextureAndShaderResourceView(mpCPURenderTargetScalar[0], mpCPUSRVScalar[0]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_Scalar"), pDummyTex2 );
	SAFE_RELEASE(pDummyTex2);

	CPUTTextureDX11 *pDummyTex3 = new CPUTTextureDX11;
	pDummyTex3->SetTextureAndShaderResourceView(mpCPURenderTargetScalar[1], mpCPUSRVScalar[1]);
	pAssetLibrary->AddTexture( _L("$depthbuf_tex_Scalar"), pDummyTex3 );
	SAFE_RELEASE(pDummyTex3);

	// Create default shaders
    CPUTPixelShaderDX11  *pPS       = CPUTPixelShaderDX11::CreatePixelShaderFromMemory(            _L("$DefaultShader"), CPUT_DX11::mpD3dDevice,          _L("PSMain"), _L("ps_4_0"), gpDefaultShaderSource );
    CPUTPixelShaderDX11  *pPSNoTex  = CPUTPixelShaderDX11::CreatePixelShaderFromMemory(   _L("$DefaultShaderNoTexture"), CPUT_DX11::mpD3dDevice, _L("PSMainNoTexture"), _L("ps_4_0"), gpDefaultShaderSource );
    CPUTVertexShaderDX11 *pVS       = CPUTVertexShaderDX11::CreateVertexShaderFromMemory(          _L("$DefaultShader"), CPUT_DX11::mpD3dDevice,          _L("VSMain"), _L("vs_4_0"), gpDefaultShaderSource );
    CPUTVertexShaderDX11 *pVSNoTex  = CPUTVertexShaderDX11::CreateVertexShaderFromMemory( _L("$DefaultShaderNoTexture"), CPUT_DX11::mpD3dDevice, _L("VSMainNoTexture"), _L("vs_4_0"), gpDefaultShaderSource );

    // We just want to create them, which adds them to the library.  We don't need them any more so release them, leaving refCount at 1 (only library owns a ref)
    SAFE_RELEASE(pPS);
    SAFE_RELEASE(pPSNoTex);
    SAFE_RELEASE(pVS);
    SAFE_RELEASE(pVSNoTex);

    // load shadow casting material+sprite object
    cString ExecutableDirectory;
    CPUTOSServices::GetOSServices()->GetExecutableDirectory(&ExecutableDirectory);
    pAssetLibrary->SetMediaDirectoryName(  ExecutableDirectory+_L("..\\..\\Media\\"));

    mpShadowRenderTarget = new CPUTRenderTargetDepth();
    mpShadowRenderTarget->CreateRenderTarget( cString(_L("$shadow_depth")), SHADOW_WIDTH_HEIGHT, SHADOW_WIDTH_HEIGHT, DXGI_FORMAT_D32_FLOAT );

    mpDebugSprite = new CPUTSprite();
    mpDebugSprite->CreateSprite( -1.0f, -1.0f, 0.5f, 0.5f, _L("Sprite") );

	int width, height;
    CPUTOSServices::GetOSServices()->GetClientDimensions(&width, &height);

	// Depth buffer visualization material
	mpShowDepthBufMtrlScalar = (CPUTMaterialDX11*)CPUTAssetLibraryDX11::GetAssetLibrary()->GetMaterial( _L("showDepthBufScalar"));
	mpShowDepthBufMtrlSSE = (CPUTMaterialDX11*)CPUTAssetLibraryDX11::GetAssetLibrary()->GetMaterial( _L("showDepthBufSSE"));
		
	if(mSOCType == SCALAR_TYPE)
	{
		mpCPURenderTarget[0] = mpCPURenderTargetScalar[0];
		mpCPURenderTarget[1] = mpCPURenderTargetScalar[1];
		mpCPUSRV[0]          = mpCPUSRVScalar[0];
		mpCPUSRV[1]          = mpCPUSRVScalar[1];
		mpShowDepthBufMtrl   = mpShowDepthBufMtrlScalar;
		rowPitch			 = SCREENW * 4;
	}
	else
	{
		mpCPURenderTarget[0] = mpCPURenderTargetSSE[0];
		mpCPURenderTarget[1] = mpCPURenderTargetSSE[1];
		mpCPUSRV[0]          = mpCPUSRVSSE[0];
		mpCPUSRV[1]          = mpCPUSRVSSE[1];
		mpShowDepthBufMtrl = mpShowDepthBufMtrlSSE;
		rowPitch			 = 2 * SCREENW * 4;
	}

    // Call ResizeWindow() because it creates some resources that our blur material needs (e.g., the back buffer)
    ResizeWindow(width, height);

    CPUTRenderStateBlockDX11 *pBlock = new CPUTRenderStateBlockDX11();
    CPUTRenderStateDX11 *pStates = pBlock->GetState();

    // Override default sampler desc for our default shadowing sampler
    pStates->SamplerDesc[1].Filter         = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
    pStates->SamplerDesc[1].AddressU       = D3D11_TEXTURE_ADDRESS_BORDER;
    pStates->SamplerDesc[1].AddressV       = D3D11_TEXTURE_ADDRESS_BORDER;
    pStates->SamplerDesc[1].ComparisonFunc = D3D11_COMPARISON_GREATER;
    pBlock->CreateNativeResources();
    CPUTAssetLibrary::GetAssetLibrary()->AddRenderStateBlock( _L("$DefaultRenderStates"), pBlock );
    pBlock->Release(); // We're done with it.  The library owns it now.

    //
    // Load .set files to load the castle scene
	//
    pAssetLibrary->SetMediaDirectoryName(_L("..\\..\\Media\\Castle\\"));

#ifdef DEBUG
    mpAssetSetDBR[0] = pAssetLibrary->GetAssetSet(_L("castleLargeOccluders"));
	ASSERT(mpAssetSetDBR[0], _L("Failed loading castle."));

	mpAssetSetDBR[1] = pAssetLibrary->GetAssetSet(_L("groundDebug"));
	ASSERT(mpAssetSetDBR[1], _L("Failed loading ground."));

	mpAssetSetAABB[0] = pAssetLibrary->GetAssetSet(_L("marketStallsDebug"));
	ASSERT(mpAssetSetAABB, _L("Failed loading marketStalls"));

	mpAssetSetAABB[1] = pAssetLibrary->GetAssetSet(_L("castleSmallDecorationsDebug"));
	ASSERT(mpAssetSetAABB, _L("Failed loading castleSmallDecorations"));
#else
    mpAssetSetDBR[0] = pAssetLibrary->GetAssetSet(_L("castleLargeOccluders"));
	ASSERT(mpAssetSetDBR[0], _L("Failed loading castle."));

	mpAssetSetDBR[1] = pAssetLibrary->GetAssetSet(_L("ground"));
	ASSERT(mpAssetSetDBR[1], _L("Failed loading ground."));

	mpAssetSetAABB[0] = pAssetLibrary->GetAssetSet(_L("marketStalls"));
	ASSERT(mpAssetSetAABB, _L("Failed loading marketStalls"));

	mpAssetSetAABB[1] = pAssetLibrary->GetAssetSet(_L("castleSmallDecorations"));
	ASSERT(mpAssetSetAABB, _L("Failed loading castleSmallDecorations"));
#endif

	mpAssetSetSky = pAssetLibrary->GetAssetSet(_L("sky"));
	ASSERT(mpAssetSetSky, _L("Failed loading sky"));

	// For every occluder model in the sene create a place holder 
	// for the CPU transformed vertices of the model.   
	mpDBR->CreateTransformedModels(mpAssetSetDBR, OCCLUDER_SETS);
	// Get number of occluders in the scene
	mNumOccluders = mpDBR->GetNumOccluders();
	// Get number of occluder triangles in the scene 
	mNumOccluderTris = mpDBR->GetNumTriangles();


	// For every occludee model in the scene create a place holder
	// for the triangles that make up the model axis aligned bounding box
	mpAssetSetAABB[2] = mpAssetSetDBR[0];
	mpAssetSetAABB[3] = mpAssetSetDBR[1];

	mpAABB->CreateTransformedAABBoxes(mpAssetSetAABB, OCCLUDEE_SETS);
	// Get number of occludees in the scene
	mNumOccludees = mpAABB->GetNumOccludees();
	// Get number of occluddee triangles in the scene
	mNumOccludeeTris = mpAABB->GetNumTriangles();
	
	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Models: \t%d"), mNumOccluders);
	mpNumOccludersText->SetText(string);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t\t%d"), mNumOccluderTris);
	mpOccluderTrisText->SetText(string);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of Model: \t%d"), mNumOccludees);
	mpNumOccludeesText->SetText(string);

	swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("\tNumber of tris: \t\t%d"), mNumOccludeeTris);
	mpOccludeeTrisText->SetText(string);

	CPUTCheckboxState state;
	if(mEnableCulling)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpCullingCheckBox->SetCheckboxState(state);

	if(mEnableFCulling)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpFCullingCheckBox->SetCheckboxState(state);
	mpDBR->SetEnableFCulling(mEnableFCulling);
	mpAABB->SetEnableFCulling(mEnableFCulling);

	if(mViewDepthBuffer)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpDBCheckBox->SetCheckboxState(state);

	if(mEnableTasks)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else 
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpTasksCheckBox->SetCheckboxState(state);

	if(mSyncInterval)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpVsyncCheckBox->SetCheckboxState(state);

	if(mPipeline)
	{
		state = CPUT_CHECKBOX_CHECKED;
	}
	else
	{
		state = CPUT_CHECKBOX_UNCHECKED;
	}
	mpPipelineCheckBox->SetCheckboxState(state);

	// Setting occluder size threshold in DepthBufferRasterizer
	mpDBR->SetOccluderSizeThreshold(mOccluderSizeThreshold);
	// Setting occludee size threshold in AABBoxRasterizer
	mpAABB->SetOccludeeSizeThreshold(mOccludeeSizeThreshold);
	
	//
	// If no cameras were created from the model sets then create a default simple camera
	// and add it to the camera array.
	//
    if( mpAssetSetDBR[0] && mpAssetSetDBR[0]->GetCameraCount() )
    {
        mpCamera = mpAssetSetDBR[0]->GetFirstCamera();
        mpCamera->AddRef(); 
    } else
    {
        mpCamera = new CPUTCamera();
        CPUTAssetLibraryDX11::GetAssetLibrary()->AddCamera( _L("SampleStart Camera"), mpCamera );

        mpCamera->SetPosition( 0.0f, 0.0f, 5.0f );
        // Set the projection matrix for all of the cameras to match our window.
        // TODO: this should really be a viewport matrix.  Otherwise, all cameras will have the same FOV and aspect ratio, etc instead of just viewport dimensions.
        mpCamera->SetAspectRatio(((float)width)/((float)height));
    }
    mpCamera->SetFov(XMConvertToRadians(60.0f)); // TODO: Fix converter's FOV bug (Maya generates cameras for which fbx reports garbage for fov)
    mpCamera->SetFarPlaneDistance(gFarClipDistance);
	mpCamera->SetPosition(27.0f, 2.0f, 47.0f);
	mpCamera->LookAt(41.0f, 8.0f, -50.0f);
    mpCamera->Update();

    // Set up the shadow camera (a camera that sees what the light sees)
    float3 lookAtPoint(0.0f, 0.0f, 0.0f);
    float3 half(1.0f, 1.0f, 1.0f);
    if( mpAssetSetDBR[0] )
    {
        mpAssetSetDBR[0]->GetBoundingBox( &lookAtPoint, &half );
    }
    float length = half.length();

    mpShadowCamera = new CPUTCamera();
    mpShadowCamera->SetFov(XMConvertToRadians(45));
    mpShadowCamera->SetAspectRatio(1.0f);
    float fov = mpShadowCamera->GetFov();
    float tanHalfFov = tanf(fov * 0.5f);
    float cameraDistance = length/tanHalfFov;
    float nearDistance = cameraDistance * 0.1f;
    mpShadowCamera->SetNearPlaneDistance(nearDistance);
    mpShadowCamera->SetFarPlaneDistance(2.0f * cameraDistance);
    CPUTAssetLibraryDX11::GetAssetLibrary()->AddCamera( _L("ShadowCamera"), mpShadowCamera );
    float3 shadowCameraPosition = lookAtPoint - gLightDir * cameraDistance;
    mpShadowCamera->SetPosition( shadowCameraPosition );
    mpShadowCamera->LookAt( lookAtPoint.x, lookAtPoint.y, lookAtPoint.z );
    mpShadowCamera->Update();

    mpCameraController = new CPUTCameraControllerFPS();
    mpCameraController->SetCamera(mpCamera);
    mpCameraController->SetLookSpeed(0.004f);
    mpCameraController->SetMoveSpeed(2.5f);

	gLightDir = float3(-40.48f, -142.493f, -3.348f);
	gLightDir = gLightDir.normalize();

	QueryPerformanceFrequency(&glFrequency); 
}