LineRenderer::LineRenderer(ID3D11Device* device) { // create vertex buffer. uint32_t vertCount = 1000; m_vbPC = CreateVertexBuffer(device, VertexFormat::VF_PC, NULL, vertCount, D3D11_USAGE_DYNAMIC); assert(m_vbPC); // compile shaders ID3DBlob* vsBlob = CompileShaderFromResource(L"LineShader.hlsl", "VS","vs_4_0", NULL); ID3DBlob* psBlob = CompileShaderFromResource(L"LineShader.hlsl", "PS","ps_4_0", NULL); assert(vsBlob); assert(psBlob); m_vsShader = CreateVertexShader(device, vsBlob); m_psShader = CreatePixelShader(device, psBlob); assert(m_vsShader); assert(m_psShader); m_vertexLayoutPC = CreateInputLayout(device, vsBlob, VertexFormat::VF_PC); // create constant buffer. m_perframeCB = CreateConstantBuffer(device,sizeof(Matrix)); vsBlob->Release(); psBlob->Release(); }
uint Texture2DShader::Init(ID3D11Device* pDevice, GraphicSettings* settings) { uint result; // Create buffer mBuffer = new BufferClass(); if (!mBuffer) return 5010018; // Init buffer result = mBuffer->Init(pDevice, sizeof(TBuffer), D3D11_BIND_CONSTANT_BUFFER); iferr(result) return result; D3D11_INPUT_ELEMENT_DESC vertexDesc[] = { { "POSITION",0, DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; int numElements = sizeof(vertexDesc) / sizeof(vertexDesc[0]); /// Create the vertex shader and input layout result = CreateVertexShaderAndInputLayout(pDevice, &mVertexShader, L"data/shaders/TextureVertexShader.hlsl", "main", &mLayout, vertexDesc, numElements); iferr (result) return result; /// Create the pixel shader result = CreatePixelShader(pDevice, &mPixelShader, L"data/shaders/TexturePixelShader.hlsl", "main"); iferr (result) return result; return 0; }
void overlay::init_shaders() { auto device = d3d_device::instance()->raw(); com_ptr<ID3DBlob> vs_blob, ps_blob; const string & vs_code = vertex_shader_code(); const string & ps_code = pixel_shader_code(); HRESULT result = D3DCompile(vs_code.c_str(), vs_code.size(), nullptr, nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs_blob, nullptr); if (FAILED(result)) throw std::runtime_error("Error compiling vertex shader"); result = D3DCompile(ps_code.c_str(), ps_code.size(), nullptr, nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps_blob, nullptr); if (FAILED(result)) throw std::runtime_error("Error compiling pixel shader"); D3D11_INPUT_ELEMENT_DESC input_desc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; device->CreateInputLayout(input_desc, 2, vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout); device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nullptr, &vertex_shader); device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nullptr, &pixel_shader); }
AEResult SkinningMaterial::LoadContent() { AEAssert(m_GraphicDevice != nullptr); if(m_GraphicDevice == nullptr) { return AEResult::GraphicDeviceNull; } AEAssert(m_GameResourceManager != nullptr); if(m_GameResourceManager == nullptr) { return AEResult::GameResourceManagerNull; } if(m_IsReady) { return AEResult::Ok; } //////////////////////////////////// //Clean up memory CleanUp(); AEResult ret = AEResult::Ok; /*************************** *Vertex Shader ***************************/ ret = CreateVertexShader(); if(ret != AEResult::Ok) { CleanUp(); return ret; } /*************************** *Pixel Shader ***************************/ ret = CreatePixelShader(); if(ret != AEResult::Ok) { CleanUp(); return ret; } /*************************** *Finish ***************************/ m_IsReady = true; return AEResult::Ok; }
Shader* GraphicsSystem::CreatePixelShaderFromFile(CTSTR lpFileName) { XFile ShaderFile; if(!ShaderFile.Open(lpFileName, XFILE_READ|XFILE_SHARED, XFILE_OPENEXISTING)) return NULL; String strShader; ShaderFile.ReadFileToString(strShader); return CreatePixelShader(strShader, lpFileName); }
Shader::Shader(const char* vertex_path, const char* pixel_path, const char* geometry_path /*= nullptr*/) { vertex_shader = CreateVertexShader(vertex_path); pixel_shader = CreatePixelShader(pixel_path); if (geometry_path) { geometry_shader = CreateGeometryShader(geometry_path); } else { geometry_shader = nullptr; } compute_shader = nullptr; }
Shader* GraphicsSystem::CreatePixelShaderFromFile(CTSTR lpFileName) { XFile ShaderFile; String fullPathFilename; // if ((lpFileName[0] != '.' && lpFileName[0] != '/' && lpFileName[0] != '\\') && !(lpFileName[0] && lpFileName[1] == ':')) // fullPathFilename << API->GetAppPath() << L"\\" << lpFileName; // else fullPathFilename << lpFileName; ShaderFile.Open(fullPathFilename, XFILE_READ | XFILE_SHARED, XFILE_OPENEXISTING); String strShader; ShaderFile.ReadFileToString(strShader); return CreatePixelShader(strShader, lpFileName); }
//============================================================================== // Shader //------------------------------------------------------------------------------ unsigned int Shader::createPixShader(const char * file) { HRESULT hr; auto pDevice = _renderer->getDevice(); PixShader* pixelShader = new PixShader(); if(!isfile((kBaceShaderFolder + file).c_str())) { MessageBoxA(NULL,"そんなファイルネェ","error",MB_OK); App::instance().exit(); return 0; } DWORD* shader = fileread((kBaceShaderFolder + file).c_str()); // constTable取得 hr = D3DXGetShaderConstantTable(shader, &pixelShader->_constTable); if(FAILED(hr)) { MessageBoxA(NULL,"よくわからんけどエラー",("D3DXGetShaderConstantTable"),MB_OK); App::instance().exit(); SafeDeleteArray(shader); return 0; } // ピクセルシェーダ生成 hr = pDevice->CreatePixelShader(shader, &pixelShader->_shader); if(FAILED(hr)) { MessageBox(NULL,TEXT("PixelShaderFailed"),TEXT("CreatePixelShader"),MB_OK); App::instance().exit(); SafeDeleteArray(shader); return 0; } pixelShader->filename = file; // インサート _pixShaderList.push_back(pixelShader); _pixShaderMap.insert(std::pair<std::string,unsigned int>(file,_pixShaderList.size() - 1)); SafeDeleteArray(shader); return _pixShaderList.size() - 1; }
// ╔════════════════════════════════════════════════════════════════════════════════════╗ // ║ Constructor and Destructor. ║ // ╚════════════════════════════════════════════════════════════════════════════════════╝ Shader::Shader(ID3D11Device* p_device, HWND p_windowHandle) { // Set variables to initial values. m_matrixBuffer = 0; m_lightSourceBuffer = 0; m_lightBuffer = 0; m_vertexShader = 0; m_pixelShader = 0; m_layout = 0; m_samplerState = 0; m_shadowMapSamplerState = 0; m_rasterizerState = 0; // Compile and create the shaders. CreateVertexShader(p_device); CreatePixelShader(p_device); // Create the states. CreateRasterizerState(p_device); CreateSamplerStates(p_device); // Setup buffers. SetupBuffers(p_device); }
/// 生成する bool D3DShader::Create(DXGIManager *pDxgi) { if(m_pVsh)return true; auto pDevice=pDxgi->GetD3DDevice(); // vertex shader { Microsoft::WRL::ComPtr<ID3DBlob> vblob; HRESULT hr = CompileShaderFromFile(m_info.path, m_info.vs , vblob.GetAddressOf()); if (FAILED(hr)) return false; hr = pDevice->CreateVertexShader( vblob->GetBufferPointer(), vblob->GetBufferSize() , NULL, m_pVsh.ReleaseAndGetAddressOf()); if (FAILED(hr)) return false; // vertex shader reflection Microsoft::WRL::ComPtr<ID3D11ShaderReflection> pReflector; hr = D3DReflect(vblob->GetBufferPointer(), vblob->GetBufferSize() , IID_ID3D11ShaderReflection, &pReflector); if (FAILED(hr)) return false; D3D11_SHADER_DESC shaderdesc; pReflector->GetDesc(&shaderdesc); // Create InputLayout std::vector<D3D11_INPUT_ELEMENT_DESC> vbElement; for (size_t i = 0; i < shaderdesc.InputParameters; ++i){ D3D11_SIGNATURE_PARAMETER_DESC sigdesc; pReflector->GetInputParameterDesc(i, &sigdesc); auto format = GetDxgiFormat(sigdesc.ComponentType, sigdesc.Mask); D3D11_INPUT_ELEMENT_DESC eledesc = { sigdesc.SemanticName , sigdesc.SemanticIndex , format , 0 // 決め打ち , D3D11_APPEND_ALIGNED_ELEMENT // 決め打ち , D3D11_INPUT_PER_VERTEX_DATA // 決め打ち , 0 // 決め打ち }; vbElement.push_back(eledesc); } if (!vbElement.empty()){ hr = pDevice->CreateInputLayout(&vbElement[0], vbElement.size(), vblob->GetBufferPointer(), vblob->GetBufferSize(), &m_pInputLayout); if (FAILED(hr)) return false; } } // pixel shader { Microsoft::WRL::ComPtr<ID3DBlob> pblob; auto hr = CompileShaderFromFile(m_info.path, m_info.ps , pblob.GetAddressOf()); if (FAILED(hr)) return false; hr = pDevice->CreatePixelShader( pblob->GetBufferPointer(), pblob->GetBufferSize() , NULL, m_pPsh.ReleaseAndGetAddressOf()); if (FAILED(hr)) return false; } 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; } }