// Initialize the 3D objects & effects HRESULT InitScene() { HRESULT hr = S_OK; // Create effect DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // shaderFlags |= D3D10_SHADER_DEBUG; #endif // DX10 requires shaders (no fixed function anymore). We will read the shaders from the following string. char shaderFX[] = " struct PSInput { float4 Pos : SV_POSITION; float4 Col : COLOR0; }; \n" " PSInput VertShad(float4 pos : POSITION, float4 col : COLOR) { \n" " PSInput ps; ps.Pos=pos; ps.Col=col; return ps; } \n" " float4 PixShad(PSInput input) : SV_Target { return input.Col; } \n" " technique10 Render { pass P0 { \n" " SetVertexShader( CompileShader( vs_4_0, VertShad() ) ); \n" " SetGeometryShader( NULL ); \n" " SetPixelShader( CompileShader( ps_4_0, PixShad() ) ); \n" " } }\n"; ID3D10Blob *compiledFX = NULL; ID3D10Blob *errors = NULL; hr = D3D10CompileEffectFromMemory(shaderFX, strlen(shaderFX), "TestDX10", NULL, NULL, shaderFlags, 0, &compiledFX, &errors); if( FAILED(hr) ) { char *errMsg = static_cast<char *>(errors->GetBufferPointer()); errMsg[errors->GetBufferSize()-1] = '\0'; MessageBoxA( NULL, errMsg, "Effect compilation failed", MB_OK|MB_ICONERROR ); errors->Release(); return hr; } hr = D3D10CreateEffectFromMemory(compiledFX->GetBufferPointer(), compiledFX->GetBufferSize(), 0, g_D3DDevice, NULL, &g_Effect); compiledFX->Release(); if( FAILED( hr ) ) { MessageBox( NULL, L"Effect creation failed", L"Error", MB_OK ); return hr; } // Obtain the technique g_Technique = g_Effect->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, 3*sizeof(float), D3D10_INPUT_PER_VERTEX_DATA, 0 } }; // Create the input layout D3D10_PASS_DESC passDesc; g_Technique->GetPassByIndex(0)->GetDesc(&passDesc); hr = g_D3DDevice->CreateInputLayout(layout, sizeof(layout)/sizeof(layout[0]), passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &g_VertexLayout); if( FAILED( hr ) ) return hr; const int VERTEX_SIZE = (3 + 4)*sizeof(float); // 3 floats for POSITION + 4 floats for COLOR // Set the input layout g_D3DDevice->IASetInputLayout(g_VertexLayout); // Create vertex buffer D3D10_BUFFER_DESC bd; bd.Usage = D3D10_USAGE_DYNAMIC; bd.ByteWidth = VERTEX_SIZE * NB_VERTS; bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; bd.MiscFlags = 0; hr = g_D3DDevice->CreateBuffer(&bd, NULL, &g_VertexBuffer); if( FAILED( hr ) ) return hr; // Set vertex buffer UINT stride = VERTEX_SIZE; UINT offset = 0; g_D3DDevice->IASetVertexBuffers(0, 1, &g_VertexBuffer, &stride, &offset); // Set primitive topology g_D3DDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Blend state D3D10_BLEND_DESC bsd; bsd.AlphaToCoverageEnable = FALSE; for(int i=0; i<8; ++i) { bsd.BlendEnable[i] = TRUE; bsd.RenderTargetWriteMask[i] = D3D10_COLOR_WRITE_ENABLE_ALL; } bsd.SrcBlend = D3D10_BLEND_SRC_ALPHA; bsd.DestBlend = D3D10_BLEND_INV_SRC_ALPHA; bsd.BlendOp = D3D10_BLEND_OP_ADD; bsd.SrcBlendAlpha = D3D10_BLEND_SRC_ALPHA; bsd.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA; bsd.BlendOpAlpha = D3D10_BLEND_OP_ADD; g_D3DDevice->CreateBlendState(&bsd, &g_BlendState); float blendFactors[4] = { 1, 1, 1, 1 }; g_D3DDevice->OMSetBlendState(g_BlendState, blendFactors, 0xffffffff); // Rasterizer state D3D10_RASTERIZER_DESC rs; ZeroMemory(&rs, sizeof(rs)); rs.FillMode = D3D10_FILL_SOLID; rs.CullMode = D3D10_CULL_NONE; g_D3DDevice->CreateRasterizerState(&rs, &g_RasterState); g_D3DDevice->RSSetState(g_RasterState); return S_OK; }
void CGFXShader::SetVertexFormat(VertexElement format[], uint32 nElem) { if(m_pIL != NULL) { m_pIL->Release(); } //DXGI_FORMAT_R32G32B32_FLOAT ID3D11Device* pDevice = cgD3D11GetDevice(m_pCG); D3D11_INPUT_ELEMENT_DESC* layout = new D3D11_INPUT_ELEMENT_DESC[nElem]; for(uint32 i = 0; i < nElem; ++i) { switch(format[i].semantic) { case VertexElement::POSITION: layout[i].SemanticName = "POSITION"; break; case VertexElement::NORMAL: layout[i].SemanticName = "NORMAL"; break; case VertexElement::COLOR: layout[i].SemanticName = "COLOR"; break; case VertexElement::POSITION_T: layout[i].SemanticName = "POSITIONT"; break; case VertexElement::TEXCOORD: layout[i].SemanticName = "TEXCOORD"; break; default: break; } switch(format[i].type) { case VertexElement::VE_FLOAT1: layout[i].Format = DXGI_FORMAT_R32_FLOAT; break; case VertexElement::VE_FLOAT2: layout[i].Format = DXGI_FORMAT_R32G32_FLOAT; break; case VertexElement::VE_FLOAT3: layout[i].Format = DXGI_FORMAT_R32G32B32_FLOAT; break; case VertexElement::VE_FLOAT4: layout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case VertexElement::VE_UINT32: layout[i].Format = DXGI_FORMAT_R32_UINT; break; default: break; } layout[i].SemanticIndex = format[i].element_slot; layout[i].InputSlot = 0; layout[i].AlignedByteOffset = 0; layout[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; layout[i].InstanceDataStepRate = 0; } CGpass pass = cgGetFirstPass( m_pTechnique ); ID3D10Blob * pVSBuf = cgD3D11GetIASignatureByPass( pass ); pDevice->CreateInputLayout( layout, nElem, pVSBuf->GetBufferPointer(), pVSBuf->GetBufferSize(), &m_pIL ); }
bool vprColorShader::initializeShader(ID3D11Device* device, HWND hwnd, CHAR* vsFilename, CHAR* psFilename) { // Initialize the pointers this function will use to null. ID3D10Blob* errorMessage = 0; // Compile the vertex shader code. ID3D10Blob* vertexShaderBuffer = 0; if (FAILED(D3DX11CompileFromFile(vsFilename, NULL, NULL, "ColorVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL))) { // If the shader failed to compile it should have written something to the error message. if (errorMessage) { outputShaderErrorMessage(errorMessage, hwnd, vsFilename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, vsFilename, "Missing Shader File", MB_OK); } return false; } // Compile the pixel shader code. ID3D10Blob* pixelShaderBuffer = 0; if (FAILED(D3DX11CompileFromFile(psFilename, NULL, NULL, "ColorPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL))) { // If the shader failed to compile it should have written something to the error message. if (errorMessage) { outputShaderErrorMessage(errorMessage, hwnd, psFilename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, psFilename, "Missing Shader File", MB_OK); } return false; } // Create the vertex shader from the buffer. if (FAILED(device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader))) { return false; } // Create the pixel shader from the buffer. if (FAILED(device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader))) { return false; } // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the vprModel and in the shader. D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; 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 = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "COLOR"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // Get a count of the elements in the layout. unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. if (FAILED(device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout))) { return false; } // Release the vertex buffer and pixel shader buffer since they are no longer needed. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Setup the description of the dynamic matrix constant buffer that is the vertex shader. D3D11_BUFFER_DESC matrixBufferDesc; matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. if (FAILED(device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer))) { return false; } return true; }
void TextureModelDemo::Initialize() { SetCurrentDirectory(Utility::ExecutableDirectory().c_str()); // Compile the shader UINT shaderFlags = 0; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3DCOMPILE_DEBUG; shaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; #endif ID3D10Blob* compiledShader = nullptr; ID3D10Blob* errorMessages = nullptr; HRESULT hr = D3DCompileFromFile(L"..\\source\\Library\\Content\\Effects\\TextureMapping.fx", nullptr, nullptr, nullptr, "fx_5_0", shaderFlags, 0, &compiledShader, &errorMessages); if (FAILED(hr)) { char* errorMessage = (errorMessages != nullptr ? (char*)errorMessages->GetBufferPointer() : "D3DX11CompileFromFile() failed"); GameException ex(errorMessage, hr); ReleaseObject(errorMessages); throw ex; } // Create an effect object from the compiled shader hr = D3DX11CreateEffectFromMemory(compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), 0, mGame->Direct3DDevice(), &mEffect); if (FAILED(hr)) { throw GameException("D3DX11CreateEffectFromMemory() failed.", hr); } ReleaseObject(compiledShader); // Look up the technique, pass, and WVP variable from the effect mTechnique = mEffect->GetTechniqueByName("main11"); if (mTechnique == nullptr) { throw GameException("ID3DX11Effect::GetTechniqueByName() could not find the specified technique.", hr); } mPass = mTechnique->GetPassByName("p0"); if (mPass == nullptr) { throw GameException("ID3DX11EffectTechnique::GetPassByName() could not find the specified pass.", hr); } ID3DX11EffectVariable* variable = mEffect->GetVariableByName("WorldViewProjection"); if (variable == nullptr) { throw GameException("ID3DX11Effect::GetVariableByName() could not find the specified variable.", hr); } mWvpVariable = variable->AsMatrix(); if (mWvpVariable->IsValid() == false) { throw GameException("Invalid effect variable cast."); } variable = mEffect->GetVariableByName("ColorTexture"); if (variable == nullptr) { throw GameException("ID3DX11Effect::GetVariableByName() could not find the specified variable.", hr); } mColorTextureVariable = variable->AsShaderResource(); if (mColorTextureVariable->IsValid() == false) { throw GameException("Invalid effect variable cast."); } // Create the input layout D3DX11_PASS_DESC passDesc; mPass->GetDesc(&passDesc); D3D11_INPUT_ELEMENT_DESC inputElementDescriptions[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; if (FAILED(hr = mGame->Direct3DDevice()->CreateInputLayout(inputElementDescriptions, ARRAYSIZE(inputElementDescriptions), passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &mInputLayout))) { throw GameException("ID3D11Device::CreateInputLayout() failed.", hr); } // Load the model std::unique_ptr<Model> model(new Model(*mGame, "..\\source\\Library\\Content\\Models\\Sphere.obj", true)); // Create the vertex and index buffers Mesh* mesh = model->Meshes().at(0); CreateVertexBuffer(mGame->Direct3DDevice(), *mesh, &mVertexBuffer); mesh->CreateIndexBuffer(&mIndexBuffer); mIndexCount = mesh->Indices().size(); // Load the texture std::wstring textureName = L"..\\source\\Library\\Content\\Textures\\EarthComposite.jpg"; if (FAILED(hr = DirectX::CreateWICTextureFromFile(mGame->Direct3DDevice(), mGame->Direct3DDeviceContext(), textureName.c_str(), nullptr, &mTextureShaderResourceView))) { throw GameException("CreateWICTextureFromFile() failed.", hr); } }
bool InitResourceDX10(void) { g_pDevice = GutGetGraphicsDeviceDX10(); ID3D10Blob *pVSCode = NULL; // 載入Vertex Shader g_pVertexShader = GutLoadVertexShaderDX10_HLSL("../../shaders/vertex_color_dx10.hlsl", "VS", "vs_4_0", &pVSCode); if ( NULL==g_pVertexShader ) return false; // 載入Pixel Shader g_pPixelShader = GutLoadPixelShaderDX10_HLSL("../../shaders/vertex_color_dx10.hlsl", "PS", "ps_4_0"); if ( NULL==g_pPixelShader ) return false; CGutModel_DX10::LoadDefaultShader("../../shaders/gmodel_dx10.hlsl"); for ( int i=0; i<3; i++ ) { g_Model_DX10[i].ConvertToDX10Model(&g_Models[i]); } // 設定Vertex資料格式 D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 } }; if ( D3D_OK != g_pDevice->CreateInputLayout( layout, sizeof(layout)/sizeof(D3D10_INPUT_ELEMENT_DESC), pVSCode->GetBufferPointer(), pVSCode->GetBufferSize(), &g_pVertexLayout ) ) return false; SAFE_RELEASE(pVSCode); // g_pBorderVertexBuffer = GutCreateVertexBuffer_DX10(sizeof(g_Border), g_Border); // 配置Shader讀取參數的記憶體空間 g_pConstantBuffer = GutCreateShaderConstant_DX10(sizeof(Matrix4x4)); // 計算出一個可以轉換到鏡頭座標系的矩陣 g_proj_matrix = GutMatrixPerspectiveRH_DirectX(70.0f, 1.0f, 0.1f, 100.0f); // 開?rasterizer state物件 D3D10_RASTERIZER_DESC rasterizer_state_desc; rasterizer_state_desc.FillMode = D3D10_FILL_SOLID; rasterizer_state_desc.CullMode = D3D10_CULL_BACK; rasterizer_state_desc.FrontCounterClockwise = true; rasterizer_state_desc.DepthBias = 0; rasterizer_state_desc.DepthBiasClamp = 0.0f; rasterizer_state_desc.SlopeScaledDepthBias = 0.0f; rasterizer_state_desc.DepthClipEnable = false; rasterizer_state_desc.ScissorEnable = false; rasterizer_state_desc.MultisampleEnable = false; rasterizer_state_desc.AntialiasedLineEnable = false; if ( D3D_OK != g_pDevice->CreateRasterizerState(&rasterizer_state_desc, &g_pRasterizerState) ) return false; g_pDevice->RSSetState(g_pRasterizerState); return true; }
bool CMtlShader2D::Initialize(CD3D11Class* p3DRoot) { ID3D10Blob* errorMessage = 0; std::wstring strErrorMessage; // 编译vs代码. ID3D10Blob* vertexShaderBuffer = 0; HRESULT result = D3DX11CompileFromFile(m_strVSName.c_str(), NULL, NULL, "ColorVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { // 如果vs编译失败,输出错误消息. if (errorMessage) { char* compileErrors = (char*)(errorMessage->GetBufferPointer()); ULONG nSize = errorMessage->GetBufferSize(); DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, compileErrors, -1, NULL, 0); wchar_t *pwText = new wchar_t[dwNum]; MultiByteToWideChar(CP_ACP, 0, compileErrors, -1, pwText, dwNum); strErrorMessage = pwText; } // 如果没有任何错误消息,可能是shader文件丢失. else { strErrorMessage = L"Missing Shader File"; } return false; } // 编译ps. ID3D10Blob* pixelShaderBuffer = 0; result = D3DX11CompileFromFile(m_strPSName.c_str(), NULL, NULL, "ColorPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { // 如果vs编译失败,输出错误消息. if (errorMessage) { char* compileErrors = (char*)(errorMessage->GetBufferPointer()); ULONG nSize = errorMessage->GetBufferSize(); DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, compileErrors, -1, NULL, 0); wchar_t *pwText = new wchar_t[dwNum]; MultiByteToWideChar(CP_ACP, 0, compileErrors, -1, pwText, dwNum); strErrorMessage = pwText; } // 如果没有任何错误消息,可能是shader文件丢失. else { strErrorMessage = L"Missing Shader File"; } return false; } // 从缓冲创建vs shader. result = p3DRoot->GetDevice()->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if (FAILED(result)) { return false; } // 从缓冲创建ps shader. result = p3DRoot->GetDevice()->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if (FAILED(result)) { return false; } // 设置数据布局,以便在shader中使用. // 定义要和ModelClass中的顶点结构一致. D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; polygonLayout[0].SemanticName = "POSITION";//vs中的输入参数 polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // 得到layout中的元素数量 int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // 创建顶点输入布局. result = p3DRoot->GetDevice()->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if (FAILED(result)) { return false; } //释放顶点和像素缓冲. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // 创建纹理采样描述符 D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 1.0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 1.0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // 创建纹理采样状态. result = p3DRoot->GetDevice()->CreateSamplerState(&samplerDesc, &m_sampleState); if (FAILED(result)) { return false; } return true; }
bool CGELightMapShader::_initialize_shader(ID3D11Device *pDevice, HWND hWnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; D3D11_BUFFER_DESC bufferDesc; ID3D10Blob* pVertexShaderBuf; ID3D10Blob* pPixelShaderBuf; ID3D10Blob* pErrorMessage; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElem; D3D11_SAMPLER_DESC samplerDesc; pErrorMessage = 0; pVertexShaderBuf = 0; pPixelShaderBuf = 0; result = ::D3DX11CompileFromFile(vsFilename, NULL, NULL, "LightMapVS", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pVertexShaderBuf, &pErrorMessage, NULL); if( FAILED(result) ) { if( pErrorMessage ) { this->_output_error_message(pErrorMessage, hWnd, vsFilename); } else { MessageBox(hWnd, vsFilename, L"Missing Shader File", MB_OK); } return false; } result = ::D3DX11CompileFromFile(psFilename, NULL, NULL, "LightMapPS", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pPixelShaderBuf, &pErrorMessage, NULL); if( FAILED(result) ) { if( pErrorMessage ) { this->_output_error_message(pErrorMessage, hWnd, psFilename); } else { MessageBox(hWnd, psFilename, L"Missing Shader File", MB_OK); } return false; } result = pDevice->CreateVertexShader(pVertexShaderBuf->GetBufferPointer(), pVertexShaderBuf->GetBufferSize(), NULL, &this->m_pVertexShader); if( FAILED(result) ) return false; result = pDevice->CreatePixelShader(pPixelShaderBuf->GetBufferPointer(), pPixelShaderBuf->GetBufferSize(), NULL, &this->m_pPixelShader); if( FAILED(result) ) return false; 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; numElem = sizeof(polygonLayout) / sizeof(polygonLayout[0]); result = pDevice->CreateInputLayout(polygonLayout, numElem, pVertexShaderBuf->GetBufferPointer(), pVertexShaderBuf->GetBufferSize(), &this->m_pInputLayout); if( FAILED(result) ) return false; ::ReleaseWithoutDel<ID3D10Blob*>(pVertexShaderBuf); ::ReleaseWithoutDel<ID3D10Blob*>(pPixelShaderBuf); // Matrix buffer desc bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(MatrixBufferType); bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bufferDesc.MiscFlags = 0; bufferDesc.StructureByteStride = 0; result = pDevice->CreateBuffer(&bufferDesc, NULL, &this->m_pMatrixBuffer); if( FAILED(result) ) return false; // Sampler desc samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; result = pDevice->CreateSamplerState(&samplerDesc, &this->m_pSamplerState); if( FAILED(result) ) return false; return true; }
bool CTextureShader::InitializeShader(ID3D11Device* device, HWND hwnd, char* vsFilename, char* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_SAMPLER_DESC samplerDesc; errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; // compile the vertex shader result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "TextureVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); else CLog::Write("CTextureShader::InitializeShader() : Missing vertex shader file"); return false; } result = D3DX11CompileFromFile(psFilename, NULL, NULL, "TexturePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); else CLog::Write("CTextureShader::InitializeShader() : Missing pixel shader file"); return false; } result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &vertexShader); if (FAILED(result)) { CLog::Write("CTextureShader::InitializeShader() : could not create the vertex shader"); return false; } result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &pixelShader); if (FAILED(result)) { CLog::Write("CTextureShader::InitializeShader() : could not create the vertex shader"); return false; } // Create the vertex input layout 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; numElements = sizeof(polygonLayout)/sizeof(polygonLayout[0]); result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &layout); if (FAILED(result)) { CLog::Write("CTextureShader::InitializeShader() : could not create the input layout"); return false; } // release the vertex and pixel shader buffers vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Setup the description of the dynamic matrix constant buffer matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader result = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer); if (FAILED(result)) { CLog::Write("CTextureShader::InitializeShader() : could not create the matrix buffer"); return false; } // Create a texture sampler state description samplerDesc.Filter = Settings::TextureFilter; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Create the texture sampler state result = device->CreateSamplerState(&samplerDesc, &sampleState); if (FAILED(result)) { CLog::Write("CTextureShader::InitializeShader() : could not create the sampler state"); return false; } return true; }
bool VerticalBlurShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_BUFFER_DESC screenSizeBufferDesc; // Initialize the pointers this function will use to null. errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "VerticalBlurVertexShader", "vs_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); } else { MessageBox(hwnd, vsFilename, L"Missing shader file", MB_OK); } return false; } result = D3DX11CompileFromFile(psFilename, NULL, NULL, "VerticalBlurPixelShader", "ps_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psFilename); } else { MessageBox(hwnd, psFilename, L"Missing shader file", MB_OK); } } result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if (FAILED(result)) { return false; } result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if (FAILED(result)) { return false; } 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if (FAILED(result)) { return false; } vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MipLODBias = 0; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if (FAILED(result)) { return false; } matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if (FAILED(result)) { return false; } screenSizeBufferDesc.Usage = D3D11_USAGE_DYNAMIC; screenSizeBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; screenSizeBufferDesc.ByteWidth = sizeof(MatrixBufferType); screenSizeBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; screenSizeBufferDesc.MiscFlags = 0; screenSizeBufferDesc.StructureByteStride = 0; result = device->CreateBuffer(&screenSizeBufferDesc, NULL, &m_screenSizeBuffer); if (FAILED(result)) { return false; } return true; }
bool CLightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[3]; unsigned int numElements; D3D11_BUFFER_DESC MatrixBufferDesc; D3D11_BUFFER_DESC LightBufferDesc; D3D11_SAMPLER_DESC samplerDesc; //Inicializamos los valores errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; /************************************************************************/ /* Compilamos los Shaders */ /************************************************************************/ //Compilamos el vertex shader, si ay un error lo dira result = D3DX11CompileFromFile( vsFilename, NULL, NULL, "LightVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { //Si hubo un error, lo debio de haber escrito if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); } //Si no esribio nada, significa que no encontro el archivo else { MessageBox(hwnd, L"no se encontro el archivo", L"Error", MB_OK); } return false; } //Compilamos el pixel shader, si ay un error lo dira result = D3DX11CompileFromFile( psFilename, NULL, NULL, "LightPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { //Si hubo un error, lo debio de haber escrito if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psFilename); } //Si no esribio nada, significa que no encontro el archivo else { MessageBox(hwnd, L"no se encontro el archivo", L"Error", MB_OK); } return false; } /************************************************************************/ /* Creamos los buffers a partir de la compilacion */ /************************************************************************/ //creamos el vertex shader del buffer result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if (FAILED(result)) { return false; } //creamos el pixel shader del buffer result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if (FAILED(result)) { return false; } /************************************************************************/ /* Creamos el Layout */ /************************************************************************/ 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "NORMAL"; polygonLayout[2].SemanticIndex = 0; polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; //Obtenemos el numero de elementos del Layout numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); //Creamos el Layout del vertex result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if (FAILED(result)) { return false; } //Liberamos memoria vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; /************************************************************************/ /* creamos el buffer de constantes */ /************************************************************************/ //Creamos el descriptor del buffer de constantes MatrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; MatrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); MatrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; MatrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; MatrixBufferDesc.MiscFlags = 0; MatrixBufferDesc.StructureByteStride = 0; //Creamos el buffer de contsntantes result = device->CreateBuffer(&MatrixBufferDesc, NULL, &m_matrixBuffer); if (FAILED(result)) { return false; } /************************************************************************/ /* creamos el buffer de luces */ /************************************************************************/ //Creamos el descriptor del buffer de constantes LightBufferDesc.Usage = D3D11_USAGE_DYNAMIC; LightBufferDesc.ByteWidth = sizeof(LightBufferType); LightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; LightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; LightBufferDesc.MiscFlags = 0; LightBufferDesc.StructureByteStride = 0; //Creamos el buffer de contsntantes result = device->CreateBuffer(&LightBufferDesc, NULL, &m_lightBuffer); if (FAILED(result)) { return false; } /************************************************************************/ /* Creamos el sampler para la textura */ /************************************************************************/ //Describimos el comportamiento con la textura samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; //y creamos el sample state result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if (FAILED(result)) { return false; } return true; }
bool SkyDomeShader::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[1]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_BUFFER_DESC gradientBufferDesc; // Initialize the pointers this function will use to null. errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; // Compile the vertex shader code. result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "SkyDomeVertexShader", "vs_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &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, vsFilename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK); } return false; } // Compile the pixel shader code. result = D3DX11CompileFromFile(psFilename, NULL, NULL, "SkyDomePixelShader", "ps_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &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, psFilename); } // If there was nothing in the error message then it simply could not find the file itself. else { MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK); } return false; } // Create the vertex shader from the buffer. result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if(FAILED(result)) { return false; } // Create the pixel shader from the buffer. result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if(FAILED(result)) { return false; } // Create the vertex input layout description. 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 = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if(FAILED(result)) { return false; } // Release the vertex shader buffer and pixel shader buffer since they are no longer needed. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this . result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if(FAILED(result)) { return false; } // Setup the description of the gradient constant buffer that is in the pixel shader. gradientBufferDesc.Usage = D3D11_USAGE_DYNAMIC; gradientBufferDesc.ByteWidth = sizeof(GradientBufferType); gradientBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; gradientBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; gradientBufferDesc.MiscFlags = 0; gradientBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this . result = device->CreateBuffer(&gradientBufferDesc, NULL, &m_gradientBuffer); if(FAILED(result)) { return false; } return true; }
bool InitResourceDX10(void) { g_pDevice = GutGetGraphicsDeviceDX10(); ID3D10Blob *pVSCode = NULL; // 載入Vertex Shader g_pVertexShader = GutLoadVertexShaderDX10_HLSL("../../shaders/vertex_lighting_dx10.hlsl", "VS", "vs_4_0", &pVSCode); if ( NULL==g_pVertexShader ) return false; // 載入Pixel Shader g_pPixelShader = GutLoadPixelShaderDX10_HLSL("../../shaders/vertex_lighting_dx10.hlsl", "PS", "ps_4_0"); if ( NULL==g_pPixelShader ) return false; // 設定Vertex資料格式 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 } }; if ( D3D_OK != g_pDevice->CreateInputLayout( layout, sizeof(layout)/sizeof(D3D10_INPUT_ELEMENT_DESC), pVSCode->GetBufferPointer(), pVSCode->GetBufferSize(), &g_pVertexLayout ) ) return false; SAFE_RELEASE(pVSCode); D3D10_BUFFER_DESC cbDesc; // vertex buffer cbDesc.ByteWidth = sizeof(Vertex_V3N3) * g_iMaxNumGridVertices; cbDesc.Usage = D3D10_USAGE_DYNAMIC ; cbDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pVertexBuffer ) ) return false; // 設定一塊可以用來放Index的記憶體. cbDesc.ByteWidth = sizeof(unsigned short) * g_iMaxNumGridIndices; cbDesc.Usage = D3D10_USAGE_DYNAMIC; cbDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; // 配置一塊可以存放Index的記憶體, 也就是Index Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pIndexBuffer ) ) return false; // 配置Shader讀取參數的記憶體空間 cbDesc.ByteWidth = sizeof(Matrix4x4) * 2; cbDesc.Usage = D3D10_USAGE_DYNAMIC; cbDesc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pMatrixConstantBuffer ) ) return false; cbDesc.ByteWidth = sizeof(Light_Info) * g_iNumLights; cbDesc.Usage = D3D10_USAGE_DYNAMIC; cbDesc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pLightConstantBuffer ) ) return false; // 計算投影矩陣 g_proj_matrix = GutMatrixPerspectiveRH_DirectX(g_fFovW, 1.0f, 0.1f, 100.0f); // rasterizer state物件 D3D10_RASTERIZER_DESC rasterizer_state_desc; rasterizer_state_desc.FillMode = D3D10_FILL_SOLID; rasterizer_state_desc.CullMode = D3D10_CULL_NONE; rasterizer_state_desc.FrontCounterClockwise = true; rasterizer_state_desc.DepthBias = 0; rasterizer_state_desc.DepthBiasClamp = 0.0f; rasterizer_state_desc.SlopeScaledDepthBias = 0.0f; rasterizer_state_desc.DepthClipEnable = false; rasterizer_state_desc.ScissorEnable = false; rasterizer_state_desc.MultisampleEnable = false; rasterizer_state_desc.AntialiasedLineEnable = false; if ( D3D_OK != g_pDevice->CreateRasterizerState(&rasterizer_state_desc, &g_pRasterizerState) ) return false; g_pDevice->RSSetState(g_pRasterizerState); g_view_matrix = GutMatrixLookAtRH(g_eye, g_lookat, g_up); return true; }
App::App(ID3D11Device *d3dDevice, unsigned int activeLights, unsigned int msaaSamples) : mMSAASamples(msaaSamples) , mTotalTime(0.0f) , mActiveLights(0) , mLightBuffer(0) , mDepthBufferReadOnlyDSV(0) { std::string msaaSamplesStr; { std::ostringstream oss; oss << mMSAASamples; msaaSamplesStr = oss.str(); } // Set up macros D3D10_SHADER_MACRO defines[] = { {"MSAA_SAMPLES", msaaSamplesStr.c_str()}, {0, 0} }; // Create shaders mGeometryVS = new VertexShader(d3dDevice, L"Rendering.hlsl", "GeometryVS", defines); mGBufferPS = new PixelShader(d3dDevice, L"GBuffer.hlsl", "GBufferPS", defines); mGBufferAlphaTestPS = new PixelShader(d3dDevice, L"GBuffer.hlsl", "GBufferAlphaTestPS", defines); mForwardPS = new PixelShader(d3dDevice, L"Forward.hlsl", "ForwardPS", defines); mForwardAlphaTestPS = new PixelShader(d3dDevice, L"Forward.hlsl", "ForwardAlphaTestPS", defines); mForwardAlphaTestOnlyPS = new PixelShader(d3dDevice, L"Forward.hlsl", "ForwardAlphaTestOnlyPS", defines); mFullScreenTriangleVS = new VertexShader(d3dDevice, L"Rendering.hlsl", "FullScreenTriangleVS", defines); mSkyboxVS = new VertexShader(d3dDevice, L"SkyboxToneMap.hlsl", "SkyboxVS", defines); mSkyboxPS = new PixelShader(d3dDevice, L"SkyboxToneMap.hlsl", "SkyboxPS", defines); mRequiresPerSampleShadingPS = new PixelShader(d3dDevice, L"GBuffer.hlsl", "RequiresPerSampleShadingPS", defines); mBasicLoopPS = new PixelShader(d3dDevice, L"BasicLoop.hlsl", "BasicLoopPS", defines); mBasicLoopPerSamplePS = new PixelShader(d3dDevice, L"BasicLoop.hlsl", "BasicLoopPerSamplePS", defines); mComputeShaderTileCS = new ComputeShader(d3dDevice, L"ComputeShaderTile.hlsl", "ComputeShaderTileCS", defines); mGPUQuadVS = new VertexShader(d3dDevice, L"GPUQuad.hlsl", "GPUQuadVS", defines); mGPUQuadGS = new GeometryShader(d3dDevice, L"GPUQuad.hlsl", "GPUQuadGS", defines); mGPUQuadPS = new PixelShader(d3dDevice, L"GPUQuad.hlsl", "GPUQuadPS", defines); mGPUQuadPerSamplePS = new PixelShader(d3dDevice, L"GPUQuad.hlsl", "GPUQuadPerSamplePS", defines); mGPUQuadDLPS = new PixelShader(d3dDevice, L"GPUQuadDL.hlsl", "GPUQuadDLPS", defines); mGPUQuadDLPerSamplePS = new PixelShader(d3dDevice, L"GPUQuadDL.hlsl", "GPUQuadDLPerSamplePS", defines); mGPUQuadDLResolvePS = new PixelShader(d3dDevice, L"GPUQuadDL.hlsl", "GPUQuadDLResolvePS", defines); mGPUQuadDLResolvePerSamplePS = new PixelShader(d3dDevice, L"GPUQuadDL.hlsl", "GPUQuadDLResolvePerSamplePS", defines); // Create input layout { // We need the vertex shader bytecode for this... rather than try to wire that all through the // shader interface, just recompile the vertex shader. UINT shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_PACK_MATRIX_ROW_MAJOR; ID3D10Blob *bytecode = 0; HRESULT hr = D3DX11CompileFromFile(L"Rendering.hlsl", defines, 0, "GeometryVS", "vs_5_0", shaderFlags, 0, 0, &bytecode, 0, 0); if (FAILED(hr)) { assert(false); // It worked earlier... } const D3D11_INPUT_ELEMENT_DESC layout[] = { {"position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"normal", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"texCoord", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; d3dDevice->CreateInputLayout( layout, ARRAYSIZE(layout), bytecode->GetBufferPointer(), bytecode->GetBufferSize(), &mMeshVertexLayout); bytecode->Release(); } // Create standard rasterizer state { CD3D11_RASTERIZER_DESC desc(D3D11_DEFAULT); d3dDevice->CreateRasterizerState(&desc, &mRasterizerState); desc.CullMode = D3D11_CULL_NONE; d3dDevice->CreateRasterizerState(&desc, &mDoubleSidedRasterizerState); } { CD3D11_DEPTH_STENCIL_DESC desc(D3D11_DEFAULT); // NOTE: Complementary Z => GREATER test desc.DepthFunc = D3D11_COMPARISON_GREATER_EQUAL; d3dDevice->CreateDepthStencilState(&desc, &mDepthState); } // Stencil states for MSAA { CD3D11_DEPTH_STENCIL_DESC desc( FALSE, D3D11_DEPTH_WRITE_MASK_ZERO, D3D11_COMPARISON_GREATER_EQUAL, // Depth TRUE, 0xFF, 0xFF, // Stencil D3D11_STENCIL_OP_REPLACE, D3D11_STENCIL_OP_REPLACE, D3D11_STENCIL_OP_REPLACE, D3D11_COMPARISON_ALWAYS, // Front face stencil D3D11_STENCIL_OP_REPLACE, D3D11_STENCIL_OP_REPLACE, D3D11_STENCIL_OP_REPLACE, D3D11_COMPARISON_ALWAYS // Back face stencil ); d3dDevice->CreateDepthStencilState(&desc, &mWriteStencilState); } { CD3D11_DEPTH_STENCIL_DESC desc( TRUE, D3D11_DEPTH_WRITE_MASK_ZERO, D3D11_COMPARISON_GREATER_EQUAL, // Depth TRUE, 0xFF, 0xFF, // Stencil D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_EQUAL, // Front face stencil D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_EQUAL // Back face stencil ); d3dDevice->CreateDepthStencilState(&desc, &mEqualStencilState); } // Create geometry phase blend state { CD3D11_BLEND_DESC desc(D3D11_DEFAULT); d3dDevice->CreateBlendState(&desc, &mGeometryBlendState); } // Create lighting phase blend state { CD3D11_BLEND_DESC desc(D3D11_DEFAULT); // Additive blending desc.RenderTarget[0].BlendEnable = true; desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; desc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; d3dDevice->CreateBlendState(&desc, &mLightingBlendState); } // Create constant buffers { CD3D11_BUFFER_DESC desc( sizeof(PerFrameConstants), D3D11_BIND_CONSTANT_BUFFER, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE); d3dDevice->CreateBuffer(&desc, 0, &mPerFrameConstants); } // Create sampler state { CD3D11_SAMPLER_DESC desc(D3D11_DEFAULT); desc.Filter = D3D11_FILTER_ANISOTROPIC; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MaxAnisotropy = 16; d3dDevice->CreateSamplerState(&desc, &mDiffuseSampler); } // Create skybox mesh mSkyboxMesh.Create(d3dDevice, L"Media\\Skybox\\Skybox.sdkmesh"); InitializeLightParameters(d3dDevice); SetActiveLights(d3dDevice, activeLights); }
bool ColorShader::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; // Compile vertex shader result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "VS_Main", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); } else { MessageBox(hwnd, vsFilename, L"Missing shader file", MB_OK); } } // Compile pixel shader result = D3DX11CompileFromFile(psFilename, NULL, NULL, "PS_Main", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psFilename); } else { MessageBox(hwnd, psFilename, L"Missing shader file", MB_OK); } return false; } // Create shaders from buffers result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if (FAILED(result)) return false; result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if (FAILED(result)) return false; 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 = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "COLOR"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_inputLayout); if (FAILED(result)) return false; vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if (FAILED(result)) return false; return true; }
bool ReflectionShader::Initialize(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* vertexShaderBuffer = 0; ID3D10Blob* pixelShaderBuffer = 0; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC reflectionBufferDesc; CompileShader(vsFilename, "ReflectionVertexShader", "vs_4_0", &vertexShaderBuffer, hwnd); CompileShader(psFilename, "ReflectionPixelShader", "ps_4_0", &pixelShaderBuffer, hwnd); result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if(FAILED(result)) return false; result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if(FAILED(result)) return false; D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE(layout); result = device->CreateInputLayout( layout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if(FAILED(result)) return false; vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if(FAILED(result)) return false; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if(FAILED(result)) return false; reflectionBufferDesc.Usage = D3D11_USAGE_DYNAMIC; reflectionBufferDesc.ByteWidth = sizeof(ReflectionBufferType); reflectionBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; reflectionBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; reflectionBufferDesc.MiscFlags = 0; reflectionBufferDesc.StructureByteStride = 0; result = device->CreateBuffer(&reflectionBufferDesc, NULL, &m_reflectionBuffer); if(FAILED(result)) return false; return true; }
//-------------------------------------------------------------------------------------- // Create any D3D11 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { DXUT_SetDebugName( pd3dDevice, "Main Device" ); HRESULT hr; ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); V_RETURN( g_SettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); IDXGIDevice* pDXGIDevice; hr = pd3dDevice->QueryInterface( __uuidof(IDXGIDevice), (VOID**)&pDXGIDevice ); if( SUCCEEDED(hr) ) { IDXGIAdapter* pAdapter; hr = pDXGIDevice->GetAdapter( &pAdapter ); if( SUCCEEDED(hr) ) { DXGI_ADAPTER_DESC AdapterDesc; pAdapter->GetDesc( &AdapterDesc ); SetAdapterInfoForShaderCompilation( AdapterDesc.Description ); SAFE_RELEASE( pAdapter ); } SAFE_RELEASE( pDXGIDevice ); } ID3D10Blob* pVSBlob = NULL; g_pVSTransform = CompileVertexShader( pd3dDevice, L"SceneRender.hlsl", "VSTransform", &pVSBlob ); g_pPSSceneRender = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRender" ); g_pPSSceneRenderArray = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRenderArray" ); g_pPSSceneRenderQuilt = CompilePixelShader( pd3dDevice, L"SceneRender.hlsl", "PSSceneRenderQuilt" ); // Create a layout for the object data const D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pDefaultInputLayout ) ); // No longer need the shader blobs SAFE_RELEASE( pVSBlob ); // Create state objects D3D11_SAMPLER_DESC samDesc; ZeroMemory( &samDesc, sizeof(samDesc) ); samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samDesc.AddressU = samDesc.AddressV = samDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.MaxAnisotropy = 1; samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samDesc.MaxLOD = D3D11_FLOAT32_MAX; V_RETURN( pd3dDevice->CreateSamplerState( &samDesc, &g_pSamLinear ) ); DXUT_SetDebugName( g_pSamLinear, "Linear" ); D3D11_BLEND_DESC BlendDesc; ZeroMemory( &BlendDesc, sizeof( D3D11_BLEND_DESC ) ); BlendDesc.RenderTarget[0].BlendEnable = FALSE; BlendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; BlendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; BlendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; BlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA; BlendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; BlendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; BlendDesc.RenderTarget[0].RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL; hr = pd3dDevice->CreateBlendState( &BlendDesc, &g_pBlendState ); ASSERT( SUCCEEDED(hr) ); D3D11_DEPTH_STENCIL_DESC DSDesc; ZeroMemory( &DSDesc, sizeof(D3D11_DEPTH_STENCIL_DESC) ); DSDesc.DepthEnable = FALSE; DSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; DSDesc.DepthFunc = D3D11_COMPARISON_LESS; DSDesc.StencilEnable = FALSE; DSDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; DSDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; hr = pd3dDevice->CreateDepthStencilState( &DSDesc, &g_pDepthStencilState ); ASSERT( SUCCEEDED(hr) ); D3D11_RASTERIZER_DESC RSDesc; ZeroMemory( &RSDesc, sizeof(RSDesc) ); RSDesc.AntialiasedLineEnable = FALSE; RSDesc.CullMode = D3D11_CULL_BACK; RSDesc.DepthBias = 0; RSDesc.DepthBiasClamp = 0.0f; RSDesc.DepthClipEnable = TRUE; RSDesc.FillMode = D3D11_FILL_SOLID; RSDesc.FrontCounterClockwise = FALSE; RSDesc.MultisampleEnable = TRUE; RSDesc.ScissorEnable = FALSE; RSDesc.SlopeScaledDepthBias = 0.0f; hr = pd3dDevice->CreateRasterizerState( &RSDesc, &g_pRasterizerState ); ASSERT( SUCCEEDED(hr) ); g_pcbVSPerObject11 = CreateConstantBuffer( pd3dDevice, sizeof(CB_VS_PER_OBJECT) ); DXUT_SetDebugName( g_pcbVSPerObject11, "CB_VS_PER_OBJECT" ); // Create other render resources here D3D11_TILED_EMULATION_PARAMETERS EmulationParams; EmulationParams.DefaultPhysicalTileFormat = DXGI_FORMAT_R8G8B8A8_UNORM; EmulationParams.MaxPhysicalTileCount = 1000; D3D11CreateTiledResourceDevice( pd3dDevice, pd3dImmediateContext, &EmulationParams, &g_pd3dDeviceEx ); g_pd3dDeviceEx->CreateTilePool( &g_pTilePool ); g_pTitleResidencyManager = new TitleResidencyManager( pd3dDevice, pd3dImmediateContext, 1, EmulationParams.MaxPhysicalTileCount, g_pTilePool ); ResidencySampleRender::Initialize( pd3dDevice ); g_PageDebugRender.Initialize( pd3dDevice ); CreateSceneGeometry( pd3dDevice ); // Setup the camera's view parameters XMMATRIX matProjection = XMMatrixPerspectiveFovLH( XM_PIDIV4, (FLOAT)pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height, 0.001f, 100.0f ); XMStoreFloat4x4A( &g_matProjection, matProjection ); UpdateViewMatrix(); g_pTitleResidencyManager->StartThreads(); return S_OK; }
bool ShaderClass::Init(ID3D11Device *pDevice, HWND hwnd) { HRESULT res = S_OK; ID3D10Blob *pErr = NULL; // 存放编译shader的错误信息 ID3D10Blob *pVertexShaderBuffer = NULL; // 编译出来的VS字节 ID3D10Blob *pPixelShaderBuffer = NULL; // 编译出来的PS字节 D3D11_INPUT_ELEMENT_DESC polygonLayout[3]; // 描述 unsigned int numElem = sizeof(polygonLayout)/sizeof(polygonLayout[0]); // 一个点中的成员量 D3D11_BUFFER_DESC matrixBufferDesc = { 0 }; // 编译VS res = D3DX11CompileFromMemory((LPCSTR)s_lpShaderContentStr, sizeof(s_lpShaderContentStr), NULL, NULL, NULL, "ColorVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pVertexShaderBuffer, &pErr, NULL); assert(SUCCEEDED(res)); // 编译PS res = D3DX11CompileFromMemory((LPCSTR)s_lpShaderContentStr, sizeof(s_lpShaderContentStr), NULL, NULL, NULL, "ColorPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pPixelShaderBuffer, &pErr, NULL); assert(SUCCEEDED(res)); // 创建VS Shader res = pDevice->CreateVertexShader(pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), NULL, &m_pVertexShader); assert(SUCCEEDED(res)); // 创建PS Shader res = pDevice->CreatePixelShader(pPixelShaderBuffer->GetBufferPointer(), pPixelShaderBuffer->GetBufferSize(), NULL, &m_pPixelShader); assert(SUCCEEDED(res)); // 创建定点布局,在Input-Assemble 阶段使用 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 = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "COLOR"; // 语义 polygonLayout[1].SemanticIndex = 0; // 语义 polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; // 语义 polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "TEXCOORD"; // 语义 polygonLayout[2].SemanticIndex = 0; // 语义 polygonLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT; // 语义 polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; res = pDevice->CreateInputLayout(polygonLayout, numElem, pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), &m_pLayout); assert(SUCCEEDED(res)); pVertexShaderBuffer->Release(); pVertexShaderBuffer = NULL; pPixelShaderBuffer->Release(); pPixelShaderBuffer = NULL; // 创建Content 矩阵Buffer matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; res = pDevice->CreateBuffer(&matrixBufferDesc, NULL, &m_pConstantBuffer); assert(SUCCEEDED(res)); // 创建纹理采样描述 D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; // 线性插值方式采样 // 地址模式 samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // 创建纹理采样状态. res = pDevice->CreateSamplerState(&samplerDesc, &m_pSampleState); assert(SUCCEEDED(res)); if (FAILED(res)) { return false; } return true; }
bool LightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; //The polygonLayout variable has been changed to have three elements instead of two. This is so that it can accommodate a normal vector in the layout. D3D11_INPUT_ELEMENT_DESC polygonLayout[3]; unsigned int numElements; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_BUFFER_DESC cameraBufferDesc; D3D11_BUFFER_DESC lightBufferDesc; // Initialize the pointers this function will use to null. errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; //Load in the new light vertex shader. // Compile the vertex shader code. result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "LightVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &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, vsFilename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK); } return false; } //Load in the new light pixel shader. // Compile the pixel shader code. result = D3DX11CompileFromFile(psFilename, NULL, NULL, "LightPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &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, psFilename); } // If there was nothing in the error message then it simply could not find the file itself. else { MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK); } return false; } // Create the vertex shader from the buffer. result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if(FAILED(result)) { return false; } // Create the pixel shader from the buffer. result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if(FAILED(result)) { return false; } // Create the vertex input layout description. // 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; //One of the major changes to the shader initialization is here in the polygonLayout. We add a third element for the normal vector that will be used for lighting. The semantic name is NORMAL and the format is the regular DXGI_FORMAT_R32G32B32_FLOAT which handles 3 floats for the x, y, and z of the normal vector. The layout will now match the expected input to the HLSL vertex shader. polygonLayout[2].SemanticName = "NORMAL"; polygonLayout[2].SemanticIndex = 0; polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if(FAILED(result)) { return false; } // Release the vertex shader buffer and pixel shader buffer since they are no longer needed. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Create a texture sampler state description. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Create the texture sampler state. result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if(FAILED(result)) { return false; } // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if(FAILED(result)) { return false; } // Setup the description of the camera dynamic constant buffer that is in the vertex shader. cameraBufferDesc.Usage = D3D11_USAGE_DYNAMIC; cameraBufferDesc.ByteWidth = sizeof(CameraBufferType); cameraBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cameraBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cameraBufferDesc.MiscFlags = 0; cameraBufferDesc.StructureByteStride = 0; // Create the camera constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&cameraBufferDesc, NULL, &m_cameraBuffer); if(FAILED(result)) { return false; } // Setup the description of the light dynamic constant buffer that is in the pixel shader. // Note that ByteWidth always needs to be a multiple of 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail. lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC; lightBufferDesc.ByteWidth = sizeof(LightBufferType); lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; lightBufferDesc.MiscFlags = 0; lightBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&lightBufferDesc, NULL, &m_lightBuffer); if(FAILED(result)) { return false; } return true; }
bool InitResourceDX10(void) { g_pDevice = GutGetGraphicsDeviceDX10(); ID3D10Blob *pVSCode = NULL; // 載入Vertex Shader g_pVertexShader = GutLoadVertexShaderDX10_HLSL("../../shaders/vertex_color_dx10.hlsl", "VS", "vs_4_0", &pVSCode); if ( NULL==g_pVertexShader ) return false; // 載入Pixel Shader g_pPixelShader = GutLoadPixelShaderDX10_HLSL("../../shaders/vertex_color_dx10.hlsl", "PS", "ps_4_0"); if ( NULL==g_pPixelShader ) return false; // 設定Vertex資料格式 D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 } }; if ( D3D_OK != g_pDevice->CreateInputLayout( layout, sizeof(layout)/sizeof(D3D10_INPUT_ELEMENT_DESC), pVSCode->GetBufferPointer(), pVSCode->GetBufferSize(), &g_pVertexLayout ) ) return false; SAFE_RELEASE(pVSCode); // 設定一塊可以用來放Vertex的記憶體. D3D10_BUFFER_DESC cbDesc; cbDesc.ByteWidth = sizeof(g_vertices); cbDesc.Usage = D3D10_USAGE_IMMUTABLE; cbDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; cbDesc.CPUAccessFlags = 0; cbDesc.MiscFlags = 0; // 開啟Vertex Buffer時同時把資料拷貝過去 D3D10_SUBRESOURCE_DATA sbDesc; sbDesc.pSysMem = g_vertices; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pVertexBuffer ) ) return false; // 設定一塊可以用來放Index的記憶體. cbDesc.ByteWidth = sizeof(g_indices); cbDesc.Usage = D3D10_USAGE_IMMUTABLE; cbDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; cbDesc.CPUAccessFlags = 0; cbDesc.MiscFlags = 0; // 開啟Index Buffer時同時把資料拷貝過去 sbDesc.pSysMem = g_indices; // 配置一塊可以存放Index的記憶體, 也就是Index Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pIndexBuffer ) ) return false; // 配置Shader讀取參數的記憶體空間 cbDesc.ByteWidth = sizeof(Matrix4x4); cbDesc.Usage = D3D10_USAGE_DYNAMIC; cbDesc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pConstantBuffer ) ) return false; // 計算出一個可以轉換到鏡頭座標系的矩陣 Matrix4x4 view_matrix = GutMatrixLookAtRH(g_eye, g_lookat, g_up); Matrix4x4 projection_matrix = GutMatrixPerspectiveRH_DirectX(90.0f, 1.0f, 1.0f, 100.0f); g_view_proj_matrix = view_matrix * projection_matrix; // 開?rasterizer state物件 D3D10_RASTERIZER_DESC rasterizer_state_desc; rasterizer_state_desc.FillMode = D3D10_FILL_SOLID; rasterizer_state_desc.CullMode = D3D10_CULL_BACK; rasterizer_state_desc.FrontCounterClockwise = true; rasterizer_state_desc.DepthBias = 0; rasterizer_state_desc.DepthBiasClamp = 0.0f; rasterizer_state_desc.SlopeScaledDepthBias = 0.0f; rasterizer_state_desc.DepthClipEnable = false; rasterizer_state_desc.ScissorEnable = false; rasterizer_state_desc.MultisampleEnable = false; rasterizer_state_desc.AntialiasedLineEnable = false; if ( D3D_OK != g_pDevice->CreateRasterizerState(&rasterizer_state_desc, &g_pRasterizerState) ) return false; g_pDevice->RSSetState(g_pRasterizerState); return true; }
//----------------------------------------------------------------------- void D3D10HLSLProgram::loadFromSource(void) { class HLSLIncludeHandler : public ID3D10Include { public: HLSLIncludeHandler(Resource* sourceProgram) : mProgram(sourceProgram) {} ~HLSLIncludeHandler() {} STDMETHOD(Open)(D3D10_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pByteLen ) { // find & load source code DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource( String(pFileName), mProgram->getGroup(), true, mProgram); String source = stream->getAsString(); // copy into separate c-string // Note - must NOT copy the null terminator, otherwise this will terminate // the entire program string! *pByteLen = static_cast<UINT>(source.length()); char* pChar = new char[*pByteLen]; memcpy(pChar, source.c_str(), *pByteLen); *ppData = pChar; return S_OK; } STDMETHOD(Close)(LPCVOID pData) { char* pChar = (char*)pData; delete [] pChar; return S_OK; } protected: Resource* mProgram; }; // include handler HLSLIncludeHandler includeHandler(this); ID3D10Blob * errors = 0; /*String profile; // Instruction set to be used when generating code. Possible values: "vs_4_0", "ps_4_0", or "gs_4_0". switch(mType) { case GPT_VERTEX_PROGRAM: profile = "vs_4_0"; break; case GPT_FRAGMENT_PROGRAM: profile = "ps_4_0"; break; }*/ HRESULT hr = D3DX10CompileFromMemory( mSource.c_str(), // [in] Pointer to the shader in memory. mSource.size(), // [in] Size of the shader in memory. NULL, // [in] The name of the file that contains the shader code. NULL, // [in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D10_SHADER_MACRO. If not used, set this to NULL. &includeHandler, // [in] Optional. Pointer to an ID3D10Include Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include. mEntryPoint.c_str(), // [in] Name of the shader-entrypoint function where shader execution begins. mTarget.c_str(), // [in] A string that specifies the shader model; can be any profile in shader model 2, shader model 3, or shader model 4. 0, // [in] Effect compile flags - no D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY at the first try... NULL, // [in] Effect compile flags NULL, // [in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed. &mpMicroCode, // [out] A pointer to an ID3D10Blob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information. &errors, // [out] A pointer to an ID3D10Blob Interface which contains a listing of errors and warnings that occured during compilation. These errors and warnings are identical to the the debug output from a debugger. NULL // [out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes. ); if (FAILED(hr)) // if fails - try with backwards compatibility flag { hr = D3DX10CompileFromMemory( mSource.c_str(), // [in] Pointer to the shader in memory. mSource.size(), // [in] Size of the shader in memory. NULL, // [in] The name of the file that contains the shader code. NULL, // [in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D10_SHADER_MACRO. If not used, set this to NULL. &includeHandler, // [in] Optional. Pointer to an ID3D10Include Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include. mEntryPoint.c_str(), // [in] Name of the shader-entrypoint function where shader execution begins. mTarget.c_str(), // [in] A string that specifies the shader model; can be any profile in shader model 2, shader model 3, or shader model 4. D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, // [in] Effect compile flags - D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY enables older shaders to compile to 4_0 targets NULL, // [in] Effect compile flags NULL, // [in] A pointer to a thread pump interface (see ID3DX10ThreadPump Interface). Use NULL to specify that this function should not return until it is completed. &mpMicroCode, // [out] A pointer to an ID3D10Blob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information. &errors, // [out] A pointer to an ID3D10Blob Interface which contains a listing of errors and warnings that occured during compilation. These errors and warnings are identical to the the debug output from a debugger. NULL // [out] A pointer to the return value. May be NULL. If pPump is not NULL, then pHResult must be a valid memory location until the asynchronous execution completes. ); } #if 0 // this is how you disassemble LPCSTR commentString = NULL; ID3D10Blob* pIDisassembly = NULL; char* pDisassembly = NULL; if( mpMicroCode ) { D3D10DisassembleShader( (UINT*) mpMicroCode->GetBufferPointer(), mpMicroCode->GetBufferSize(), TRUE, commentString, &pIDisassembly ); } const char* assemblyCode = static_cast<const char*>(pIDisassembly->GetBufferPointer()); #endif if (FAILED(hr)) { mErrorsInCompile = true; String message = "Cannot assemble D3D10 high-level shader " + mName + " Errors:\n" + static_cast<const char*>(errors->GetBufferPointer()); errors->Release(); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message, "D3D10HLSLProgram::loadFromSource"); } SIZE_T BytecodeLength = mpMicroCode->GetBufferSize(); // this is a temp patch for the nov 08 DX SDK #ifdef D3DX10ReflectShader hr = D3DX10ReflectShader( (void*) mpMicroCode->GetBufferPointer(), BytecodeLength, &mpIShaderReflection ); #else hr = D3D10ReflectShader( (void*) mpMicroCode->GetBufferPointer(), BytecodeLength, &mpIShaderReflection ); #endif if (!FAILED(hr)) { hr = mpIShaderReflection->GetDesc( &mShaderDesc ); if (!FAILED(hr)) { if (mShaderDesc.ConstantBuffers == 1) { mShaderReflectionConstantBuffer = mpIShaderReflection->GetConstantBufferByIndex(0); hr = mShaderReflectionConstantBuffer->GetDesc(&mConstantBufferDesc); createConstantBuffer(mConstantBufferDesc.Size); for(unsigned int i = 0; i < mConstantBufferDesc.Variables ; i++) { ID3D10ShaderReflectionVariable* varRef; varRef = mShaderReflectionConstantBuffer->GetVariableByIndex(i); D3D10_SHADER_VARIABLE_DESC shaderVerDesc; HRESULT hr = varRef->GetDesc(&shaderVerDesc); ShaderVarWithPosInBuf newVar; newVar.var = shaderVerDesc; newVar.wasInit = false; mShaderVars.push_back(newVar); } } } } switch(mType) { case GPT_VERTEX_PROGRAM: CreateVertexShader(); break; case GPT_FRAGMENT_PROGRAM: CreatePixelShader(); break; } }
bool InitResourceDX10(void) { g_pDevice = GutGetGraphicsDeviceDX10(); ID3D10Blob *pVSCode = NULL; const char *shader = "../../shaders/texture_dx10.hlsl"; // 載入Vertex Shader g_pVertexShader = GutLoadVertexShaderDX10_HLSL(shader, "VS", "vs_4_0", &pVSCode); if ( NULL==g_pVertexShader ) return false; // 載入Pixel Shader g_pPixelShader = GutLoadPixelShaderDX10_HLSL(shader, "PS", "ps_4_0"); if ( NULL==g_pPixelShader ) return false; g_pTexture0 = GutLoadTexture_DX10("../../textures/brickwall.tga"); g_pTexture1 = GutLoadTexture_DX10("../../textures/spotlight_effect.tga"); if ( g_pTexture0==NULL || g_pTexture1==NULL ) return false; // 設定Vertex資料格式 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 } }; if ( D3D_OK != g_pDevice->CreateInputLayout( layout, sizeof(layout)/sizeof(D3D10_INPUT_ELEMENT_DESC), pVSCode->GetBufferPointer(), pVSCode->GetBufferSize(), &g_pVertexLayout ) ) return false; SAFE_RELEASE(pVSCode); D3D10_BUFFER_DESC cbDesc; // vertex buffer cbDesc.ByteWidth = sizeof(Vertex_VT) * 4; cbDesc.Usage = D3D10_USAGE_DYNAMIC ; cbDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; D3D10_SUBRESOURCE_DATA subDesc; ZeroMemory(&subDesc, sizeof(subDesc)); subDesc.pSysMem = g_Quad; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &subDesc, &g_pVertexBuffer ) ) return false; subDesc.pSysMem = g_FullScreenQuad; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &subDesc, &g_pVertexBufferFullScreen ) ) return false; // 配置Shader參數的記憶體空間 cbDesc.ByteWidth = sizeof(Matrix4x4); cbDesc.Usage = D3D10_USAGE_DYNAMIC; cbDesc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pConstantBuffer ) ) return false; { // rasterizer state物件 D3D10_RASTERIZER_DESC rasterizer_state_desc; rasterizer_state_desc.FillMode = D3D10_FILL_SOLID; rasterizer_state_desc.CullMode = D3D10_CULL_NONE; rasterizer_state_desc.FrontCounterClockwise = true; rasterizer_state_desc.DepthBias = 0; rasterizer_state_desc.DepthBiasClamp = 0.0f; rasterizer_state_desc.SlopeScaledDepthBias = 0.0f; rasterizer_state_desc.DepthClipEnable = false; rasterizer_state_desc.ScissorEnable = false; rasterizer_state_desc.MultisampleEnable = false; rasterizer_state_desc.AntialiasedLineEnable = false; if ( D3D_OK != g_pDevice->CreateRasterizerState(&rasterizer_state_desc, &g_pRasterizerState) ) return false; g_pDevice->RSSetState(g_pRasterizerState); } { D3D10_BLEND_DESC blend_desc; ZeroMemory(&blend_desc, sizeof(blend_desc)); blend_desc.BlendEnable[0] = TRUE; blend_desc.SrcBlend = D3D10_BLEND_ONE; blend_desc.DestBlend = D3D10_BLEND_ONE; blend_desc.BlendOp = D3D10_BLEND_OP_ADD; blend_desc.SrcBlendAlpha = D3D10_BLEND_ONE; blend_desc.DestBlendAlpha = D3D10_BLEND_ONE; blend_desc.BlendOpAlpha = D3D10_BLEND_OP_ADD; blend_desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL; if ( D3D_OK != g_pDevice->CreateBlendState(&blend_desc, &g_pBlendState) ) return false; float dummy[4]; g_pDevice->OMSetBlendState(g_pBlendState, dummy, 0xffffffff); } { D3D10_DEPTH_STENCIL_DESC depthstencil_desc; ZeroMemory(&depthstencil_desc, sizeof(depthstencil_desc)); depthstencil_desc.DepthEnable = TRUE; depthstencil_desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL; depthstencil_desc.DepthFunc = D3D10_COMPARISON_ALWAYS; depthstencil_desc.StencilEnable = FALSE; g_pDevice->CreateDepthStencilState(&depthstencil_desc, &g_pDepthStencilState_ZDisable); } g_view_matrix = GutMatrixLookAtRH(g_eye, g_lookat, g_up); g_proj_matrix = GutMatrixOrthoRH_DirectX(g_fOrthoWidth, g_fOrthoHeight, 0.1f, 100.0f); return true; }
bool Shader::initializeShader(ID3D11Device * device, HWND hwnd, LPCSTR vsFileName, LPCSTR psFileName, LPCSTR vertexFuncName, LPCSTR pixelFuncName) { HRESULT result; ID3D10Blob * errorMessage = nullptr; ID3D10Blob * vertexShaderBuffer = nullptr; ID3D10Blob * pixelShaderBuffer = nullptr; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC maxtrixBufferDesc; // Compilo el vertex shader result = D3DX11CompileFromFile( vsFileName, NULL, NULL, vertexFuncName, "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL ); if (FAILED(result)) { if (errorMessage != nullptr) { OutputShaderErrorMessage(errorMessage, hwnd, vsFileName); } else { MessageBox(hwnd, vsFileName, "Error in Shader File", MB_OK); } return false; } // Compilo el pixel shader result = D3DX11CompileFromFile( psFileName, NULL, NULL, pixelFuncName, "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL ); if (FAILED(result)) { if (errorMessage != nullptr) { OutputShaderErrorMessage(errorMessage, hwnd, vsFileName); } else { MessageBox(hwnd, vsFileName, "Error in Shader File", MB_OK); } return false; } // creo el vertex shader buffer result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &mp_vertexShader); if (FAILED(result)) { //TODO: Informar del Error return false; } // Creo el pixel shader result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &mp_pixelShader); if (FAILED(result)) { //TODO: Informar del Error return false; } // Configuro el layaut 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); result = device->CreateInputLayout( polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &mp_layaout ); if (FAILED(result)) { //TODO: Informar del Error return false; } // Released Buffers vertexShaderBuffer->Release(); vertexShaderBuffer = nullptr; pixelShaderBuffer->Release(); pixelShaderBuffer = nullptr; // Configuro la matrix Buffer Description ZeroMemory(&maxtrixBufferDesc, sizeof(D3D11_BUFFER_DESC)); maxtrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; maxtrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); maxtrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; maxtrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; maxtrixBufferDesc.MiscFlags = 0; maxtrixBufferDesc.StructureByteStride = 0; // Creo el puntero al buffer constante result = device->CreateBuffer(&maxtrixBufferDesc, NULL, &mp_matrixBuffer); if (FAILED(result)) { //TODO: Informar del Error return false; } return true; }
void SetupTerrain() { D3D11_BUFFER_DESC vertexBufferDesc; D3D11_SUBRESOURCE_DATA vertexData; UINT vertexCount = (GRID_SIZE+1)*(GRID_SIZE+1); TerrainVertexType * vertices = (TerrainVertexType*)malloc(sizeof(TerrainVertexType)*vertexCount); float scale = TILE_BASE_SIZE / (float)(GRID_SIZE - 2* OVERLAP_WIDTH); for (int i=0;i<=GRID_SIZE;i++) { for (int j=0;j<=GRID_SIZE;j++) { float overlap = 0; if (i< OVERLAP_WIDTH) overlap+=OVERLAP_WIDTH-i; if (i >= GRID_SIZE - OVERLAP_WIDTH) overlap+=i-GRID_SIZE + OVERLAP_WIDTH; if (j< OVERLAP_WIDTH) overlap+=OVERLAP_WIDTH-j; if (j >= GRID_SIZE - OVERLAP_WIDTH) overlap+=j-GRID_SIZE + OVERLAP_WIDTH; if (OVERLAP_WIDTH != 0) overlap /= -2*OVERLAP_WIDTH; int baseIndex = (i+j*(GRID_SIZE+1)); vertices[baseIndex].position=XMFLOAT3(scale*(i-OVERLAP_WIDTH),scale*(j-OVERLAP_WIDTH),overlap*1000); } } vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC; vertexBufferDesc.ByteWidth = sizeof(TerrainVertexType) * vertexCount; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; vertexData.pSysMem = vertices; vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; dev->CreateBuffer(&vertexBufferDesc, &vertexData, &terrainVertexBuffer); free(vertices); ID3D10Blob* errorMessage = NULL; ID3D10Blob* vertexShaderBlob = NULL; D3DX11CompileFromFile(L"Terrain.hlsl", NULL, NULL, "TerrainGenerateVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBlob, &errorMessage, NULL); if (errorMessage) { OutputShaderErrorMessage(errorMessage); } dev->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), NULL, &terrainGenerateVertexShader); D3D11_INPUT_ELEMENT_DESC inputLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; UINT numElements = sizeof(inputLayout) / sizeof(inputLayout[0]); // Create the vertex input layout. dev->CreateInputLayout(inputLayout, numElements, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &terrainInputLayout); D3D11_SO_DECLARATION_ENTRY soDecl[] = { { 0, "POSITION", 0, 0, 3, 0 } , { 0, "TANGENTU", 0, 0, 3, 0 } , { 0, "TANGENTV", 0, 0, 3, 0 } , { 0, "TEXCOORDS", 0, 0, 2, 0 } }; UINT stride[1] = {11 * sizeof(float)}; // *NOT* sizeof the above array! UINT elems = sizeof(soDecl) / sizeof(D3D11_SO_DECLARATION_ENTRY); HRESULT res = dev->CreateGeometryShaderWithStreamOutput(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(),soDecl,elems,stride,1,D3D11_SO_NO_RASTERIZED_STREAM,NULL, &terrainDummyGS); vertexShaderBlob->Release(); // setup constants buffer D3D11_BUFFER_DESC matrixBufferDesc; // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(TerrainConstantsBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. dev->CreateBuffer(&matrixBufferDesc, NULL, &terrainConstantsBuffer); // Prepare Index buffer UINT * indices = (UINT*)malloc(sizeof(UINT)*GRID_SIZE*GRID_SIZE*6); for (int i=0;i<GRID_SIZE;i++) { for (int j=0;j<GRID_SIZE;j++) { int baseIndex = 6*(i+j*GRID_SIZE); indices[baseIndex]=i+j*(GRID_SIZE+1)+1; indices[baseIndex+1]=i+j*(GRID_SIZE+1); indices[baseIndex+2]=i+(j+1)*(GRID_SIZE+1); indices[baseIndex+3]=i+(j+1)*(GRID_SIZE+1); indices[baseIndex+4]=i+(j+1)*(GRID_SIZE+1)+1; indices[baseIndex+5]=i+1+j*(GRID_SIZE+1); } } // Fill in a buffer description. D3D11_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.ByteWidth = sizeof( UINT ) *GRID_SIZE*GRID_SIZE * 6; bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; // Define the resource data. D3D11_SUBRESOURCE_DATA indicesData; indicesData.pSysMem = indices; indicesData.SysMemPitch = 0; indicesData.SysMemSlicePitch = 0; dev->CreateBuffer( &bufferDesc, &indicesData, &terrainIndexBuffer ); free(indices); // setup textures // Create a texture sampler state description. D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Create the texture sampler state. dev->CreateSamplerState(&samplerDesc, &sampleStateLinear); D3DX11CreateShaderResourceViewFromFile(dev, L"textures/am_diffuse.png", NULL, NULL, &diffuseTexture, NULL); D3DX11CreateShaderResourceViewFromFile(dev, L"textures/am_specular.png", NULL, NULL, &specularTexture, NULL); D3DX11CreateShaderResourceViewFromFile(dev, L"textures/am_bump.png", NULL, NULL, &bumpTexture, NULL); D3DX11CreateShaderResourceViewFromFile(dev, L"textures/am_normal.png", NULL, NULL, &normalTexture, NULL); D3DX11CreateShaderResourceViewFromFile(dev, L"textures/am_glow.png", NULL, NULL, &glowTexture, NULL); /////////////// // setup pixel shader ID3D10Blob * pixelShaderBlob = NULL; D3DX11CompileFromFile(L"Terrain.hlsl", NULL, NULL, "TerrainPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBlob, &errorMessage, NULL); if (errorMessage) { OutputShaderErrorMessage(errorMessage); } dev->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), NULL, &terrainPixelShader); pixelShaderBlob->Release(); }
int TANGD3DShader::InitShader(TCHAR *vsFilename,TCHAR *psFilename, TANGVERTEX_TYPE vertexType) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "UserVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if(FAILED(result)) { if(errorMessage) { PrintShaderCompileError(errorMessage, vsFilename); } else { UtilTools::log("Error: %s not exist.", vsFilename); } return E_FAILED; } result = D3DX11CompileFromFile(psFilename, NULL, NULL, "UserPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if(FAILED(result)) { if(errorMessage) { PrintShaderCompileError(errorMessage, psFilename); } else { UtilTools::log("Error: %s not exist.", psFilename); } return E_FAILED; } result = m_pDevice->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if(FAILED(result)) { return E_FAILED; } result = m_pDevice->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if(FAILED(result)) { return E_FAILED; } D3D11_INPUT_ELEMENT_DESC *polygonLayout; int numElements = 0; switch (vertexType) { case E_VERTEX_POS: break; case E_VERTEX_POS_COLOR: numElements = 2; polygonLayout = (D3D11_INPUT_ELEMENT_DESC *)malloc(numElements * sizeof(D3D11_INPUT_ELEMENT_DESC)); polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "COLOR"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; break; case E_VERTEX_POS_TEXTURE: numElements = 2; polygonLayout = (D3D11_INPUT_ELEMENT_DESC *)malloc(numElements * sizeof(D3D11_INPUT_ELEMENT_DESC)); polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; result = m_pDevice->CreateSamplerState(&samplerDesc, &m_sampleState); if (FAILED(result)) { UtilTools::log("Error: CreateSamplerState failed."); vertexShaderBuffer->Release(); vertexShaderBuffer = NULL; pixelShaderBuffer->Release(); pixelShaderBuffer = NULL; return E_FAILED; } break; default: UtilTools::log("Error: TANGVERTEX_TYPE %d invalid.", vertexType); return E_FAILED; } result = m_pDevice->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); vertexShaderBuffer->Release(); vertexShaderBuffer = NULL; pixelShaderBuffer->Release(); pixelShaderBuffer = NULL; if (FAILED(result)) { return E_FAILED; } return E_SUCCESS; }
void Application::CreatePSO() { ComPtr<ID3DBlob> vertexShader, pixelShader; #ifdef _DEBUG // Enable better shader debugging with the graphics debugging tools. UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #else UINT compileFlags = 0; #endif ID3D10Blob* errorMessages; if (FAILED(D3DCompileFromFile(L"shaders.hlsl", nullptr, nullptr, "VSMain", "vs_5_0", compileFlags, 0, &vertexShader, &errorMessages))) { if (errorMessages) { std::cout << static_cast<char*>(errorMessages->GetBufferPointer()) << std::endl; errorMessages->Release(); } if (errorMessages) errorMessages->Release(); CRITICAL_ERROR("Failed to compile vertex shader."); } if (FAILED(D3DCompileFromFile(L"shaders.hlsl", nullptr, nullptr, "PSMain", "ps_5_0", compileFlags, 0, &pixelShader, &errorMessages))) { if (errorMessages) { std::cout << static_cast<char*>(errorMessages->GetBufferPointer()) << std::endl; errorMessages->Release(); } if (errorMessages) errorMessages->Release(); CRITICAL_ERROR("Failed to compile pixel shader."); } // Define the vertex input layout. D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 } }; // Describe and create the graphics pipeline state object (PSO). D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.pRootSignature = rootSignature.Get(); psoDesc.VS = { reinterpret_cast<UINT8*>(vertexShader->GetBufferPointer()), vertexShader->GetBufferSize() }; psoDesc.PS = { reinterpret_cast<UINT8*>(pixelShader->GetBufferPointer()), pixelShader->GetBufferSize() }; psoDesc.DS; psoDesc.HS; psoDesc.GS; psoDesc.StreamOutput; psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); psoDesc.SampleMask = UINT_MAX; psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); psoDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; psoDesc.DepthStencilState.DepthEnable = FALSE; psoDesc.DepthStencilState.StencilEnable = FALSE; psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) }; psoDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT; psoDesc.SampleDesc.Count = 1; psoDesc.CachedPSO; if(FAILED(device->GetD3D12Device()->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pso)))) CRITICAL_ERROR("Failed to PSO."); }
bool InitResourceDX10(void) { g_pDevice = GutGetGraphicsDeviceDX10(); ID3D10Blob *pVSCode = NULL; { const char *shader = "../../shaders/texture3D_dx10.hlsl"; // 載入Vertex Shader g_pVertexShader = GutLoadVertexShaderDX10_HLSL(shader, "VS", "vs_4_0", &pVSCode); if ( NULL==g_pVertexShader ) return false; // 載入Pixel Shader g_pPixelShader = GutLoadPixelShaderDX10_HLSL(shader, "PS", "ps_4_0"); if ( NULL==g_pPixelShader ) return false; } // 載入貼圖 g_pTexture = GutLoadVolumeTexture_DX10("../../textures/CT_256x256x256.dds"); if ( NULL==g_pTexture ) return false; // 設定Vertex資料格式 D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 } }; if ( D3D_OK != g_pDevice->CreateInputLayout( layout, sizeof(layout)/sizeof(D3D10_INPUT_ELEMENT_DESC), pVSCode->GetBufferPointer(), pVSCode->GetBufferSize(), &g_pVertexLayout ) ) return false; SAFE_RELEASE(pVSCode); D3D10_BUFFER_DESC cbDesc; D3D10_SUBRESOURCE_DATA subDesc; { // vertex buffer cbDesc.ByteWidth = sizeof(Vertex_VT) * 4; cbDesc.Usage = D3D10_USAGE_DYNAMIC ; cbDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; ZeroMemory(&subDesc, sizeof(subDesc)); subDesc.pSysMem = g_Quad; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &subDesc, &g_pVertexBuffer ) ) return false; } { // 配置Shader參數的記憶體空間 cbDesc.ByteWidth = sizeof(Matrix4x4) * 2; cbDesc.Usage = D3D10_USAGE_DYNAMIC; cbDesc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pConstantBuffer ) ) return false; } // 計算投影矩陣 g_proj_matrix = GutMatrixPerspectiveRH_DirectX(g_fFovW, 1.0f, 0.1f, 100.0f); { // rasterizer state物件 D3D10_RASTERIZER_DESC rasterizer_state_desc; rasterizer_state_desc.FillMode = D3D10_FILL_SOLID; rasterizer_state_desc.CullMode = D3D10_CULL_NONE; rasterizer_state_desc.FrontCounterClockwise = true; rasterizer_state_desc.DepthBias = 0; rasterizer_state_desc.DepthBiasClamp = 0.0f; rasterizer_state_desc.SlopeScaledDepthBias = 0.0f; rasterizer_state_desc.DepthClipEnable = false; rasterizer_state_desc.ScissorEnable = false; rasterizer_state_desc.MultisampleEnable = false; rasterizer_state_desc.AntialiasedLineEnable = false; if ( D3D_OK != g_pDevice->CreateRasterizerState(&rasterizer_state_desc, &g_pRasterizerState) ) return false; g_pDevice->RSSetState(g_pRasterizerState); } { D3D10_SAMPLER_DESC sampler_desc; ZeroMemory(&sampler_desc, sizeof(sampler_desc)); sampler_desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR; sampler_desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP; sampler_desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP; sampler_desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP; if ( D3D_OK != g_pDevice->CreateSamplerState(&sampler_desc, &g_pSamplerState) ) return false; g_pDevice->PSSetSamplers(0, 1, &g_pSamplerState); } g_view_matrix = GutMatrixLookAtRH(g_eye, g_lookat, g_up); return true; }
D3DFontShader::D3DFontShader(ID3D11Device* device, HWND hwnd, std::wstring vsFilename, std::wstring psFilename) { m_vertexShader = nullptr; m_pixelShader = nullptr; m_layout = nullptr; m_matrixBuffer = nullptr; m_sampleState = nullptr; m_pixelBuffer = nullptr; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC pixelBufferDesc; // Initialize the pointers this function will use to null. errorMessage = nullptr; vertexShaderBuffer = nullptr; pixelShaderBuffer = nullptr; // Compile the vertex shader code. if (FAILED(D3DX11CompileFromFile(vsFilename.c_str(), NULL, NULL, "FontVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL))) { // If the shader failed to compile it should have writen something to the error message. handleShaderError(errorMessage, hwnd, vsFilename); } // Compile the pixel shader code. if (FAILED(D3DX11CompileFromFile(psFilename.c_str(), NULL, NULL, "FontPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL))) { // If the shader failed to compile it should have writen something to the error message. handleShaderError(errorMessage, hwnd, psFilename); } // Create the vertex shader from the buffer. if (FAILED(device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader))) THROW_RACCOON_DX("Failed to create vertex shader") // Create the pixel shader from the buffer. if (FAILED(device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader))) THROW_RACCOON_DX("Failed to create pixel shader") // 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. if (FAILED(device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout))) THROW_RACCOON_DX("Failed to create the vertex input layout"); // Release the vertex shader buffer and pixel shader buffer since they are no longer needed. vertexShaderBuffer->Release(); pixelShaderBuffer->Release(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(RaccoonData::MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. if (FAILED(device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer))) THROW_RACCOON_DX("Failed to create shader buffer"); // Create a texture sampler state description. samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 16; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Create the texture sampler state. if (FAILED(device->CreateSamplerState(&samplerDesc, &m_sampleState))) THROW_RACCOON_DX("Failed to create sampler state"); // Setup the description of the dynamic pixel constant buffer that is in the pixel shader. pixelBufferDesc.Usage = D3D11_USAGE_DYNAMIC; pixelBufferDesc.ByteWidth = sizeof(RaccoonData::PixelBufferType); pixelBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; pixelBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; pixelBufferDesc.MiscFlags = 0; pixelBufferDesc.StructureByteStride = 0; // Create the pixel constant buffer pointer so we can access the pixel shader constant buffer from within this class. if (FAILED(device->CreateBuffer(&pixelBufferDesc, NULL, &m_pixelBuffer))) THROW_RACCOON_DX("Failed to create pixel buffer desc"); }
//the layout will need the match the VertexType in the modelclass.h file as well as the one defined in the color.vsh file bool ParticleShaderClass::InitializeShader( ID3D11Device* device, HWND hwnd, WCHAR* vshFilename, WCHAR* pshFilename ) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[3]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_SAMPLER_DESC samplerDesc; errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; result = D3DX11CompileFromFile( //compile the vertex shader code vshFilename, NULL, NULL, "ParticleVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL ); if(FAILED(result)) { if(errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vshFilename); } else { MessageBox(hwnd, vshFilename, L"Missing Shader File", MB_OK); } return false; } result = D3DX11CompileFromFile(//compile the pixel shader code pshFilename, NULL, NULL, "ParticlePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL ); if(FAILED(result)) { if(errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, pshFilename); } else { MessageBox(hwnd, pshFilename, L"Missing Shader File", MB_OK); } return false; } result = device->CreateVertexShader( //create a vertex shader from vertex buffer vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader ); if(FAILED(result)) { return false; } result = device->CreatePixelShader( //create a pixel shader from pixel buffer pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader ); if(FAILED(result)) { return false; } //now setup the layout of the data that goes into the shader, D3D11_APPEND_ALIGNED_ELEMENT figures out the spacing between the data in the buffer //this setup needs to match the vertextype structure in the modelclass and in the shader //create a three component layout for the particle shader, the third component being the individual color of each particle 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "COLOR"; polygonLayout[2].SemanticIndex = 0; polygonLayout[2].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); result = device->CreateInputLayout( //create vertex input layout polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout ); if(FAILED(result)) { return false; } //release the vertex and shader buffer vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; //needs to be dynamic since it'll be updating each frame matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); //create the constant buffer pointer so we can access the vertex shader constant buffer from within this class if(FAILED(result)) { return false; } //here are all the settings for how to sample the texture samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if(FAILED(result)) { return false; } return true; }
bool TextureShader::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_SAMPLER_DESC samplerDesc; // Initialize the pointers this function will use to null. errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; // Compile the vertex shader code. result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "TextureVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &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, vsFilename); } // If there was nothing in the error message then it simply could not find the shader file itself. else { MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK); } return false; } // Compile the pixel shader code. result = D3DX11CompileFromFile(psFilename, NULL, NULL, "TexturePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &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, psFilename); } // If there was nothing in the error message then it simply could not find the file itself. else { MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK); } return false; } // Create the vertex shader from the buffer. device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); // Create the pixel shader from the buffer. device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); // Create the vertex input layout description. // 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 = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); // Release the vertex shader buffer and pixel shader buffer since they are no longer needed. vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); // Create a texture sampler state description. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Create the texture sampler state. device->CreateSamplerState(&samplerDesc, &m_sampleState); return true; }
bool ShaderShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[3]; unsigned int numElements; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC matrixBufferDesc; D3D11_BUFFER_DESC lightBufferDesc; D3D11_BUFFER_DESC materialBufferDesc; errorMessage = 0; vertexShaderBuffer = 0; pixelShaderBuffer = 0; //shadow vertex shader result = D3DCompileFromFile(vsFilename, NULL, NULL, "vertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage); if (FAILED(result)) { //if shader failed to compile if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); } // if it couldn't find the shader and it was nothing in the error message else { MessageBox(hwnd, vsFilename, L"Missing Vertex Shader File", MB_OK); } return false; } //shadow pixel shader result = D3DCompileFromFile(psFilename, NULL, NULL, "pixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage); if (FAILED(result)) { //if shader failed to compile if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psFilename); } // if it couldn't find the shader and it was nothing in the error message else { MessageBox(hwnd, psFilename, L"Missing Pixel Shader File", MB_OK); } return false; } result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader); if (FAILED(result)) { return false; } result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader); if (FAILED(result)) { return false; } //INPUT LAYOUT: // Create the layout description for input into the vertex shader. polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_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 = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "NORMAL"; polygonLayout[2].SemanticIndex = 0; polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; //count of elements in the layout numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if (FAILED(result)) { return false; } // we no longer need the shader buffers, so release them vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; // Create a texture sampler state description. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; //Create the texture sampler state. result = device->CreateSamplerState(&samplerDesc, &m_sampleState); if (FAILED(result)) { return false; } //CONSTANT BUFFER DESCRIPTIONS: //this is the dynamic matrix constant buffer that is in the VERTEX SHADER matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; //create a pointer to constant buffer, so we can acess the vertex shader constant buffer within this class result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if (FAILED(result)) { return false; } //Setup the description of the light dynamic constant buffer that is in the pixel shader. //Note that ByteWidth always needs to be a multiple of 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail. lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC; lightBufferDesc.ByteWidth = sizeof(LightBufferType); lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; lightBufferDesc.MiscFlags = 0; lightBufferDesc.StructureByteStride = 0; //Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&lightBufferDesc, NULL, &m_lightBuffer); if (FAILED(result)) { return false; } //Setup the description of the material buffer that is in the pixel shader. //Note that ByteWidth always needs to be a multiple of 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail. materialBufferDesc.Usage = D3D11_USAGE_DYNAMIC; materialBufferDesc.ByteWidth = sizeof(MaterialBufferType); materialBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; materialBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; materialBufferDesc.MiscFlags = 0; materialBufferDesc.StructureByteStride = 0; //Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&materialBufferDesc, NULL, &m_materialBuffer); if (FAILED(result)) { return false; } return true; }