1: //--------------------------------------------------------------------------------------
   2: // File: main.cpp
   3: //--------------------------------------------------------------------------------------
   4: #include "DXUT.h"
   5: #include "DXUTgui.h"
   6: #include "DXUTmisc.h"
   7: #include "DXUTCamera.h"
   8: #include "DXUTSettingsDlg.h"
   9: #include "SDKmisc.h"
  10: #include "SDKmesh.h"
  11: #include "resource.h"
  12: #include "ModelXFile.h"
  13: 
  14: #define frand() ((float)rand()/(float)RAND_MAX)
  15: 
  16: //--------------------------------------------------------------------------------------
  17: // Parameters for test
  18: //--------------------------------------------------------------------------------------
  19: 
  20: //#define DEBUG_VS   // Uncomment this line to debug D3D9 vertex shaders 
  21: //#define DEBUG_PS   // Uncomment this line to debug D3D9 pixel shaders 
  22: 
  23: #define MAX_SO_POLYGONE 65536
  24: 
  25: 
  26: //--------------------------------------------------------------------------------------
  27: // Global variables
  28: //--------------------------------------------------------------------------------------
  29: CModelViewerCamera      g_Camera;               // A model viewing camera
  30: CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs
  31: CD3DSettingsDlg         g_SettingsDlg;          // Device settings dialog
  32: CDXUTTextHelper*		g_pTxtHelper = NULL;
  33: CDXUTDialog             g_HUD;                  // dialog for standard controls
  34: CDXUTDialog             g_SampleUI;             // dialog for sample specific controls
  35: ID3D10Device*           g_pd3dDevice = NULL;
  36: 
  37: // Direct3D 10 resources
  38: ID3DX10Font*            g_pFont10 = NULL;       
  39: ID3DX10Sprite*          g_pSprite10 = NULL;     
  40: ID3D10Effect*           g_pEffect10 = NULL;     
  41: ID3D10InputLayout*      g_pVertexLayout = NULL; 
  42: ID3D10EffectTechnique*  g_pTechRenderScene = NULL;
  43: ID3D10EffectTechnique*  g_pTechRenderSceneClipping = NULL;
  44: ID3D10EffectTechnique*  g_pTechPartialSortBack = NULL;
  45: ID3D10EffectTechnique*  g_pTechPartialSortFront = NULL;
  46: ID3D10EffectMatrixVariable*   g_pmWorldViewProj = NULL;
  47: ID3D10EffectMatrixVariable*   g_pmWorldView = NULL;
  48: ID3D10EffectMatrixVariable*   g_pmWorld = NULL;
  49: ID3D10EffectVectorVariable*   g_pMaterialAmbientColor = NULL;
  50: ID3D10EffectVectorVariable*   g_pMaterialDiffuseColor = NULL;
  51: ID3D10EffectVectorVariable*   g_pLightDir = NULL;
  52: ID3D10EffectVectorVariable*   g_pLightDiffuse = NULL;
  53: ID3D10EffectScalarVariable*   g_pfZMin = NULL;
  54: ID3D10EffectScalarVariable*   g_pfZMid = NULL;
  55: ID3D10EffectScalarVariable*   g_pfZMax = NULL;
  56: ID3D10EffectShaderResourceVariable* g_ptxMesh = NULL;
  57: 
  58: // SO objects
  59: enum
  60: {
  61: 	METHOD_NONE = 0,
  62: 	METHOD_SLICE,
  63: 	METHOD_PARTIAL,
  64: };
  65: unsigned int g_dwMethodIdx = METHOD_NONE;
  66: unsigned int g_dwNumPartsLog = 1;
  67: unsigned int g_dwNumParts = (1<<g_dwNumPartsLog);
  68: ID3D10Buffer*           *g_pSO = NULL;
  69: 
  70: 
  71: MeshXFile              *g_pMesh = 0;
  72: 
  73: // 背景
  74: typedef struct {
  75:   float x,y,z;
  76:   float u,v;
  77: } BGVERTEX;
  78: ID3D10ShaderResourceView* g_pTexRVBg = NULL;
  79: ID3D10Texture2D* g_pTextureBg = NULL;
  80: ID3D10InputLayout*      g_pVertexLayoutBg = NULL; 
  81: ID3D10EffectTechnique*  g_pTechRenderBg = NULL;
  82: ID3D10Buffer*                               g_pVBBg = NULL;
  83: ID3D10Buffer*                               g_pIBBg = NULL;
  84: 
  85: // 雪
  86: #define SNOW_COUNT 10240
  87: #define SNOW_VELOCITY 0.05
  88: #define SNOW_X_MAX 1.0
  89: #define SNOW_X_MIN -1.0
  90: #define SNOW_Y_MAX 1.0
  91: #define SNOW_Y_MIN -1.0
  92: #define SNOW_Z_MAX 100.0
  93: #define SNOW_Z_MIN 1.0
  94: typedef struct {
  95:   float x,y,z;
  96:   float bx,by,bz;
  97:   float tx,ty,tz;
  98: } SNOWVERTEX;
  99: ID3D10ShaderResourceView* g_pTexRVSnow = NULL;
 100: ID3D10Texture2D*          g_pTextureSnow = NULL;
 101: ID3D10InputLayout*        g_pVertexLayoutSnow = NULL; 
 102: ID3D10EffectTechnique*    g_pTechRenderSnow = NULL;
 103: ID3D10Buffer*             g_pVBSnow = NULL;
 104: SNOWVERTEX                g_aSnowVertex[SNOW_COUNT];
 105: 
 106: // 積もった雪
 107: typedef struct {
 108:   float x,y,z;
 109:   float u,v;
 110: } SNOWMAPVERTEX;
 111: #define SNOWMAPSIZE 256
 112: #define SNOWMAPINDEX_COUNT (6 * (SNOWMAPSIZE-1) * (SNOWMAPSIZE-1))
 113: ID3D10Texture2D*            g_pSnowMapDepth;     // Depth stencil for the environment map
 114: ID3D10DepthStencilView*     g_pSnowMapDSV;       // Depth stencil view for environment map for all 6 faces
 115: ID3D10Texture2D*            g_pSnowMap;          // Environment map
 116: ID3D10RenderTargetView*     g_pSnowMapRTV;       // Render target view for the alpha map
 117: ID3D10ShaderResourceView*   g_pSnowMapSRV;       // Shader resource view for the cubic env map
 118: ID3D10EffectTechnique*      g_pTechRenderDepth = NULL;
 119: ID3D10EffectTechnique*      g_pTechRenderSnowMap = NULL;
 120: ID3D10InputLayout*          g_pVertexLayoutSnowMap = NULL; 
 121: ID3D10Buffer*               g_pVBSnowMap = NULL;
 122: ID3D10Buffer*               g_pIBSnowMap = NULL;
 123: ID3D10EffectScalarVariable* g_pfBaseValue = NULL;
 124: ID3D10EffectScalarVariable* g_pfCompValue = NULL;
 125: 
 126: //--------------------------------------------------------------------------------------
 127: // UI control IDs
 128: //--------------------------------------------------------------------------------------
 129: #define IDC_TOGGLEFULLSCREEN    1
 130: #define IDC_TOGGLEREF           2
 131: #define IDC_CHANGEDEVICE        3
 132: #define IDC_METHOD              4
 133: #define IDC_PARTITIONLABEL      5
 134: #define IDC_PARTITION           6
 135: 
 136: 
 137: //--------------------------------------------------------------------------------------
 138: // Forward declarations 
 139: //--------------------------------------------------------------------------------------
 140: LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext );
 141: void    CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
 142: void    CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
 143: void    CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
 144: bool    CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
 145: 
 146: bool    CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
 147: HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
 148: HRESULT CALLBACK OnD3D10ResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
 149: void    CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
 150: void    CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext );
 151: void    CALLBACK OnD3D10DestroyDevice( void* pUserContext );
 152: 
 153: void    InitApp();
 154: void    RenderText();
 155: 
 156: 
 157: //--------------------------------------------------------------------------------------
 158: // Entry point to the program. Initializes everything and goes into a message processing 
 159: // loop. Idle time is used to render the scene.
 160: //--------------------------------------------------------------------------------------
 161: int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
 162: {
 163:     // Enable run-time memory check for debug builds.
 164: #if defined(DEBUG) | defined(_DEBUG)
 165:     _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
 166: #endif
 167: 
 168:     // DXUT will create and use the best device (either D3D9 or D3D10) 
 169:     // that is available on the system depending on which D3D callbacks are set below
 170: 
 171:     // Set DXUT callbacks
 172:     DXUTSetCallbackMsgProc( MsgProc );
 173:     DXUTSetCallbackKeyboard( OnKeyboard );
 174:     DXUTSetCallbackFrameMove( OnFrameMove );
 175:     DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
 176: 
 177:     DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable );
 178:     DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice );
 179:     DXUTSetCallbackD3D10SwapChainResized( OnD3D10ResizedSwapChain );
 180:     DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10ReleasingSwapChain );
 181:     DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice );
 182:     DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender );
 183: 
 184:     InitApp();
 185:     DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params
 186:     DXUTSetCursorSettings( true, true );
 187:     DXUTCreateWindow( L"Partial Sorting" );
 188:     DXUTCreateDevice( true, 640, 480 );
 189: 
 190:     DXUTMainLoop(); // Enter into the DXUT render loop
 191: 
 192:     return DXUTGetExitCode();
 193: }
 194: 
 195: 
 196: //--------------------------------------------------------------------------------------
 197: // Initialize the app 
 198: //--------------------------------------------------------------------------------------
 199: void InitApp()
 200: {
 201:     g_SettingsDlg.Init( &g_DialogResourceManager );
 202:     g_HUD.Init( &g_DialogResourceManager );
 203:     g_SampleUI.Init( &g_DialogResourceManager );
 204: 
 205:     g_HUD.SetCallback( OnGUIEvent ); int iY = 10; 
 206:     g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 );
 207:     g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22, VK_F3 );
 208:     g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 );
 209: 
 210:     g_SampleUI.SetCallback( OnGUIEvent ); iY = 10; 
 211:     g_SampleUI.AddComboBox( IDC_METHOD, 10, iY, 150, 24, L'M' );
 212:     g_SampleUI.GetComboBox( IDC_METHOD )->AddItem( L"(M)ethod: None", (void*)0 );
 213:     g_SampleUI.GetComboBox( IDC_METHOD )->AddItem( L"(M)ethod: Slice", (void*)1 );
 214:     g_SampleUI.GetComboBox( IDC_METHOD )->AddItem( L"(M)ethod: Partial Sort", (void*)2 );
 215: 	g_SampleUI.GetComboBox( IDC_METHOD )->SetSelectedByData( (void*)g_dwMethodIdx );
 216:     WCHAR wszBuf[256];
 217:     StringCchPrintf( wszBuf, 256, L"Number of partitions: %u", g_dwNumParts );
 218:     g_SampleUI.AddStatic( IDC_PARTITIONLABEL, wszBuf, 10, iY += 30, 150, 16 );
 219:     g_SampleUI.AddSlider( IDC_PARTITION, 10, iY += 14, 140, 24, 1, 10, g_dwNumPartsLog );
 220: }
 221: 
 222: 
 223: //--------------------------------------------------------------------------------------
 224: // Render the help and statistics text. This function uses the ID3DXFont interface for 
 225: // efficient text rendering.
 226: //--------------------------------------------------------------------------------------
 227: void RenderText()
 228: {
 229:     g_pTxtHelper->Begin();
 230:     g_pTxtHelper->SetInsertionPos( 5, 5 );
 231:     g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
 232:     g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );  
 233:     g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() );
 234:     g_pTxtHelper->End();
 235: }
 236: 
 237: 
 238: //--------------------------------------------------------------------------------------
 239: // Reject any D3D10 devices that aren't acceptable by returning false
 240: //--------------------------------------------------------------------------------------
 241: bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
 242: {
 243:     return true;
 244: }
 245: 
 246: //--------------------------------------------------------------------------------------
 247: void DestroyPartitions()
 248: {
 249:     for(unsigned int i = 0; i < g_dwNumPartsLog; i++)
 250:     {
 251: 		SAFE_RELEASE(g_pSO[i]);
 252: 	}
 253: 
 254: 	SAFE_DELETE( g_pSO );
 255: }
 256: typedef ID3D10Buffer *LPD3D10Buffer;
 257: 
 258: //--------------------------------------------------------------------------------------
 259: HRESULT CreatePartitions(ID3D10Device* pd3dDevice)
 260: {
 261:     HRESULT hr;
 262: 
 263: 	g_pSO = new LPD3D10Buffer[g_dwNumPartsLog];
 264: 
 265:     D3D10_BUFFER_DESC vbdesc =
 266:     {
 267: 		3 * MAX_SO_POLYGONE * g_pMesh->GetVertexSize(),
 268:         D3D10_USAGE_DEFAULT,
 269:         D3D10_BIND_VERTEX_BUFFER | D3D10_BIND_STREAM_OUTPUT,
 270:         0,
 271:         0
 272:     };
 273: 
 274:     for(unsigned int i = 0; i < g_dwNumPartsLog; i++)
 275:     {
 276: 	    V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pSO[i]) );
 277: 	}
 278: 
 279: 	return S_OK;
 280: }
 281: 
 282: //--------------------------------------------------------------------------------------
 283: // Create any D3D10 resources that aren't dependant on the back buffer
 284: //--------------------------------------------------------------------------------------
 285: HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc, void* pUserContext )
 286: {
 287:     HRESULT hr;
 288: 
 289: 	g_pd3dDevice = pd3dDevice;
 290: 
 291:     V_RETURN( D3DX10CreateSprite( pd3dDevice, 500, &g_pSprite10 ) );
 292:     V_RETURN( g_DialogResourceManager.OnD3D10CreateDevice( pd3dDevice ) );
 293:     V_RETURN( g_SettingsDlg.OnD3D10CreateDevice( pd3dDevice ) );
 294:     V_RETURN( D3DX10CreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, 
 295:                                 OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, 
 296:                                 L"Arial", &g_pFont10 ) );
 297:     g_pTxtHelper = new CDXUTTextHelper( NULL, NULL, g_pFont10, g_pSprite10, 15 );
 298: 
 299:     // Read the D3DX effect file
 300:     WCHAR str[MAX_PATH];
 301:     V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"main.fx" ) );
 302:     DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
 303:     #if defined( DEBUG ) || defined( _DEBUG )
 304:     // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders.
 305:     // Setting this flag improves the shader debugging experience, but still allows 
 306:     // the shaders to be optimized and to run exactly the way they will run in 
 307:     // the release configuration of this program.
 308:     dwShaderFlags |= D3D10_SHADER_DEBUG;
 309:     #endif
 310:     V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", dwShaderFlags, 0, pd3dDevice, NULL, NULL, &g_pEffect10, NULL, NULL ) );
 311: 
 312:     // Get effects variables
 313: 	g_pTechRenderScene = g_pEffect10->GetTechniqueByName("RenderScene");
 314: 	g_pTechRenderSceneClipping = g_pEffect10->GetTechniqueByName("RenderSceneClipping");
 315: 	g_pTechPartialSortFront = g_pEffect10->GetTechniqueByName("TechPartialSortFront");
 316: 	g_pTechPartialSortBack  = g_pEffect10->GetTechniqueByName("TechPartialSortBack");
 317: 	g_pTechRenderBg = g_pEffect10->GetTechniqueByName("RenderSceneBg");
 318: 	g_pTechRenderSnow = g_pEffect10->GetTechniqueByName("RenderSceneSnow");
 319: 	g_pTechRenderDepth = g_pEffect10->GetTechniqueByName("RenderSceneDepth");
 320: 	g_pTechRenderSnowMap = g_pEffect10->GetTechniqueByName("RenderSnowMap");
 321:     g_pmWorldViewProj = g_pEffect10->GetVariableByName( "g_mWorldViewProjection" )->AsMatrix();
 322:     g_pmWorldView = g_pEffect10->GetVariableByName( "g_mWorldView" )->AsMatrix();
 323:     g_pmWorld = g_pEffect10->GetVariableByName( "g_mWorld" )->AsMatrix();
 324: 	g_ptxMesh = g_pEffect10->GetVariableByName( "g_MeshTexture" )->AsShaderResource();
 325:     g_pfZMin  = g_pEffect10->GetVariableByName( "g_fZmin" )->AsScalar();
 326:     g_pfZMid  = g_pEffect10->GetVariableByName( "g_fZmid" )->AsScalar();
 327: 	g_pfZMax  = g_pEffect10->GetVariableByName( "g_fZmax" )->AsScalar();
 328: 	g_pfBaseValue = g_pEffect10->GetVariableByName( "g_fBaseValue" )->AsScalar();
 329: 	g_pfCompValue = g_pEffect10->GetVariableByName( "g_fCompValue" )->AsScalar();
 330: 
 331: 	g_pMaterialAmbientColor = g_pEffect10->GetVariableByName( "g_MaterialAmbientColor" )->AsVector();
 332: 	g_pMaterialDiffuseColor = g_pEffect10->GetVariableByName( "g_MaterialDiffuseColor" )->AsVector();
 333: 	g_pLightDir             = g_pEffect10->GetVariableByName( "g_LightDir"             )->AsVector();
 334: 	g_pLightDiffuse         = g_pEffect10->GetVariableByName( "g_LightDiffuse"         )->AsVector();
 335: 
 336: 	FLOAT vMaterialAmbientColor[4] = {0.3f, 0.3f, 0.3f, 0.3f};
 337: 	g_pMaterialAmbientColor->SetFloatVector(vMaterialAmbientColor);
 338: 	FLOAT vMaterialDiffuseColor[4] = {0.7f, 0.7f, 0.7f, 0.0f};
 339: 	g_pMaterialDiffuseColor->SetFloatVector(vMaterialDiffuseColor);
 340: 	FLOAT vLightDir[4] = {0.7f, 0.7f, 0.7f, 0.0f};
 341: 	g_pLightDir->SetFloatVector(vLightDir);
 342: 	FLOAT vLightDiffuse[4] = {1.0f, 1.0f, 1.0f, 0.0f};
 343: 	g_pLightDiffuse->SetFloatVector(vLightDiffuse);
 344: 
 345:     const D3D10_INPUT_ELEMENT_DESC layout[] =
 346:     {
 347:         { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 348:         { "NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 349:         { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 350:     };
 351:     D3D10_PASS_DESC PassDesc;
 352:     g_pTechRenderScene->GetPassByIndex( 0 )->GetDesc( &PassDesc );
 353:     V_RETURN( pd3dDevice->CreateInputLayout( layout, 3, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayout ) );
 354: 
 355: 	g_pMesh = new MeshXFile();
 356: 	g_pMesh->OnCreateDevice(pd3dDevice, TEXT("t-pot.x"), TEXT("t-pot.bmp"), g_pTechRenderScene);
 357: 	
 358: 	// 背景
 359: 	LoadTexture(pd3dDevice, TEXT("bg.jpg"), &g_pTexRVBg, &g_pTextureBg);
 360:     const D3D10_INPUT_ELEMENT_DESC layoutBg[] =
 361:     {
 362:         { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 363:         { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 364:     };
 365:     g_pTechRenderBg->GetPassByIndex( 0 )->GetDesc( &PassDesc );
 366:     V_RETURN( pd3dDevice->CreateInputLayout( layoutBg, sizeof(layoutBg)/sizeof(D3D10_INPUT_ELEMENT_DESC)
 367: 		, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayoutBg ) );
 368: 	// 頂点バッファの作成
 369: 	D3D10_BUFFER_DESC vbdesc =
 370: 	{
 371: 		4 * sizeof(BGVERTEX),
 372: 		D3D10_USAGE_DEFAULT,
 373: 		D3D10_BIND_VERTEX_BUFFER,
 374: 		0,
 375: 		0
 376: 	};
 377: 	BGVERTEX pVertexBg[4] = {{-1,1,0.5,0,0},{1,1,0.5,1,0},{-1,-1,0.5,0,1},{1,-1,0.5,1,1}};
 378: 	D3D10_SUBRESOURCE_DATA InitData;
 379: 	InitData.pSysMem = pVertexBg;
 380: 	InitData.SysMemPitch = 0;
 381: 	InitData.SysMemSlicePitch = 0;
 382: 	V( pd3dDevice->CreateBuffer( &vbdesc, &InitData, &g_pVBBg ) );
 383: 	// インデックスバッファの作成
 384: 	vbdesc.BindFlags = D3D10_BIND_INDEX_BUFFER;
 385: 	vbdesc.ByteWidth = 6 * sizeof(DWORD);
 386: 	DWORD pIndexBg[] = {0,1,2,1,3,2};
 387: 	InitData.pSysMem = pIndexBg;
 388: 	V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, &InitData, &g_pIBBg ) );
 389: 
 390: 	// 雪
 391: 	LoadTexture(pd3dDevice, TEXT("snow.jpg"), &g_pTexRVSnow, &g_pTextureSnow);
 392:     const D3D10_INPUT_ELEMENT_DESC layoutSnow[] =
 393:     {
 394:         { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 395:         { "BINORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 396:         { "TANGENT",  0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 397:     };
 398:     g_pTechRenderSnow->GetPassByIndex( 0 )->GetDesc( &PassDesc );
 399:     V_RETURN( pd3dDevice->CreateInputLayout( layoutSnow, sizeof(layoutSnow)/sizeof(D3D10_INPUT_ELEMENT_DESC)
 400: 		, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayoutSnow ) );
 401:     vbdesc.ByteWidth = sizeof( SNOWVERTEX ) * SNOW_COUNT;
 402:     vbdesc.Usage = D3D10_USAGE_DYNAMIC;
 403:     vbdesc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
 404:     vbdesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
 405:     vbdesc.MiscFlags = 0;
 406: 	V( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pVBSnow ) );
 407: 	SNOWVERTEX *pVertex = g_aSnowVertex;
 408: 	for(unsigned int i = 0; i < SNOW_COUNT; i++){
 409: 		pVertex->x = (SNOW_X_MAX - SNOW_X_MIN) * frand() + SNOW_X_MIN;
 410: 		pVertex->z = (SNOW_Z_MAX - SNOW_Z_MIN) * frand() + SNOW_Z_MIN;
 411: 		pVertex->y = (SNOW_Y_MAX - SNOW_Y_MIN) * (float)i / (float)SNOW_COUNT + SNOW_Y_MIN;
 412: 		pVertex->tx = 0.1f * (frand() - 0.5);
 413: 		pVertex->tz = 0.1f * (frand() - 0.5);
 414: 		pVertex->ty = -1.0f;
 415: 		// normalize
 416: 		float d = 1.0f/sqrtf(pVertex->tx*pVertex->tx+pVertex->ty*pVertex->ty+pVertex->tz*pVertex->tz);
 417: 		pVertex->tx *= d;
 418: 		pVertex->ty *= d;
 419: 		pVertex->tz *= d;
 420: 		// binormal = (0,1,0)×tangent
 421: 		pVertex->bx = pVertex->tz;
 422: 		pVertex->by = 0.0f;
 423: 		pVertex->bz = -pVertex->tx;
 424: 		d = 1.0f/sqrtf(pVertex->bx*pVertex->bx+pVertex->by*pVertex->by+pVertex->bz*pVertex->bz);
 425: 		pVertex->bx *= d;
 426: 		pVertex->by *= d;
 427: 		pVertex->bz *= d;
 428: 
 429: 		pVertex++;
 430: 	}
 431: 
 432: 	// 雪面
 433:     D3D10_TEXTURE2D_DESC dstex;
 434:     dstex.Width = SNOWMAPSIZE;
 435:     dstex.Height = SNOWMAPSIZE;
 436:     dstex.MipLevels = 1;
 437:     dstex.ArraySize = 1;
 438:     dstex.SampleDesc.Count = 1;
 439:     dstex.SampleDesc.Quality = 0;
 440:     dstex.Format = DXGI_FORMAT_D32_FLOAT;
 441:     dstex.Usage = D3D10_USAGE_DEFAULT;
 442:     dstex.BindFlags = D3D10_BIND_DEPTH_STENCIL;
 443:     dstex.CPUAccessFlags = 0;
 444:     dstex.MiscFlags = 0;
 445:     V_RETURN( pd3dDevice->CreateTexture2D( &dstex, NULL, &g_pSnowMapDepth ));
 446: 
 447:     D3D10_DEPTH_STENCIL_VIEW_DESC DescDS;
 448:     DescDS.Format = DXGI_FORMAT_D32_FLOAT;
 449:     DescDS.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
 450:     DescDS.Texture2DArray.FirstArraySlice = 0;
 451:     DescDS.Texture2DArray.ArraySize = 1;
 452:     DescDS.Texture2DArray.MipSlice = 0;
 453:     V_RETURN( pd3dDevice->CreateDepthStencilView( g_pSnowMapDepth, &DescDS, &g_pSnowMapDSV ));
 454: 
 455: //    dstex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
 456:     dstex.Format = DXGI_FORMAT_R32_FLOAT;
 457: //    dstex.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
 458:     dstex.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
 459:     V_RETURN( pd3dDevice->CreateTexture2D( &dstex, NULL, &g_pSnowMap ));
 460: 	
 461:     D3D10_RENDER_TARGET_VIEW_DESC DescRT;
 462:     DescRT.Format = dstex.Format;
 463:     DescRT.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
 464:     DescRT.Texture2DArray.FirstArraySlice = 0;
 465:     DescRT.Texture2DArray.ArraySize = 1;
 466:     DescRT.Texture2DArray.MipSlice = 0;
 467:     V_RETURN( pd3dDevice->CreateRenderTargetView( g_pSnowMap, &DescRT, &g_pSnowMapRTV ));
 468: 
 469:     // Create the shader resource view for the cubic env map
 470:     D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
 471:     ZeroMemory( &SRVDesc, sizeof(SRVDesc) );
 472:     SRVDesc.Format = dstex.Format;
 473:     SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
 474:     SRVDesc.TextureCube.MipLevels = 1;
 475:     SRVDesc.TextureCube.MostDetailedMip = 0;
 476:     V_RETURN( pd3dDevice->CreateShaderResourceView( g_pSnowMap, &SRVDesc, &g_pSnowMapSRV ));
 477: 
 478:     const D3D10_INPUT_ELEMENT_DESC layoutSnowMap[] =
 479:     {
 480:         { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 481:         { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
 482:     };
 483:     g_pTechRenderBg->GetPassByIndex( 0 )->GetDesc( &PassDesc );
 484:     V_RETURN( pd3dDevice->CreateInputLayout( layoutSnowMap, sizeof(layoutSnowMap)/sizeof(D3D10_INPUT_ELEMENT_DESC)
 485: 		, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayoutSnowMap ) );
 486: 	{
 487: 	// 頂点バッファの作成
 488: 	D3D10_BUFFER_DESC vbdesc =
 489: 	{
 490: 		SNOWMAPSIZE * SNOWMAPSIZE * sizeof(SNOWMAPVERTEX),
 491: 		D3D10_USAGE_DEFAULT,
 492: 		D3D10_BIND_VERTEX_BUFFER,
 493: 		0,
 494: 		0
 495: 	};
 496: 	SNOWMAPVERTEX *pVertexSnowMap = new SNOWMAPVERTEX[SNOWMAPSIZE * SNOWMAPSIZE];
 497: 	unsigned int idx = 0;
 498: 	for(unsigned int y = 0; y < SNOWMAPSIZE; y++)
 499: 		for(unsigned int x = 0; x < SNOWMAPSIZE; x++)
 500: 		{
 501: 			pVertexSnowMap[idx].u = (float)x/(float)SNOWMAPSIZE;
 502: 			pVertexSnowMap[idx].v = (float)y/(float)SNOWMAPSIZE;
 503: 			pVertexSnowMap[idx].x = 3.0*(+(pVertexSnowMap[idx].u - 0.5f)-(pVertexSnowMap[idx].v - 0.5f))/1.41421356f;
 504: 			pVertexSnowMap[idx].z = 3.0*(-(pVertexSnowMap[idx].v - 0.5f)-(pVertexSnowMap[idx].u - 0.5f))/1.41421356f;
 505: 			pVertexSnowMap[idx].y = 1;
 506: 			idx++;
 507: 		}
 508: 	D3D10_SUBRESOURCE_DATA InitData;
 509: 	InitData.pSysMem = pVertexSnowMap;
 510: 	InitData.SysMemPitch = 0;
 511: 	InitData.SysMemSlicePitch = 0;
 512: 	V( pd3dDevice->CreateBuffer( &vbdesc, &InitData, &g_pVBSnowMap ) );
 513: 	delete[] pVertexSnowMap;
 514: 	// インデックスバッファの作成
 515: 	vbdesc.BindFlags = D3D10_BIND_INDEX_BUFFER;
 516: 	vbdesc.ByteWidth = SNOWMAPINDEX_COUNT * sizeof(DWORD);
 517: 	DWORD *pIndexSnowMap = new DWORD[SNOWMAPINDEX_COUNT];
 518: 	idx = 0;
 519: 	for(unsigned int y = 0; y < SNOWMAPSIZE-1; y++)
 520: 		for(unsigned int x = 0; x < SNOWMAPSIZE-1; x++)
 521: 		{
 522: 			unsigned int id0 = y * SNOWMAPSIZE + x;
 523: 			pIndexSnowMap[idx + 0] = id0;
 524: 			pIndexSnowMap[idx + 1] = id0+1;
 525: 			pIndexSnowMap[idx + 2] = id0+SNOWMAPSIZE;
 526: 			pIndexSnowMap[idx + 3] = id0+1;
 527: 			pIndexSnowMap[idx + 4] = id0+SNOWMAPSIZE;
 528: 			pIndexSnowMap[idx + 5] = id0+SNOWMAPSIZE+1;
 529: 			idx+=6;
 530: 		}
 531: 	InitData.pSysMem = pIndexSnowMap;
 532: 	V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, &InitData, &g_pIBSnowMap ) );
 533: 	delete[] pIndexSnowMap;
 534: 	}
 535: 
 536: 	CreatePartitions(pd3dDevice);
 537: 
 538: 	// Setup the camera's view parameters
 539:     D3DXVECTOR3 vecEye(2.0f, 2.0f, -2.0f);
 540:     D3DXVECTOR3 vecAt (0.0f, 0.0f, -0.0f);
 541:     g_Camera.SetViewParams( &vecEye, &vecAt );
 542: 
 543: 
 544:     return S_OK;
 545: }
 546: 
 547: //--------------------------------------------------------------------------------------
 548: // Release D3D10 resources created in OnD3D10CreateDevice 
 549: //--------------------------------------------------------------------------------------
 550: void CALLBACK OnD3D10DestroyDevice( void* pUserContext )
 551: {
 552: 	SAFE_RELEASE( g_pVBSnowMap );
 553:     SAFE_RELEASE( g_pIBSnowMap );
 554:     SAFE_RELEASE( g_pVertexLayoutSnowMap );
 555:     SAFE_RELEASE( g_pSnowMapDepth );
 556:     SAFE_RELEASE( g_pSnowMapDSV );
 557:     SAFE_RELEASE( g_pSnowMapRTV );
 558:     SAFE_RELEASE( g_pSnowMapSRV );
 559:     SAFE_RELEASE( g_pSnowMap );
 560: 
 561: 	SAFE_RELEASE( g_pVBSnow );
 562:     SAFE_RELEASE( g_pVertexLayoutSnow );
 563:     SAFE_RELEASE( g_pTexRVSnow );
 564:     SAFE_RELEASE( g_pTextureSnow );
 565: 
 566: 	SAFE_RELEASE( g_pVBBg );
 567:     SAFE_RELEASE( g_pIBBg );
 568:     SAFE_RELEASE( g_pVertexLayoutBg );
 569:     SAFE_RELEASE( g_pTexRVBg );
 570:     SAFE_RELEASE( g_pTextureBg );
 571: 
 572: 	g_pMesh->OnDestroyDevice();
 573:     SAFE_DELETE( g_pMesh );
 574: 
 575: 	DestroyPartitions();
 576: 
 577:     g_DialogResourceManager.OnD3D10DestroyDevice();
 578:     g_SettingsDlg.OnD3D10DestroyDevice();
 579:     SAFE_RELEASE( g_pFont10 );
 580:     SAFE_RELEASE( g_pEffect10 );
 581:     SAFE_RELEASE( g_pVertexLayout );
 582:     SAFE_RELEASE( g_pSprite10 );
 583:     SAFE_DELETE( g_pTxtHelper );
 584: }
 585: 
 586: //--------------------------------------------------------------------------------------
 587: // Create any D3D10 resources that depend on the back buffer
 588: //--------------------------------------------------------------------------------------
 589: HRESULT CALLBACK OnD3D10ResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
 590: {
 591:     HRESULT hr;
 592: 
 593:     V_RETURN( g_DialogResourceManager.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
 594:     V_RETURN( g_SettingsDlg.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
 595: 
 596:     // Setup the camera's projection parameters
 597:     float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height;
 598:     g_Camera.SetProjParams( D3DX_PI/4, fAspectRatio, 0.1f, 1000.0f );
 599:     g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
 600:     g_Camera.SetButtonMasks( MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON );
 601: 
 602:     g_HUD.SetLocation( pBackBufferSurfaceDesc->Width-170, 0 );
 603:     g_HUD.SetSize( 170, 170 );
 604:     g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width-170, pBackBufferSurfaceDesc->Height-300 );
 605:     g_SampleUI.SetSize( 170, 300 );
 606: 
 607:     return S_OK;
 608: }
 609: 
 610: //--------------------------------------------------------------------------------------
 611: //--------------------------------------------------------------------------------------
 612: void RenderSort(ID3D10Device* pd3dDevice, float z_min, float z_max, unsigned int level, ID3D10Buffer *pSoSrc, MeshXFile *pMesh=NULL)
 613: {
 614: 	float z_mid = 0.5f * (z_min + z_max);
 615: 	
 616: 	if(0==--level){
 617: 		// pSoSrc を描画
 618: 	    ID3D10Buffer *buffersRT[1] = {NULL};
 619: 		UINT offsetRT[1] = {0};
 620: 	    pd3dDevice->SOSetTargets( 1, buffersRT, offsetRT );
 621: 
 622: 	    ID3D10Buffer *buffers[1] = {pSoSrc};
 623: 	    UINT stride[1] = { sizeof(CUSTOMVERTEX) };
 624: 	    UINT offset[1] = { 0 };
 625: 	    pd3dDevice->IASetVertexBuffers( 0, 1, buffers, stride, offset );
 626: 	    pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
 627: 	    pd3dDevice->IASetInputLayout( g_pVertexLayout );
 628: 
 629: 	    D3D10_TECHNIQUE_DESC techDesc;
 630: 	    g_pTechRenderScene->GetDesc( &techDesc );
 631: 
 632: 	    for( UINT p = 0; p < techDesc.Passes; ++p )
 633: 	    {
 634: 	        g_pTechRenderScene->GetPassByIndex( p )->Apply(0);
 635:             pd3dDevice->DrawAuto();
 636: 	    }
 637: 		buffers[0] = NULL;
 638: 		pd3dDevice->IASetVertexBuffers( 0, 1, buffers, stride, offset );
 639: 	}else{
 640: 		// pSoSrc を元に、pSO0 に 半分から手前のポリゴンを、pSO1 に半分から奥のポリゴンを書き込む
 641: 		for(unsigned int i = 0; i < 2; i++)
 642: 		{
 643: 			ID3D10Buffer *buffersRT[1] = {g_pSO[level-1]};
 644: 			UINT offsetRT[1] = { 0 };
 645: 			pd3dDevice->SOSetTargets( 1, buffersRT, offsetRT );
 646: 
 647: 			// Set Effects Parameters
 648: 			g_pfZMid->SetFloat( z_mid );
 649: 
 650: 			ID3D10EffectTechnique *pTech = (0==i) ? g_pTechPartialSortBack : g_pTechPartialSortFront; 
 651: 			D3D10_TECHNIQUE_DESC techDesc;
 652: 			pTech->GetDesc( &techDesc );
 653: 
 654: 			if(NULL != pMesh)
 655: 			{
 656: 				pMesh->SetBuffers();
 657: 
 658: 				for( UINT p = 0; p < techDesc.Passes; ++p )
 659: 				{
 660: 					pTech->GetPassByIndex( p )->Apply(0);
 661: 					pMesh->Draw();
 662: 				}
 663: 			}else{
 664: 				ID3D10Buffer *buffers[1] = {pSoSrc};
 665: 				UINT stride[1] = { sizeof(CUSTOMVERTEX) };
 666: 				UINT offset[1] = { 0 };
 667: 				pd3dDevice->IASetVertexBuffers( 0, 1, buffers, stride, offset );
 668: 				pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
 669: 
 670: 				for( UINT p = 0; p < techDesc.Passes; ++p )
 671: 				{
 672: 					pTech->GetPassByIndex( p )->Apply(0);
 673: 					pd3dDevice->DrawAuto();
 674: 				}
 675: 				ID3D10Buffer *buffersRT[1] = {NULL};
 676: 				pd3dDevice->SOSetTargets( 1, buffersRT, offsetRT );
 677: 				buffers[0] = NULL;
 678: 				pd3dDevice->IASetVertexBuffers( 0, 1, buffers, stride, offset );
 679: 			}
 680: 			// 再帰的に、奥から描画
 681: 			if(0==i)
 682: 			{
 683: 				RenderSort(pd3dDevice, z_mid, z_max, level, buffersRT[0]);
 684: 			}else{
 685: 				RenderSort(pd3dDevice, z_min, z_mid, level, buffersRT[0]);
 686: 			}
 687: 		}
 688: 	}
 689: }
 690: 
 691: //--------------------------------------------------------------------------------------
 692: //--------------------------------------------------------------------------------------
 693: void RenderSnowCover(ID3D10Device* pd3dDevice, float fElapsedTime, bool reset = false)
 694: {
 695: 	static float rate = 0.5;
 696: 	if(reset) rate = 0.0;
 697: 	rate += fElapsedTime * 0.05f;
 698: 	if(1.0f < rate)rate = 1.0f;
 699: 	g_pfCompValue->SetFloat(rate * 0.00035);
 700: 	float alpha = rate * 100;
 701: 	alpha = (1.0 < alpha) ? 1.0 : alpha;
 702: 	g_pfBaseValue->SetFloat(alpha);
 703: 	
 704: 	// Save
 705:     ID3D10RenderTargetView* apOldRTVs[1] = { NULL };
 706:     ID3D10DepthStencilView* pOldDS = NULL;
 707:     pd3dDevice->OMGetRenderTargets( 1, apOldRTVs, &pOldDS );
 708:     D3D10_VIEWPORT OldVP;
 709:     UINT cRT = 1;
 710:     pd3dDevice->RSGetViewports( &cRT, &OldVP );
 711: 
 712:     // Set a new viewport
 713:     D3D10_VIEWPORT MVP;
 714:     MVP.Height = SNOWMAPSIZE;
 715:     MVP.Width = SNOWMAPSIZE;
 716:     MVP.MinDepth = 0;
 717:     MVP.MaxDepth = 1;
 718:     MVP.TopLeftX = 0;
 719:     MVP.TopLeftY = 0;
 720:     pd3dDevice->RSSetViewports( 1, &MVP );
 721: 
 722: 	g_ptxMesh->SetResource(NULL);
 723:     pd3dDevice->IASetInputLayout( NULL );
 724: 	UINT uStrides = sizeof(CUSTOMVERTEX);
 725:     UINT uOffsets = 0;
 726:     ID3D10Buffer *pBuffers[1] = { NULL };
 727:     pd3dDevice->IASetVertexBuffers( 0, 1, pBuffers, &uStrides, &uOffsets );
 728:     pd3dDevice->IASetIndexBuffer( NULL, DXGI_FORMAT_R32_UINT, 0 );
 729: 
 730:     float ClearColor[4] = { 10.0, 10.0, 0.0, 0.0 };
 731:     pd3dDevice->ClearRenderTargetView( g_pSnowMapRTV, ClearColor);
 732:     pd3dDevice->ClearDepthStencilView( g_pSnowMapDSV, D3D10_CLEAR_DEPTH, 1.0, 0);
 733: 
 734:     ID3D10RenderTargetView* aRTViews[ 1 ] = { g_pSnowMapRTV };
 735:     pd3dDevice->OMSetRenderTargets( sizeof(aRTViews) / sizeof(aRTViews[0]), aRTViews, g_pSnowMapDSV );
 736: 
 737: 	// Render scene	
 738:     D3DXMATRIX  mWorld, mView, mProj;
 739:     D3DXMATRIX  mWorldViewProjection;
 740: 	D3DXVECTOR3 vEyePt    = D3DXVECTOR3(0, 1, 0);
 741: 	D3DXVECTOR3 vLookatPt = D3DXVECTOR3(0, 0, 0);
 742: 	D3DXVECTOR3 vUp       = D3DXVECTOR3(1, 0, 1);
 743: 	D3DXMatrixLookAtLH( &mView, &vEyePt, &vLookatPt, &vUp );
 744: 	D3DXMatrixOrthoLH( &mProj, 3.0f, 3.0f, 0.0, 2.0f );// w,h,n,f
 745: 	mWorld = *g_Camera.GetWorldMatrix();
 746: 	mWorldViewProjection = mWorld * mView * mProj;
 747: 	g_pmWorldViewProj->SetMatrix( (float*)&mWorldViewProjection );
 748: 	g_pMesh->SetBuffers();
 749: 	D3D10_TECHNIQUE_DESC techDesc;
 750: 	g_pTechRenderDepth->GetDesc( &techDesc );
 751: 	for( UINT p = 0; p < techDesc.Passes; ++p )
 752: 	{
 753: 		g_pTechRenderDepth->GetPassByIndex( p )->Apply(0);
 754: 
 755: 		g_pMesh->Draw();
 756: 	}
 757: 
 758: 
 759: 	// Restore
 760: 	pd3dDevice->RSSetViewports( 1, &OldVP );
 761:     pd3dDevice->OMSetRenderTargets( 1, apOldRTVs, pOldDS );
 762:     SAFE_RELEASE( apOldRTVs[0] );
 763:     SAFE_RELEASE( pOldDS );
 764: 
 765: 	// VTF で雪を描く
 766:     ID3D10Buffer *buffers[1] = {g_pVBSnowMap};
 767:     UINT stride[1] = { sizeof(SNOWMAPVERTEX) };
 768:     UINT offset[1] = { 0 };
 769:     pd3dDevice->IASetVertexBuffers( 0, 1, buffers, stride, offset );
 770:     pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
 771:     pd3dDevice->IASetInputLayout( g_pVertexLayoutSnowMap );
 772:     pd3dDevice->IASetIndexBuffer( g_pIBSnowMap, DXGI_FORMAT_R32_UINT, 0 );
 773: 
 774: 	mWorld = *g_Camera.GetWorldMatrix();
 775: 	mProj = *g_Camera.GetProjMatrix();
 776: 	mView = *g_Camera.GetViewMatrix();
 777: 	mWorldViewProjection =  mView * mProj;
 778: //	mWorldViewProjection = mWorld * mView * mProj;
 779: 	g_pmWorldViewProj->SetMatrix( (float*)&mWorldViewProjection );
 780: 
 781: 	g_ptxMesh->SetResource(g_pSnowMapSRV);
 782: 
 783:     g_pTechRenderSnowMap->GetPassByIndex( 0 )->Apply(0);
 784:     pd3dDevice->DrawIndexed( SNOWMAPINDEX_COUNT, 0, 0 );
 785: 
 786: 	g_ptxMesh->SetResource(NULL);
 787: }
 788: 
 789: 
 790: //--------------------------------------------------------------------------------------
 791: // Render the scene using the D3D10 device
 792: //--------------------------------------------------------------------------------------
 793: void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
 794: {
 795:     D3DXMATRIX  mWorldViewProjection;
 796:     D3DXMATRIX  mWorldView;
 797:     D3DXMATRIX  mWorld;
 798:     D3DXMATRIX  mView;
 799:     D3DXMATRIX  mProj;
 800: 
 801: #if 0
 802: 	float ClearColor[4] = { 1.f, 1.f, 1.f, 0.0f };
 803: //    float ClearColor[4] = { 0.176f, 0.196f, 0.667f, 0.0f };
 804:     ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView();
 805:     pd3dDevice->ClearRenderTargetView( pRTV, ClearColor );
 806: #else
 807: 	// 背景描画
 808:     ID3D10Buffer *buffers[1] = {g_pVBBg};
 809:     UINT stride[1] = { sizeof(BGVERTEX) };
 810:     UINT offset[1] = { 0 };
 811:     pd3dDevice->IASetVertexBuffers( 0, 1, buffers, stride, offset );
 812:     pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
 813:     pd3dDevice->IASetInputLayout( g_pVertexLayoutBg );
 814:     pd3dDevice->IASetIndexBuffer( g_pIBBg, DXGI_FORMAT_R32_UINT, 0 );
 815: 	g_ptxMesh->SetResource(g_pTexRVBg);
 816: 
 817: //g_ptxMesh->SetResource(g_pSnowMapSRV);
 818: 
 819: 	D3D10_TECHNIQUE_DESC techDesc;
 820:     g_pTechRenderBg->GetDesc( &techDesc );
 821: 
 822:     for( UINT p = 0; p < techDesc.Passes; ++p )
 823:     {
 824:         g_pTechRenderBg->GetPassByIndex( p )->Apply(0);
 825:         pd3dDevice->DrawIndexed( 6, 0, 0 );
 826:     }
 827: #endif
 828: 
 829:     // Clear the depth stencil
 830:     ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView();
 831:     pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 );
 832: 
 833:     // If the settings dialog is being shown, then render it instead of rendering the app's scene
 834:     if( g_SettingsDlg.IsActive() )
 835:     {
 836:         g_SettingsDlg.OnRender( fElapsedTime );
 837:         return;
 838:     }
 839: 
 840: 	switch(g_dwMethodIdx)
 841: 	{
 842: 	case METHOD_NONE:
 843: 		{
 844: 		// Get the projection & view matrix from the camera class
 845: 		mWorld = *g_Camera.GetWorldMatrix();
 846: 		mProj = *g_Camera.GetProjMatrix();
 847: 		mView = *g_Camera.GetViewMatrix();
 848: 		mWorldViewProjection = mWorld * mView * mProj;
 849: 
 850: 		// Update the effect's variables.  Instead of using strings, it would 
 851: 		// be more efficient to cache a handle to the parameter by calling 
 852: 		// ID3DXEffect::GetParameterByName
 853: 		g_pmWorldViewProj->SetMatrix( (float*)&mWorldViewProjection );
 854: 		g_pmWorld->SetMatrix( (float*)&mWorld );
 855: 
 856: 		// Set vertex Layout
 857: 		pd3dDevice->IASetInputLayout( g_pVertexLayout );
 858: 
 859: 		g_pMesh->SetBuffers();
 860: 		g_ptxMesh->SetResource(g_pMesh->GetTexture());
 861: 
 862: 		D3D10_TECHNIQUE_DESC techDesc;
 863: 		g_pTechRenderScene->GetDesc( &techDesc );
 864: 		for( UINT p = 0; p < techDesc.Passes; ++p )
 865: 		{
 866: 			g_pTechRenderScene->GetPassByIndex( p )->Apply(0);
 867: 
 868: 			g_pMesh->Draw();
 869: 		}
 870: 		}
 871: 		break;
 872: 	case METHOD_SLICE:
 873: 		{
 874: 		// Get the projection & view matrix from the camera class
 875: 		mWorld = *g_Camera.GetWorldMatrix();
 876: 		mProj = *g_Camera.GetProjMatrix();
 877: 		mView = *g_Camera.GetViewMatrix();
 878: 		mWorldView = mWorld * mView;
 879: 		mWorldViewProjection = mWorldView * mProj;
 880: 
 881: 		// Update the effect's variables.  Instead of using strings, it would 
 882: 		// be more efficient to cache a handle to the parameter by calling 
 883: 		// ID3DXEffect::GetParameterByName
 884: 		g_pmWorldViewProj->SetMatrix( (float*)&mWorldViewProjection );
 885: 		g_pmWorld->SetMatrix( (float*)&mWorld );
 886: 
 887: 		// Set vertex Layout
 888: 		pd3dDevice->IASetInputLayout( g_pVertexLayout );
 889: 
 890: 		g_pMesh->SetBuffers();
 891: 		g_ptxMesh->SetResource(g_pMesh->GetTexture());
 892: 
 893: 		D3D10_TECHNIQUE_DESC techDesc;
 894: 		g_pTechRenderSceneClipping->GetDesc( &techDesc );
 895: 
 896: 		const D3DXVECTOR3 *pCenter = g_pMesh->GetBoundingSphereCenter();
 897: 		FLOAT radius = g_pMesh->GetBoundingSphereRadius();
 898: 
 899: 		for(unsigned int i = g_dwNumParts; 0 < i; i--)
 900: 		{
 901: 			D3DXVECTOR3 v_near;
 902: 			D3DXVECTOR3 v_far;
 903: 
 904: 			D3DXVec3TransformCoord(&v_near, pCenter, &mWorldView);
 905: 			v_far = v_near;
 906: 			v_near.z += radius * (2.0f * (FLOAT)(i-1)/(FLOAT)g_dwNumParts-1.0f);
 907: 			v_far.z  += radius * (2.0f * (FLOAT)(i  )/(FLOAT)g_dwNumParts-1.0f);
 908: 
 909: 			g_pfZMin->SetFloat( v_near.z );
 910: 			g_pfZMax->SetFloat( v_far.z );
 911: 
 912: 			for( UINT p = 0; p < techDesc.Passes; ++p )
 913: 			{
 914: 				g_pTechRenderSceneClipping->GetPassByIndex( p )->Apply(0);
 915: 
 916: 				g_pMesh->Draw();
 917: 			}
 918: 		}
 919: 		}
 920: 		break;
 921: 	case METHOD_PARTIAL:
 922: 		{
 923: 		// Get the projection & view matrix from the camera class
 924: 		mWorld = *g_Camera.GetWorldMatrix();
 925: 		mProj = *g_Camera.GetProjMatrix();
 926: 		mView = *g_Camera.GetViewMatrix();
 927: 		mWorldView = mWorld * mView;
 928: 		mWorldViewProjection = mWorldView * mProj;
 929: 
 930: 		g_ptxMesh->SetResource(g_pMesh->GetTexture());
 931: 		g_pmWorldViewProj->SetMatrix( (float*)&mWorldViewProjection );
 932: 		g_pmWorldView->SetMatrix( (float*)&mWorldView );
 933: 		g_pmWorld->SetMatrix( (float*)&mWorld );
 934: 
 935: 
 936: 		const D3DXVECTOR3 *pCenter = g_pMesh->GetBoundingSphereCenter();
 937: 		D3DXVECTOR3 vCenter;
 938: 		D3DXVec3TransformCoord(&vCenter, pCenter, &mWorldView);
 939: 		FLOAT radius = g_pMesh->GetBoundingSphereRadius();
 940: 
 941: 		RenderSort(pd3dDevice
 942: 				 , vCenter.z-radius
 943: 				 , vCenter.z+radius
 944: 				 , g_dwNumPartsLog+1, NULL, g_pMesh);
 945: 		}
 946: 		break;
 947: 	default:
 948: 		assert(0);
 949: 		break;
 950: 	}
 951: 
 952: 	// 雪
 953: 	SNOWVERTEX *pVertex = g_aSnowVertex;
 954: 	float velo = SNOW_VELOCITY * fElapsedTime;
 955: 	for(unsigned int i = 0; i < SNOW_COUNT; i++){
 956: 		pVertex->x += pVertex->tx * velo;
 957: 		pVertex->x += (pVertex->x < SNOW_X_MIN) ? (SNOW_X_MAX - SNOW_X_MIN) : 0;
 958: 		pVertex->x -= (SNOW_X_MAX < pVertex->x) ? (SNOW_X_MAX - SNOW_X_MIN) : 0;
 959: 		pVertex->y += pVertex->ty * velo;
 960: 		pVertex->y += (pVertex->y < SNOW_Y_MIN) ? (SNOW_Y_MAX - SNOW_Y_MIN) : 0;
 961: 		pVertex->y -= (SNOW_Y_MAX < pVertex->y) ? (SNOW_Y_MAX - SNOW_Y_MIN) : 0;
 962: 		pVertex->z += pVertex->tz * velo;
 963: 		pVertex->z += (pVertex->z < SNOW_Z_MIN) ? (SNOW_Z_MAX - SNOW_Z_MIN) : 0;
 964: 		pVertex->z -= (SNOW_Z_MAX < pVertex->z) ? (SNOW_Z_MAX - SNOW_Z_MIN) : 0;
 965: 		pVertex++;
 966: 	}
 967:     SNOWVERTEX *pVB;
 968:     if( SUCCEEDED( g_pVBSnow->Map( D3D10_MAP_WRITE_DISCARD, 0, (LPVOID*)&pVB ) ) )
 969:     {
 970:         CopyMemory( pVB, g_aSnowVertex, sizeof(g_aSnowVertex) );
 971:         g_pVBSnow->Unmap();
 972:     }
 973:     buffers[0] = g_pVBSnow;
 974:     stride[0] = sizeof(SNOWVERTEX);
 975:     offset[0] = 0;
 976:     pd3dDevice->IASetVertexBuffers( 0, 1, buffers, stride, offset );
 977:     pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_POINTLIST );
 978:     pd3dDevice->IASetInputLayout( g_pVertexLayoutSnow );
 979:     pd3dDevice->IASetIndexBuffer( g_pIBBg, DXGI_FORMAT_R32_UINT, 0 );
 980: 	g_ptxMesh->SetResource(g_pTexRVSnow);
 981: 	mProj = *g_Camera.GetProjMatrix();
 982: 	mView = *g_Camera.GetViewMatrix();
 983: 	mWorldViewProjection = mProj;
 984: 	g_pmWorldViewProj->SetMatrix( (float*)&mWorldViewProjection );
 985: 	g_pTechRenderSnow->GetPassByIndex(0)->Apply(0);
 986:     pd3dDevice->Draw( SNOW_COUNT, 0 );
 987: 
 988: 	bool bReset = false;
 989: 	D3DXVECTOR3 vecEye(2.0f, 2.0f, -2.0f);
 990: 	static D3DXVECTOR3 vecEyeLast(2.0f, 2.0f, -2.0f);
 991: 	mWorldView = mWorld * mView;
 992: 	static bool init = false;
 993: 	if(!init){init = true;
 994: 		mWorldView = mWorld * mView;
 995: 		D3DXVec3TransformCoord(&vecEyeLast, &vecEyeLast, &mWorldView);
 996: 	}
 997: 	D3DXVec3TransformCoord(&vecEye, &vecEye, &mWorldView);
 998: 	if(0.001 < (vecEyeLast.x - vecEye.x) * (vecEyeLast.x - vecEye.x)) bReset = true;// 強く首を振るとリセット
 999: 	vecEyeLast = vecEye;
1000: 	RenderSnowCover(pd3dDevice, fElapsedTime, bReset);
1001: 
1002: 
1003: 	DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
1004:     RenderText();
1005:     g_HUD.OnRender( fElapsedTime ); 
1006:     g_SampleUI.OnRender( fElapsedTime );
1007:     DXUT_EndPerfEvent();
1008: }
1009: 
1010: 
1011: //--------------------------------------------------------------------------------------
1012: // Release D3D10 resources created in OnD3D10ResizedSwapChain 
1013: //--------------------------------------------------------------------------------------
1014: void CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext )
1015: {
1016:     g_DialogResourceManager.OnD3D10ReleasingSwapChain();
1017: }
1018: 
1019: 
1020: //--------------------------------------------------------------------------------------
1021: // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed
1022: //--------------------------------------------------------------------------------------
1023: bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
1024: {
1025:     // For the first device created if its a REF device, optionally display a warning dialog box
1026:     static bool s_bFirstTime = true;
1027:     if( s_bFirstTime )
1028:     {
1029:         s_bFirstTime = false;
1030:         if( (DXUT_D3D10_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_REFERENCE) )
1031:             DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver );
1032:     }
1033: 
1034: 	pDeviceSettings->d3d10.SyncInterval = 0;
1035: 
1036:     return true;
1037: }
1038: 
1039: 
1040: //--------------------------------------------------------------------------------------
1041: // Handle updates to the scene.  This is called regardless of which D3D API is used
1042: //--------------------------------------------------------------------------------------
1043: void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
1044: {
1045:     // Update the camera's position based on user input 
1046:     g_Camera.FrameMove( fElapsedTime );
1047: }
1048: 
1049: 
1050: //--------------------------------------------------------------------------------------
1051: // Handle messages to the application
1052: //--------------------------------------------------------------------------------------
1053: LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext )
1054: {
1055:     // Pass messages to dialog resource manager calls so GUI state is updated correctly
1056:     *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
1057:     if( *pbNoFurtherProcessing )
1058:         return 0;
1059: 
1060:     // Pass messages to settings dialog if its active
1061:     if( g_SettingsDlg.IsActive() )
1062:     {
1063:         g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
1064:         return 0;
1065:     }
1066: 
1067:     // Give the dialogs a chance to handle the message first
1068:     *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
1069:     if( *pbNoFurtherProcessing )
1070:         return 0;
1071:     *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
1072:     if( *pbNoFurtherProcessing )
1073:         return 0;
1074: 
1075:     // Pass all remaining windows messages to camera so it can respond to user input
1076:     g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
1077: 
1078:     return 0;
1079: }
1080: 
1081: 
1082: //--------------------------------------------------------------------------------------
1083: // Handle key presses
1084: //--------------------------------------------------------------------------------------
1085: void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
1086: {
1087: }
1088: 
1089: 
1090: //--------------------------------------------------------------------------------------
1091: // Handles the GUI events
1092: //--------------------------------------------------------------------------------------
1093: void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
1094: {
1095:     switch( nControlID )
1096:     {
1097:         case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break;
1098:         case IDC_TOGGLEREF:        DXUTToggleREF(); break;
1099:         case IDC_CHANGEDEVICE:     g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break;
1100:         case IDC_METHOD:
1101:         {
1102:             g_dwMethodIdx = (unsigned int)((CDXUTComboBox*)pControl)->GetSelectedData();
1103: //            pd3dDevice->SetRenderState( D3DRS_FILLMODE, g_bWireframe ? D3DFILL_WIREFRAME : D3DFILL_SOLID );
1104:             break;
1105:         }
1106:         case IDC_PARTITION:
1107: 			DestroyPartitions();
1108:             g_dwNumPartsLog = ((CDXUTSlider*)pControl)->GetValue();
1109: 			g_dwNumParts = (1<<g_dwNumPartsLog);
1110:             WCHAR wszBuf[256];
1111:             StringCchPrintf( wszBuf, 256, L"Number of partitions: %u", g_dwNumParts );
1112:             g_SampleUI.GetStatic( IDC_PARTITIONLABEL )->SetText( wszBuf );
1113: 			CreatePartitions(g_pd3dDevice);
1114:             break;
1115: 	}
1116: }
1117: 
1118: