shaderc_hlsl.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /*
  2. * Copyright 2011-2022 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include "shaderc.h"
  6. #if SHADERC_CONFIG_HLSL
  7. #if defined(__MINGW32__)
  8. # define __REQUIRED_RPCNDR_H_VERSION__ 475
  9. # define __in
  10. # define __out
  11. #endif // defined(__MINGW32__)
  12. #define COM_NO_WINDOWS_H
  13. #include <d3dcompiler.h>
  14. #include <d3d11shader.h>
  15. #include <bx/os.h>
  16. #ifndef D3D_SVF_USED
  17. # define D3D_SVF_USED 2
  18. #endif // D3D_SVF_USED
  19. namespace bgfx { namespace hlsl
  20. {
  21. typedef HRESULT(WINAPI* PFN_D3D_COMPILE)(_In_reads_bytes_(SrcDataSize) LPCVOID pSrcData
  22. , _In_ SIZE_T SrcDataSize
  23. , _In_opt_ LPCSTR pSourceName
  24. , _In_reads_opt_(_Inexpressible_(pDefines->Name != NULL) ) CONST D3D_SHADER_MACRO* pDefines
  25. , _In_opt_ ID3DInclude* pInclude
  26. , _In_opt_ LPCSTR pEntrypoint
  27. , _In_ LPCSTR pTarget
  28. , _In_ UINT Flags1
  29. , _In_ UINT Flags2
  30. , _Out_ ID3DBlob** ppCode
  31. , _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorMsgs
  32. );
  33. typedef HRESULT(WINAPI* PFN_D3D_DISASSEMBLE)(_In_reads_bytes_(SrcDataSize) LPCVOID pSrcData
  34. , _In_ SIZE_T SrcDataSize
  35. , _In_ UINT Flags
  36. , _In_opt_ LPCSTR szComments
  37. , _Out_ ID3DBlob** ppDisassembly
  38. );
  39. typedef HRESULT(WINAPI* PFN_D3D_REFLECT)(_In_reads_bytes_(SrcDataSize) LPCVOID pSrcData
  40. , _In_ SIZE_T SrcDataSize
  41. , _In_ REFIID pInterface
  42. , _Out_ void** ppReflector
  43. );
  44. typedef HRESULT(WINAPI* PFN_D3D_STRIP_SHADER)(_In_reads_bytes_(BytecodeLength) LPCVOID pShaderBytecode
  45. , _In_ SIZE_T BytecodeLength
  46. , _In_ UINT uStripFlags
  47. , _Out_ ID3DBlob** ppStrippedBlob
  48. );
  49. PFN_D3D_COMPILE D3DCompile;
  50. PFN_D3D_DISASSEMBLE D3DDisassemble;
  51. PFN_D3D_REFLECT D3DReflect;
  52. PFN_D3D_STRIP_SHADER D3DStripShader;
  53. struct D3DCompiler
  54. {
  55. const char* fileName;
  56. const GUID IID_ID3D11ShaderReflection;
  57. };
  58. static const D3DCompiler s_d3dcompiler[] =
  59. { // BK - the only different method in interface is GetRequiresFlags at the end
  60. // of IID_ID3D11ShaderReflection47 (which is not used anyway).
  61. { "D3DCompiler_47.dll", { 0x8d536ca1, 0x0cca, 0x4956, { 0xa8, 0x37, 0x78, 0x69, 0x63, 0x75, 0x55, 0x84 } } },
  62. { "D3DCompiler_46.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  63. { "D3DCompiler_45.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  64. { "D3DCompiler_44.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  65. { "D3DCompiler_43.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  66. };
  67. static const D3DCompiler* s_compiler;
  68. static void* s_d3dcompilerdll;
  69. const D3DCompiler* load()
  70. {
  71. for (uint32_t ii = 0; ii < BX_COUNTOF(s_d3dcompiler); ++ii)
  72. {
  73. const D3DCompiler* compiler = &s_d3dcompiler[ii];
  74. s_d3dcompilerdll = bx::dlopen(compiler->fileName);
  75. if (NULL == s_d3dcompilerdll)
  76. {
  77. continue;
  78. }
  79. D3DCompile = (PFN_D3D_COMPILE )bx::dlsym(s_d3dcompilerdll, "D3DCompile");
  80. D3DDisassemble = (PFN_D3D_DISASSEMBLE )bx::dlsym(s_d3dcompilerdll, "D3DDisassemble");
  81. D3DReflect = (PFN_D3D_REFLECT )bx::dlsym(s_d3dcompilerdll, "D3DReflect");
  82. D3DStripShader = (PFN_D3D_STRIP_SHADER)bx::dlsym(s_d3dcompilerdll, "D3DStripShader");
  83. if (NULL == D3DCompile
  84. || NULL == D3DDisassemble
  85. || NULL == D3DReflect
  86. || NULL == D3DStripShader)
  87. {
  88. bx::dlclose(s_d3dcompilerdll);
  89. continue;
  90. }
  91. if (g_verbose)
  92. {
  93. char filePath[bx::kMaxFilePath];
  94. GetModuleFileNameA( (HMODULE)s_d3dcompilerdll, filePath, sizeof(filePath) );
  95. BX_TRACE("Loaded %s compiler (%s).", compiler->fileName, filePath);
  96. }
  97. return compiler;
  98. }
  99. bx::printf("Error: Unable to open D3DCompiler_*.dll shader compiler.\n");
  100. return NULL;
  101. }
  102. void unload()
  103. {
  104. bx::dlclose(s_d3dcompilerdll);
  105. }
  106. struct CTHeader
  107. {
  108. uint32_t Size;
  109. uint32_t Creator;
  110. uint32_t Version;
  111. uint32_t Constants;
  112. uint32_t ConstantInfo;
  113. uint32_t Flags;
  114. uint32_t Target;
  115. };
  116. struct CTInfo
  117. {
  118. uint32_t Name;
  119. uint16_t RegisterSet;
  120. uint16_t RegisterIndex;
  121. uint16_t RegisterCount;
  122. uint16_t Reserved;
  123. uint32_t TypeInfo;
  124. uint32_t DefaultValue;
  125. };
  126. struct CTType
  127. {
  128. uint16_t Class;
  129. uint16_t Type;
  130. uint16_t Rows;
  131. uint16_t Columns;
  132. uint16_t Elements;
  133. uint16_t StructMembers;
  134. uint32_t StructMemberInfo;
  135. };
  136. struct RemapInputSemantic
  137. {
  138. bgfx::Attrib::Enum m_attr;
  139. const char* m_name;
  140. uint8_t m_index;
  141. };
  142. static const RemapInputSemantic s_remapInputSemantic[bgfx::Attrib::Count + 1] =
  143. {
  144. { bgfx::Attrib::Position, "POSITION", 0 },
  145. { bgfx::Attrib::Normal, "NORMAL", 0 },
  146. { bgfx::Attrib::Tangent, "TANGENT", 0 },
  147. { bgfx::Attrib::Bitangent, "BITANGENT", 0 },
  148. { bgfx::Attrib::Color0, "COLOR", 0 },
  149. { bgfx::Attrib::Color1, "COLOR", 1 },
  150. { bgfx::Attrib::Color2, "COLOR", 2 },
  151. { bgfx::Attrib::Color3, "COLOR", 3 },
  152. { bgfx::Attrib::Indices, "BLENDINDICES", 0 },
  153. { bgfx::Attrib::Weight, "BLENDWEIGHT", 0 },
  154. { bgfx::Attrib::TexCoord0, "TEXCOORD", 0 },
  155. { bgfx::Attrib::TexCoord1, "TEXCOORD", 1 },
  156. { bgfx::Attrib::TexCoord2, "TEXCOORD", 2 },
  157. { bgfx::Attrib::TexCoord3, "TEXCOORD", 3 },
  158. { bgfx::Attrib::TexCoord4, "TEXCOORD", 4 },
  159. { bgfx::Attrib::TexCoord5, "TEXCOORD", 5 },
  160. { bgfx::Attrib::TexCoord6, "TEXCOORD", 6 },
  161. { bgfx::Attrib::TexCoord7, "TEXCOORD", 7 },
  162. { bgfx::Attrib::Count, "", 0 },
  163. };
  164. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  165. {
  166. for (uint32_t ii = 0; ii < bgfx::Attrib::Count; ++ii)
  167. {
  168. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  169. if (0 == bx::strCmp(ris.m_name, _name)
  170. && ris.m_index == _index)
  171. {
  172. return ris;
  173. }
  174. }
  175. return s_remapInputSemantic[bgfx::Attrib::Count];
  176. }
  177. struct UniformRemap
  178. {
  179. UniformType::Enum id;
  180. D3D_SHADER_VARIABLE_CLASS paramClass;
  181. D3D_SHADER_VARIABLE_TYPE paramType;
  182. uint8_t columns;
  183. uint8_t rows;
  184. };
  185. static const UniformRemap s_uniformRemap[] =
  186. {
  187. { UniformType::Sampler, D3D_SVC_SCALAR, D3D_SVT_INT, 0, 0 },
  188. { UniformType::Vec4, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  189. { UniformType::Mat3, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 3, 3 },
  190. { UniformType::Mat4, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 4, 4 },
  191. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLER, 0, 0 },
  192. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLER2D, 0, 0 },
  193. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLER3D, 0, 0 },
  194. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLERCUBE, 0, 0 },
  195. };
  196. UniformType::Enum findUniformType(const D3D11_SHADER_TYPE_DESC& constDesc)
  197. {
  198. for (uint32_t ii = 0; ii < BX_COUNTOF(s_uniformRemap); ++ii)
  199. {
  200. const UniformRemap& remap = s_uniformRemap[ii];
  201. if (remap.paramClass == constDesc.Class
  202. && remap.paramType == constDesc.Type)
  203. {
  204. if (D3D_SVC_MATRIX_COLUMNS != constDesc.Class)
  205. {
  206. return remap.id;
  207. }
  208. if (remap.columns == constDesc.Columns
  209. && remap.rows == constDesc.Rows)
  210. {
  211. return remap.id;
  212. }
  213. }
  214. }
  215. return UniformType::Count;
  216. }
  217. static uint32_t s_optimizationLevelD3D11[4] =
  218. {
  219. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  220. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  221. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  222. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  223. };
  224. typedef std::vector<std::string> UniformNameList;
  225. static bool isSampler(D3D_SHADER_VARIABLE_TYPE _svt)
  226. {
  227. switch (_svt)
  228. {
  229. case D3D_SVT_SAMPLER:
  230. case D3D_SVT_SAMPLER1D:
  231. case D3D_SVT_SAMPLER2D:
  232. case D3D_SVT_SAMPLER3D:
  233. case D3D_SVT_SAMPLERCUBE:
  234. return true;
  235. default:
  236. break;
  237. }
  238. return false;
  239. }
  240. bool getReflectionDataD3D9(ID3DBlob* _code, UniformArray& _uniforms)
  241. {
  242. // see reference for magic values: https://msdn.microsoft.com/en-us/library/ff552891(VS.85).aspx
  243. const uint32_t D3DSIO_COMMENT = 0x0000FFFE;
  244. const uint32_t D3DSIO_END = 0x0000FFFF;
  245. const uint32_t D3DSI_OPCODE_MASK = 0x0000FFFF;
  246. const uint32_t D3DSI_COMMENTSIZE_MASK = 0x7FFF0000;
  247. const uint32_t CTAB_CONSTANT = MAKEFOURCC('C', 'T', 'A', 'B');
  248. // parse the shader blob for the constant table
  249. const size_t codeSize = _code->GetBufferSize();
  250. const uint32_t* ptr = (const uint32_t*)_code->GetBufferPointer();
  251. const uint32_t* end = (const uint32_t*)( (const uint8_t*)ptr + codeSize);
  252. const CTHeader* header = NULL;
  253. ptr++; // first byte is shader type / version; skip it since we already know
  254. while (ptr < end && *ptr != D3DSIO_END)
  255. {
  256. uint32_t cur = *ptr++;
  257. if ( (cur & D3DSI_OPCODE_MASK) != D3DSIO_COMMENT)
  258. {
  259. continue;
  260. }
  261. // try to find CTAB comment block
  262. uint32_t commentSize = (cur & D3DSI_COMMENTSIZE_MASK) >> 16;
  263. uint32_t fourcc = *ptr;
  264. if (fourcc == CTAB_CONSTANT)
  265. {
  266. // found the constant table data
  267. header = (const CTHeader*)(ptr + 1);
  268. uint32_t tableSize = (commentSize - 1) * 4;
  269. if (tableSize < sizeof(CTHeader) || header->Size != sizeof(CTHeader) )
  270. {
  271. bx::printf("Error: Invalid constant table data\n");
  272. return false;
  273. }
  274. break;
  275. }
  276. // this is a different kind of comment section, so skip over it
  277. ptr += commentSize - 1;
  278. }
  279. if (!header)
  280. {
  281. bx::printf("Error: Could not find constant table data\n");
  282. return false;
  283. }
  284. const uint8_t* headerBytePtr = (const uint8_t*)header;
  285. const char* creator = (const char*)(headerBytePtr + header->Creator);
  286. BX_UNUSED(creator);
  287. BX_TRACE("Creator: %s 0x%08x", creator, header->Version);
  288. BX_TRACE("Num constants: %d", header->Constants);
  289. BX_TRACE("# cl ty RxC S By Name");
  290. const CTInfo* ctInfoArray = (const CTInfo*)(headerBytePtr + header->ConstantInfo);
  291. for (uint32_t ii = 0; ii < header->Constants; ++ii)
  292. {
  293. const CTInfo& ctInfo = ctInfoArray[ii];
  294. const CTType& ctType = *(const CTType*)(headerBytePtr + ctInfo.TypeInfo);
  295. const char* name = (const char*)(headerBytePtr + ctInfo.Name);
  296. BX_TRACE("%3d %2d %2d [%dx%d] %d %s[%d] c%d (%d)"
  297. , ii
  298. , ctType.Class
  299. , ctType.Type
  300. , ctType.Rows
  301. , ctType.Columns
  302. , ctType.StructMembers
  303. , name
  304. , ctType.Elements
  305. , ctInfo.RegisterIndex
  306. , ctInfo.RegisterCount
  307. );
  308. D3D11_SHADER_TYPE_DESC desc;
  309. desc.Class = (D3D_SHADER_VARIABLE_CLASS)ctType.Class;
  310. desc.Type = (D3D_SHADER_VARIABLE_TYPE)ctType.Type;
  311. desc.Rows = ctType.Rows;
  312. desc.Columns = ctType.Columns;
  313. UniformType::Enum type = findUniformType(desc);
  314. if (UniformType::Count != type)
  315. {
  316. Uniform un;
  317. un.name = '$' == name[0] ? name + 1 : name;
  318. un.type = isSampler(desc.Type)
  319. ? UniformType::Enum(kUniformSamplerBit | type)
  320. : type
  321. ;
  322. un.num = (uint8_t)ctType.Elements;
  323. un.regIndex = ctInfo.RegisterIndex;
  324. un.regCount = ctInfo.RegisterCount;
  325. _uniforms.push_back(un);
  326. }
  327. }
  328. return true;
  329. }
  330. bool getReflectionDataD3D11(ID3DBlob* _code, bool _vshader, UniformArray& _uniforms, uint8_t& _numAttrs, uint16_t* _attrs, uint16_t& _size, UniformNameList& unusedUniforms)
  331. {
  332. ID3D11ShaderReflection* reflect = NULL;
  333. HRESULT hr = D3DReflect(_code->GetBufferPointer()
  334. , _code->GetBufferSize()
  335. , s_compiler->IID_ID3D11ShaderReflection
  336. , (void**)&reflect
  337. );
  338. if (FAILED(hr) )
  339. {
  340. bx::printf("Error: D3DReflect failed 0x%08x\n", (uint32_t)hr);
  341. return false;
  342. }
  343. D3D11_SHADER_DESC desc;
  344. hr = reflect->GetDesc(&desc);
  345. if (FAILED(hr) )
  346. {
  347. bx::printf("Error: ID3D11ShaderReflection::GetDesc failed 0x%08x\n", (uint32_t)hr);
  348. return false;
  349. }
  350. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  351. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  352. BX_TRACE("Input:");
  353. if (_vshader) // Only care about input semantic on vertex shaders
  354. {
  355. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  356. {
  357. D3D11_SIGNATURE_PARAMETER_DESC spd;
  358. reflect->GetInputParameterDesc(ii, &spd);
  359. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  360. , ii
  361. , spd.SemanticName
  362. , spd.SemanticIndex
  363. , spd.SystemValueType
  364. , spd.ComponentType
  365. , spd.Mask
  366. , spd.Register
  367. );
  368. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, uint8_t(spd.SemanticIndex) );
  369. if (ris.m_attr != bgfx::Attrib::Count)
  370. {
  371. _attrs[_numAttrs] = bgfx::attribToId(ris.m_attr);
  372. ++_numAttrs;
  373. }
  374. }
  375. }
  376. BX_TRACE("Output:");
  377. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  378. {
  379. D3D11_SIGNATURE_PARAMETER_DESC spd;
  380. reflect->GetOutputParameterDesc(ii, &spd);
  381. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  382. }
  383. for (uint32_t ii = 0, num = bx::uint32_min(1, desc.ConstantBuffers); ii < num; ++ii)
  384. {
  385. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  386. D3D11_SHADER_BUFFER_DESC bufferDesc;
  387. hr = cbuffer->GetDesc(&bufferDesc);
  388. _size = (uint16_t)bufferDesc.Size;
  389. if (SUCCEEDED(hr) )
  390. {
  391. BX_TRACE("%s, %d, vars %d, size %d"
  392. , bufferDesc.Name
  393. , bufferDesc.Type
  394. , bufferDesc.Variables
  395. , bufferDesc.Size
  396. );
  397. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  398. {
  399. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  400. ID3D11ShaderReflectionType* type = var->GetType();
  401. D3D11_SHADER_VARIABLE_DESC varDesc;
  402. hr = var->GetDesc(&varDesc);
  403. if (SUCCEEDED(hr) )
  404. {
  405. D3D11_SHADER_TYPE_DESC constDesc;
  406. hr = type->GetDesc(&constDesc);
  407. if (SUCCEEDED(hr) )
  408. {
  409. UniformType::Enum uniformType = findUniformType(constDesc);
  410. if (UniformType::Count != uniformType
  411. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  412. {
  413. Uniform un;
  414. un.name = varDesc.Name;
  415. un.type = uniformType;
  416. un.num = uint8_t(constDesc.Elements);
  417. un.regIndex = uint16_t(varDesc.StartOffset);
  418. un.regCount = uint16_t(bx::alignUp(varDesc.Size, 16) / 16);
  419. _uniforms.push_back(un);
  420. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d (used)"
  421. , varDesc.Name
  422. , varDesc.StartOffset
  423. , varDesc.Size
  424. , varDesc.uFlags
  425. , uniformType
  426. );
  427. }
  428. else
  429. {
  430. if (0 == (varDesc.uFlags & D3D_SVF_USED) )
  431. {
  432. unusedUniforms.push_back(varDesc.Name);
  433. }
  434. BX_TRACE("\t%s, unknown type", varDesc.Name);
  435. }
  436. }
  437. }
  438. }
  439. }
  440. }
  441. BX_TRACE("Bound:");
  442. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  443. {
  444. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  445. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  446. if (SUCCEEDED(hr) )
  447. {
  448. if (D3D_SIT_SAMPLER == bindDesc.Type || D3D_SIT_TEXTURE == bindDesc.Type)
  449. {
  450. BX_TRACE("\t%s, %d, %d, %d"
  451. , bindDesc.Name
  452. , bindDesc.Type
  453. , bindDesc.BindPoint
  454. , bindDesc.BindCount
  455. );
  456. bx::StringView end = bx::strFind(bindDesc.Name, "Sampler");
  457. if (end.isEmpty())
  458. end = bx::strFind(bindDesc.Name, "Texture");
  459. if (!end.isEmpty())
  460. {
  461. Uniform un;
  462. un.name.assign(bindDesc.Name, (end.getPtr() - bindDesc.Name) );
  463. un.type = UniformType::Enum(kUniformSamplerBit | UniformType::Sampler);
  464. un.num = 1;
  465. un.regIndex = uint16_t(bindDesc.BindPoint);
  466. un.regCount = uint16_t(bindDesc.BindCount);
  467. _uniforms.push_back(un);
  468. }
  469. }
  470. else
  471. {
  472. BX_TRACE("\t%s, unknown bind data", bindDesc.Name);
  473. }
  474. }
  475. }
  476. if (NULL != reflect)
  477. {
  478. reflect->Release();
  479. }
  480. return true;
  481. }
  482. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  483. {
  484. const char* profile = _options.profile.c_str();
  485. if (profile[0] == '\0')
  486. {
  487. bx::printf("Error: Shader profile must be specified.\n");
  488. return false;
  489. }
  490. s_compiler = load();
  491. bool result = false;
  492. bool debug = _options.debugInformation;
  493. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  494. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  495. flags |= _options.avoidFlowControl ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  496. flags |= _options.noPreshader ? D3DCOMPILE_NO_PRESHADER : 0;
  497. flags |= _options.partialPrecision ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  498. flags |= _options.preferFlowControl ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  499. flags |= _options.backwardsCompatibility ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  500. bool werror = _options.warningsAreErrors;
  501. if (werror)
  502. {
  503. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  504. }
  505. if (_options.optimize )
  506. {
  507. uint32_t optimization = bx::uint32_min(_options.optimizationLevel, BX_COUNTOF(s_optimizationLevelD3D11) - 1);
  508. flags |= s_optimizationLevelD3D11[optimization];
  509. }
  510. else
  511. {
  512. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  513. }
  514. BX_TRACE("Profile: %s", profile);
  515. BX_TRACE("Flags: 0x%08x", flags);
  516. ID3DBlob* code;
  517. ID3DBlob* errorMsg;
  518. // Output preprocessed shader so that HLSL can be debugged via GPA
  519. // or PIX. Compiling through memory won't embed preprocessed shader
  520. // file path.
  521. std::string hlslfp;
  522. if (debug)
  523. {
  524. hlslfp = _options.outputFilePath + ".hlsl";
  525. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  526. }
  527. bx::ErrorAssert err;
  528. HRESULT hr = D3DCompile(_code.c_str()
  529. , _code.size()
  530. , hlslfp.c_str()
  531. , NULL
  532. , NULL
  533. , "main"
  534. , profile
  535. , flags
  536. , 0
  537. , &code
  538. , &errorMsg
  539. );
  540. if (FAILED(hr)
  541. || (werror && NULL != errorMsg) )
  542. {
  543. const char* log = (char*)errorMsg->GetBufferPointer();
  544. int32_t line = 0;
  545. int32_t column = 0;
  546. int32_t start = 0;
  547. int32_t end = INT32_MAX;
  548. if (!hlslfp.empty())
  549. {
  550. bx::StringView logfp = bx::strFind(log, hlslfp.c_str() );
  551. if (!logfp.isEmpty() )
  552. {
  553. log = logfp.getPtr() + hlslfp.length();
  554. }
  555. }
  556. bool found = false
  557. || 2 == sscanf(log, "(%u,%u", &line, &column)
  558. || 2 == sscanf(log, " :%u:%u: ", &line, &column)
  559. ;
  560. if (found
  561. && 0 != line)
  562. {
  563. start = bx::uint32_imax(1, line - 10);
  564. end = start + 20;
  565. }
  566. printCode(_code.c_str(), line, start, end, column);
  567. bx::printf("Error: D3DCompile failed 0x%08x %s\n", (uint32_t)hr, log);
  568. errorMsg->Release();
  569. return false;
  570. }
  571. UniformArray uniforms;
  572. uint8_t numAttrs = 0;
  573. uint16_t attrs[bgfx::Attrib::Count];
  574. uint16_t size = 0;
  575. if (_version < 400)
  576. {
  577. if (!getReflectionDataD3D9(code, uniforms) )
  578. {
  579. bx::printf("Error: Unable to get D3D9 reflection data.\n");
  580. goto error;
  581. }
  582. }
  583. else
  584. {
  585. UniformNameList unusedUniforms;
  586. if (!getReflectionDataD3D11(code, profile[0] == 'v', uniforms, numAttrs, attrs, size, unusedUniforms) )
  587. {
  588. bx::printf("Error: Unable to get D3D11 reflection data.\n");
  589. goto error;
  590. }
  591. if (_firstPass
  592. && unusedUniforms.size() > 0)
  593. {
  594. // first time through, we just find unused uniforms and get rid of them
  595. std::string output;
  596. bx::LineReader reader(_code.c_str() );
  597. while (!reader.isDone() )
  598. {
  599. bx::StringView strLine = reader.next();
  600. bool found = false;
  601. for (UniformNameList::iterator it = unusedUniforms.begin(), itEnd = unusedUniforms.end(); it != itEnd; ++it)
  602. {
  603. bx::StringView str = strFind(strLine, "uniform ");
  604. if (str.isEmpty() )
  605. {
  606. continue;
  607. }
  608. // matching lines like: uniform u_name;
  609. // we want to replace "uniform" with "static" so that it's no longer
  610. // included in the uniform blob that the application must upload
  611. // we can't just remove them, because unused functions might still reference
  612. // them and cause a compile error when they're gone
  613. if (!bx::findIdentifierMatch(strLine, it->c_str() ).isEmpty() )
  614. {
  615. output.append(strLine.getPtr(), str.getPtr() );
  616. output += "static ";
  617. output.append(str.getTerm(), strLine.getTerm() );
  618. output += "\n";
  619. found = true;
  620. unusedUniforms.erase(it);
  621. break;
  622. }
  623. }
  624. if (!found)
  625. {
  626. output.append(strLine.getPtr(), strLine.getTerm() );
  627. output += "\n";
  628. }
  629. }
  630. // recompile with the unused uniforms converted to statics
  631. return compile(_options, _version, output.c_str(), _writer, false);
  632. }
  633. }
  634. {
  635. uint16_t count = (uint16_t)uniforms.size();
  636. bx::write(_writer, count, &err);
  637. uint32_t fragmentBit = profile[0] == 'p' ? kUniformFragmentBit : 0;
  638. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  639. {
  640. const Uniform& un = *it;
  641. uint8_t nameSize = (uint8_t)un.name.size();
  642. bx::write(_writer, nameSize, &err);
  643. bx::write(_writer, un.name.c_str(), nameSize, &err);
  644. uint8_t type = uint8_t(un.type | fragmentBit);
  645. bx::write(_writer, type, &err);
  646. bx::write(_writer, un.num, &err);
  647. bx::write(_writer, un.regIndex, &err);
  648. bx::write(_writer, un.regCount, &err);
  649. bx::write(_writer, un.texComponent, &err);
  650. bx::write(_writer, un.texDimension, &err);
  651. bx::write(_writer, un.texFormat, &err);
  652. BX_TRACE("%s, %s, %d, %d, %d"
  653. , un.name.c_str()
  654. , getUniformTypeName(UniformType::Enum(un.type & ~kUniformMask))
  655. , un.num
  656. , un.regIndex
  657. , un.regCount
  658. );
  659. }
  660. }
  661. {
  662. ID3DBlob* stripped;
  663. hr = D3DStripShader(code->GetBufferPointer()
  664. , code->GetBufferSize()
  665. , D3DCOMPILER_STRIP_REFLECTION_DATA
  666. | D3DCOMPILER_STRIP_TEST_BLOBS
  667. , &stripped
  668. );
  669. if (SUCCEEDED(hr) )
  670. {
  671. code->Release();
  672. code = stripped;
  673. }
  674. }
  675. {
  676. uint32_t shaderSize = uint32_t(code->GetBufferSize() );
  677. bx::write(_writer, shaderSize, &err);
  678. bx::write(_writer, code->GetBufferPointer(), shaderSize, &err);
  679. uint8_t nul = 0;
  680. bx::write(_writer, nul, &err);
  681. }
  682. if (_version >= 400)
  683. {
  684. bx::write(_writer, numAttrs, &err);
  685. bx::write(_writer, attrs, numAttrs*sizeof(uint16_t), &err);
  686. bx::write(_writer, size, &err);
  687. }
  688. if (_options.disasm )
  689. {
  690. ID3DBlob* disasm;
  691. D3DDisassemble(code->GetBufferPointer()
  692. , code->GetBufferSize()
  693. , 0
  694. , NULL
  695. , &disasm
  696. );
  697. if (NULL != disasm)
  698. {
  699. std::string disasmfp = _options.outputFilePath + ".disasm";
  700. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  701. disasm->Release();
  702. }
  703. }
  704. if (NULL != errorMsg)
  705. {
  706. errorMsg->Release();
  707. }
  708. result = true;
  709. error:
  710. code->Release();
  711. unload();
  712. return result;
  713. }
  714. } // namespace hlsl
  715. bool compileHLSLShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  716. {
  717. return hlsl::compile(_options, _version, _code, _writer, true);
  718. }
  719. } // namespace bgfx
  720. #else
  721. namespace bgfx
  722. {
  723. bool compileHLSLShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  724. {
  725. BX_UNUSED(_options, _version, _code, _writer);
  726. bx::printf("HLSL compiler is not supported on this platform.\n");
  727. return false;
  728. }
  729. } // namespace bgfx
  730. #endif // SHADERC_CONFIG_HLSL