void CDX10Core::InitBasicEffects() { ID3D10Blob* pBlobErrors = NULL; HRESULT hr = D3DX10CreateEffectFromFile( _T("effects/BasicShaders.fx"), NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, m_pDevice, NULL, NULL, &m_pBasicEffect, &pBlobErrors, NULL); if ( FAILED ( hr ) ) { UINT size = pBlobErrors->GetBufferSize() + 1; TCHAR *szError = new TCHAR[size]; #ifdef UNICODE char * pErrorString = (char *)pBlobErrors->GetBufferPointer(); mbstowcs(szError, pErrorString, size); szError[size - 1] = 0; #else _tcscpy_s(szError, size, pBlobErrors->GetBufferPointer()); #endif MessageBox(m_hWnd, szError, _T("DirectX 10 shader Error"), MB_OK ); SAFE_DX_RELEASE(pBlobErrors); delete[] szError; exit(1); } SAFE_DX_RELEASE(pBlobErrors); m_pBasicTechnique = m_pBasicEffect->GetTechniqueByName("BasicRender"); m_pViewMatrixEffectVariable = m_pBasicEffect->GetVariableByName( "View" )->AsMatrix(); m_pProjectionMatrixEffectVariable = m_pBasicEffect->GetVariableByName( "Projection" )->AsMatrix(); m_pWorldMatrixEffectVariable = m_pBasicEffect->GetVariableByName( "World" )->AsMatrix(); }
void CrateApp::buildFX() { DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; //#if defined( DEBUG ) || defined( _DEBUG ) // shaderFlags |= D3D10_SHADER_DEBUG; // shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; //#endif ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; hr = D3DX10CreateEffectFromFile(L"tex.fx", 0, 0, "fx_4_0", shaderFlags, 0, md3dDevice, 0, 0, &mFX, &compilationErrors, 0); if(FAILED(hr)) { if( compilationErrors ) { MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0); ReleaseCOM(compilationErrors); } DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX10CreateEffectFromFile", true); } mTech = mFX->GetTechniqueByName("TexTech"); mfxWVPVar = mFX->GetVariableByName("gWVP")->AsMatrix(); mfxWorldVar = mFX->GetVariableByName("gWorld")->AsMatrix(); mfxEyePosVar = mFX->GetVariableByName("gEyePosW"); mfxLightVar = mFX->GetVariableByName("gLight"); mfxDiffuseMapVar = mFX->GetVariableByName("gDiffuseMap")->AsShaderResource(); mfxSpecMapVar = mFX->GetVariableByName("gSpecMap")->AsShaderResource(); mfxTexMtxVar = mFX->GetVariableByName("gTexMtx")->AsMatrix(); }
void ScreenQuad::createFX() { DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3D10_SHADER_DEBUG; shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; D3DX10CreateEffectFromFile("../../Shaders/BasicQuad.fx", NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, mpDevice, NULL, NULL, &fxEffect, &compilationErrors, &hr); if(FAILED(hr)) { if( compilationErrors ) { MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0); SAFE_RELEASE(compilationErrors); } } }
bool CMultCTextureShader::InitializeShader(HWND hwnd, char* filename) { HRESULT result; ID3D10Blob *error; if ( FAILED(result = D3DX10CreateEffectFromFile(filename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, g_pDevice, NULL, NULL, &pEffect, &error, NULL ))) { if (error) { OutputShaderErrorMessage(error, hwnd, filename); } else { char msg[128]; sprintf(msg,"Unable to load shader file %s", filename); MessageBox(hwnd, filename, msg, MB_OK); } return false; } pTechnique = pEffect->GetTechniqueByName("TextureTechnique"); if (!pTechnique) return false; D3D10_INPUT_ELEMENT_DESC layout[2]; uint32 numElements; layout[0].SemanticName = "POSITION"; layout[0].SemanticIndex = 0; layout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; layout[0].InputSlot = 0; layout[0].AlignedByteOffset = 0; layout[0].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; layout[0].InstanceDataStepRate = 0; layout[1].SemanticName = "TEXCOORD"; layout[1].SemanticIndex = 0; layout[1].Format = DXGI_FORMAT_R32G32_FLOAT; layout[1].InputSlot = 0; layout[1].AlignedByteOffset = D3D10_APPEND_ALIGNED_ELEMENT; layout[1].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; layout[1].InstanceDataStepRate = 0; numElements = sizeof(layout) / sizeof(layout[0]); D3D10_PASS_DESC passDesc; pTechnique->GetPassByIndex(0)->GetDesc(&passDesc); if ( FAILED(result = g_pDevice->CreateInputLayout(layout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &pLayout ))) { trace("Error intializing texture shader CreateInputLayout"); return false; } pWorldMatrix = pEffect->GetVariableByName("worldMatrix")->AsMatrix(); pViewMatrix = pEffect->GetVariableByName("viewMatrix")->AsMatrix(); pProjectionMatrix = pEffect->GetVariableByName("projectionMatrix")->AsMatrix(); pTextureArray = pEffect->GetVariableByName("shaderTextures")->AsShaderResource(); return true; }
ID3D10Effect* CreateFX(ID3D10Device* device, std::wstring filename) { DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3D10_SHADER_DEBUG; shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; ID3D10Effect* fx = 0; hr = D3DX10CreateEffectFromFile(filename.c_str(), 0, 0, "fx_4_0", shaderFlags, 0, device, 0, 0, &fx, &compilationErrors, 0); if(FAILED(hr)) { if( compilationErrors ) { MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0); ReleaseCOM(compilationErrors); } DXTrace(__FILE__, (DWORD)__LINE__, hr, filename.c_str(), true); } return fx; }
ID3D10Effect *GutLoadFXShaderDX10(const char *filename) { //DWORD dwShaderFlags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY; //DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; DWORD dwShaderFlags = 0; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3D10_SHADER_DEBUG; #endif ID3D10Blob *pErrorMessage = NULL; ID3D10Effect *pFXShader = NULL; char filename_fullpath[128]; sprintf(filename_fullpath, "%s%s", GutGetShaderPath(), filename); if ( D3D_OK!=D3DX10CreateEffectFromFile( filename_fullpath, g_pHLSL_Macros, NULL, "fx_4_0", dwShaderFlags, 0, g_pd3dDevice, NULL, NULL, &pFXShader, &pErrorMessage, NULL) ) { if ( pErrorMessage ) { printf("Failed to compile %s : %s\n", pErrorMessage->GetBufferPointer()); } } SAFE_RELEASE(pErrorMessage); return pFXShader; }
void Pyramid::buildFX() { DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3D10_SHADER_DEBUG; shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; hr = D3DX10CreateEffectFromFile(L"object.fx", 0, 0, "fx_4_0", shaderFlags, 0, md3dDevice, 0, 0, &mFX, &compilationErrors, 0); if (FAILED(hr)) { if (compilationErrors) { MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0); ReleaseCOM(compilationErrors); } DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX10CreateEffectFromFile", true); } mTechnique = mFX->GetTechniqueByName("ObjectTech"); mfxWVPVar = mFX->GetVariableByName("gWVP")->AsMatrix(); //D3D10_RASTERIZER_DESC cmdesc; //ZeroMemory(&cmdesc, sizeof(D3D10_RASTERIZER_DESC)); //cmdesc.CullMode = D3D10_CULL_NONE; //cmdesc.FillMode = D3D10_FILL_SOLID; //hr = md3dDevice->CreateRasterizerState(&cmdesc, &RSCullNone); }
void ColoredCubeApp::buildFX() { DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3D10_SHADER_DEBUG; shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; hr = D3DX10CreateEffectFromFile(L"color.fx", 0, 0, "fx_4_0", shaderFlags, 0, md3dDevice, 0, 0, &mFX, &compilationErrors, 0); if(FAILED(hr)) { if( compilationErrors ) { MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0); ReleaseCOM(compilationErrors); } DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX10CreateEffectFromFile", true); } mTech = mFX->GetTechniqueByName("ColorTech"); mfxWVPVar = mFX->GetVariableByName("gWVP")->AsMatrix(); mfxFLIPVar = mFX->GetVariableByName("flip"); }
void SimpleTrackballDX10::init() { alpha = 0.f; HRESULT hr; hr = D3DX10CreateEffectFromFile("C:/Users/gandalf/Documents/devel/cpp/starengine/stargraphics/tests/simpleTrackballDX10/cube.fx", NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, g_StarRenderDeviceDX10.getD3dDevice(), NULL, NULL, &m_cubeEffect, NULL, NULL); if(FAILED(hr)) throw Star::Exception("SimpleTrackballDX10::init: can't create effect"); m_cube = new Star::Cube(1.0f); ID3D10EffectTechnique* tech = m_cubeEffect->GetTechniqueByIndex(0); D3D10_PASS_DESC passDesc; hr = tech->GetPassByIndex(0)->GetDesc(&passDesc); if(FAILED(hr)) throw Star::Exception("SimpleTrackballDX10::init: can't get pass description"); m_cubeLayout = m_cube->createInputLayout(passDesc); g_StarRenderDeviceDX10.getD3dDevice()->IASetInputLayout(m_cubeLayout); m_worldVariable = m_cubeEffect->GetVariableByName("World")->AsMatrix(); m_viewVariable = m_cubeEffect->GetVariableByName("View")->AsMatrix(); m_projectionVariable = m_cubeEffect->GetVariableByName("Projection")->AsMatrix(); }
void C_DefaultShader::buildFX() { // Create the Default shader DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3D10_SHADER_DEBUG; shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; hr = D3DX10CreateEffectFromFile(DEFAULT_SHADER_FILE, 0, 0, "fx_4_0", shaderFlags, 0, d_pDevice, 0, 0, &d_pFX, &compilationErrors, 0); // TODO - make the effect file in the header file as a string and use D3DX10CreateEffectFromMemory() if(FAILED(hr)) { if( compilationErrors ) { MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0); ReleaseCOM(compilationErrors); } DXTrace(__FILE__, (DWORD)__LINE__, hr, "D3DX10CreateEffectFromFile", true); } d_pTextureTech = d_pFX->GetTechniqueByName("TextureDefaultTech"); d_pNoTextureTech = d_pFX->GetTechniqueByName("NoTextureDefaultTech"); d_fxViewProjVar = d_pFX->GetVariableByName("gVP")->AsMatrix(); d_fxWorld = d_pFX->GetVariableByName("gWorld")->AsMatrix(); d_fxEyePosVar = d_pFX->GetVariableByName("gEyePosW")->AsVector(); d_fxTextureParams = d_pFX->GetVariableByName("gTextureParams")->AsVector(); d_fxLightParams = d_pFX->GetVariableByName("gLightParams")->AsVector(); d_fxTexture = d_pFX->GetVariableByName("gTexture")->AsShaderResource(); d_fxLightVar = d_pFX->GetVariableByName("gLights"); }
HRESULT D3DEngine::OnCreateDevice(ID3D10Device* d3d_device) { HRESULT hr; // Find the D3DX effect file WCHAR str[MAX_PATH]; V_RETURN(DXUTFindDXSDKMediaFileCch(str, MAX_PATH, kFileTutFX)); DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3D10_SHADER_DEBUG; #endif V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", dwShaderFlags, 0, d3d_device, NULL, NULL, &effect_, NULL, NULL ) ); // techniqueを入手 technique_ = effect_->GetTechniqueByName( "Render" ); diffuse_variable_ = effect_->GetVariableByName( "g_txDiffuse" )->AsShaderResource(); world_variable_ = effect_->GetVariableByName( "World" )->AsMatrix(); view_variable_ = effect_->GetVariableByName( "View" )->AsMatrix(); projection_variable_ = effect_->GetVariableByName( "Projection" )->AsMatrix(); // Define the input layout const D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = sizeof( layout ) / sizeof( layout[0] ); // Create the input layout D3D10_PASS_DESC PassDesc; technique_->GetPassByIndex( 0 )->GetDesc( &PassDesc ); V_RETURN( d3d_device->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &vertex_layout_ ) ); // Set the input layout d3d_device->IASetInputLayout( vertex_layout_ ); // Load the mesh V_RETURN(mesh_.Create(d3d_device, kFileTinyMesh, true)); // Initialize the world matrices D3DXMatrixIdentity( &world_ ); // Initialize the view matrix D3DXVECTOR3 Eye( 0.0f, 3.0f, -500.0f ); D3DXVECTOR3 At( 0.0f, 1.0f, 0.0f ); D3DXVECTOR3 Up( 0.0f, 1.0f, 0.0f ); D3DXMatrixLookAtLH( &view_, &Eye, &At, &Up ); // Update Variables that never change view_variable_->SetMatrix( ( float* )&view_ ); return S_OK; }
VOID InitEffects() { ID3DBlob* pErrorBlob; // Create the effect DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3D10_SHADER_DEBUG; #endif // Compile the effects file HRESULT hr = D3DX10CreateEffectFromFile( L"spot_light.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, g_pd3dDevice, NULL, NULL, &g_pEffect, &pErrorBlob, NULL); // Output the error message if compile failed if(FAILED(hr)) { if(pErrorBlob != NULL) { OutputDebugStringA((CHAR*)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } } // Release the Blob if(pErrorBlob) pErrorBlob->Release(); // Obtain the technique g_pTechnique = g_pEffect->GetTechniqueByName("Render"); // Obtain the variables g_pWorldVariable = g_pEffect->GetVariableByName("World")->AsMatrix(); g_pViewVariable = g_pEffect->GetVariableByName("View")->AsMatrix(); g_pProjectionVariable = g_pEffect->GetVariableByName("Projection")->AsMatrix(); g_pLightVariable = g_pEffect->GetVariableByName("gLight"); g_pEyePosVariable = g_pEffect->GetVariableByName("gEyePoint"); g_pWorldViewProjVariable = g_pEffect->GetVariableByName("WorldViewProj")->AsMatrix(); // Get vertex declaration of Mesh const D3D10_INPUT_ELEMENT_DESC* pVertexDesc = NULL; UINT numElements; g_pSphere->GetVertexDescription(&pVertexDesc, &numElements); // Create the input layout D3D10_PASS_DESC PassDesc; g_pTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc ); hr = g_pd3dDevice->CreateInputLayout(pVertexDesc, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayout); if(FAILED(hr)) { MessageBox(NULL, L"Create input layout failed", L"Error", 0); } }
/* Name HeatHazeShader::initialise Syntax HeatHazeShader::initialise() Return bool - Returns true once initialised Brief Initialises the shader */ bool HeatHazeShader::initialise() { d3dDevice_ = Scene::instance()->getDevice(); if (!d3dDevice_) { MessageBox(0, "Retrieving device - Failed", "Error", MB_OK); return false; } // Build FX ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; hr = D3DX10CreateEffectFromFile("Effect Files/HeatHaze.fx", 0, 0, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, d3dDevice_, 0, 0, &fx_, &compilationErrors, 0); if (FAILED(hr)) { if ( compilationErrors ) { MessageBoxA(0, "Creating effect from file - Failed", "Error", MB_OK); MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0); compilationErrors->Release(); return false; } } technique_ = fx_->GetTechniqueByName("HeatHazeTech"); orthoVar_ = fx_->GetVariableByName("Orthogonal")->AsMatrix(); sceneVar_ = fx_->GetVariableByName("screenTexture")->AsShaderResource(); perturbanceVar_ = fx_->GetVariableByName("perturbanceTexture")->AsShaderResource(); timeVar_ = fx_->GetVariableByName("time")->AsScalar(); // Build vertex layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, }; // Create the input layout D3D10_PASS_DESC PassDesc; technique_->GetPassByIndex(0)->GetDesc(&PassDesc); hr = d3dDevice_->CreateInputLayout(layout, 2, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &vertexLayout_); if (FAILED(hr)) { MessageBoxA(0, "Creating input layout - Failed", "Error", MB_OK); return false; } return true; }
bool DirectX10Renderer::LoadShadersAndCreateInputLayouts() { DEBUG_OUT("DirectX10Renderer::LoadShadersAndCreateInputLayouts"); HRESULT result; result = D3DX10CreateEffectFromFile( "./shaders/sprite.fx", NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, pD3DDevice, NULL, NULL, &m_SpriteEffect, NULL, NULL); if(FAILED(result)) { return FatalError("Could not load effect file!"); } //get technique and desc m_SpriteTechnique = m_SpriteEffect->GetTechniqueByName("RENDER"); if(m_SpriteTechnique == NULL) { return FatalError("Could not find technique!"); } m_SpriteTechnique->GetDesc(&m_SpriteTechDesc); //create texture effect variable pColorMap = m_SpriteEffect->GetVariableByName("colorMap")->AsShaderResource(); //create input layout D3D10_PASS_DESC PassDesc; m_SpriteTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); if(FAILED(pD3DDevice->CreateInputLayout( vertexInputLayout, vertexInputLayoutNumElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &pVertexLayout))) { return FatalError("Could not create Input Layout!"); } //Set the input layout pD3DDevice->IASetInputLayout(pVertexLayout); return true; }
//-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10CreateDevice(ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext) { HRESULT hr; g_device = pd3dDevice; V_RETURN(g_DialogResourceManager.OnD3D10CreateDevice(pd3dDevice)); V_RETURN(g_D3DSettingsDlg.OnD3D10CreateDevice(pd3dDevice)); V_RETURN(D3DX10CreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont10)); V_RETURN(D3DX10CreateSprite(pd3dDevice, 512, &g_pSprite10)); g_pTxtHelper = new CDXUTTextHelper(NULL, NULL, g_pFont10, g_pSprite10, 15); V_RETURN(CDXUTDirectionWidget::StaticOnD3D10CreateDevice(pd3dDevice)); // Read the D3DX effect file WCHAR str[MAX_PATH]; ID3D10Blob* pErrBlob = NULL; V_RETURN(DXUTFindDXSDKMediaFileCch(str, MAX_PATH, L"Effect_Undistort.fx")); hr = D3DX10CreateEffectFromFile(str, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, pd3dDevice, NULL, NULL, &g_pEffect10, &pErrBlob, NULL); if (FAILED(hr)) { std::string errStr((LPCSTR)pErrBlob->GetBufferPointer(), pErrBlob->GetBufferSize()); WCHAR err[256]; MultiByteToWideChar(CP_ACP, 0, errStr.c_str(), (int)errStr.size(), err, errStr.size()); MessageBox(NULL, (LPCWSTR)err, L"Error", MB_OK); return hr; } // Setup the vector image and the display UINT width = (DXUTIsAppRenderingWithD3D9()) ? DXUTGetD3D9BackBufferSurfaceDesc()->Width : DXUTGetDXGIBackBufferSurfaceDesc()->Width; UINT height = (DXUTIsAppRenderingWithD3D9()) ? DXUTGetD3D9BackBufferSurfaceDesc()->Height : DXUTGetDXGIBackBufferSurfaceDesc()->Height; g_vsObj = new VSObject(pd3dDevice); D3D10_RASTERIZER_DESC rasterizerState; rasterizerState.FillMode = D3D10_FILL_SOLID; rasterizerState.CullMode = D3D10_CULL_NONE; rasterizerState.FrontCounterClockwise = true; rasterizerState.DepthBias = false; rasterizerState.DepthBiasClamp = 0; rasterizerState.SlopeScaledDepthBias = 0; rasterizerState.DepthClipEnable = true; rasterizerState.ScissorEnable = false; rasterizerState.MultisampleEnable = false; rasterizerState.AntialiasedLineEnable = false; pd3dDevice->CreateRasterizerState(&rasterizerState, &g_pRasterState); return S_OK; }
bool Effect::LoadEffectFile(const std::string& filename) { // Release the old effect and clear the old techniques SafeRelease(mEffect); mTechniques.clear(); // Load and compile the new effect UINT shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #ifdef DEBUG_MODE shaderFlags |= D3D10_SHADER_DEBUG; #endif ID3D10Blob* errors = NULL; HRESULT result = D3DX10CreateEffectFromFile(filename.c_str(), NULL, NULL, "fx_4_0", shaderFlags, 0, mDevice, NULL, NULL, &mEffect, &errors, NULL); // See if load and compile was successful if (FAILED(result)) { // If we have compile errors, print them if (errors != NULL) { MessageBox(NULL, static_cast<char*>(errors->GetBufferPointer()), "Error", MB_OK | MB_ICONERROR); SafeRelease(errors); } return false; } // Store all techniques D3D10_EFFECT_DESC effectDescription; mEffect->GetDesc(&effectDescription); mTechniques.reserve(effectDescription.Techniques); for (unsigned int i = 0; i < effectDescription.Techniques; ++i) { mTechniques.push_back(Technique(mEffect->GetTechniqueByIndex(i))); } return true; }
TextureID Shader_Create( const char* filename ) { unsigned handle = 0; // Create from the free list if we can if( Shader_Freelist_Count > 0 ) { handle = Shader_Freelist[ Shader_Freelist_Count - 1 ]; Shader_Freelist_Count--; } else // And only expand the range if free list is empty { assert( Shader_Count < MAX_TEXTURES ); handle = Shader_Count; Shader_Count++; } if ( FAILED( D3DX10CreateEffectFromFile( filename,NULL,NULL, "fx_4_0",D3D10_SHADER_ENABLE_STRICTNESS,0,dx_device,NULL, NULL,&Shaders[handle].effect,NULL, NULL ) ) ) return false; Shaders[handle].effect_technique = Shaders[handle].effect->GetTechniqueByName("Main"); //create shader parameters pointer Shaders[handle].effect_resolution = Shaders[handle].effect->GetVariableByName( "resolution" )->AsVector(); Shaders[handle].effect_transform = Shaders[handle].effect->GetVariableByName( "t" ); Shaders[handle].effect_texture = Shaders[handle].effect->GetVariableByName( "tex2D" )->AsShaderResource(); //tell directx how to handle vertex format we defined in the vertex struct D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 } }; UINT numElements = sizeof( layout ) / sizeof( layout[0] ); //create input layout D3D10_PASS_DESC PassDesc; Shaders[handle].effect_technique->GetPassByIndex( 0 )->GetDesc( &PassDesc ); assert( SUCCEEDED( dx_device->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature,PassDesc.IAInputSignatureSize, &Shaders[handle].effect_layout ) ) ); //set the resolution parameter in the shader float resolution[2]; resolution[0] = GAME_RESOLUTION_X; resolution[1] = GAME_RESOLUTION_Y; Shaders[handle].effect_resolution->SetFloatVector( resolution ); return handle; }
bool D3D10Model::LoadMeshEffect(ID3D10Device* pdev, int i, LPCWSTR shader) { if (!m_ppMeshEffect) return false; //Load effect file ID3D10Blob *ppErrors; if (FAILED(D3DX10CreateEffectFromFile(shader, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, D3D10_EFFECT_SINGLE_THREADED, pdev, NULL, NULL, &m_ppMeshEffect[i], &ppErrors, NULL))) { char *lpError = (char*)ppErrors->GetBufferPointer(); return false; } return true; }
Shader::Shader(const char *pShaderFileName) { // Chargement du shader std::string path = "Shaders\\"; path += pShaderFileName; DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #ifdef _DEBUG dwShaderFlags |= D3D10_SHADER_DEBUG; #endif if(FAILED(D3DX10CreateEffectFromFile(path.c_str(), NULL, NULL, "fx_4_0", dwShaderFlags, 0, Graphics::getSingleton()->getD3DDevice(), NULL, NULL, &m_pEffect, NULL, NULL))) Core::getSingleton()->error("Could not create effect."); // Récupération de la technique m_pTechnique = m_pEffect->GetTechniqueByIndex(0); }
// Initialise general method data bool InitialiseMethods() { ID3D10Blob* pErrors; // This strangely typed variable collects any errors when compiling the effect file DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; // These "flags" are used to set the compiler options // Load and compile the effect file string fullFileName = ShaderFolder + "Scene.fx"; if( FAILED( D3DX10CreateEffectFromFile( fullFileName.c_str(), NULL, NULL, "fx_4_0", dwShaderFlags, 0, g_pd3dDevice, NULL, NULL, &Effect, &pErrors, NULL ) )) { if (pErrors != 0) MessageBox( NULL, reinterpret_cast<char*>(pErrors->GetBufferPointer()), "Error", MB_OK ); // Compiler error: display error message else MessageBox( NULL, "Error loading FX file. Ensure your FX file is in the same folder as this executable.", "Error", MB_OK ); // No error message - probably file not found return false; } // Access matrix / camera shader variables WorldMatrixVar = Effect->GetVariableByName( "WorldMatrix" )->AsMatrix(); ViewMatrixVar = Effect->GetVariableByName( "ViewMatrix" )->AsMatrix(); ProjMatrixVar = Effect->GetVariableByName( "ProjMatrix" )->AsMatrix(); ViewProjMatrixVar = Effect->GetVariableByName( "ViewProjMatrix" )->AsMatrix(); CameraPosVar = Effect->GetVariableByName( "CameraPos" )->AsVector(); // Access lighting shader variables Light1PosVar = Effect->GetVariableByName( "Light1Pos" )->AsVector(); Light1ColourVar = Effect->GetVariableByName( "Light1Colour" )->AsVector(); Light2PosVar = Effect->GetVariableByName( "Light2Pos" )->AsVector(); Light2ColourVar = Effect->GetVariableByName( "Light2Colour" )->AsVector(); AmbientColourVar = Effect->GetVariableByName( "AmbientColour" )->AsVector(); // Access material colour shader variables DiffuseColourVar = Effect->GetVariableByName( "DiffuseColour" )->AsVector(); SpecularColourVar = Effect->GetVariableByName( "SpecularColour" )->AsVector(); SpecularPowerVar = Effect->GetVariableByName( "SpecularPower" )->AsScalar(); // Access texture shader variables (not referred to as textures - any GPU memory accessed in a shader is a "Shader Resource") DiffuseMapVar = Effect->GetVariableByName( "DiffuseMap" )->AsShaderResource(); DiffuseMap2Var = Effect->GetVariableByName( "DiffuseMap2" )->AsShaderResource(); NormalMapVar = Effect->GetVariableByName( "NormalMap" )->AsShaderResource(); // Polygon post-processing variables SceneTexturePolyVar = Effect->GetVariableByName( "SceneTexture" )->AsShaderResource(); ViewportWidthVar = Effect->GetVariableByName( "ViewportWidth" )->AsScalar(); ViewportHeightVar = Effect->GetVariableByName( "ViewportHeight" )->AsScalar(); // Access to other shader variables ParallaxDepthVar = Effect->GetVariableByName( "ParallaxDepth" )->AsScalar(); return true; }
void Scene::BuildFX() { DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined (DEBUG) || (_DEBUG) shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* compilationErrors = 0; HRESULT hr = 0; hr = D3DX10CreateEffectFromFile(L"tex.fx", // The name of the effects file to compile 0, // pDefines 0, // pInlcude "fx_4_0", // The version of the shader we are using shaderFlags, // Specify how the shader code will be complied 0, // FXflags m_Direct3DDevice, // A pointer to the direct device 0, // pEffectPool 0, // pPump &m_FX, // Returns a pointer to the created object &compilationErrors, // Returns a pointer to a string containing the comiplation errors 0 // pttResult, used with pPump ); if( FAILED(hr) ) { if( compilationErrors ) { // Print out any errors MessageBoxA( 0, (char*)compilationErrors->GetBufferPointer(), 0, 0); ReleaseCOM(compilationErrors); } DXTrace(__FILE__, (DWORD)__LINE__, hr, L"D3DX10CreateEffectFromFile", true); } // Set the technique to color tech m_Tech = m_FX->GetTechniqueByName("ColorTech"); // Setup variable pointers to the designated name in effect files m_fxWVPVar = m_FX->GetVariableByName("gWVP")->AsMatrix(); // Set the effect file WVP matrix to m_fxDiffuseMapVar = m_FX->GetVariableByName("gDiffuseMap")->AsShaderResource(); m_FxSpecMapVar = m_FX->GetVariableByName("gSpecMap")->AsShaderResource(); m_FxEyePosVar = m_FX->GetVariableByName("gEyePosW"); m_FxLightVar = m_FX->GetVariableByName("gLight"); m_FxTexMatVar = m_FX->GetVariableByName("gTexMat")->AsMatrix(); m_FxBoxWorldVar = m_FX->GetVariableByName("gBoxWorld")->AsMatrix(); }
//-------------------------------------------------------------------------------------- // Load an effect file //-------------------------------------------------------------------------------------- HRESULT LoadEffect10( ID3D10Device* pd3dDevice ) { HRESULT hr = S_OK; SAFE_RELEASE( g_pEffect10 ); g_fLastWriteTime = GetFileTime( g_strEffect ); // Read the D3DX effect file WCHAR str[MAX_PATH]; DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE; dwShaderFlags |= D3DXSHADER_DEBUG; UINT uFlags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY | D3D10_SHADER_DEBUG; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Exercise01.fx" ) ); V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", uFlags, 0, pd3dDevice, NULL, NULL, &g_pEffect10, NULL, NULL ) ); // Get the effect variable handles g_pRenderTerrain = g_pEffect10->GetTechniqueByName( "RenderTerrain10" ); g_pRenderBall = g_pEffect10->GetTechniqueByName( "RenderBall10" ); g_pRenderGrass = g_pEffect10->GetTechniqueByName( "RenderGrass10" ); g_pRenderSky = g_pEffect10->GetTechniqueByName( "RenderSky10" ); g_pmWorldViewProj = g_pEffect10->GetVariableByName( "g_mWorldViewProj" )->AsMatrix(); g_pmViewProj = g_pEffect10->GetVariableByName( "g_mViewProj" )->AsMatrix(); g_pmWorld = g_pEffect10->GetVariableByName( "g_mWorld" )->AsMatrix(); g_pvWorldLightDir = g_pEffect10->GetVariableByName( "g_vWorldLightDir" )->AsVector(); g_pfTime = g_pEffect10->GetVariableByName( "g_fTime" )->AsScalar(); g_pfElapsedTime = g_pEffect10->GetVariableByName( "g_fElapsedTime" )->AsScalar(); g_pvColor = g_pEffect10->GetVariableByName( "g_vColor" )->AsVector(); g_pfWorldScale = g_pEffect10->GetVariableByName( "g_fWorldScale" )->AsScalar(); g_pfHeightScale = g_pEffect10->GetVariableByName( "g_fHeightScale" )->AsScalar(); g_pvEyePt = g_pEffect10->GetVariableByName( "g_vEyePt" )->AsVector(); g_pfFadeStart = g_pEffect10->GetVariableByName( "g_fFadeStart" )->AsScalar(); g_pfFadeEnd = g_pEffect10->GetVariableByName( "g_fFadeEnd" )->AsScalar(); g_ptxDiffuse = g_pEffect10->GetVariableByName( "g_txDiffuse" )->AsShaderResource(); g_ptxNormal = g_pEffect10->GetVariableByName( "g_txNormal" )->AsShaderResource(); g_ptxHeight = g_pEffect10->GetVariableByName( "g_txHeight" )->AsShaderResource(); g_ptxDirt = g_pEffect10->GetVariableByName( "g_txDirt" )->AsShaderResource(); g_ptxGrass = g_pEffect10->GetVariableByName( "g_txGrass" )->AsShaderResource(); g_ptxMask = g_pEffect10->GetVariableByName( "g_txMask" )->AsShaderResource(); g_ptxShadeNormals = g_pEffect10->GetVariableByName( "g_txShadeNormals" )->AsShaderResource(); return hr; }
template<> unique_ptr<ID3D10Effect> ResourceService::LoadResource<ID3D10Effect>(const std::tstring& filePath) { ID3D10Blob* pErrorBlob; ID3D10Effect* pEffect; HRESULT hr = D3DX10CreateEffectFromFile(filePath.c_str(), NULL, NULL, "fx_4_0", #ifndef NDEBUG D3D10_SHADER_DEBUG|D3D10_SHADER_SKIP_OPTIMIZATION|D3D10_SHADER_WARNINGS_ARE_ERRORS|D3D10_SHADER_PACK_MATRIX_ROW_MAJOR, //HLSL Flags: http://msdn.microsoft.com/en-us/library/windows/desktop/bb172416%28v=vs.85%29.aspx #else D3D10_SHADER_OPTIMIZATION_LEVEL3|D3D10_SHADER_IEEE_STRICTNESS|D3D10_SHADER_PACK_MATRIX_ROW_MAJOR, #endif 0, MyServiceLocator::GetInstance()->GetService<IGraphicsService>()->GetGraphicsDevice()->GetDevice(), NULL, NULL, &pEffect, &pErrorBlob, NULL); if(FAILED(hr)) { tstringstream ss; if(pErrorBlob!=nullptr) { char *errors = (char*)pErrorBlob->GetBufferPointer(); for(unsigned int i = 0; i < pErrorBlob->GetBufferSize(); i++) ss<<errors[i]; OutputDebugString(ss.str().c_str()); pErrorBlob->Release(); throw LoaderException(_T("effect ") + filePath, ss.str() ); } MyServiceLocator::GetInstance()->GetService<DebugService>()->LogDirectXError(hr, __LINE__, __FILE__); } return unique_ptr<ID3D10Effect>(pEffect); }
bool D3D10Model::Load(ID3D10Device* pdev, const TCHAR *name, const TCHAR *texture_path, LPCWSTR shader, BoneMatrixConstantType t) { ID3D10Effect* pEffect; ID3D10Blob *ppErrors; if (SUCCEEDED(D3DX10CreateEffectFromFile(shader, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, D3D10_EFFECT_SINGLE_THREADED, pdev, NULL, NULL, &pEffect, &ppErrors, NULL))) { /*ID3D10Blob *assembly = NULL; D3D10DisassembleEffect(pEffect, FALSE, &assembly); if (assembly) { // Write the assembly to file FILE *file = _tfopen(_T("Dump.txt"), _T("wb")); if (file) { fwrite(assembly->GetBufferPointer(), assembly->GetBufferSize(), 1, file); fclose(file); } // Write the assembly to debug output //OutputDebugStringA((char *) assembly->GetBufferPointer()); assembly->Release(); }*/ } else { char *lpError = (char*) ppErrors->GetBufferPointer(); OutputDebugStringA(lpError); return false; } if (!D3D10Model::Load(pdev, name, texture_path, pEffect, t)) return false; SAFE_RELEASE(pEffect); return true; }
bool CFontShader::InitShader(ID3D10Device* device, HWND hwnd, WCHAR* filename) { HRESULT result; ID3D10Blob* errorMessage; D3D10_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D10_PASS_DESC passDesc; // Met a zero le message d'erreur errorMessage = 0; // Charge le shader result = D3DX10CreateEffectFromFile(filename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, device, NULL, NULL, &m_effect, &errorMessage, NULL); if(FAILED(result)){ // Si la compilation a echouee, elle devrait renvoyer un message d'erreur if(errorMessage){ OutputShaderErrorMessage(errorMessage, hwnd, filename);} // Si la compilation a echouee au point de meme pas renvoyer d'erreur else{ MessageBox(hwnd, filename, L"Missing Shader File", MB_OK);} return false; } // Attrape le pointeur vers la technique a l'interieur du shader m_technique = m_effect->GetTechniqueByName("FontTechnique"); if(!m_technique){ #ifdef _SPHDEBUG_H SPHDebug::Msg("\t /!\\ CFontShader::InitShader() : Failed to get technique."); #endif return false;} // Met en place le format des donnees a envoyer au shader // Ca doit etre compatible avec la structure VertexTyoe de la classe ET du shader polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D10_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // Calcul le nombre d'element numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Attrape la description de la premiere pass de la technique m_technique->GetPassByIndex(0)->GetDesc(&passDesc); // Cree l'input layout result = device->CreateInputLayout(polygonLayout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_layout); if(FAILED(result)){ #ifdef _SPHDEBUG_H SPHDebug::Msg("\t /!\\ CFontShader::InitShader() : Failed to create input layout."); #endif return false;} // Attrape les pointeurs des trois matrices du shader m_worldMatrixPtr = m_effect->GetVariableByName("worldMatrix")->AsMatrix(); m_viewMatrixPtr = m_effect->GetVariableByName("viewMatrix")->AsMatrix(); m_projectionMatrixPtr = m_effect->GetVariableByName("projectionMatrix")->AsMatrix(); // Attrape le pointeur de la ressource de texture du shader m_texturePtr = m_effect->GetVariableByName("shaderTexture")->AsShaderResource(); // Attrape le pointeur de la couleur du shader m_pixelColorPtr = m_effect->GetVariableByName("pixelColor")->AsVector(); return true; }
bool AlphaMapShaderClass::InitializeShader(ID3D10Device* device, HWND hwnd, WCHAR* filename) { HRESULT result; ID3D10Blob* errorMessage; D3D10_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D10_PASS_DESC passDesc; // Initialize the error message. errorMessage = 0; // Load the shader in from the file. result = D3DX10CreateEffectFromFile(filename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, device, NULL, NULL, &m_effect, &errorMessage, NULL); if(FAILED(result)) { // If the shader failed to compile it should have writen something to the error message. if(errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, filename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, filename, L"Missing Shader File", MB_OK); } return false; } // Get a pointer to the technique inside the shader. m_technique = m_effect->GetTechniqueByName("AlphaMapTechnique"); if(!m_technique) { return false; } // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType stucture in the ModelClass and in the shader. polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D10_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Get the description of the first pass described in the shader technique. m_technique->GetPassByIndex(0)->GetDesc(&passDesc); // Create the input layout. result = device->CreateInputLayout(polygonLayout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_layout); if(FAILED(result)) { return false; } // Get pointers to the three matrices inside the shader so we can update them from this class. m_worldMatrixPtr = m_effect->GetVariableByName("worldMatrix")->AsMatrix(); m_viewMatrixPtr = m_effect->GetVariableByName("viewMatrix")->AsMatrix(); m_projectionMatrixPtr = m_effect->GetVariableByName("projectionMatrix")->AsMatrix(); // Get pointer to the texture array resource inside the shader. m_textureArrayPtr = m_effect->GetVariableByName("shaderTextures")->AsShaderResource(); return true; }
bool initD3DDevice(HWND hWnd) { // Création du device DXGI_SWAP_CHAIN_DESC swapChainDesc; memset(&swapChainDesc, 0, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = SCREEN_WIDTH; swapChainDesc.BufferDesc.Height = SCREEN_HEIGHT; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.RefreshRate.Numerator = REFRESHRATE; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hWnd; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = true; UINT deviceFlags = 0; #ifdef _DEBUG deviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif if(FAILED(D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, D3D10_SDK_VERSION, &swapChainDesc, &g_pSwapChain, &g_pD3DDevice))) return false; // Création de la vue ID3D10Texture2D *pBackBuffer; if(FAILED(g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (void **)&pBackBuffer))) return false; HRESULT res = g_pD3DDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_pRenderTargetView); pBackBuffer->Release(); if(FAILED(res)) return false; g_pD3DDevice->OMSetRenderTargets(1, &g_pRenderTargetView, NULL); // Initialisation du viewport D3D10_VIEWPORT viewport; viewport.Width = SCREEN_WIDTH; viewport.Height = SCREEN_HEIGHT; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0; viewport.TopLeftY = 0; g_pD3DDevice->RSSetViewports(1, &viewport); // Chargement des shaders DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #ifdef _DEBUG dwShaderFlags |= D3D10_SHADER_DEBUG; #endif if(FAILED(D3DX10CreateEffectFromFile("raytracing.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, g_pD3DDevice, NULL, NULL, &g_pEffect, NULL, NULL))) return false; // Récupération de la technique g_pTechnique = g_pEffect->GetTechniqueByName("Render"); // Création du input layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D10_APPEND_ALIGNED_ELEMENT, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D10_APPEND_ALIGNED_ELEMENT, D3D10_INPUT_PER_VERTEX_DATA, 0}, }; D3D10_PASS_DESC PassDesc; g_pTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); if(FAILED(g_pD3DDevice->CreateInputLayout(layout, 2, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayout))) return false; g_pD3DDevice->IASetInputLayout(g_pVertexLayout); // Création du vertex buffer SimpleVertex vertices[] = { {D3DXVECTOR3(-1.0f, -1.0f, 0.5f), D3DXVECTOR2(0.0f, 0.0f)}, {D3DXVECTOR3(-1.0f, 1.0f, 0.5f), D3DXVECTOR2(0.0f, 1.0f)}, {D3DXVECTOR3(1.0f, -1.0f, 0.5f), D3DXVECTOR2(1.0f, 0.0f)}, {D3DXVECTOR3(1.0f, 1.0f, 0.5f), D3DXVECTOR2(1.0f, 1.0f)} }; D3D10_BUFFER_DESC bd; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(SimpleVertex)*4; bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = vertices; if(FAILED(g_pD3DDevice->CreateBuffer(&bd, &InitData, &g_pVertexBuffer))) return false; UINT stride = sizeof(SimpleVertex); UINT offset = 0; g_pD3DDevice->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset); g_pD3DDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); return true; }
// Create Direct3D device and swap chain HRESULT DxWidget::InitDevice() { HRESULT hrResult = E_FAIL; HRESULT hrRetCode = E_FAIL; m_driverType = D3D10_DRIVER_TYPE_NULL; UINT createDeviceFlags = 0; D3D10_DRIVER_TYPE driverTypes[] = { D3D10_DRIVER_TYPE_HARDWARE, D3D10_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); ZeroMemory(&m_swapChainDesc, sizeof(m_swapChainDesc)); m_swapChainDesc.BufferCount = 1; m_swapChainDesc.BufferDesc.Width = width(); m_swapChainDesc.BufferDesc.Height = height(); m_swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; m_swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; m_swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; m_swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; m_swapChainDesc.OutputWindow = (HWND)winId(); m_swapChainDesc.SampleDesc.Count = 1; m_swapChainDesc.SampleDesc.Quality = 0; m_swapChainDesc.Windowed = TRUE; for(UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { m_driverType = driverTypes[driverTypeIndex]; hrRetCode = D3D10CreateDeviceAndSwapChain(NULL, m_driverType, NULL, createDeviceFlags, D3D10_SDK_VERSION, &m_swapChainDesc, &m_pSwapChain, &m_pd3dDevice); if(SUCCEEDED(hrRetCode)) break; } KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pSwapChain); KE_PROCESS_ERROR(m_pd3dDevice); // Create a render target view ID3D10Texture2D* pBackBuffer; hrRetCode = m_pSwapChain->GetBuffer(0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBackBuffer); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(pBackBuffer); hrRetCode = m_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pRenderTargetView); m_pd3dDevice->OMSetRenderTargets(1, &m_pRenderTargetView, NULL); // Setup the viewport m_viewPort.Width = width(); m_viewPort.Height = height(); m_viewPort.MinDepth = 0.0f; m_viewPort.MaxDepth = 1.0f; m_viewPort.TopLeftX = 0; m_viewPort.TopLeftY = 0; m_pd3dDevice->RSSetViewports(1, &m_viewPort); // Create the effect DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; hrRetCode = D3DX10CreateEffectFromFile(L"testqt.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, m_pd3dDevice, NULL, NULL, &m_pEffect, NULL, NULL ); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pEffect); // Obtain the technique m_pTechnique = m_pEffect->GetTechniqueByName("Render"); // Define the input layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, }; UINT numElements = sizeof(layout) / sizeof(layout[0]); // Create the input layout D3D10_PASS_DESC PassDesc; m_pTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); hrRetCode = m_pd3dDevice->CreateInputLayout(layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_pVertexLayout); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pVertexLayout); // Set the input layout m_pd3dDevice->IASetInputLayout(m_pVertexLayout); // Set primitive topology m_pd3dDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINELIST); hrResult = S_OK; Exit0: return hrResult; }
bool DX10Renderer::InitializeScene() { //set light params //================================================================== lightPos = XMFLOAT3(0, 20, -30); //light volume proj //XMMATRIX pm = XMMatrixOrthographicLH(75, 75, 20.0f, 80.f); XMMATRIX pm = XMMatrixPerspectiveFovLH( XM_PIDIV4, 4.0f/3, 20.0f, 80.f ); XMStoreFloat4x4(&lightProjMatrix, pm); //view XMFLOAT3 o = XMFLOAT3(0,0,0), up = XMFLOAT3(0,1,0); XMVECTOR e = XMLoadFloat3( &lightPos ), fp = XMLoadFloat3( &o ), u = XMLoadFloat3( &up ); XMMATRIX vm = XMMatrixLookAtLH( e, fp, u ); pm = XMMatrixMultiply(vm,pm); XMStoreFloat4x4(&lightViewProjMatrix, pm); //Load rendering techniques //================================================================== if ( FAILED( D3DX10CreateEffectFromFile( L"ShadowMap.fx", 0, 0, (LPCSTR) "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, pD3DDevice, 0, 0, &pEffect, 0, 0) ) ) return false; pRenderTechnique = pEffect->GetTechniqueByName("RenderPassStandard"); pRenderShadowMapTechnique = pEffect->GetTechniqueByName("ShadowMapRenderPassFrontFaces"); pBillboardTechnique = pEffect->GetTechniqueByName("RenderBillboard"); //create input layout D3D10_PASS_DESC passDesc; pRenderTechnique->GetPassByIndex( 0 )->GetDesc( &passDesc ); D3D10_INPUT_ELEMENT_DESC inLayoutDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "BITANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D10_INPUT_PER_VERTEX_DATA, 0 } }; if ( FAILED( pD3DDevice->CreateInputLayout( inLayoutDesc, 4, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &pInputLayout ) ) ) return false; pD3DDevice->IASetInputLayout(pInputLayout); //load scene elements //================================================================== MeshData md; loadMeshDataFromOBJ("models\\floor.obj", &md); meshes.push_back( DX10Mesh() ); meshes.back().CreateMesh(pD3DDevice, &md); loadMeshDataFromOBJ("models\\girl.obj", &md); meshes.push_back( DX10Mesh() ); meshes.back().CreateMesh(pD3DDevice, &md); RenderMessage rm; XMMATRIX mat = XMMatrixIdentity(); rm.modelID = 0; XMStoreFloat4x4(&rm.world, mat); //add floor to scene scene.push_back(rm); //add 9 meshes to scene float y = 0.0f; XMFLOAT3 a(1,0,0); XMVECTOR axis = XMLoadFloat3( &a); for (float z = -10; z <= 10; z+=5) { for (float x = -10; x <= 10; x+=5 ) { mat = XMMatrixRotationAxis( axis, -XM_PIDIV2) * XMMatrixTranslation(x,y,z); scene.push_back( rm ); scene.back().modelID = 1; XMStoreFloat4x4(&scene.back().world, mat); } } return true; }
bool CDX10Renderer::Initialise(HINSTANCE _hInstance, HWND _hwnd, int _iClientWidth, int _iClientHeight) { m_hAppInst = _hInstance; m_hMainWnd = _hwnd; m_iTargetWidth = _iClientWidth; m_iTargetHeight = _iClientHeight; m_iClientWidth = _iClientWidth; m_iClientHeight = _iClientHeight; // Set up DX swap chain DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = m_iTargetWidth; sd.BufferDesc.Height = m_iTargetHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = m_hMainWnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // Create DX10 device UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif // Create the ID3D10Device and IDXGISwapChain which interfaces // with the D3D10CreateDeviceAndSwapChain function if(FAILED(D3D10CreateDeviceAndSwapChain(0, //default adapter D3D10_DRIVER_TYPE_HARDWARE, 0, // no software device createDeviceFlags, D3D10_SDK_VERSION, &sd, &m_pSwapChain, &m_pDevice))) { MessageBoxA(0, "Failed to create DX10 device.", "ERROR", MB_OK); return (false); } // Create raster states. And set an initial state D3D10_RASTERIZER_DESC rsDesc; ZeroMemory(&rsDesc, sizeof(D3D10_RASTERIZER_DESC)); // Make backface cull solid and set this as initial state rsDesc.FillMode = D3D10_FILL_SOLID; rsDesc.CullMode = D3D10_CULL_BACK; m_pDevice->CreateRasterizerState(&rsDesc, &m_pDefaultRasterState); m_pDevice->RSSetState(m_pDefaultRasterState); Resize(m_iClientWidth, m_iClientHeight); // Load the effect if (FAILED(D3DX10CreateEffectFromFile(L"default.fx", 0, 0, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, m_pDevice, 0, 0, &m_pDefaultEffect, 0, 0))) { MessageBoxA(0, "Failed to create DX10 device.", "ERROR", MB_OK); return (false); } m_pDefaultTech = m_pDefaultEffect->GetTechniqueByName("DefaultTech"); // Create matrix effect pointers m_pWorldMatrixEffectVariable = m_pDefaultEffect->GetVariableByName( "gWorld" )->AsMatrix(); m_pViewMatrixEffectVariable = m_pDefaultEffect->GetVariableByName( "gView" )->AsMatrix(); m_pProjectionMatrixEffectVariable = m_pDefaultEffect->GetVariableByName( "gProjection" )->AsMatrix(); // Vert layout D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 } }; UINT numElements = 2; D3D10_PASS_DESC passDesc; m_pDefaultTech->GetPassByIndex(0)->GetDesc(&passDesc); if (FAILED(m_pDevice->CreateInputLayout(layout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_pDefaultVertexInputLayout ) ) ) { MessageBoxA(0, "Failed to create DX10 device.", "ERROR", MB_OK); return (false); }; // Set the input layout m_pDevice->IASetInputLayout(m_pDefaultVertexInputLayout); m_pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); // Set effect values now because they will not change D3DXMATRIX world; D3DXMatrixIdentity(&world); D3DXMatrixTranslation(&world, m_iClientWidth * -0.5f, m_iClientHeight * -0.5f, 0.0f); D3DXMATRIX rot; D3DXMatrixRotationX(&rot, static_cast<float>(D3DX_PI)); world = world * rot; // Set up the view matrix //-------------------------------------------------------------- D3DXVECTOR3 eye(0.0f, 0.0f, -1.0f); D3DXVECTOR3 view(0.0f, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX viewMatrix; D3DXMatrixLookAtLH( &viewMatrix, &eye, &view, &up); //Set up projection matrix //-------------------------------------------------------------- D3DXMATRIX projectionMatrix; D3DXMatrixOrthoLH(&projectionMatrix, static_cast<float>(m_iClientWidth), static_cast<float>(m_iClientHeight), 0.0f, 1.0f); //D3DXMatrixPerspectiveFovLH(&projectionMatrix, (float)D3DX_PI * 0.5f, (float)m_iClientWidth/m_iClientHeight, 0.1f, 100.0f); m_pWorldMatrixEffectVariable->SetMatrix(world); m_pViewMatrixEffectVariable->SetMatrix(viewMatrix); m_pProjectionMatrixEffectVariable->SetMatrix(projectionMatrix); D3D10_TECHNIQUE_DESC techDesc; m_pDefaultTech->GetDesc(&techDesc); for(unsigned int p = 0; p < techDesc.Passes; ++p ) { m_pDefaultTech->GetPassByIndex(p)->Apply(0); } //create vertex buffer (space for 100 vertices) //--------------------------------------------- UINT numVertices = 100; D3D10_BUFFER_DESC bd; bd.Usage = D3D10_USAGE_DYNAMIC; bd.ByteWidth = sizeof( TVertex ) * numVertices; //total size of buffer in bytes bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; bd.MiscFlags = 0; if ( FAILED( m_pDevice->CreateBuffer( &bd, 0, &m_pVertexBuffer ) ) ) { MessageBoxA(0, "Failed to create DX10 device.", "ERROR", MB_OK); return (false); } PushPenColour(TColour(0, 0, 0, 255).Value()); PushBrushColour(TColour(0, 0, 0, 255).Value()); // Init font D3DX10_FONT_DESC fontDesc; fontDesc.Height = 16; fontDesc.Width = 0; fontDesc.Weight = 0; fontDesc.MipLevels = 1; fontDesc.Italic = false; fontDesc.CharSet = DEFAULT_CHARSET; fontDesc.OutputPrecision = OUT_DEFAULT_PRECIS; fontDesc.Quality = DEFAULT_QUALITY; fontDesc.PitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; wcscpy_s(fontDesc.FaceName, L"Times New Roman"); D3DX10CreateFontIndirect(m_pDevice, &fontDesc, &m_pFont); D3DX10CreateSprite(m_pDevice, 512, &m_pSprite); return(true); }