CmD3D11HLSLProgram.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #include "CmD3D11HLSLProgram.h"
  2. #include "CmD3D11HLSLProgramRTTI.h"
  3. #include "CmRenderSystem.h"
  4. #include "CmGpuProgramManager.h"
  5. #include "CmD3D11GpuProgram.h"
  6. #include "CmHardwareBufferManager.h"
  7. #include "CmHardwareConstantBuffer.h"
  8. #include "CmD3D11RenderSystem.h"
  9. #include "CmException.h"
  10. #include "CmDebug.h"
  11. namespace CamelotEngine
  12. {
  13. D3D11HLSLProgram::D3D11HLSLProgram(const String& source, const String& entryPoint, const String& language,
  14. GpuProgramType gptype, GpuProgramProfile profile, bool isAdjacencyInfoRequired)
  15. : HighLevelGpuProgram(source, entryPoint, language, gptype, profile, isAdjacencyInfoRequired),
  16. mColumnMajorMatrices(true), mEnableBackwardsCompatibility(false)
  17. {
  18. }
  19. D3D11HLSLProgram::~D3D11HLSLProgram()
  20. {
  21. unload_internal();
  22. }
  23. void D3D11HLSLProgram::loadFromSource()
  24. {
  25. ID3DBlob* microcode = compileMicrocode();
  26. mMicrocode.resize(microcode->GetBufferSize());
  27. memcpy(&mMicrocode[0], microcode->GetBufferPointer(), microcode->GetBufferSize());
  28. populateParametersAndConstants(microcode);
  29. createConstantBuffers();
  30. mAssemblerProgram = GpuProgramManager::instance().createProgram("", "", "", mType, GPP_NONE); // We load it from microcode, so none of this matters
  31. D3D11RenderSystem* rs = static_cast<D3D11RenderSystem*>(RenderSystem::instancePtr());
  32. switch(mType)
  33. {
  34. case GPT_VERTEX_PROGRAM:
  35. {
  36. D3D11GpuVertexProgramPtr vertProgram = std::static_pointer_cast<D3D11GpuVertexProgram>(mAssemblerProgram);
  37. vertProgram->loadFromMicrocode(rs->getPrimaryDevice(), microcode);
  38. }
  39. break;
  40. case GPT_FRAGMENT_PROGRAM:
  41. {
  42. D3D11GpuFragmentProgramPtr fragProgram = std::static_pointer_cast<D3D11GpuFragmentProgram>(mAssemblerProgram);
  43. fragProgram->loadFromMicrocode(rs->getPrimaryDevice(), microcode);
  44. }
  45. break;
  46. case GPT_GEOMETRY_PROGRAM:
  47. {
  48. D3D11GpuGeometryProgramPtr geomProgram = std::static_pointer_cast<D3D11GpuGeometryProgram>(mAssemblerProgram);
  49. geomProgram->loadFromMicrocode(rs->getPrimaryDevice(), microcode);
  50. }
  51. break;
  52. case GPT_HULL_PROGRAM:
  53. {
  54. D3D11GpuHullProgramPtr hullProgram = std::static_pointer_cast<D3D11GpuHullProgram>(mAssemblerProgram);
  55. hullProgram->loadFromMicrocode(rs->getPrimaryDevice(), microcode);
  56. }
  57. break;
  58. case GPT_DOMAIN_PROGRAM:
  59. {
  60. D3D11GpuDomainProgramPtr domainProgram = std::static_pointer_cast<D3D11GpuDomainProgram>(mAssemblerProgram);
  61. domainProgram->loadFromMicrocode(rs->getPrimaryDevice(), microcode);
  62. }
  63. break;
  64. }
  65. SAFE_RELEASE(microcode);
  66. }
  67. void D3D11HLSLProgram::unload_internal()
  68. {
  69. mAssemblerProgram = nullptr;
  70. mShaderBuffers.clear();
  71. mInputParameters.clear();
  72. mOutputParameters.clear();
  73. mConstantBuffers.clear();
  74. mMicrocode.clear();
  75. }
  76. const String& D3D11HLSLProgram::getLanguage() const
  77. {
  78. static String name = "hlsl";
  79. return name;
  80. }
  81. bool D3D11HLSLProgram::isSupported() const
  82. {
  83. RenderSystem* rs = RenderSystem::instancePtr();
  84. return rs->getCapabilities()->isShaderProfileSupported(getSyntaxCode()) && HighLevelGpuProgram::isSupported();
  85. }
  86. ID3DBlob* D3D11HLSLProgram::compileMicrocode()
  87. {
  88. // TODO - Preprocessor defines aren't supported
  89. UINT compileFlags = 0;
  90. #if defined(CM_DEBUG_MODE)
  91. compileFlags |= D3DCOMPILE_DEBUG;
  92. compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  93. #endif
  94. if (mColumnMajorMatrices)
  95. compileFlags |= D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR;
  96. else
  97. compileFlags |= D3DCOMPILE_PACK_MATRIX_ROW_MAJOR;
  98. if (mEnableBackwardsCompatibility)
  99. compileFlags |= D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  100. ID3DBlob* microCode = nullptr;
  101. ID3DBlob* errors = nullptr;
  102. HRESULT hr = D3DCompile(
  103. mSource.c_str(), // [in] Pointer to the shader in memory.
  104. mSource.size(), // [in] Size of the shader in memory.
  105. nullptr, // [in] The name of the file that contains the shader code.
  106. nullptr, // [in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D_SHADER_MACRO. If not used, set this to NULL.
  107. nullptr, // [in] Optional. Pointer to an ID3DInclude Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include.
  108. mEntryPoint.c_str(),// [in] Name of the shader-entrypoint function where shader execution begins.
  109. mSyntaxCode.c_str(),// [in] A string that specifies the shader model; can be any profile in shader model 4 or higher.
  110. compileFlags, // [in] Effect compile flags - no D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY at the first try...
  111. 0, // [in] Effect compile flags
  112. &microCode, // [out] A pointer to an ID3DBlob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information.
  113. &errors // [out] A pointer to an ID3DBlob Interface which contains a listing of errors and warnings that occurred during compilation. These errors and warnings are identical to the the debug output from a debugger.
  114. );
  115. if (FAILED(hr))
  116. {
  117. String message = "Cannot assemble D3D11 high-level shader. Errors:\n" +
  118. String(static_cast<const char*>(errors->GetBufferPointer()));
  119. SAFE_RELEASE(errors);
  120. CM_EXCEPT(RenderingAPIException, message);
  121. }
  122. SAFE_RELEASE(errors);
  123. return microCode;
  124. }
  125. void D3D11HLSLProgram::populateParametersAndConstants(ID3DBlob* microcode)
  126. {
  127. assert(microcode != nullptr);
  128. mShaderBuffers.clear();
  129. mInputParameters.clear();
  130. mOutputParameters.clear();
  131. const char* commentString = nullptr;
  132. ID3DBlob* pIDisassembly = nullptr;
  133. char* pDisassembly = nullptr;
  134. HRESULT hr = D3DDisassemble((UINT*)microcode->GetBufferPointer(),
  135. microcode->GetBufferSize(), D3D_DISASM_ENABLE_COLOR_CODE, commentString, &pIDisassembly);
  136. const char* assemblyCode = static_cast<const char*>(pIDisassembly->GetBufferPointer());
  137. if (FAILED(hr))
  138. CM_EXCEPT(RenderingAPIException, "Unable to disassemble shader.");
  139. ID3D11ShaderReflection* shaderReflection;
  140. hr = D3DReflect((void*)microcode->GetBufferPointer(), microcode->GetBufferSize(),
  141. IID_ID3D11ShaderReflection, (void**)&shaderReflection);
  142. if (FAILED(hr))
  143. CM_EXCEPT(RenderingAPIException, "Cannot reflect D3D11 high-level shader.");
  144. D3D11_SHADER_DESC shaderDesc;
  145. hr = shaderReflection->GetDesc(&shaderDesc);
  146. if (FAILED(hr))
  147. CM_EXCEPT(RenderingAPIException, "Cannot reflect D3D11 high-level shader.");
  148. mInputParameters.resize(shaderDesc.InputParameters);
  149. for (UINT32 i = 0; i < shaderDesc.InputParameters; i++)
  150. shaderReflection->GetInputParameterDesc(i, &(mInputParameters[i]));
  151. mOutputParameters.resize(shaderDesc.OutputParameters);
  152. for (UINT32 i = 0; i < shaderDesc.OutputParameters; i++)
  153. shaderReflection->GetOutputParameterDesc(i, &(mOutputParameters[i]));
  154. mShaderBuffers.resize(shaderDesc.ConstantBuffers);
  155. for(UINT32 i = 0; i < shaderDesc.ConstantBuffers; i++)
  156. {
  157. ID3D11ShaderReflectionConstantBuffer* shaderReflectionConstantBuffer;
  158. shaderReflectionConstantBuffer = shaderReflection->GetConstantBufferByIndex(i);
  159. populateConstantBufferParameters(shaderReflectionConstantBuffer);
  160. }
  161. shaderReflection->Release();
  162. }
  163. void D3D11HLSLProgram::buildConstantDefinitions() const
  164. {
  165. createParameterMappingStructures(true);
  166. for(auto shaderBufferIter = mShaderBuffers.begin(); shaderBufferIter != mShaderBuffers.end(); ++shaderBufferIter)
  167. {
  168. for(size_t i = 0; i < shaderBufferIter->variables.size(); i++)
  169. {
  170. const D3D11_SHADER_VARIABLE_DESC& variableDesc = shaderBufferIter->variables[i];
  171. const D3D11_SHADER_TYPE_DESC& variableType = shaderBufferIter->variableTypes[i];
  172. String name = variableDesc.Name;
  173. if (name.at(0) == '$')
  174. name.erase(name.begin());
  175. // Also trim the '[0]' suffix if it exists, we will add our own indexing later
  176. if (StringUtil::endsWith(name, "[0]", false))
  177. name.erase(name.size() - 3);
  178. UINT32 paramIndex = (UINT32)i;
  179. // TODO - Need to add support for more types. ESPECIALLY TEXTURES & STRUCTS!
  180. if(variableType.Type == D3D_SVT_FLOAT || variableType.Type == D3D_SVT_INT || variableType.Type == D3D_SVT_BOOL || variableType.Type == D3D_SVT_SAMPLER1D ||
  181. variableType.Type == D3D_SVT_SAMPLER2D || variableType.Type == D3D_SVT_SAMPLER3D || variableType.Type == D3D_SVT_SAMPLERCUBE)
  182. {
  183. GpuConstantDefinition def;
  184. def.logicalIndex = paramIndex;
  185. // populate type, array size & element size
  186. populateParameterDefinition(variableDesc, variableType, def);
  187. if(def.isSampler())
  188. {
  189. def.physicalIndex = variableDesc.StartSampler;
  190. mSamplerLogicalToPhysical->map.insert(
  191. GpuLogicalIndexUseMap::value_type(paramIndex,
  192. GpuLogicalIndexUse(def.physicalIndex, def.arraySize, GPV_GLOBAL)));
  193. mSamplerLogicalToPhysical->bufferSize = std::max(mSamplerLogicalToPhysical->bufferSize, def.physicalIndex + def.arraySize);
  194. mConstantDefs->samplerCount = mSamplerLogicalToPhysical->bufferSize;
  195. // TODO - Add textures!
  196. CM_EXCEPT(NotImplementedException, "Add support for texture parameters!");
  197. }
  198. else
  199. {
  200. if (def.isFloat())
  201. {
  202. def.physicalIndex = variableDesc.StartOffset;
  203. mFloatLogicalToPhysical->map.insert(
  204. GpuLogicalIndexUseMap::value_type(paramIndex,
  205. GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
  206. mFloatLogicalToPhysical->bufferSize = std::max(mFloatLogicalToPhysical->bufferSize, def.physicalIndex + def.arraySize);
  207. mConstantDefs->floatBufferSize = mFloatLogicalToPhysical->bufferSize;
  208. }
  209. else
  210. {
  211. def.physicalIndex = variableDesc.StartOffset;
  212. mIntLogicalToPhysical->map.insert(
  213. GpuLogicalIndexUseMap::value_type(paramIndex,
  214. GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
  215. mIntLogicalToPhysical->bufferSize = std::max(mIntLogicalToPhysical->bufferSize, def.physicalIndex + def.arraySize);
  216. mConstantDefs->intBufferSize = mIntLogicalToPhysical->bufferSize;
  217. }
  218. }
  219. mConstantDefs->map.insert(GpuConstantDefinitionMap::value_type(name, def));
  220. // Now deal with arrays
  221. mConstantDefs->generateConstantDefinitionArrayEntries(name, def);
  222. }
  223. }
  224. }
  225. }
  226. void D3D11HLSLProgram::populateConstantBufferParameters(ID3D11ShaderReflectionConstantBuffer* bufferReflection)
  227. {
  228. D3D11_SHADER_BUFFER_DESC constantBufferDesc;
  229. HRESULT hr = bufferReflection->GetDesc(&constantBufferDesc);
  230. if (FAILED(hr))
  231. CM_EXCEPT(RenderingAPIException, "Failed to retrieve HLSL constant buffer description.");
  232. if(constantBufferDesc.Type != D3D_CBUFFER_TYPE::D3D_CT_CBUFFER && constantBufferDesc.Type != D3D_CBUFFER_TYPE::D3D_CT_TBUFFER)
  233. {
  234. LOGDBG("D3D11 HLSL parsing: Unsupported constant buffer type, skipping. Type: " + toString(constantBufferDesc.Type));
  235. return;
  236. }
  237. mShaderBuffers.push_back(D3D11_ShaderBufferDesc());
  238. D3D11_ShaderBufferDesc& newShaderBufferDesc = *mShaderBuffers.end();
  239. for(UINT32 j = 0; j < constantBufferDesc.Variables; j++)
  240. {
  241. ID3D11ShaderReflectionVariable* varRef;
  242. varRef = bufferReflection->GetVariableByIndex(j);
  243. D3D11_SHADER_VARIABLE_DESC varDesc;
  244. HRESULT hr = varRef->GetDesc(&varDesc);
  245. if (FAILED(hr))
  246. CM_EXCEPT(RenderingAPIException, "Failed to retrieve HLSL constant buffer variable description.");
  247. ID3D11ShaderReflectionType* varRefType;
  248. varRefType = varRef->GetType();
  249. D3D11_SHADER_TYPE_DESC varTypeDesc;
  250. varRefType->GetDesc(&varTypeDesc);
  251. switch(varTypeDesc.Type)
  252. {
  253. case D3D_SVT_FLOAT:
  254. case D3D_SVT_INT:
  255. case D3D_SVT_SAMPLER1D:
  256. case D3D_SVT_SAMPLER2D:
  257. case D3D_SVT_SAMPLER3D:
  258. case D3D_SVT_SAMPLERCUBE: // TODO - Need to add support for other types!
  259. newShaderBufferDesc.variables.push_back(varDesc);
  260. newShaderBufferDesc.variableTypes.push_back(varTypeDesc);
  261. default:
  262. CM_EXCEPT(RenderingAPIException, "Unsupported shader variable type!");
  263. }
  264. }
  265. }
  266. void D3D11HLSLProgram::populateParameterDefinition(const D3D11_SHADER_VARIABLE_DESC& paramDesc, const D3D11_SHADER_TYPE_DESC& paramType, GpuConstantDefinition& def) const
  267. {
  268. def.arraySize = paramType.Elements + 1;
  269. switch(paramType.Type)
  270. {
  271. case D3D_SVT_SAMPLER1D:
  272. def.constType = GCT_SAMPLER1D;
  273. def.elementSize = paramDesc.SamplerSize / def.arraySize;
  274. break;
  275. case D3D_SVT_SAMPLER2D:
  276. CM_EXCEPT(NotImplementedException, "Break here because I want to check what is the elementSize of the sampler. It has to be 1.");
  277. def.constType = GCT_SAMPLER2D;
  278. def.elementSize = paramDesc.SamplerSize / def.arraySize;
  279. break;
  280. case D3D_SVT_SAMPLER3D:
  281. def.constType = GCT_SAMPLER3D;
  282. def.elementSize = paramDesc.SamplerSize / def.arraySize;
  283. break;
  284. case D3D_SVT_SAMPLERCUBE:
  285. def.constType = GCT_SAMPLERCUBE;
  286. def.elementSize = paramDesc.SamplerSize / def.arraySize;
  287. break;
  288. case D3D_SVT_INT:
  289. switch(paramType.Columns)
  290. {
  291. case 1:
  292. def.constType = GCT_INT1;
  293. def.elementSize = paramDesc.Size / def.arraySize;
  294. break;
  295. case 2:
  296. def.constType = GCT_INT2;
  297. def.elementSize = paramDesc.Size / def.arraySize;
  298. break;
  299. case 3:
  300. def.constType = GCT_INT3;
  301. def.elementSize = paramDesc.Size / def.arraySize;
  302. break;
  303. case 4:
  304. def.constType = GCT_INT4;
  305. def.elementSize = paramDesc.Size / def.arraySize;
  306. break;
  307. } // columns
  308. break;
  309. case D3D_SVT_FLOAT:
  310. CM_EXCEPT(NotImplementedException, "Break here because I want to check if paramDesc.Size is size per element or total size of the array.");
  311. switch(paramType.Rows)
  312. {
  313. case 1:
  314. switch(paramType.Columns)
  315. {
  316. case 1:
  317. def.constType = GCT_FLOAT1;
  318. def.elementSize = paramDesc.Size / def.arraySize;
  319. break;
  320. case 2:
  321. def.constType = GCT_FLOAT2;
  322. def.elementSize = paramDesc.Size / def.arraySize;
  323. break;
  324. case 3:
  325. def.constType = GCT_FLOAT3;
  326. def.elementSize = paramDesc.Size / def.arraySize;
  327. break;
  328. case 4:
  329. def.constType = GCT_FLOAT4;
  330. def.elementSize = paramDesc.Size / def.arraySize;
  331. break;
  332. } // columns
  333. break;
  334. case 2:
  335. switch(paramType.Columns)
  336. {
  337. case 2:
  338. def.constType = GCT_MATRIX_2X2;
  339. def.elementSize = paramDesc.Size / def.arraySize;
  340. break;
  341. case 3:
  342. def.constType = GCT_MATRIX_2X3;
  343. def.elementSize = paramDesc.Size / def.arraySize;
  344. break;
  345. case 4:
  346. def.constType = GCT_MATRIX_2X4;
  347. def.elementSize = paramDesc.Size / def.arraySize;
  348. break;
  349. } // columns
  350. break;
  351. case 3:
  352. switch(paramType.Columns)
  353. {
  354. case 2:
  355. def.constType = GCT_MATRIX_3X2;
  356. def.elementSize = paramDesc.Size / def.arraySize;
  357. break;
  358. case 3:
  359. def.constType = GCT_MATRIX_3X3;
  360. def.elementSize = paramDesc.Size / def.arraySize;
  361. break;
  362. case 4:
  363. def.constType = GCT_MATRIX_3X4;
  364. def.elementSize = paramDesc.Size / def.arraySize;
  365. break;
  366. } // columns
  367. break;
  368. case 4:
  369. switch(paramType.Columns)
  370. {
  371. case 2:
  372. def.constType = GCT_MATRIX_4X2;
  373. def.elementSize = paramDesc.Size / def.arraySize;
  374. break;
  375. case 3:
  376. def.constType = GCT_MATRIX_4X3;
  377. def.elementSize = paramDesc.Size / def.arraySize;
  378. break;
  379. case 4:
  380. def.constType = GCT_MATRIX_4X4;
  381. def.elementSize = paramDesc.Size / def.arraySize;
  382. break;
  383. } // columns
  384. break;
  385. } // rows
  386. break;
  387. default:
  388. break;
  389. };
  390. }
  391. void D3D11HLSLProgram::createConstantBuffers()
  392. {
  393. mConstantBuffers.clear();
  394. for(auto shaderBufferIter = mShaderBuffers.begin(); shaderBufferIter != mShaderBuffers.end(); ++shaderBufferIter)
  395. {
  396. HardwareConstantBufferPtr constantBuffer = HardwareBufferManager::instance().createConstantBuffer(shaderBufferIter->desc.Size, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY);
  397. mConstantBuffers.push_back(constantBuffer);
  398. }
  399. }
  400. /************************************************************************/
  401. /* SERIALIZATION */
  402. /************************************************************************/
  403. RTTITypeBase* D3D11HLSLProgram::getRTTIStatic()
  404. {
  405. return D3D11HLSLProgramRTTI::instance();
  406. }
  407. RTTITypeBase* D3D11HLSLProgram::getRTTI() const
  408. {
  409. return D3D11HLSLProgram::getRTTIStatic();
  410. }
  411. }