// 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; }
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); D3D10_BUFFER_DESC cbDesc; D3D10_SUBRESOURCE_DATA sbDesc; { // sun vertex buffer cbDesc.ByteWidth = sizeof(Vertex_VC) * g_iNumSphereVertices; 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_pSunVertices; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pSunVertexBuffer ) ) return false; // 開啟Vertex Buffer時同時把資料拷貝過去 sbDesc.pSysMem = g_pEarthVertices; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pEarthVertexBuffer ) ) return false; // 開啟Vertex Buffer時同時把資料拷貝過去 sbDesc.pSysMem = g_pMoonVertices; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pMoonVertexBuffer ) ) return false; } { // 設定一塊可以用來放Index的記憶體. cbDesc.ByteWidth = sizeof(unsigned short) * g_iNumSphereIndices; cbDesc.Usage = D3D10_USAGE_IMMUTABLE; cbDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; cbDesc.CPUAccessFlags = 0; cbDesc.MiscFlags = 0; // 開啟Index Buffer時同時把資料拷貝過去 sbDesc.pSysMem = g_pSphereIndices; // 配置一塊可以存放Index的記憶體, 也就是Index Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pSphereIndexBuffer ) ) 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_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); } { D3D10_QUERY_DESC desc; desc.Query = D3D10_QUERY_OCCLUSION; desc.MiscFlags = 0; g_pDevice->CreateQuery(&desc, &g_pOcclusionQuery[0]); g_pDevice->CreateQuery(&desc, &g_pOcclusionQuery[1]); } // 投影矩陣 g_proj_matrix = GutMatrixPerspectiveRH_DirectX(90.0f, 1.0f, 0.1f, 100.0f); return true; }
bool ParticleShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsfile, WCHAR* psfile) { 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 = NULL; vertexShaderBuffer = NULL; pixelShaderBuffer = NULL; result = D3DX11CompileFromFile(vsfile, NULL, NULL, "VS", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, vsfile); } else { MessageBox(hwnd, vsfile, L"MissingSahderFile", MB_OK); } return false; } result = D3DX11CompileFromFile(psfile, NULL, NULL, "PS", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pixelShaderBuffer, &errorMessage, NULL); if (FAILED(result)) { if (errorMessage) { OutputShaderErrorMessage(errorMessage, hwnd, psfile); } else { MessageBox(hwnd, psfile, L"Missing Shader File", MB_OK); } return false; } result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &_vertexShader); if (FAILED(result)) { return false; } result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &_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; 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(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &_layout); if (FAILED(result)) { return false; } vertexShaderBuffer->Release(); vertexShaderBuffer = NULL; pixelShaderBuffer->Release(); pixelShaderBuffer = NULL; 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, &_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, &_sampleState); if (FAILED(result)) { return false; } 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; }
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; }
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); }
services::Direct3D11Graphics::Direct3D11Graphics( HWND window ) : _window( window ), _factory( 0 ), _device( 0 ), _deviceContext( 0 ), _swapChain( 0 ), _renderTarget( 0 ), _currentGeometry( -1 ), _currentVertex( -1 ) { _initDeviceAndSwapChain(); _initRenderTarget(); _initViewport(); _setBlendState(); HRESULT hr = FW1CreateFactory(FW1_VERSION, &_fw1Factory); hr = _fw1Factory->CreateFontWrapper(_device, L"Arial", &_fontWrapper); // TODO: REMOVE SHADERS ID3D10Blob* vertexShader = 0; ID3D10Blob* pixelShader = 0; ID3D10Blob* geometryShader = 0; ID3D10Blob* directVertex = 0; ID3D10Blob* directPixel = 0; ID3D10Blob* errors = 0; hr = D3DCompileFromFile( L"resources\\shaders\\vertex\\testvs.hlsl", 0, 0, "VS", "vs_5_0", D3DCOMPILE_ENABLE_STRICTNESS|D3DCOMPILE_DEBUG, 0, &vertexShader, &errors ); if ( FAILED(hr) ) { int strsize = errors->GetBufferSize(); std::string str = (char*)errors->GetBufferPointer(); throw "Erreur"; } loadShader<ID3D11VertexShader>(0, vertexShader); createConstantBuffer( 0, 0, sizeof(WVPMatrix) ); hr = D3DCompileFromFile( L"resources\\shaders\\pixel\\testps.hlsl", 0, 0, "PS", "ps_5_0", D3DCOMPILE_ENABLE_STRICTNESS|D3DCOMPILE_DEBUG, 0, &pixelShader, &errors ); if ( FAILED(hr) ) { char* str = (char*)errors->GetBufferPointer(); throw "Erreur"; } loadShader<ID3D11PixelShader>(1, pixelShader); hr = D3DCompileFromFile( L"resources\\shaders\\geometry\\testgs.hlsl", 0, 0, "GS", "gs_5_0", D3DCOMPILE_ENABLE_STRICTNESS|D3DCOMPILE_DEBUG, 0, &geometryShader, &errors ); if ( FAILED(hr) ) { int strsize = errors->GetBufferSize(); std::string str = (char*)errors->GetBufferPointer(); throw "Erreur"; } loadShader<ID3D11GeometryShader>(2, geometryShader); hr = D3DCompileFromFile( L"resources\\shaders\\vertex\\direct.hlsl", 0, 0, "VS", "vs_5_0", D3DCOMPILE_ENABLE_STRICTNESS|D3DCOMPILE_DEBUG, 0, &directVertex, &errors ); if ( FAILED(hr) ) { int strsize = errors->GetBufferSize(); std::string str = (char*)errors->GetBufferPointer(); throw "Erreur"; } loadShader<ID3D11VertexShader>(3, directVertex); hr = D3DCompileFromFile( L"resources\\shaders\\pixel\\direct.hlsl", 0, 0, "PS", "ps_5_0", D3DCOMPILE_ENABLE_STRICTNESS|D3DCOMPILE_DEBUG, 0, &directPixel, &errors ); if ( FAILED(hr) ) { int strsize = errors->GetBufferSize(); std::string str = (char*)errors->GetBufferPointer(); throw "Erreur"; } loadShader<ID3D11PixelShader>(4, directPixel); };
bool iEffect::LoadFXFile( std::wstring fileName, ID3D11Device* pDevice ) { if ( mbInitialized ) { return false; } mEffectFileName = fileName; HRESULT result = S_OK; DWORD shaderFlags = 0; bool bDebugMode = false; #if defined(DEBUG) || defined(_DEBUG) bDebugMode = true; shaderFlags |= D3D10_SHADER_DEBUG; shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* pShaderBlob = 0; ID3D10Blob* pErrorBlob = 0; result = D3DX11CompileFromFile( mEffectFileName.c_str(), /* file name */ NULL, /* no defines */ NULL, /* no includes */ NULL, /* using effects framework so no entry point specified */ "fx_5_0", /* using Direct3D 11 effects.. shader version 5.0 */ shaderFlags,/* specify flags */ 0, /* advanced effect compiling options */ 0, /* thread pump... if compiling asynchronously */ &pShaderBlob, /* output: the compiled shader structure */ &pErrorBlob, /* output: errors */ NULL /* output: errors... if compiling asynchronously */ ); // failed!...? if ( FAILED( result ) ) { // check for recorded errors if ( pErrorBlob != 0 ) { if ( bDebugMode ) { std::string error = reinterpret_cast<char*>( pErrorBlob->GetBufferPointer() ); std::wstring werror = nEncoding::ASCIItoUNICODE( error ); MessageBox( NULL, werror.c_str(), L"iEffect error: couldn't load fx file", MB_OK ); } pErrorBlob->Release(); return false; } if ( bDebugMode ) { MessageBox( NULL, L"Unknown error...", L"iEffect error: couldn't load fx file", MB_OK ); } return false; } // check for warnings if ( pErrorBlob ) { if ( bDebugMode ) { std::string warning = reinterpret_cast<char*>( pErrorBlob->GetBufferPointer() ); std::wstring wWarning = nEncoding::ASCIItoUNICODE( warning ); MessageBox( NULL, wWarning.c_str(), L"iEffect : got some warnings loading fx file", MB_OK ); } pErrorBlob->Release(); } // create the effect result = D3DX11CreateEffectFromMemory( pShaderBlob->GetBufferPointer(), /* the compiled shader data */ pShaderBlob->GetBufferSize(), /* size of the compiled shader */ 0, /* any flags */ pDevice, /* the device */ &mEffect /* output: the effect */ ); if ( FAILED( result ) ) { if ( bDebugMode ) { MessageBox( NULL, L"Couldn't create the effect!", L"iEffect error", MB_OK ); } return false; } // done with mr shader blob pShaderBlob->Release(); // horray! we're initialized! mbInitialized = true; return true; }
bool D3D11EffectMaterial::LoadFromFile(const char* szFile) { ID3D10Blob* pBlob = NULL; ID3D10Blob* pErrorBlob = NULL; if( FAILED( D3DX11CompileFromFileA( szFile, NULL, NULL, NULL, "fx_5_0", D3DCOMPILE_ENABLE_STRICTNESS, NULL, NULL, &pBlob, &pErrorBlob, NULL ) ) ) { OutputDebugInfo(pErrorBlob); return false; } OutputDebugInfo(pErrorBlob); HRESULT ret = D3DX11CreateEffectFromMemory(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), 0, m_pDevice, &m_pEffect); if(FAILED(ret)) { return false; } if(m_pEffect->IsValid() == FALSE) { m_pEffect->Release(); m_pEffect = NULL; return false; } D3DX11_EFFECT_DESC desc; if(FAILED(m_pEffect->GetDesc(&desc))) { m_pEffect->Release(); m_pEffect = NULL; return false; } for(UINT i = 0; i < desc.Techniques; ++i) { ID3DX11EffectTechnique* pTech = m_pEffect->GetTechniqueByIndex(i); if(TRUE == pTech->IsValid()) { m_pTech = pTech; break; } } if(m_pTech == NULL) { m_pEffect->Release(); m_pEffect = NULL; m_pTech = NULL; return false; } D3DX11_TECHNIQUE_DESC tech; if(FAILED(m_pTech->GetDesc(&tech))) { m_pEffect->Release(); m_pEffect = NULL; m_pTech = NULL; } m_nPass = tech.Passes; m_semantics.m_pViewTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_VIEW"); m_semantics.m_pWorldTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_WORLD"); m_semantics.m_pProjTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_PROJ"); m_semantics.m_pInvViewTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_VIEW"); m_semantics.m_pInvWorldTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_WORLD"); m_semantics.m_pInvProjTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_PROJ"); m_semantics.m_pWVTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_WV"); m_semantics.m_pWVPTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_WVP"); m_semantics.m_pInvWVTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_WV"); m_semantics.m_pInvWVPTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_WVP"); m_semantics.m_pInvVPTM = (ID3DX11EffectMatrixVariable*)m_pEffect->GetVariableBySemantic("MATRIX_I_VP"); m_semantics.m_pGBuffer = (ID3DX11EffectShaderResourceVariable*)m_pEffect->GetVariableBySemantic("DR_GBUFFER"); m_semantics.m_pABuffer = (ID3DX11EffectShaderResourceVariable*)m_pEffect->GetVariableBySemantic("DR_ABUFFER"); return true; }
bool ColorShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, TCHAR* vsFilename, TCHAR* psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC matrixBufferDesc; errorMessage = nullptr; vertexShaderBuffer = nullptr; pixelShaderBuffer = nullptr; // 编译vs代码 result = D3DX11CompileFromFile(vsFilename, nullptr, nullptr, "ColorVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, nullptr, &vertexShaderBuffer, &errorMessage, nullptr); if(FAILED(result)) { // 如果vs编译失败,输出错误消息 if(errorMessage) OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); // 如果没有任何错误消息,可能是shader文件丢失 else MessageBox(hwnd, vsFilename, TEXT("Missing Shader File"), MB_OK); return false; } // 编译ps result = D3DX11CompileFromFile(psFilename, nullptr, nullptr, "ColorPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, nullptr, &pixelShaderBuffer, &errorMessage, nullptr); if(FAILED(result)) { // 如果ps编译失败,输出错误信息 if(errorMessage) OutputShaderErrorMessage(errorMessage, hwnd, psFilename); // 如果没有任何错误消息,可能是shader文件丢失 else MessageBox(hwnd, psFilename, TEXT("Missing Shader File"), MB_OK); return false; } // 从缓冲创建vs shader result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), nullptr, &m_vertexShader); if(FAILED(result)) return false; // 从缓冲创建ps shader result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), nullptr, &m_pixelShader); if(FAILED(result)) return false; // 设置数据布局layout,以便在shader中使用. // 定义要和ModelClass中的顶点结构一致 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 = "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; // 得到layout中的元素数量 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 = nullptr; pixelShaderBuffer->Release(); pixelShaderBuffer = nullptr; // 设置动态矩阵描述 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; // 创建const buffer指针,以便访问shader常量 result = device->CreateBuffer(&matrixBufferDesc, nullptr, &m_matrixBuffer); if(FAILED(result)) return false; return true; }
void CShaderCreator::FinalizeRes( TResource * pRes ) { // Компилируем шейдер -------------------------------------------------- ID3D10Blob * pByteCode = NULL; CShader * pShader = (CShader *)pRes->pResource; uint nConstBufferSize; const char * szEntry = NULL; const char * szProfile = NULL; bool bIsVertexShader = true; if ( CStr::FinishWith( pRes->sFileName.GetString(), ".vsh" ) ) { szEntry = "Ripple"; szProfile = "vs_4_0"; } else if ( CStr::FinishWith( pRes->sFileName.GetString(), ".psh" ) ) { szEntry = "main"; szProfile = "ps_4_0"; bIsVertexShader = false; } EResult rStatus = CompileShader( pRes->sFileName.GetString(), (const char *)pRes->pBuffer, szEntry, szProfile, &pByteCode ); // После компиляции исходный код уже не нужен DEL_ARRAY( pRes->pBuffer ); if ( R_OK != rStatus ) { // Компиляция провалилась pRes->eState = TResource::FAILED; return; } ID3D10ShaderReflection * pRef = NULL; HRESULT hRes; if ( bIsVertexShader ) { pShader->m_pByteCodeVS = pByteCode; // Обрабатываем переменные --------------------------------------------- hRes = D3D10ReflectShader( pByteCode->GetBufferPointer(), pByteCode->GetBufferSize(), &pRef ); if ( ( S_OK == hRes ) && ( NULL != pRef ) ) { D3D10_SHADER_DESC desc; pRef->GetDesc( &desc ); DEBUG_ASSERT( 1 == desc.ConstantBuffers ) // Перебираем каждый буффер констант for ( uint i = 0; i < desc.ConstantBuffers; ++i ) { ID3D10ShaderReflectionConstantBuffer * pCBuf = pRef->GetConstantBufferByIndex( i ); D3D10_SHADER_BUFFER_DESC bufDesc; pCBuf->GetDesc( &bufDesc ); const char * szCBName = bufDesc.Name; nConstBufferSize = bufDesc.Size; pShader->m_nUniformCount = bufDesc.Variables; pShader->m_pUniforms = NEW CShader::TUniform [ pShader->m_nUniformCount ]; // Перебираем каждую переменную в буффере for ( uint nVar = 0; nVar < bufDesc.Variables; ++nVar ) { ID3D10ShaderReflectionVariable * pVar = pCBuf->GetVariableByIndex( nVar ); D3D10_SHADER_VARIABLE_DESC varDesc; pVar->GetDesc( &varDesc ); CShader::TUniform & tUniform = pShader->m_pUniforms[ nVar ]; tUniform.sName = varDesc.Name; tUniform.nCount = varDesc.Size / sizeof( vec4 ); tUniform.nLoc = varDesc.StartOffset / sizeof( vec4 ); } } } hRes = g_pDevice->CreateVertexShader( pByteCode->GetBufferPointer(), pByteCode->GetBufferSize(), &pShader->m_pVS ); }
void PeaksAndValleys::init(int row, int column) { initMesh(row, column); //Create Effect Technique int shaderFlag = D3D10_SHADER_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG ) shaderFlag |= D3D10_SHADER_DEBUG |D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Device *device = DirectEngine::getInstance()->getDevice(); ID3D10Blob *errorBlob = nullptr; int result = D3DX10CreateEffectFromFile(L"color.fx", nullptr,nullptr, "fx_4_0", shaderFlag, 0, device, nullptr, nullptr, &_effect,&errorBlob,nullptr ); if (result < 0) { if (errorBlob) { MessageBoxA(nullptr, (char*)errorBlob->GetBufferPointer(), nullptr, 0); errorBlob->Release(); } DXTrace(__FILE__, __LINE__, result, L"D3DX10CreateEffectFromFile",true); } _effectTech = _effect->GetTechniqueByName("ColorTech"); _mvpMatrixV = _effect->GetVariableByName("g_MVPMatrix")->AsMatrix(); //Create Layout D3D10_INPUT_ELEMENT_DESC inputDesc[2]; inputDesc[0].SemanticName = "POSITION"; inputDesc[0].SemanticIndex = 0; inputDesc[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; inputDesc[0].InputSlot = 0; inputDesc[0].AlignedByteOffset = 0; inputDesc[0].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; inputDesc[0].InstanceDataStepRate = 0; inputDesc[1].SemanticName = "COLOR"; inputDesc[1].SemanticIndex = 0; inputDesc[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; inputDesc[1].InputSlot = 0; inputDesc[1].AlignedByteOffset = sizeof(float) * 3; inputDesc[1].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; inputDesc[1].InstanceDataStepRate = 0; // D3D10_PASS_DESC passDesc; _effectTech->GetPassByName("P0")->GetDesc(&passDesc); result = device->CreateInputLayout(inputDesc, 2, passDesc.pIAInputSignature,passDesc.IAInputSignatureSize,&_inputLayout); assert(result>=0); //Matrix D3DXMatrixIdentity(&_modelMatrix); D3DXMatrixIdentity(&_projMatrix); D3DXMatrixIdentity(&_viewMatrix); //Create Project Matrix auto &winSize = DirectEngine::getInstance()->getWinSize(); D3DXMatrixPerspectiveFovLH(&_projMatrix,M_PI/4,winSize.width/winSize.height,1.0f,400.0f); D3DXVECTOR3 eyePosition(0,80,-120); D3DXVECTOR3 targetPosition(0,0,0); D3DXVECTOR3 upperVec(0,1,0); D3DXMatrixLookAtLH(&_viewMatrix, &eyePosition, &targetPosition, &upperVec); }
bool ColorShaderClass::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; // 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, "ColorVertexShader", "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, "ColorPixelShader", "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; } // 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; //important 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; // 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 class. result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer); if(FAILED(result)) { return false; } return true; }
bool RectClass::Initialize(ID3D11Device* pDevice) { D3D11_BUFFER_DESC vertexBufferDesc; // 顶点缓存的描述 D3D11_BUFFER_DESC indexBufferDesc; // 顶点索引缓存的描述 D3D11_SUBRESOURCE_DATA vertexData; // 顶点需要访问的资源 D3D11_SUBRESOURCE_DATA indexData; // 顶点索引需要访问的资源 HRESULT res = S_OK; // 设置顶点缓冲描述 vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(s_RectClassVertexs); vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; // 将资源绑定到顶点,供管线访问 vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; // 指向保存顶点数据的临时缓冲. vertexData.pSysMem = s_RectClassVertexs; // 将三角形的顶点数据放入顶点缓冲中 vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; // 创建顶点缓冲. res = pDevice->CreateBuffer(&vertexBufferDesc, &vertexData, &m_pVertexBuffer); assert(SUCCEEDED(res)); // 设置顶点索引缓冲描述 indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(s_RectClassIndexs); indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; // 将资源绑定到顶点索引,供管线访问 indexBufferDesc.CPUAccessFlags = 0; indexBufferDesc.MiscFlags = 0; indexBufferDesc.StructureByteStride = 0; // 指向保存顶点数据的临时缓冲. indexData.pSysMem = s_RectClassIndexs; // 将三角形的顶点数据放入顶点缓冲中 indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; // 创建顶点缓冲. res = pDevice->CreateBuffer(&indexBufferDesc, &indexData, &m_pIndexBuffer); assert(SUCCEEDED(res)); // 初始化Shader 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_RectShaderStr, sizeof(s_RectShaderStr), NULL, NULL, NULL, "ColorVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &pVertexShaderBuffer, &pErr, NULL); assert(SUCCEEDED(res)); // 编译PS res = D3DX11CompileFromMemory((LPCSTR)s_RectShaderStr, sizeof(s_RectShaderStr), NULL, NULL, NULL, "ColorPixelShaderColor", "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 = "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; 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_pContantBuffer); assert(SUCCEEDED(res)); return true; }
bool FontShaderClass::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 constantBufferDesc; D3D11_SAMPLER_DESC samplerDesc; D3D11_BUFFER_DESC pixelBufferDesc; // 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, "FontVertexShader", "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, "FontPixelShader", "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 vertex 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; // 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 constant buffer that is in the vertex shader. constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; constantBufferDesc.ByteWidth = sizeof(ConstantBufferType); constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; constantBufferDesc.MiscFlags = 0; constantBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. result = device->CreateBuffer(&constantBufferDesc, NULL, &m_constantBuffer); if(FAILED(result)) { return false; } // 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 pixel constant buffer that is in the pixel shader. pixelBufferDesc.Usage = D3D11_USAGE_DYNAMIC; pixelBufferDesc.ByteWidth = sizeof(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. result = device->CreateBuffer(&pixelBufferDesc, NULL, &m_pixelBuffer); if(FAILED(result)) { return false; } return true; }
D3DTextureShader::D3DTextureShader(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; 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 = nullptr; vertexShaderBuffer = nullptr; pixelShaderBuffer = nullptr; // Compile the vertex shader code. if (FAILED(D3DX11CompileFromFile(vsFilename.c_str(), NULL, NULL, "TextureVertexShader", "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, "TexturePixelShader", "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"); }
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; }
void DXWindow::initPipeline() { HRESULT hr; #ifdef USE_CG // INIT CG { std::cout << "Initialize Cg-Runtime-Direct3D 11" << std::endl; //qDebug("[Cg] Initialize Cg"); // register the error handler cgSetErrorHandler(&_cgErrorHandler, NULL); // create a new Cg Context mCgContext = cgCreateContext(); HRESULT hr = cgD3D11SetDevice(mCgContext, mDevice); if (hr != S_OK) return; // Register the default state assignment for OpenGL cgD3D11RegisterStates(mCgContext); // This will allow the Cg runtime to manage texture binding cgD3D11SetManageTextureParameters(mCgContext, CG_TRUE); } // LOAD SHADER Cg { std::string sourcePtr = read("vshader.cg"); int num = sizeof(CG_VERTEX_SHADER_PROFILES) / sizeof(CG_VERTEX_SHADER_PROFILES[0]); for (int i = 0; i < num; ++i) { auto optimal = cgD3D11GetOptimalOptions(CG_VERTEX_SHADER_PROFILES[i]); mVertexShaderId = cgCreateProgram(mCgContext, CG_SOURCE, sourcePtr.c_str(), CG_VERTEX_SHADER_PROFILES[i], "main", optimal); hr = cgD3D11LoadProgram(mVertexShaderId, NULL); if (SUCCEEDED(hr)) break; } if (SUCCEEDED(hr)) { std::cout << "Loaded vertex shader!\n"; } else { std::cout << "Could not load vertex shader!\n"; exit(-1); } sourcePtr = read("fshader.cg"); num = sizeof(CG_PIXEL_SHADER_PROFILES) / sizeof(CG_PIXEL_SHADER_PROFILES[0]); for (int i = 0; i < num; ++i) { auto optimal = cgD3D11GetOptimalOptions(CG_PIXEL_SHADER_PROFILES[i]); mFragmentShaderId = cgCreateProgram(mCgContext, CG_SOURCE, sourcePtr.c_str(), CG_PIXEL_SHADER_PROFILES[i], "main", optimal); hr = cgD3D11LoadProgram(mFragmentShaderId, NULL); if (SUCCEEDED(hr)) break; } if (SUCCEEDED(hr)) { std::cout << "Loaded pixel shader!\n"; } else { std::cout << "Could not load pixel shader!\n"; exit(-1); } // get a D3D shader resource from CG shader resource ID3D10Blob* VS = cgD3D11GetCompiledProgram(mVertexShaderId); // activate the shader objects cgD3D11BindProgram(mVertexShaderId); cgD3D11BindProgram(mFragmentShaderId); // create the input layout object D3D11_INPUT_ELEMENT_DESC ied[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; hr = mDevice->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &mLayout); if (SUCCEEDED(hr)) { std::cout << "Created vertex layout for shader!\n"; } else { std::cout << "Could not create vertex layout for shader!\n"; exit(-1); } mDeviceContext->IASetInputLayout(mLayout); } // Load Shader HLSL #else { //Compile Shaders from shader file hr = D3DX11CompileFromFile("shaders.shader", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0); hr = D3DX11CompileFromFile("shaders.shader", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0); //Create the Shader Objects hr = mDevice->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS); hr = mDevice->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS); //Set Vertex and Pixel Shaders mDeviceContext->VSSetShader(VS, 0, 0); mDeviceContext->PSSetShader(PS, 0, 0); // create the input layout object D3D11_INPUT_ELEMENT_DESC ied[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; hr = mDevice->CreateInputLayout(ied, 2, VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), &mLayout); if (SUCCEEDED(hr)) { std::cout << "Created vertex layout for shader!\n"; } else { std::cout << "Could not create vertex layout for shader!\n"; exit(-1); } mDeviceContext->IASetInputLayout(mLayout); } #endif }
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; }
bool ColorShader::InitShader(ID3D11Device * device, HWND hwnd, WCHAR * vsFilename, WCHAR * psFilename) { HRESULT result; ID3D10Blob* errorMessage; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; UINT numElements; D3D11_BUFFER_DESC matrixBufferDesc; //init the pointers this function will use to null; errorMessage = nullptr; vertexShaderBuffer = nullptr; pixelShaderBuffer = nullptr; //thsi is were we compile the shader programs into buffrers //Error CODES************* //No Error Code = file not found //Otherwise print out code to error handler //************************* result = D3DCompileFromFile(vsFilename, NULL, NULL, "ColorVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &vertexShaderBuffer, &errorMessage); if (FAILED(result)) { //if the shader failed to compile it will write something to the error mesage buffer if (errorMessage) OutputShaderErrorMessage(errorMessage, hwnd, vsFilename); else MessageBoxW(hwnd, vsFilename, L"Missing Shader File", MB_OK); return false; } result = D3DCompileFromFile(psFilename, NULL, NULL, "ColorPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, &pixelShaderBuffer, &errorMessage); if (FAILED(result)) { //if the shader failed to compile it will write something to the error mesage buffer if (errorMessage) OutputShaderErrorMessage(errorMessage, hwnd, psFilename); else MessageBoxW(hwnd, psFilename, L"Missing Shader File", MB_OK); return false; } //now that we have compiled the shaers into the bufferes we can acess the code the create the shaders result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_pVertexShader); if (FAILED(result)) { return false; } //create the pixel shader from the buffer result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pPixelShader); if (FAILED(result)) { Error::WriteError("ColorShader::InitShader Error::86"); 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 = "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; //Get 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_pLayout); if (FAILED(result)) { Error::WriteError("ColorShader::InitShader Error::113"); return false; } //release the bufferes since you are done with them Memory::SafeRelease(vertexShaderBuffer); Memory::SafeRelease(pixelShaderBuffer); //Setup thet 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_pMatrixBuffer); if (FAILED(result)) { Error::WriteError("ColorShader::InitShader Error::131"); return false; } return true; }