shaderc_spirv.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. /*
  2. * Copyright 2011-2024 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include "shaderc.h"
  6. #include <iostream> // std::cout
  7. BX_PRAGMA_DIAGNOSTIC_PUSH()
  8. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4100) // error C4100: 'inclusionDepth' : unreferenced formal parameter
  9. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4265) // error C4265: 'spv::spirvbin_t': class has virtual functions, but destructor is not virtual
  10. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wattributes") // warning: attribute ignored
  11. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wdeprecated-declarations") // warning: ‘MSLVertexAttr’ is deprecated
  12. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits") // warning: comparison of unsigned expression in ‘< 0’ is always false
  13. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow") // warning: declaration of 'userData' shadows a member of 'glslang::TShader::Includer::IncludeResult'
  14. #define ENABLE_OPT 1
  15. #include <ShaderLang.h>
  16. #include <ResourceLimits.h>
  17. #include <SPIRV/SPVRemapper.h>
  18. #include <SPIRV/GlslangToSpv.h>
  19. #include <SPIRV/SpvTools.h>
  20. #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
  21. #include <spirv_msl.hpp>
  22. #include <spirv_reflect.hpp>
  23. #include <spirv-tools/optimizer.hpp>
  24. BX_PRAGMA_DIAGNOSTIC_POP()
  25. namespace bgfx
  26. {
  27. static bx::DefaultAllocator s_allocator;
  28. bx::AllocatorI* g_allocator = &s_allocator;
  29. struct TinyStlAllocator
  30. {
  31. static void* static_allocate(size_t _bytes);
  32. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  33. };
  34. void* TinyStlAllocator::static_allocate(size_t _bytes)
  35. {
  36. return bx::alloc(g_allocator, _bytes);
  37. }
  38. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  39. {
  40. if (NULL != _ptr)
  41. {
  42. bx::free(g_allocator, _ptr);
  43. }
  44. }
  45. } // namespace bgfx
  46. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  47. #include <tinystl/allocator.h>
  48. #include <tinystl/string.h>
  49. #include <tinystl/unordered_map.h>
  50. #include <tinystl/vector.h>
  51. namespace stl = tinystl;
  52. #include "../../src/shader.h"
  53. #include "../../src/shader_spirv.h"
  54. #include "../../3rdparty/khronos/vulkan-local/vulkan.h"
  55. namespace bgfx { namespace spirv
  56. {
  57. const TBuiltInResource resourceLimits =
  58. {
  59. 32, // MaxLights
  60. 6, // MaxClipPlanes
  61. 32, // MaxTextureUnits
  62. 32, // MaxTextureCoords
  63. 64, // MaxVertexAttribs
  64. 4096, // MaxVertexUniformComponents
  65. 64, // MaxVaryingFloats
  66. 32, // MaxVertexTextureImageUnits
  67. 80, // MaxCombinedTextureImageUnits
  68. 32, // MaxTextureImageUnits
  69. 4096, // MaxFragmentUniformComponents
  70. 32, // MaxDrawBuffers
  71. 128, // MaxVertexUniformVectors
  72. 8, // MaxVaryingVectors
  73. 16, // MaxFragmentUniformVectors
  74. 16, // MaxVertexOutputVectors
  75. 15, // MaxFragmentInputVectors
  76. -8, // MinProgramTexelOffset
  77. 7, // MaxProgramTexelOffset
  78. 8, // MaxClipDistances
  79. 65535, // MaxComputeWorkGroupCountX
  80. 65535, // MaxComputeWorkGroupCountY
  81. 65535, // MaxComputeWorkGroupCountZ
  82. 1024, // MaxComputeWorkGroupSizeX
  83. 1024, // MaxComputeWorkGroupSizeY
  84. 64, // MaxComputeWorkGroupSizeZ
  85. 1024, // MaxComputeUniformComponents
  86. 16, // MaxComputeTextureImageUnits
  87. 8, // MaxComputeImageUniforms
  88. 8, // MaxComputeAtomicCounters
  89. 1, // MaxComputeAtomicCounterBuffers
  90. 60, // MaxVaryingComponents
  91. 64, // MaxVertexOutputComponents
  92. 64, // MaxGeometryInputComponents
  93. 128, // MaxGeometryOutputComponents
  94. 128, // MaxFragmentInputComponents
  95. 8, // MaxImageUnits
  96. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  97. 8, // MaxCombinedShaderOutputResources
  98. 0, // MaxImageSamples
  99. 0, // MaxVertexImageUniforms
  100. 0, // MaxTessControlImageUniforms
  101. 0, // MaxTessEvaluationImageUniforms
  102. 0, // MaxGeometryImageUniforms
  103. 8, // MaxFragmentImageUniforms
  104. 8, // MaxCombinedImageUniforms
  105. 16, // MaxGeometryTextureImageUnits
  106. 256, // MaxGeometryOutputVertices
  107. 1024, // MaxGeometryTotalOutputComponents
  108. 1024, // MaxGeometryUniformComponents
  109. 64, // MaxGeometryVaryingComponents
  110. 128, // MaxTessControlInputComponents
  111. 128, // MaxTessControlOutputComponents
  112. 16, // MaxTessControlTextureImageUnits
  113. 1024, // MaxTessControlUniformComponents
  114. 4096, // MaxTessControlTotalOutputComponents
  115. 128, // MaxTessEvaluationInputComponents
  116. 128, // MaxTessEvaluationOutputComponents
  117. 16, // MaxTessEvaluationTextureImageUnits
  118. 1024, // MaxTessEvaluationUniformComponents
  119. 120, // MaxTessPatchComponents
  120. 32, // MaxPatchVertices
  121. 64, // MaxTessGenLevel
  122. 16, // MaxViewports
  123. 0, // MaxVertexAtomicCounters
  124. 0, // MaxTessControlAtomicCounters
  125. 0, // MaxTessEvaluationAtomicCounters
  126. 0, // MaxGeometryAtomicCounters
  127. 8, // MaxFragmentAtomicCounters
  128. 8, // MaxCombinedAtomicCounters
  129. 1, // MaxAtomicCounterBindings
  130. 0, // MaxVertexAtomicCounterBuffers
  131. 0, // MaxTessControlAtomicCounterBuffers
  132. 0, // MaxTessEvaluationAtomicCounterBuffers
  133. 0, // MaxGeometryAtomicCounterBuffers
  134. 1, // MaxFragmentAtomicCounterBuffers
  135. 1, // MaxCombinedAtomicCounterBuffers
  136. 16384, // MaxAtomicCounterBufferSize
  137. 4, // MaxTransformFeedbackBuffers
  138. 64, // MaxTransformFeedbackInterleavedComponents
  139. 8, // MaxCullDistances
  140. 8, // MaxCombinedClipAndCullDistances
  141. 4, // MaxSamples
  142. 0, // maxMeshOutputVerticesNV
  143. 0, // maxMeshOutputPrimitivesNV
  144. 0, // maxMeshWorkGroupSizeX_NV
  145. 0, // maxMeshWorkGroupSizeY_NV
  146. 0, // maxMeshWorkGroupSizeZ_NV
  147. 0, // maxTaskWorkGroupSizeX_NV
  148. 0, // maxTaskWorkGroupSizeY_NV
  149. 0, // maxTaskWorkGroupSizeZ_NV
  150. 0, // maxMeshViewCountNV
  151. 0, // maxMeshOutputVerticesEXT
  152. 0, // maxMeshOutputPrimitivesEXT
  153. 0, // maxMeshWorkGroupSizeX_EXT
  154. 0, // maxMeshWorkGroupSizeY_EXT
  155. 0, // maxMeshWorkGroupSizeZ_EXT
  156. 0, // maxTaskWorkGroupSizeX_EXT
  157. 0, // maxTaskWorkGroupSizeY_EXT
  158. 0, // maxTaskWorkGroupSizeZ_EXT
  159. 0, // maxMeshViewCountEXT
  160. 0, // maxDualSourceDrawBuffersEXT
  161. { // limits
  162. true, // nonInductiveForLoops
  163. true, // whileLoops
  164. true, // doWhileLoops
  165. true, // generalUniformIndexing
  166. true, // generalAttributeMatrixVectorIndexing
  167. true, // generalVaryingIndexing
  168. true, // generalSamplerIndexing
  169. true, // generalVariableIndexing
  170. true, // generalConstantMatrixVectorIndexing
  171. },
  172. };
  173. bgfx::TextureComponentType::Enum SpirvCrossBaseTypeToFormatType(spirv_cross::SPIRType::BaseType spirvBaseType, bool depth)
  174. {
  175. if (depth)
  176. return bgfx::TextureComponentType::Depth;
  177. switch (spirvBaseType)
  178. {
  179. case spirv_cross::SPIRType::Float:
  180. return bgfx::TextureComponentType::Float;
  181. case spirv_cross::SPIRType::Int:
  182. return bgfx::TextureComponentType::Int;
  183. case spirv_cross::SPIRType::UInt:
  184. return bgfx::TextureComponentType::Uint;
  185. default:
  186. return bgfx::TextureComponentType::Float;
  187. }
  188. }
  189. bgfx::TextureDimension::Enum SpirvDimToTextureViewDimension(spv::Dim _dim, bool _arrayed)
  190. {
  191. switch (_dim)
  192. {
  193. case spv::Dim::Dim1D:
  194. return bgfx::TextureDimension::Dimension1D;
  195. case spv::Dim::Dim2D:
  196. return _arrayed
  197. ? bgfx::TextureDimension::Dimension2DArray
  198. : bgfx::TextureDimension::Dimension2D
  199. ;
  200. case spv::Dim::Dim3D:
  201. return bgfx::TextureDimension::Dimension3D;
  202. case spv::Dim::DimCube:
  203. return _arrayed
  204. ? bgfx::TextureDimension::DimensionCubeArray
  205. : bgfx::TextureDimension::DimensionCube
  206. ;
  207. default:
  208. BX_ASSERT(false, "Unknown texture dimension %d", _dim);
  209. return bgfx::TextureDimension::Dimension2D;
  210. }
  211. }
  212. static bgfx::TextureFormat::Enum s_textureFormats[] =
  213. {
  214. bgfx::TextureFormat::Unknown, // spv::ImageFormatUnknown = 0
  215. bgfx::TextureFormat::RGBA32F, // spv::ImageFormatRgba32f = 1
  216. bgfx::TextureFormat::RGBA16F, // spv::ImageFormatRgba16f = 2
  217. bgfx::TextureFormat::R32F, // spv::ImageFormatR32f = 3
  218. bgfx::TextureFormat::RGBA8, // spv::ImageFormatRgba8 = 4
  219. bgfx::TextureFormat::RGBA8S, // spv::ImageFormatRgba8Snorm = 5
  220. bgfx::TextureFormat::RG32F, // spv::ImageFormatRg32f = 6
  221. bgfx::TextureFormat::RG16F, // spv::ImageFormatRg16f = 7
  222. bgfx::TextureFormat::RG11B10F, // spv::ImageFormatR11fG11fB10f = 8
  223. bgfx::TextureFormat::R16F, // spv::ImageFormatR16f = 9
  224. bgfx::TextureFormat::RGBA16, // spv::ImageFormatRgba16 = 10
  225. bgfx::TextureFormat::RGB10A2, // spv::ImageFormatRgb10A2 = 11
  226. bgfx::TextureFormat::RG16, // spv::ImageFormatRg16 = 12
  227. bgfx::TextureFormat::RG8, // spv::ImageFormatRg8 = 13
  228. bgfx::TextureFormat::R16, // spv::ImageFormatR16 = 14
  229. bgfx::TextureFormat::R8, // spv::ImageFormatR8 = 15
  230. bgfx::TextureFormat::RGBA16S, // spv::ImageFormatRgba16Snorm = 16
  231. bgfx::TextureFormat::RG16S, // spv::ImageFormatRg16Snorm = 17
  232. bgfx::TextureFormat::RG8S, // spv::ImageFormatRg8Snorm = 18
  233. bgfx::TextureFormat::R16S, // spv::ImageFormatR16Snorm = 19
  234. bgfx::TextureFormat::R8S, // spv::ImageFormatR8Snorm = 20
  235. bgfx::TextureFormat::RGBA32I, // spv::ImageFormatRgba32i = 21
  236. bgfx::TextureFormat::RGBA16I, // spv::ImageFormatRgba16i = 22
  237. bgfx::TextureFormat::RGBA8I, // spv::ImageFormatRgba8i = 23
  238. bgfx::TextureFormat::R32I, // spv::ImageFormatR32i = 24
  239. bgfx::TextureFormat::RG32I, // spv::ImageFormatRg32i = 25
  240. bgfx::TextureFormat::RG16I, // spv::ImageFormatRg16i = 26
  241. bgfx::TextureFormat::RG8I, // spv::ImageFormatRg8i = 27
  242. bgfx::TextureFormat::R16I, // spv::ImageFormatR16i = 28
  243. bgfx::TextureFormat::R8I, // spv::ImageFormatR8i = 29
  244. bgfx::TextureFormat::RGBA32U, // spv::ImageFormatRgba32ui = 30
  245. bgfx::TextureFormat::RGBA16U, // spv::ImageFormatRgba16ui = 31
  246. bgfx::TextureFormat::RGBA8U, // spv::ImageFormatRgba8ui = 32
  247. bgfx::TextureFormat::R32U, // spv::ImageFormatR32ui = 33
  248. bgfx::TextureFormat::Unknown, // spv::ImageFormatRgb10a2ui = 34
  249. bgfx::TextureFormat::RG32U, // spv::ImageFormatRg32ui = 35
  250. bgfx::TextureFormat::RG16U, // spv::ImageFormatRg16ui = 36
  251. bgfx::TextureFormat::RG8U, // spv::ImageFormatRg8ui = 37
  252. bgfx::TextureFormat::R16U, // spv::ImageFormatR16ui = 38
  253. bgfx::TextureFormat::R8U, // spv::ImageFormatR8ui = 39
  254. bgfx::TextureFormat::Unknown, // spv::ImageFormatR64ui = 40
  255. bgfx::TextureFormat::Unknown, // spv::ImageFormatR64i = 41
  256. };
  257. static EShLanguage getLang(char _p)
  258. {
  259. switch (_p)
  260. {
  261. case 'c': return EShLangCompute;
  262. case 'f': return EShLangFragment;
  263. case 'v': return EShLangVertex;
  264. default: return EShLangCount;
  265. }
  266. }
  267. static const char* s_attribName[] =
  268. {
  269. "a_position",
  270. "a_normal",
  271. "a_tangent",
  272. "a_bitangent",
  273. "a_color0",
  274. "a_color1",
  275. "a_color2",
  276. "a_color3",
  277. "a_indices",
  278. "a_weight",
  279. "a_texcoord0",
  280. "a_texcoord1",
  281. "a_texcoord2",
  282. "a_texcoord3",
  283. "a_texcoord4",
  284. "a_texcoord5",
  285. "a_texcoord6",
  286. "a_texcoord7",
  287. };
  288. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  289. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  290. {
  291. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  292. {
  293. if (0 == bx::strCmp(s_attribName[ii], _name) )
  294. {
  295. return bgfx::Attrib::Enum(ii);
  296. }
  297. }
  298. return bgfx::Attrib::Count;
  299. }
  300. static const char* s_samplerTypes[] =
  301. {
  302. "BgfxSampler2D",
  303. "BgfxISampler2D",
  304. "BgfxUSampler2D",
  305. "BgfxSampler2DArray",
  306. "BgfxSampler2DShadow",
  307. "BgfxSampler2DArrayShadow",
  308. "BgfxSampler3D",
  309. "BgfxISampler3D",
  310. "BgfxUSampler3D",
  311. "BgfxSamplerCube",
  312. "BgfxSamplerCubeShadow",
  313. "BgfxSampler2DMS",
  314. };
  315. static uint16_t writeUniformArray(bx::WriterI* _shaderWriter, const UniformArray& uniforms, bool isFragmentShader)
  316. {
  317. uint16_t size = 0;
  318. bx::ErrorAssert err;
  319. uint16_t count = uint16_t(uniforms.size());
  320. bx::write(_shaderWriter, count, &err);
  321. uint32_t fragmentBit = isFragmentShader ? kUniformFragmentBit : 0;
  322. for (uint16_t ii = 0; ii < count; ++ii)
  323. {
  324. const Uniform& un = uniforms[ii];
  325. if ( (un.type & ~kUniformMask) > UniformType::End)
  326. {
  327. size = bx::max(size, (uint16_t)(un.regIndex + un.regCount*16) );
  328. }
  329. uint8_t nameSize = (uint8_t)un.name.size();
  330. bx::write(_shaderWriter, nameSize, &err);
  331. bx::write(_shaderWriter, un.name.c_str(), nameSize, &err);
  332. bx::write(_shaderWriter, uint8_t(un.type | fragmentBit), &err);
  333. bx::write(_shaderWriter, un.num, &err);
  334. bx::write(_shaderWriter, un.regIndex, &err);
  335. bx::write(_shaderWriter, un.regCount, &err);
  336. bx::write(_shaderWriter, un.texComponent, &err);
  337. bx::write(_shaderWriter, un.texDimension, &err);
  338. bx::write(_shaderWriter, un.texFormat, &err);
  339. BX_TRACE("%s, %s, %d, %d, %d"
  340. , un.name.c_str()
  341. , getUniformTypeName(UniformType::Enum(un.type & ~kUniformMask))
  342. , un.num
  343. , un.regIndex
  344. , un.regCount
  345. );
  346. }
  347. return size;
  348. }
  349. static spv_target_env getSpirvTargetVersion(uint32_t _version, bx::WriterI* _messageWriter)
  350. {
  351. bx::ErrorAssert err;
  352. switch (_version)
  353. {
  354. case 1010:
  355. return SPV_ENV_VULKAN_1_0;
  356. case 1311:
  357. return SPV_ENV_VULKAN_1_1;
  358. case 1411:
  359. return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
  360. case 1512:
  361. return SPV_ENV_VULKAN_1_2;
  362. case 1613:
  363. return SPV_ENV_VULKAN_1_3;
  364. default:
  365. bx::write(_messageWriter, &err, "Warning: Unknown SPIR-V version requested. Returning SPV_ENV_VULKAN_1_0 as default.\n");
  366. return SPV_ENV_VULKAN_1_0;
  367. }
  368. }
  369. static glslang::EShTargetClientVersion getGlslangTargetVulkanVersion(uint32_t _version, bx::WriterI* _messageWriter)
  370. {
  371. bx::ErrorAssert err;
  372. switch (_version)
  373. {
  374. case 1010:
  375. return glslang::EShTargetVulkan_1_0;
  376. case 1311:
  377. case 1411:
  378. return glslang::EShTargetVulkan_1_1;
  379. case 1512:
  380. return glslang::EShTargetVulkan_1_2;
  381. case 1613:
  382. return glslang::EShTargetVulkan_1_3;
  383. default:
  384. bx::write(_messageWriter, &err, "Warning: Unknown SPIR-V version requested. Returning EShTargetVulkan_1_0 as default.\n");
  385. return glslang::EShTargetVulkan_1_0;
  386. }
  387. }
  388. static glslang::EShTargetLanguageVersion getGlslangTargetSpirvVersion(uint32_t _version, bx::WriterI* _messageWriter)
  389. {
  390. bx::ErrorAssert err;
  391. switch (_version)
  392. {
  393. case 1010:
  394. return glslang::EShTargetSpv_1_0;
  395. case 1311:
  396. return glslang::EShTargetSpv_1_3;
  397. case 1411:
  398. return glslang::EShTargetSpv_1_4;
  399. case 1512:
  400. return glslang::EShTargetSpv_1_5;
  401. case 1613:
  402. return glslang::EShTargetSpv_1_6;
  403. default:
  404. bx::write(_messageWriter, &err, "Warning: Unknown SPIR-V version requested. Returning EShTargetSpv_1_0 as default.\n");
  405. return glslang::EShTargetSpv_1_0;
  406. }
  407. }
  408. /// This is the value used to fill out GLSLANG's SpvVersion object.
  409. /// The required value is that which is defined by GL_KHR_vulkan_glsl, which is defined here:
  410. /// https://github.com/KhronosGroup/GLSL/blob/master/extensions/khr/GL_KHR_vulkan_glsl.txt
  411. /// The value is 100.
  412. constexpr int s_GLSL_VULKAN_CLIENT_VERSION = 100;
  413. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _shaderWriter, bx::WriterI* _messageWriter, bool _firstPass)
  414. {
  415. BX_UNUSED(_version);
  416. bx::ErrorAssert messageErr;
  417. glslang::InitializeProcess();
  418. EShLanguage stage = getLang(_options.shaderType);
  419. if (EShLangCount == stage)
  420. {
  421. bx::write(_messageWriter, &messageErr, "Error: Unknown shader type '%c'.\n", _options.shaderType);
  422. return false;
  423. }
  424. glslang::TProgram* program = new glslang::TProgram;
  425. glslang::TShader* shader = new glslang::TShader(stage);
  426. EShMessages messages = EShMessages(0
  427. | EShMsgDefault
  428. | EShMsgReadHlsl
  429. | EShMsgVulkanRules
  430. | EShMsgSpvRules
  431. | EShMsgDebugInfo
  432. );
  433. shader->setEntryPoint("main");
  434. shader->setAutoMapBindings(true);
  435. shader->setEnvInput(glslang::EShSourceHlsl, stage, glslang::EShClientVulkan, s_GLSL_VULKAN_CLIENT_VERSION);
  436. shader->setEnvClient(glslang::EShClientVulkan, getGlslangTargetVulkanVersion(_version, _messageWriter));
  437. shader->setEnvTarget(glslang::EShTargetSpv, getGlslangTargetSpirvVersion(_version, _messageWriter));
  438. // Reserve two spots for the stage UBOs
  439. shader->setShiftBinding(glslang::EResUbo, (stage == EShLanguage::EShLangFragment ? kSpirvFragmentBinding : kSpirvVertexBinding));
  440. shader->setShiftBinding(glslang::EResTexture, kSpirvBindShift);
  441. shader->setShiftBinding(glslang::EResSampler, kSpirvBindShift + kSpirvSamplerShift);
  442. shader->setShiftBinding(glslang::EResSsbo, kSpirvBindShift);
  443. shader->setShiftBinding(glslang::EResImage, kSpirvBindShift);
  444. const char* shaderStrings[] = { _code.c_str() };
  445. shader->setStrings(
  446. shaderStrings
  447. , BX_COUNTOF(shaderStrings)
  448. );
  449. bool compiled = shader->parse(&resourceLimits
  450. , 110
  451. , false
  452. , messages
  453. );
  454. bool linked = false;
  455. bool validated = true;
  456. if (!compiled)
  457. {
  458. const char* log = shader->getInfoLog();
  459. if (NULL != log)
  460. {
  461. int32_t source = 0;
  462. int32_t line = 0;
  463. int32_t column = 0;
  464. int32_t start = 0;
  465. int32_t end = INT32_MAX;
  466. bx::StringView err = bx::strFind(log, "ERROR:");
  467. bool found = false;
  468. if (!err.isEmpty() )
  469. {
  470. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  471. if (found)
  472. {
  473. ++line;
  474. }
  475. }
  476. if (found)
  477. {
  478. start = bx::uint32_imax(1, line-10);
  479. end = start + 20;
  480. }
  481. printCode(_code.c_str(), line, start, end, column);
  482. bx::write(_messageWriter, &messageErr, "%s\n", log);
  483. }
  484. }
  485. else
  486. {
  487. program->addShader(shader);
  488. linked = true
  489. && program->link(messages)
  490. && program->mapIO()
  491. ;
  492. if (!linked)
  493. {
  494. const char* log = program->getInfoLog();
  495. if (NULL != log)
  496. {
  497. bx::write(_messageWriter, &messageErr, "%s\n", log);
  498. }
  499. }
  500. else
  501. {
  502. program->buildReflection();
  503. if (_firstPass)
  504. {
  505. // first time through, we just find unused uniforms and get rid of them
  506. std::string output;
  507. struct Uniform
  508. {
  509. std::string name;
  510. std::string decl;
  511. };
  512. std::vector<Uniform> uniforms;
  513. bx::LineReader reader(_code.c_str() );
  514. while (!reader.isDone() )
  515. {
  516. bx::StringView strLine = reader.next();
  517. bool moved = false;
  518. bx::StringView str = strFind(strLine, "uniform ");
  519. if (!str.isEmpty() )
  520. {
  521. bool found = false;
  522. bool sampler = false;
  523. std::string name = "";
  524. // add to samplers
  525. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  526. {
  527. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  528. {
  529. found = true;
  530. sampler = true;
  531. break;
  532. }
  533. }
  534. if (!found)
  535. {
  536. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  537. {
  538. // matching lines like: uniform u_name;
  539. // we want to replace "uniform" with "static" so that it's no longer
  540. // included in the uniform blob that the application must upload
  541. // we can't just remove them, because unused functions might still reference
  542. // them and cause a compile error when they're gone
  543. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  544. {
  545. found = true;
  546. name = program->getUniformName(ii);
  547. break;
  548. }
  549. }
  550. }
  551. if (!found)
  552. {
  553. output.append(strLine.getPtr(), str.getPtr() );
  554. output += "static ";
  555. output.append(str.getTerm(), strLine.getTerm() );
  556. output += "\n";
  557. moved = true;
  558. }
  559. else if (!sampler)
  560. {
  561. Uniform uniform;
  562. uniform.name = name;
  563. uniform.decl = std::string(strLine.getPtr(), strLine.getTerm() );
  564. uniforms.push_back(uniform);
  565. moved = true;
  566. }
  567. }
  568. if (!moved)
  569. {
  570. output.append(strLine.getPtr(), strLine.getTerm() );
  571. output += "\n";
  572. }
  573. }
  574. std::string uniformBlock;
  575. uniformBlock += "cbuffer UniformBlock\n";
  576. uniformBlock += "{\n";
  577. for (const Uniform& uniform : uniforms)
  578. {
  579. uniformBlock += uniform.decl.substr(7 /* uniform */);
  580. uniformBlock += "\n";
  581. }
  582. uniformBlock += "};\n";
  583. output = uniformBlock + output;
  584. // recompile with the unused uniforms converted to statics
  585. delete program;
  586. delete shader;
  587. return compile(_options, _version, output.c_str(), _shaderWriter, _messageWriter, false);
  588. }
  589. UniformArray uniforms;
  590. {
  591. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  592. for (uint16_t ii = 0; ii < count; ++ii)
  593. {
  594. Uniform un;
  595. un.name = program->getUniformName(ii);
  596. if (bx::hasSuffix(un.name.c_str(), ".@data") )
  597. {
  598. continue;
  599. }
  600. un.num = uint8_t(program->getUniformArraySize(ii) );
  601. const uint32_t offset = program->getUniformBufferOffset(ii);
  602. un.regIndex = uint16_t(offset);
  603. un.regCount = un.num;
  604. switch (program->getUniformType(ii) )
  605. {
  606. case 0x1404: // GL_INT:
  607. un.type = UniformType::Sampler;
  608. break;
  609. case 0x8B52: // GL_FLOAT_VEC4:
  610. un.type = UniformType::Vec4;
  611. break;
  612. case 0x8B5B: // GL_FLOAT_MAT3:
  613. un.type = UniformType::Mat3;
  614. un.regCount *= 3;
  615. break;
  616. case 0x8B5C: // GL_FLOAT_MAT4:
  617. un.type = UniformType::Mat4;
  618. un.regCount *= 4;
  619. break;
  620. default:
  621. continue;
  622. }
  623. uniforms.push_back(un);
  624. }
  625. }
  626. if (g_verbose)
  627. {
  628. program->dumpReflection();
  629. }
  630. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  631. std::vector<uint32_t> spirv;
  632. glslang::SpvOptions options;
  633. options.disableOptimizer = _options.debugInformation;
  634. options.generateDebugInfo = _options.debugInformation;
  635. options.emitNonSemanticShaderDebugInfo = _options.debugInformation;
  636. options.emitNonSemanticShaderDebugSource = _options.debugInformation;
  637. glslang::GlslangToSpv(*intermediate, spirv, &options);
  638. spvtools::Optimizer opt(getSpirvTargetVersion(_version, _messageWriter));
  639. auto print_msg_to_stderr = [_messageWriter, &messageErr](
  640. spv_message_level_t
  641. , const char*
  642. , const spv_position_t&
  643. , const char* m
  644. )
  645. {
  646. bx::write(_messageWriter, &messageErr, "Error: %s\n", m);
  647. };
  648. opt.SetMessageConsumer(print_msg_to_stderr);
  649. opt.RegisterLegalizationPasses();
  650. spvtools::ValidatorOptions validatorOptions;
  651. validatorOptions.SetBeforeHlslLegalization(true);
  652. if (!opt.Run(
  653. spirv.data()
  654. , spirv.size()
  655. , &spirv
  656. , validatorOptions
  657. , false
  658. ) )
  659. {
  660. compiled = false;
  661. }
  662. else
  663. {
  664. if (g_verbose)
  665. {
  666. glslang::SpirvToolsDisassemble(std::cout, spirv, getSpirvTargetVersion(_version, _messageWriter));
  667. }
  668. spirv_cross::CompilerReflection refl(spirv);
  669. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  670. // Loop through the separate_images, and extract the uniform names:
  671. for (auto &resource : resourcesrefl.separate_images)
  672. {
  673. std::string name = refl.get_name(resource.id);
  674. if (name.size() > 7
  675. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  676. {
  677. name = name.substr(0, name.length() - 7);
  678. }
  679. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  680. auto imageType = refl.get_type(resource.base_type_id).image;
  681. auto componentType = refl.get_type(imageType.type).basetype;
  682. bool isCompareSampler = false;
  683. for (auto& sampler : resourcesrefl.separate_samplers)
  684. {
  685. if (binding_index + 16 == refl.get_decoration(sampler.id, spv::Decoration::DecorationBinding) )
  686. {
  687. std::string samplerName = refl.get_name(sampler.id);
  688. isCompareSampler = refl.variable_is_depth_or_compare(sampler.id) || samplerName.find("Comparison") != std::string::npos;
  689. break;
  690. }
  691. }
  692. Uniform un;
  693. un.name = name;
  694. un.type = UniformType::Enum(UniformType::Sampler
  695. | kUniformSamplerBit
  696. | (isCompareSampler ? kUniformCompareBit : 0)
  697. );
  698. un.texComponent = textureComponentTypeToId(SpirvCrossBaseTypeToFormatType(componentType, imageType.depth) );
  699. un.texDimension = textureDimensionToId(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  700. un.texFormat = uint16_t(s_textureFormats[imageType.format]);
  701. un.regIndex = uint16_t(binding_index);
  702. un.regCount = 0; // unused
  703. uniforms.push_back(un);
  704. }
  705. // Loop through the storage_images, and extract the uniform names:
  706. for (auto &resource : resourcesrefl.storage_images)
  707. {
  708. std::string name = refl.get_name(resource.id);
  709. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  710. auto imageType = refl.get_type(resource.base_type_id).image;
  711. auto componentType = refl.get_type(imageType.type).basetype;
  712. spirv_cross::Bitset flags = refl.get_decoration_bitset(resource.id);
  713. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  714. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  715. : UniformType::End;
  716. Uniform un;
  717. un.name = name;
  718. un.type = type;
  719. un.texComponent = textureComponentTypeToId(SpirvCrossBaseTypeToFormatType(componentType, imageType.depth) );
  720. un.texDimension = textureDimensionToId(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  721. un.texFormat = uint16_t(s_textureFormats[imageType.format]);
  722. un.regIndex = uint16_t(binding_index);
  723. un.regCount = descriptorTypeToId(DescriptorType::StorageImage);
  724. uniforms.push_back(un);
  725. }
  726. bx::Error err;
  727. // Loop through the storage buffer, and extract the uniform names:
  728. for (auto& resource : resourcesrefl.storage_buffers)
  729. {
  730. std::string name = refl.get_name(resource.id);
  731. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  732. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  733. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  734. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  735. : UniformType::End;
  736. Uniform un;
  737. un.name = name;
  738. un.type = type;
  739. un.num = 0;
  740. un.regIndex = uint16_t(binding_index);
  741. un.regCount = descriptorTypeToId(DescriptorType::StorageBuffer);
  742. uniforms.push_back(un);
  743. }
  744. uint16_t size = writeUniformArray(_shaderWriter, uniforms, _options.shaderType == 'f');
  745. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  746. bx::write(_shaderWriter, shaderSize, &err);
  747. bx::write(_shaderWriter, spirv.data(), shaderSize, &err);
  748. uint8_t nul = 0;
  749. bx::write(_shaderWriter, nul, &err);
  750. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  751. bx::write(_shaderWriter, numAttr, &err);
  752. for (uint8_t ii = 0; ii < numAttr; ++ii)
  753. {
  754. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  755. if (bgfx::Attrib::Count != attr)
  756. {
  757. bx::write(_shaderWriter, bgfx::attribToId(attr), &err);
  758. }
  759. else
  760. {
  761. bx::write(_shaderWriter, uint16_t(UINT16_MAX), &err);
  762. }
  763. }
  764. bx::write(_shaderWriter, size, &err);
  765. }
  766. }
  767. }
  768. delete program;
  769. delete shader;
  770. glslang::FinalizeProcess();
  771. return compiled && linked && validated;
  772. }
  773. } // namespace spirv
  774. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _shaderWriter, bx::WriterI* _messageWriter)
  775. {
  776. return spirv::compile(_options, _version, _code, _shaderWriter, _messageWriter, true);
  777. }
  778. } // namespace bgfx