Example #1
0
//-----------------------------------------------------------------------------
void MySample::Update(double deltaSeconds)
{
	ImGui_ImplDX11_NewFrame();
	if (mpWindow->DoesWindowHaveFocus())
	{
		mpCameraController->SetCamera(mpCamera);
		if (mpCameraController)
			mpCameraController->Update((float)deltaSeconds);
	}

	MenuController_Update((float)deltaSeconds);

    CPUTGetGuiController()->ControlModified();
    CPUTGetGuiController()->Update();
}
Example #2
0
void MySample::CreateInstancingControlButtons()
{
    CPUTGuiControllerOGL *pGUI = (CPUTGuiControllerOGL*)CPUTGetGuiController();
    CPUTButton *pButton;

	if(isInstanced)
	{
		pGUI->CreateButton(_L("Enable Instancing     "), TOGGLE_INSTANCING, ID_MAIN_PANEL, &pButton);
		pButton->SetAutoArranged(true);
		pButton->SetDimensions(INSTANCING_BUTTON_SIZE, INSTANCING_BUTTON_SIZE);
	}
	else
	{
		pGUI->CreateButton(_L("Disable Instancing"), TOGGLE_INSTANCING, ID_MAIN_PANEL, &pButton);
		pButton->SetAutoArranged(true);
		pButton->SetDimensions(INSTANCING_BUTTON_SIZE, INSTANCING_BUTTON_SIZE);
	}

	pToggleButton = pButton;
    pGUI->CreateButton(_L("Add Row                 "), ROW_INCREASE, ID_MAIN_PANEL, &pButton);
    pButton->SetAutoArranged(true);
    pButton->SetDimensions(INSTANCING_BUTTON_SIZE, INSTANCING_BUTTON_SIZE);

    pGUI->CreateButton(_L("Remove Row          "), ROW_DECREASE, ID_MAIN_PANEL, &pButton);
    pButton->SetAutoArranged(true);
    pButton->SetDimensions(INSTANCING_BUTTON_SIZE, INSTANCING_BUTTON_SIZE);

    pGUI->CreateButton(_L("Add Column           "), COLUMN_INCREASE, ID_MAIN_PANEL, &pButton);
    pButton->SetAutoArranged(true);
    pButton->SetDimensions(INSTANCING_BUTTON_SIZE, INSTANCING_BUTTON_SIZE);
   
    pGUI->CreateButton(_L("Remove Column    "), COLUMN_DECREASE, ID_MAIN_PANEL, &pButton);
    pButton->SetAutoArranged(true);
    pButton->SetDimensions(INSTANCING_BUTTON_SIZE, INSTANCING_BUTTON_SIZE);
}
Example #3
0
// Handle keyboard events
//-----------------------------------------------------------------------------
CPUTEventHandledCode MySample::HandleKeyboardEvent(CPUTKey key, CPUTKeyState state)
{
    static bool panelToggle = false;
    CPUTEventHandledCode    handled = CPUT_EVENT_UNHANDLED;

    CPUTGuiController*  pGUI = CPUTGetGuiController();

    switch(key)
    {   
    case KEY_ESCAPE:
        handled = CPUT_EVENT_HANDLED;
        PostQuitMessage(0);
        break;
    
    default:
        break;
    }

	if (handled == CPUT_EVENT_UNHANDLED)
	{
		handled = MenuController_HandleKeyboardEvent(key, state);
	}

    // pass it to the camera controller
    if(handled == CPUT_EVENT_UNHANDLED)
    {
        if (mpCameraController)
        handled = mpCameraController->HandleKeyboardEvent(key, state);
    }
    return handled;
}
Example #4
0
//-----------------------------------------------------------------------------
void MySample::ResizeWindow(UINT width, UINT height)
{
    CPUTAssetLibrary *pAssetLibrary = CPUTAssetLibrary::GetAssetLibrary();

    // Before we can resize the swap chain, we must release any references to it.
    // We could have a "AssetLibrary::ReleaseSwapChainResources(), or similar.  But,
    // Generic "release all" works, is simpler to implement/maintain, and is not performance critical.

    CPUT_DX11::ResizeWindow( width, height );

    // Resize any application-specific render targets here
    if( mpCamera ) 
        mpCamera->SetAspectRatio(((float)width)/((float)height));
    CPUTGetGuiController()->Resize(width, height);

	MenuController_Resize(width, height);
}
Example #5
0
void MySample::CreateResources()
{
    CPUT_DX11::CreateResources();
    int width, height;
    mpWindow->GetClientDimensions(&width, &height);

    CPUTAssetLibrary *pAssetLibrary = CPUTAssetLibrary::GetAssetLibrary();

    std::string executableDirectory;
    std::string mediaDirectory;

    CPUTFileSystem::GetExecutableDirectory(&executableDirectory);
    CPUTFileSystem::ResolveAbsolutePathAndFilename(executableDirectory + "../../../../Media/", &mediaDirectory);
    
	pAssetLibrary->SetMediaDirectoryName(mediaDirectory + "gui_assets/");
    pAssetLibrary->SetSystemDirectoryName(mediaDirectory + "System/");
    pAssetLibrary->SetFontDirectoryName(mediaDirectory + "gui_assets/Font/");

    CPUTGuiController *pGUI = CPUTGetGuiController();
    pGUI->Initialize("guimaterial_dds_16", "arial_16.fnt");

    pGUI->SetCallback(this);

    pAssetLibrary->SetMediaDirectoryName(mediaDirectory);

    mpShadowRenderTarget = CPUTRenderTargetDepth::Create();
    mpShadowRenderTarget->CreateRenderTarget(std::string("$shadow_depth"), SHADOW_WIDTH_HEIGHT, SHADOW_WIDTH_HEIGHT, DXGI_FORMAT_D32_FLOAT);

    CPUTMaterial* pDebugMaterial = pAssetLibrary->GetMaterial("%sprite");
    mpDebugSprite = CPUTSprite::Create(-1.0f, -1.0f, 0.5f, 0.5f, pDebugMaterial);
    SAFE_RELEASE(pDebugMaterial);

    mpCameraController = CPUTCameraControllerFPS::Create();
    mpShadowCamera = CPUTCamera::Create(CPUT_ORTHOGRAPHIC);
     
    pGUI->Resize(width, height);
	
}
Example #6
0
// Instancing Controls for Touch interface
void MySample::PositionInstancingControlButtons(int width, int height)
{
    int offset = INSTANCING_BUTTON_SIZE * 2;
    int top = height - 2 * offset;
    int left = 0;

    CPUTGuiControllerOGL *pGUI = (CPUTGuiControllerOGL*)CPUTGetGuiController();
    
    CPUTControl* pControl = NULL;
    pControl = pGUI->GetControl(ROW_INCREASE);
    pControl->SetPosition(left + 0 * offset, top + 0 * offset);

    pControl = pGUI->GetControl(ROW_DECREASE);
    pControl->SetPosition(left + 1 * offset, top + 0 * offset);

    pControl = pGUI->GetControl(COLUMN_INCREASE);
    pControl->SetPosition(left + 0 * offset, top + 1 * offset);
	
    pControl = pGUI->GetControl(COLUMN_DECREASE);
    pControl->SetPosition(left + 1 * offset, top + 1 * offset);
	
    pControl = pGUI->GetControl(TOGGLE_INSTANCING);
    pControl->SetPosition(left + 2 * offset, top + 0 * offset);
}
Example #7
0
void MySample::Create()
{
	CPUTAssetLibrary *pAssetLibrary = CPUTAssetLibrary::GetAssetLibrary();
    cString ExecutableDirectory;
    CPUTFileSystem::GetExecutableDirectory(&ExecutableDirectory);
    ExecutableDirectory.append(_L(ASSET_LOCATION));
    pAssetLibrary->SetMediaDirectoryName(ExecutableDirectory);

#ifdef ENABLE_GUI
    CPUTGuiControllerOGL *pGUI = (CPUTGuiControllerOGL*)CPUTGetGuiController();
    std::string mediaDirectory = ws2s(pAssetLibrary->GetMediaDirectoryName());
    std::string fontDirectory("Font/");
    CPUTFont *pFont = CPUTFont::CreateFont(SYSTEM_LOCATION + fontDirectory, "arial_64.fnt");

    pGUI->SetFont(pFont);

    //
    // Create some controls
    //   
	CPUTDropdown *pDropdownMethod;
	
	pGUI->CreateText(_L("Test Font"), ID_IGNORE_CONTROL_ID, ID_MAIN_PANEL, &pTextMethod);
	pTextMethod->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
	CreateInstancingControlButtons();
#endif

	CPUTFileSystem::GetExecutableDirectory(&ExecutableDirectory);
    ExecutableDirectory.append(_L(ASSET_LOCATION));
    pAssetLibrary->SetMediaDirectoryName(ExecutableDirectory);


    int width, height;
    mpWindow->GetClientDimensions(&width, &height);
    DEBUG_PRINT(_L("Resize Window"));

    ResizeWindow(width, height);

    mpScene = new CPUTScene();
    DEBUG_PRINT(_L("Load Scene"));

    // Load the scene
    if (CPUTFAILED(mpScene->LoadScene(SCENE_FILE)))
    {
        LOGI("Failed to Load Scene, try loading asset set individually");
        CPUTAssetSet *pAssetSet = NULL;
        pAssetSet = pAssetLibrary->GetAssetSet( ASSET_SET_FILE );
        mpScene->AddAssetSet(pAssetSet);
        pAssetSet->Release();
    }
    LOGI("Loaded the scene");

    // Get the camera. Get the first camera encountered in the scene or
    // if there are none, create a new one.
    unsigned int numAssets = mpScene->GetNumAssetSets();
    for (unsigned int i = 0; i < numAssets; ++i) {
        CPUTAssetSet *pAssetSet = mpScene->GetAssetSet(i);
        if (pAssetSet->GetCameraCount() > 0) {
            mpCamera = pAssetSet->GetFirstCamera();
            break;
        }
    }

    // Create the camera
    if (mpCamera == NULL)
    {
        mpCamera = new CPUTCamera();
        pAssetLibrary->AddCamera( _L(""), _L("SampleStart Camera"), _L(""), mpCamera );
		
		mpCamera->SetPosition( 0.0f, cameraY, 100.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(DegToRad(90.0)); // TODO: Fix converter's FOV bug (Maya generates cameras for which fbx reports garbage for fov)
    mpCamera->SetFarPlaneDistance(100000.0f);
    mpCamera->Update();

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

	// retrieve function pointer
    glDrawElementsInstancedEXT = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC) ( eglGetProcAddress( "glDrawElementsInstanced" ) );


    if( glDrawElementsInstancedEXT == NULL )
    {
        LOGE( "Failed to load extension pointer" );
    }
	
	currentRowCount = NUM_ROWS / 1.5;
	currentColCount = NUM_COLUMNS;
	
	LOGI("Getting handles for materials");

	// get handles to switch instancing / non instancing
	pAssetLibrary->PrintAssetLibrary();

	supportMaterial = pAssetLibrary->GetMaterialByName("instanceV2/Material/concreteMultiMaterial.mtl");
	techMaterial = pAssetLibrary->GetMaterialByName("instanceV2/Material/techALowMultiMataterial.mtl");

	isInstanced = true;
	
	CPUTModel *pModel = pAssetLibrary->GetModelByName( _L( ".instangeGrptechALow" ) );
	pModel->SetDrawModelCallBack((DrawModelCallBackFunc)drawCallback);
	pModel = pAssetLibrary->GetModelByName( _L( ".instangeGrpconcrete" ) );
	pModel->SetDrawModelCallBack((DrawModelCallBackFunc)drawCallback);

	UINT supportCount = supportMaterial->GetMaterialEffectCount();
	UINT techCount = techMaterial->GetMaterialEffectCount();

	glFrontFace(GL_CW);
    UpdateMatrixBuffers();
}
// Handle keyboard events
//-----------------------------------------------------------------------------
CPUTEventHandledCode MySample::HandleKeyboardEvent(CPUTKey key)
{
    static bool panelToggle = false;
    CPUTEventHandledCode    handled = CPUT_EVENT_UNHANDLED;
    cString fileName;
    CPUTGuiControllerDX11*  pGUI = CPUTGetGuiController();

    switch(key)
    {
    case KEY_F1:
        panelToggle = !panelToggle;
        if(panelToggle)
        {
            pGUI->SetActivePanel(ID_SECONDARY_PANEL);
        }
        else
        {
            pGUI->SetActivePanel(ID_MAIN_PANEL);
        }
        handled = CPUT_EVENT_HANDLED;
        break;
    case KEY_L:
        {
            static int cameraObjectIndex = 0;
            CPUTRenderNode *pCameraList[] = { mpCamera, mpShadowCamera };
            cameraObjectIndex = (++cameraObjectIndex) % (sizeof(pCameraList)/sizeof(*pCameraList));
            CPUTRenderNode *pCamera = pCameraList[cameraObjectIndex];
            mpCameraController->SetCamera( pCamera );
        }
        handled = CPUT_EVENT_HANDLED;
        break;
    case KEY_ESCAPE:
        handled = CPUT_EVENT_HANDLED;
        Shutdown();
        break;

	case KEY_1:
		{
			CPUTToggleFullScreenMode();
			break;
		}
	case KEY_2:
		{
			mEnableCulling = !mEnableCulling;
			CPUTCheckboxState state;
			if(mEnableCulling)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else 
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				memset(mpCPUDepthBuf[mCurrId], 0, SCREENW * SCREENH *4);

				mpOccludersR2DBText->SetText(         _L("\tDepth rasterized models: 0"));
				mpOccluderRasterizedTrisText->SetText(_L("\tDepth rasterized tris: \t0"));
				mpRasterizeTimeText->SetText(         _L("\tDepth rasterizer time: \t0 ms"));

				mpCulledText->SetText(       _L("\tModels culled: \t\t0"));
				mpVisibleText->SetText(      _L("\tModels visible: \t\t0"));
				mpCulledTrisText->SetText(   _L("\tCulled tris: \t\t0"));
				mpVisibleTrisText->SetText(   _L("\tVisible tris: \t\t0"));
				mpDepthTestTimeText->SetText(_L("\tDepth test time: \t0 ms"));
			}
			mpCullingCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_3:
		{
			mEnableFCulling = !mEnableFCulling;
			CPUTCheckboxState state;
			if(mEnableFCulling)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				mpDBR->ResetInsideFrustum();
				mpAABB->ResetInsideFrustum();
			}
			mpFCullingCheckBox->SetCheckboxState(state);
			break;			
		}
	case KEY_4:
		{
			mViewDepthBuffer = !mViewDepthBuffer;
			CPUTCheckboxState state;
			if(mViewDepthBuffer)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else 
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpDBCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_5:
		{
			mViewBoundingBox = !mViewBoundingBox;
			CPUTCheckboxState state;
			if(mViewBoundingBox)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpBBCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_6:
		{
			TaskCleanUp();
			mEnableTasks = !mEnableTasks;
			CPUTCheckboxState state;
			
			SAFE_DELETE_ARRAY(mpDBR);
			SAFE_DELETE_ARRAY(mpAABB);

			if(mEnableTasks)
			{
				state = CPUT_CHECKBOX_CHECKED;
				mpPipelineCheckBox->SetVisibility(true);
				mpDepthTestTaskSlider->SetVisibility(true);

				wchar_t string[CPUT_MAX_STRING_LENGTH];
				swprintf_s(&string[0], CPUT_MAX_STRING_LENGTH, _L("Depth Test Task: \t%d"), mNumDepthTestTasks);
				mpDepthTestTaskSlider->SetText(string);
			
				if(mSOCType == SCALAR_TYPE)
				{
					mpDBRScalarMT = new DepthBufferRasterizerScalarMT;
					mpDBR = mpDBRScalarMT;

					mpAABBScalarMT = new AABBoxRasterizerScalarMT;
					mpAABB = mpAABBScalarMT;
				}
				else if(mSOCType == SSE_TYPE)
				{
					mpDBRSSEMT = new DepthBufferRasterizerSSEMT;
					mpDBR = mpDBRSSEMT;
					
					mpAABBSSEMT = new AABBoxRasterizerSSEMT;
					mpAABB = mpAABBSSEMT;
				}
				mpAABB->SetDepthTestTasks(mNumDepthTestTasks);
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
				mpPipelineCheckBox->SetVisibility(false);
				mpDepthTestTaskSlider->SetVisibility(false);
				if(mSOCType == SCALAR_TYPE)
				{
					mpDBRScalarST = new DepthBufferRasterizerScalarST;
					mpDBR = mpDBRScalarST;
	
					mpAABBScalarST = new AABBoxRasterizerScalarST;
					mpAABB = mpAABBScalarST;
				}
				else if(mSOCType == SSE_TYPE)
				{
					mpDBRSSEST = new DepthBufferRasterizerSSEST;
					mpDBR = mpDBRSSEST;
					
					mpAABBSSEST = new AABBoxRasterizerSSEST;
					mpAABB = mpAABBSSEST;
				}	
			}
			mpDBR->CreateTransformedModels(mpAssetSetDBR, OCCLUDER_SETS);		
			mpDBR->SetOccluderSizeThreshold(mOccluderSizeThreshold);
			mpAABB->CreateTransformedAABBoxes(mpAssetSetAABB, OCCLUDEE_SETS);
			mpAABB->SetOccludeeSizeThreshold(mOccludeeSizeThreshold);
			mpTasksCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_7:
		{
			if(mSyncInterval == 1)
			{
				mSyncInterval = 0;
			}
			else 
			{
				mSyncInterval = 1;
			}
			CPUTCheckboxState state;
			if(mSyncInterval == 1)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpVsyncCheckBox->SetCheckboxState(state);
			break;
		}
	case KEY_8:
		{
			TaskCleanUp();
			mPipeline = !mPipeline;
			CPUTCheckboxState state;
			if(mPipeline)
			{
				state = CPUT_CHECKBOX_CHECKED;
			}
			else
			{
				state = CPUT_CHECKBOX_UNCHECKED;
			}
			mpPipelineCheckBox->SetCheckboxState(state);
			break;
		}
    }
	

    // pass it to the camera controller
    if(handled == CPUT_EVENT_UNHANDLED)
    {
        handled = mpCameraController->HandleKeyboardEvent(key);
    }
    return handled;
}
// 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); 
}