shaderc_spirv.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. /*
  2. * Copyright 2011-2020 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "shaderc.h"
  6. BX_PRAGMA_DIAGNOSTIC_PUSH()
  7. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4100) // error C4100: 'inclusionDepth' : unreferenced formal parameter
  8. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4265) // error C4265: 'spv::spirvbin_t': class has virtual functions, but destructor is not virtual
  9. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow") // warning: declaration of 'userData' shadows a member of 'glslang::TShader::Includer::IncludeResult'
  10. #define ENABLE_OPT 1
  11. #include <ShaderLang.h>
  12. #include <ResourceLimits.h>
  13. #include <SPIRV/SPVRemapper.h>
  14. #include <SPIRV/GlslangToSpv.h>
  15. #include <webgpu/webgpu_cpp.h>
  16. #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
  17. #include <spirv_msl.hpp>
  18. #include <spirv_reflect.hpp>
  19. #include <spirv-tools/optimizer.hpp>
  20. BX_PRAGMA_DIAGNOSTIC_POP()
  21. namespace bgfx
  22. {
  23. static bx::DefaultAllocator s_allocator;
  24. bx::AllocatorI* g_allocator = &s_allocator;
  25. struct TinyStlAllocator
  26. {
  27. static void* static_allocate(size_t _bytes);
  28. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  29. };
  30. void* TinyStlAllocator::static_allocate(size_t _bytes)
  31. {
  32. return BX_ALLOC(g_allocator, _bytes);
  33. }
  34. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  35. {
  36. if (NULL != _ptr)
  37. {
  38. BX_FREE(g_allocator, _ptr);
  39. }
  40. }
  41. } // namespace bgfx
  42. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  43. #include <tinystl/allocator.h>
  44. #include <tinystl/string.h>
  45. #include <tinystl/unordered_map.h>
  46. #include <tinystl/vector.h>
  47. namespace stl = tinystl;
  48. #include "../../src/shader_spirv.h"
  49. #include "../../3rdparty/khronos/vulkan-local/vulkan.h"
  50. namespace bgfx { namespace spirv
  51. {
  52. const TBuiltInResource resourceLimits =
  53. {
  54. 32, // MaxLights
  55. 6, // MaxClipPlanes
  56. 32, // MaxTextureUnits
  57. 32, // MaxTextureCoords
  58. 64, // MaxVertexAttribs
  59. 4096, // MaxVertexUniformComponents
  60. 64, // MaxVaryingFloats
  61. 32, // MaxVertexTextureImageUnits
  62. 80, // MaxCombinedTextureImageUnits
  63. 32, // MaxTextureImageUnits
  64. 4096, // MaxFragmentUniformComponents
  65. 32, // MaxDrawBuffers
  66. 128, // MaxVertexUniformVectors
  67. 8, // MaxVaryingVectors
  68. 16, // MaxFragmentUniformVectors
  69. 16, // MaxVertexOutputVectors
  70. 15, // MaxFragmentInputVectors
  71. -8, // MinProgramTexelOffset
  72. 7, // MaxProgramTexelOffset
  73. 8, // MaxClipDistances
  74. 65535, // MaxComputeWorkGroupCountX
  75. 65535, // MaxComputeWorkGroupCountY
  76. 65535, // MaxComputeWorkGroupCountZ
  77. 1024, // MaxComputeWorkGroupSizeX
  78. 1024, // MaxComputeWorkGroupSizeY
  79. 64, // MaxComputeWorkGroupSizeZ
  80. 1024, // MaxComputeUniformComponents
  81. 16, // MaxComputeTextureImageUnits
  82. 8, // MaxComputeImageUniforms
  83. 8, // MaxComputeAtomicCounters
  84. 1, // MaxComputeAtomicCounterBuffers
  85. 60, // MaxVaryingComponents
  86. 64, // MaxVertexOutputComponents
  87. 64, // MaxGeometryInputComponents
  88. 128, // MaxGeometryOutputComponents
  89. 128, // MaxFragmentInputComponents
  90. 8, // MaxImageUnits
  91. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  92. 8, // MaxCombinedShaderOutputResources
  93. 0, // MaxImageSamples
  94. 0, // MaxVertexImageUniforms
  95. 0, // MaxTessControlImageUniforms
  96. 0, // MaxTessEvaluationImageUniforms
  97. 0, // MaxGeometryImageUniforms
  98. 8, // MaxFragmentImageUniforms
  99. 8, // MaxCombinedImageUniforms
  100. 16, // MaxGeometryTextureImageUnits
  101. 256, // MaxGeometryOutputVertices
  102. 1024, // MaxGeometryTotalOutputComponents
  103. 1024, // MaxGeometryUniformComponents
  104. 64, // MaxGeometryVaryingComponents
  105. 128, // MaxTessControlInputComponents
  106. 128, // MaxTessControlOutputComponents
  107. 16, // MaxTessControlTextureImageUnits
  108. 1024, // MaxTessControlUniformComponents
  109. 4096, // MaxTessControlTotalOutputComponents
  110. 128, // MaxTessEvaluationInputComponents
  111. 128, // MaxTessEvaluationOutputComponents
  112. 16, // MaxTessEvaluationTextureImageUnits
  113. 1024, // MaxTessEvaluationUniformComponents
  114. 120, // MaxTessPatchComponents
  115. 32, // MaxPatchVertices
  116. 64, // MaxTessGenLevel
  117. 16, // MaxViewports
  118. 0, // MaxVertexAtomicCounters
  119. 0, // MaxTessControlAtomicCounters
  120. 0, // MaxTessEvaluationAtomicCounters
  121. 0, // MaxGeometryAtomicCounters
  122. 8, // MaxFragmentAtomicCounters
  123. 8, // MaxCombinedAtomicCounters
  124. 1, // MaxAtomicCounterBindings
  125. 0, // MaxVertexAtomicCounterBuffers
  126. 0, // MaxTessControlAtomicCounterBuffers
  127. 0, // MaxTessEvaluationAtomicCounterBuffers
  128. 0, // MaxGeometryAtomicCounterBuffers
  129. 1, // MaxFragmentAtomicCounterBuffers
  130. 1, // MaxCombinedAtomicCounterBuffers
  131. 16384, // MaxAtomicCounterBufferSize
  132. 4, // MaxTransformFeedbackBuffers
  133. 64, // MaxTransformFeedbackInterleavedComponents
  134. 8, // MaxCullDistances
  135. 8, // MaxCombinedClipAndCullDistances
  136. 4, // MaxSamples
  137. 0, // maxMeshOutputVerticesNV
  138. 0, // maxMeshOutputPrimitivesNV
  139. 0, // maxMeshWorkGroupSizeX_NV
  140. 0, // maxMeshWorkGroupSizeY_NV
  141. 0, // maxMeshWorkGroupSizeZ_NV
  142. 0, // maxTaskWorkGroupSizeX_NV
  143. 0, // maxTaskWorkGroupSizeY_NV
  144. 0, // maxTaskWorkGroupSizeZ_NV
  145. 0, // maxMeshViewCountNV
  146. 0, // maxDualSourceDrawBuffersEXT
  147. { // limits
  148. true, // nonInductiveForLoops
  149. true, // whileLoops
  150. true, // doWhileLoops
  151. true, // generalUniformIndexing
  152. true, // generalAttributeMatrixVectorIndexing
  153. true, // generalVaryingIndexing
  154. true, // generalSamplerIndexing
  155. true, // generalVariableIndexing
  156. true, // generalConstantMatrixVectorIndexing
  157. },
  158. };
  159. bool printAsm(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  160. {
  161. BX_UNUSED(_userData);
  162. char temp[512];
  163. toString(temp, sizeof(temp), _instruction);
  164. BX_TRACE("%5d: %s", _offset, temp);
  165. return true;
  166. }
  167. wgpu::TextureComponentType SpirvCrossBaseTypeToFormatType(spirv_cross::SPIRType::BaseType spirvBaseType)
  168. {
  169. switch (spirvBaseType)
  170. {
  171. case spirv_cross::SPIRType::Float:
  172. return wgpu::TextureComponentType::Float;
  173. case spirv_cross::SPIRType::Int:
  174. return wgpu::TextureComponentType::Sint;
  175. case spirv_cross::SPIRType::UInt:
  176. return wgpu::TextureComponentType::Uint;
  177. default:
  178. return wgpu::TextureComponentType::Float;
  179. }
  180. }
  181. wgpu::TextureViewDimension SpirvDimToTextureViewDimension(spv::Dim dim, bool arrayed)
  182. {
  183. switch (dim)
  184. {
  185. case spv::Dim::Dim1D:
  186. return wgpu::TextureViewDimension::e1D;
  187. case spv::Dim::Dim2D:
  188. return arrayed
  189. ? wgpu::TextureViewDimension::e2DArray
  190. : wgpu::TextureViewDimension::e2D;
  191. case spv::Dim::Dim3D:
  192. return wgpu::TextureViewDimension::e3D;
  193. case spv::Dim::DimCube:
  194. return arrayed
  195. ? wgpu::TextureViewDimension::CubeArray
  196. : wgpu::TextureViewDimension::Cube;
  197. default:
  198. return wgpu::TextureViewDimension::Undefined;
  199. }
  200. }
  201. struct SpvReflection
  202. {
  203. struct TypeId
  204. {
  205. enum Enum
  206. {
  207. Void,
  208. Bool,
  209. Int32,
  210. Int64,
  211. Uint32,
  212. Uint64,
  213. Float,
  214. Double,
  215. Vector,
  216. Matrix,
  217. Count
  218. };
  219. TypeId()
  220. : baseType(Enum::Count)
  221. , type(Enum::Count)
  222. , numComponents(0)
  223. {
  224. }
  225. Enum baseType;
  226. Enum type;
  227. uint32_t numComponents;
  228. stl::string toString()
  229. {
  230. stl::string result;
  231. switch (type)
  232. {
  233. case Float:
  234. result.append("float");
  235. break;
  236. case Vector:
  237. bx::stringPrintf(result, "vec%d"
  238. , numComponents
  239. );
  240. break;
  241. case Matrix:
  242. bx::stringPrintf(result, "mat%d"
  243. , numComponents
  244. );
  245. default:
  246. break;
  247. }
  248. return result;
  249. }
  250. };
  251. struct Id
  252. {
  253. struct Variable
  254. {
  255. Variable()
  256. : decoration(SpvDecoration::Count)
  257. , builtin(SpvBuiltin::Count)
  258. , storageClass(SpvStorageClass::Count)
  259. , location(UINT32_MAX)
  260. , offset(UINT32_MAX)
  261. , type(UINT32_MAX)
  262. {
  263. }
  264. stl::string name;
  265. SpvDecoration::Enum decoration;
  266. SpvBuiltin::Enum builtin;
  267. SpvStorageClass::Enum storageClass;
  268. uint32_t location;
  269. uint32_t offset;
  270. uint32_t type;
  271. };
  272. typedef stl::vector<Variable> MemberArray;
  273. Variable var;
  274. MemberArray members;
  275. };
  276. typedef stl::unordered_map<uint32_t, TypeId> TypeIdMap;
  277. typedef stl::unordered_map<uint32_t, Id> IdMap;
  278. TypeIdMap typeIdMap;
  279. IdMap idMap;
  280. stl::string getTypeName(uint32_t _typeId)
  281. {
  282. return getTypeId(_typeId).toString();
  283. }
  284. Id& getId(uint32_t _id)
  285. {
  286. IdMap::iterator it = idMap.find(_id);
  287. if (it == idMap.end() )
  288. {
  289. Id id;
  290. stl::pair<IdMap::iterator, bool> result = idMap.insert(stl::make_pair(_id, id) );
  291. it = result.first;
  292. }
  293. return it->second;
  294. }
  295. Id::Variable& get(uint32_t _id, uint32_t _idx)
  296. {
  297. Id& id = getId(_id);
  298. id.members.resize(bx::uint32_max(_idx+1, uint32_t(id.members.size() ) ) );
  299. return id.members[_idx];
  300. }
  301. TypeId& getTypeId(uint32_t _id)
  302. {
  303. TypeIdMap::iterator it = typeIdMap.find(_id);
  304. if (it == typeIdMap.end() )
  305. {
  306. TypeId id;
  307. stl::pair<TypeIdMap::iterator, bool> result = typeIdMap.insert(stl::make_pair(_id, id) );
  308. it = result.first;
  309. }
  310. return it->second;
  311. }
  312. void update(uint32_t _id, const stl::string& _name)
  313. {
  314. getId(_id).var.name = _name;
  315. }
  316. BX_NO_INLINE void update(Id::Variable& _variable, SpvDecoration::Enum _decoration, uint32_t _literal)
  317. {
  318. _variable.decoration = _decoration;
  319. switch (_decoration)
  320. {
  321. case SpvDecoration::Location:
  322. _variable.location = _literal;
  323. break;
  324. case SpvDecoration::Offset:
  325. _variable.offset = _literal;
  326. break;
  327. case SpvDecoration::BuiltIn:
  328. _variable.builtin = SpvBuiltin::Enum(_literal);
  329. break;
  330. default:
  331. break;
  332. }
  333. }
  334. BX_NO_INLINE void update(Id::Variable& _variable, uint32_t _type, SpvStorageClass::Enum _storageClass)
  335. {
  336. _variable.type = _type;
  337. _variable.storageClass = _storageClass;
  338. }
  339. void update(uint32_t _id, SpvDecoration::Enum _decoration, uint32_t _literal)
  340. {
  341. update(getId(_id).var, _decoration, _literal);
  342. }
  343. void update(uint32_t _id, uint32_t _type, SpvStorageClass::Enum _storageClass)
  344. {
  345. update(getId(_id).var, _type, _storageClass);
  346. }
  347. void update(uint32_t _id, uint32_t _idx, const stl::string& _name)
  348. {
  349. Id::Variable& var = get(_id, _idx);
  350. var.name = _name;
  351. }
  352. BX_NO_INLINE void update(uint32_t _id, uint32_t _idx, SpvDecoration::Enum _decoration, uint32_t _literal)
  353. {
  354. update(get(_id, _idx), _decoration, _literal);
  355. }
  356. void update(uint32_t _id, TypeId::Enum _type)
  357. {
  358. TypeId& type = getTypeId(_id);
  359. type.type = _type;
  360. }
  361. void update(uint32_t _id, TypeId::Enum _type, uint32_t _baseTypeId, uint32_t _numComonents)
  362. {
  363. TypeId& type = getTypeId(_id);
  364. type.type = _type;
  365. type.baseType = getTypeId(_baseTypeId).type;
  366. type.numComponents = _numComonents;
  367. }
  368. };
  369. bool spvParse(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  370. {
  371. BX_UNUSED(_offset);
  372. SpvReflection* spv = (SpvReflection*)_userData;
  373. switch (_instruction.opcode)
  374. {
  375. case SpvOpcode::Name:
  376. spv->update(_instruction.result
  377. , _instruction.operand[0].literalString
  378. );
  379. break;
  380. case SpvOpcode::Decorate:
  381. spv->update(_instruction.operand[0].data
  382. , SpvDecoration::Enum(_instruction.operand[1].data)
  383. , _instruction.operand[2].data
  384. );
  385. break;
  386. case SpvOpcode::MemberName:
  387. spv->update(_instruction.result
  388. , _instruction.operand[0].data
  389. , _instruction.operand[1].literalString
  390. );
  391. break;
  392. case SpvOpcode::MemberDecorate:
  393. spv->update(_instruction.operand[0].data
  394. , _instruction.operand[1].data
  395. , SpvDecoration::Enum(_instruction.operand[2].data)
  396. , _instruction.operand[3].data
  397. );
  398. break;
  399. case SpvOpcode::Variable:
  400. spv->update(_instruction.result
  401. , _instruction.type
  402. , SpvStorageClass::Enum(_instruction.operand[0].data)
  403. );
  404. break;
  405. case SpvOpcode::TypeVoid:
  406. spv->update(_instruction.result, SpvReflection::TypeId::Void);
  407. break;
  408. case SpvOpcode::TypeBool:
  409. spv->update(_instruction.result, SpvReflection::TypeId::Bool);
  410. break;
  411. case SpvOpcode::TypeInt:
  412. spv->update(_instruction.result
  413. , 32 == _instruction.operand[0].data
  414. ? 0 == _instruction.operand[1].data
  415. ? SpvReflection::TypeId::Uint32
  416. : SpvReflection::TypeId::Int32
  417. : 0 == _instruction.operand[1].data
  418. ? SpvReflection::TypeId::Uint64
  419. : SpvReflection::TypeId::Int64
  420. );
  421. break;
  422. case SpvOpcode::TypeFloat:
  423. spv->update(_instruction.result
  424. , 32 == _instruction.operand[0].data
  425. ? SpvReflection::TypeId::Float
  426. : SpvReflection::TypeId::Double
  427. );
  428. break;
  429. case SpvOpcode::TypeVector:
  430. spv->update(_instruction.result
  431. , SpvReflection::TypeId::Vector
  432. , _instruction.operand[0].data
  433. , _instruction.operand[1].data
  434. );
  435. break;
  436. case SpvOpcode::TypeMatrix:
  437. spv->update(_instruction.result
  438. , SpvReflection::TypeId::Matrix
  439. , _instruction.operand[0].data
  440. , _instruction.operand[1].data
  441. );
  442. break;
  443. case SpvOpcode::TypeImage:
  444. case SpvOpcode::TypeSampler:
  445. case SpvOpcode::TypeSampledImage:
  446. break;
  447. case SpvOpcode::TypeStruct:
  448. for (uint32_t ii = 0, num = _instruction.numOperands; ii < num; ++ii)
  449. {
  450. SpvReflection::Id::Variable& var = spv->get(_instruction.result, ii);
  451. var.type = _instruction.operand[ii].data;
  452. }
  453. break;
  454. default:
  455. break;
  456. }
  457. return true;
  458. }
  459. #define DBG(...) // bx::debugPrintf(__VA_ARGS__)
  460. void disassemble(bx::WriterI* _writer, bx::ReaderSeekerI* _reader, bx::Error* _err)
  461. {
  462. BX_UNUSED(_writer);
  463. uint32_t magic;
  464. bx::peek(_reader, magic);
  465. SpvReflection spvx;
  466. if (magic == SPV_CHUNK_HEADER)
  467. {
  468. SpirV spirv;
  469. read(_reader, spirv, _err);
  470. parse(spirv.shader, spvParse, &spvx, _err);
  471. for (SpvReflection::IdMap::const_iterator it = spvx.idMap.begin(), itEnd = spvx.idMap.end(); it != itEnd; ++it)
  472. {
  473. const SpvReflection::Id& id = it->second;
  474. uint32_t num = uint32_t(id.members.size() );
  475. if (0 < num
  476. && 0 != bx::strCmp(id.var.name.c_str(), "gl_PerVertex") )
  477. {
  478. DBG("%3d: %s %d %s\n"
  479. , it->first
  480. , id.var.name.c_str()
  481. , id.var.location
  482. , getName(id.var.storageClass)
  483. );
  484. DBG("{\n");
  485. for (uint32_t ii = 0; ii < num; ++ii)
  486. {
  487. const SpvReflection::Id::Variable& var = id.members[ii];
  488. DBG("\t\t%s %s %d %s\n"
  489. , spvx.getTypeName(var.type).c_str()
  490. , var.name.c_str()
  491. , var.offset
  492. , getName(var.storageClass)
  493. );
  494. BX_UNUSED(var);
  495. }
  496. DBG("}\n");
  497. }
  498. }
  499. }
  500. }
  501. static EShLanguage getLang(char _p)
  502. {
  503. switch (_p)
  504. {
  505. case 'c': return EShLangCompute;
  506. case 'f': return EShLangFragment;
  507. case 'v': return EShLangVertex;
  508. default: return EShLangCount;
  509. }
  510. }
  511. static const char* s_attribName[] =
  512. {
  513. "a_position",
  514. "a_normal",
  515. "a_tangent",
  516. "a_bitangent",
  517. "a_color0",
  518. "a_color1",
  519. "a_color2",
  520. "a_color3",
  521. "a_indices",
  522. "a_weight",
  523. "a_texcoord0",
  524. "a_texcoord1",
  525. "a_texcoord2",
  526. "a_texcoord3",
  527. "a_texcoord4",
  528. "a_texcoord5",
  529. "a_texcoord6",
  530. "a_texcoord7",
  531. };
  532. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  533. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  534. {
  535. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  536. {
  537. if (0 == bx::strCmp(s_attribName[ii], _name) )
  538. {
  539. return bgfx::Attrib::Enum(ii);
  540. }
  541. }
  542. return bgfx::Attrib::Count;
  543. }
  544. static const char* s_samplerTypes[] =
  545. {
  546. "BgfxSampler2D",
  547. "BgfxISampler2D",
  548. "BgfxUSampler2D",
  549. "BgfxSampler2DArray",
  550. "BgfxSampler2DShadow",
  551. "BgfxSampler2DArrayShadow",
  552. "BgfxSampler3D",
  553. "BgfxISampler3D",
  554. "BgfxUSampler3D",
  555. "BgfxSamplerCube",
  556. "BgfxSamplerCubeShadow",
  557. "BgfxSampler2DMS",
  558. };
  559. static uint16_t writeUniformArray(bx::WriterI* _writer, const UniformArray& uniforms, bool isFragmentShader)
  560. {
  561. uint16_t size = 0;
  562. uint16_t count = static_cast<uint16_t>(uniforms.size());
  563. bx::write(_writer, count);
  564. uint32_t fragmentBit = isFragmentShader ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  565. for (uint16_t ii = 0; ii < count; ++ii)
  566. {
  567. const Uniform& un = uniforms[ii];
  568. if ((un.type & ~BGFX_UNIFORM_MASK) > UniformType::End)
  569. size = bx::max(size, (uint16_t)(un.regIndex + un.regCount*16));
  570. uint8_t nameSize = (uint8_t)un.name.size();
  571. bx::write(_writer, nameSize);
  572. bx::write(_writer, un.name.c_str(), nameSize);
  573. bx::write(_writer, uint8_t(un.type | fragmentBit));
  574. bx::write(_writer, un.num);
  575. bx::write(_writer, un.regIndex);
  576. bx::write(_writer, un.regCount);
  577. bx::write(_writer, un.texComponent);
  578. bx::write(_writer, un.texDimension);
  579. BX_TRACE("%s, %s, %d, %d, %d"
  580. , un.name.c_str()
  581. , getUniformTypeName(un.type)
  582. , un.num
  583. , un.regIndex
  584. , un.regCount
  585. );
  586. }
  587. return size;
  588. }
  589. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  590. {
  591. BX_UNUSED(_version);
  592. glslang::InitializeProcess();
  593. glslang::TProgram* program = new glslang::TProgram;
  594. EShLanguage stage = getLang(_options.shaderType);
  595. if (EShLangCount == stage)
  596. {
  597. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  598. return false;
  599. }
  600. glslang::TShader* shader = new glslang::TShader(stage);
  601. EShMessages messages = EShMessages(0
  602. | EShMsgDefault
  603. | EShMsgReadHlsl
  604. | EShMsgVulkanRules
  605. | EShMsgSpvRules
  606. );
  607. shader->setEntryPoint("main");
  608. shader->setAutoMapBindings(true);
  609. uint32_t bindingOffset = (stage == EShLanguage::EShLangFragment ? 48 : 0);
  610. shader->setShiftBinding(glslang::EResUbo, bindingOffset);
  611. shader->setShiftBinding(glslang::EResTexture, bindingOffset + 16);
  612. shader->setShiftBinding(glslang::EResSampler, bindingOffset + 32);
  613. shader->setShiftBinding(glslang::EResSsbo, bindingOffset + 16);
  614. shader->setShiftBinding(glslang::EResImage, bindingOffset + 32);
  615. const char* shaderStrings[] = { _code.c_str() };
  616. shader->setStrings(
  617. shaderStrings
  618. , BX_COUNTOF(shaderStrings)
  619. );
  620. bool compiled = shader->parse(&resourceLimits
  621. , 110
  622. , false
  623. , messages
  624. );
  625. bool linked = false;
  626. bool validated = true;
  627. if (!compiled)
  628. {
  629. const char* log = shader->getInfoLog();
  630. if (NULL != log)
  631. {
  632. int32_t source = 0;
  633. int32_t line = 0;
  634. int32_t column = 0;
  635. int32_t start = 0;
  636. int32_t end = INT32_MAX;
  637. bx::StringView err = bx::strFind(log, "ERROR:");
  638. bool found = false;
  639. if (!err.isEmpty() )
  640. {
  641. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  642. if (found)
  643. {
  644. ++line;
  645. }
  646. }
  647. if (found)
  648. {
  649. start = bx::uint32_imax(1, line-10);
  650. end = start + 20;
  651. }
  652. printCode(_code.c_str(), line, start, end, column);
  653. bx::printf("%s\n", log);
  654. }
  655. }
  656. else
  657. {
  658. program->addShader(shader);
  659. linked = true
  660. && program->link(messages)
  661. && program->mapIO()
  662. ;
  663. if (!linked)
  664. {
  665. const char* log = program->getInfoLog();
  666. if (NULL != log)
  667. {
  668. bx::printf("%s\n", log);
  669. }
  670. }
  671. else
  672. {
  673. program->buildReflection();
  674. if (_firstPass)
  675. {
  676. // first time through, we just find unused uniforms and get rid of them
  677. std::string output;
  678. struct Uniform
  679. {
  680. std::string name;
  681. std::string decl;
  682. };
  683. std::vector<Uniform> uniforms;
  684. bx::Error err;
  685. LineReader reader(_code.c_str() );
  686. while (err.isOk() )
  687. {
  688. char str[4096];
  689. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  690. if (err.isOk() )
  691. {
  692. std::string strLine(str, len);
  693. bool moved = false;
  694. size_t index = strLine.find("uniform ");
  695. if (index != std::string::npos)
  696. {
  697. bool found = false;
  698. bool sampler = false;
  699. std::string name = "";
  700. // add to samplers
  701. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  702. {
  703. if (!bx::findIdentifierMatch(strLine.c_str(), s_samplerTypes[ii]).isEmpty())
  704. {
  705. found = true;
  706. sampler = true;
  707. break;
  708. }
  709. }
  710. if (!found)
  711. {
  712. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  713. {
  714. // matching lines like: uniform u_name;
  715. // we want to replace "uniform" with "static" so that it's no longer
  716. // included in the uniform blob that the application must upload
  717. // we can't just remove them, because unused functions might still reference
  718. // them and cause a compile error when they're gone
  719. if (!bx::findIdentifierMatch(strLine.c_str(), program->getUniformName(ii)).isEmpty())
  720. {
  721. found = true;
  722. name = program->getUniformName(ii);
  723. break;
  724. }
  725. }
  726. }
  727. if (!found)
  728. {
  729. strLine.replace(index, 7 /* uniform */, "static");
  730. }
  731. else if (!sampler)
  732. {
  733. Uniform uniform;
  734. uniform.name = name;
  735. uniform.decl = strLine;
  736. uniforms.push_back(uniform);
  737. moved = true;
  738. }
  739. }
  740. if (!moved)
  741. output += strLine;
  742. }
  743. }
  744. std::string uniformBlock;
  745. uniformBlock += "cbuffer UniformBlock\n";
  746. uniformBlock += "{\n";
  747. for (const Uniform& uniform : uniforms)
  748. {
  749. uniformBlock += uniform.decl.substr(7 /* uniform */);
  750. }
  751. uniformBlock += "};\n";
  752. output = uniformBlock + output;
  753. //std::cout << "[debug] uniforms: " << std::endl << uniformBlock << std::endl;
  754. // recompile with the unused uniforms converted to statics
  755. return compile(_options, _version, output.c_str(), _writer, false);
  756. }
  757. else
  758. {
  759. // second time, do nothing (todo remove)
  760. }
  761. UniformArray uniforms;
  762. {
  763. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  764. for (uint16_t ii = 0; ii < count; ++ii)
  765. {
  766. Uniform un;
  767. un.name = program->getUniformName(ii);
  768. un.num = uint8_t(program->getUniformArraySize(ii) );
  769. const uint32_t offset = program->getUniformBufferOffset(ii);
  770. un.regIndex = uint16_t(offset);
  771. un.regCount = un.num;
  772. switch (program->getUniformType(ii))
  773. {
  774. case 0x1404: // GL_INT:
  775. un.type = UniformType::Sampler;
  776. break;
  777. case 0x8B52: // GL_FLOAT_VEC4:
  778. un.type = UniformType::Vec4;
  779. break;
  780. case 0x8B5B: // GL_FLOAT_MAT3:
  781. un.type = UniformType::Mat3;
  782. un.regCount *= 3;
  783. break;
  784. case 0x8B5C: // GL_FLOAT_MAT4:
  785. un.type = UniformType::Mat4;
  786. un.regCount *= 4;
  787. break;
  788. default:
  789. un.type = UniformType::End;
  790. break;
  791. }
  792. uniforms.push_back(un);
  793. }
  794. }
  795. if (g_verbose)
  796. {
  797. program->dumpReflection();
  798. }
  799. BX_UNUSED(spv::MemorySemanticsAllMemory);
  800. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  801. std::vector<uint32_t> spirv;
  802. glslang::SpvOptions options;
  803. options.disableOptimizer = false;
  804. glslang::GlslangToSpv(*intermediate, spirv, &options);
  805. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  806. auto print_msg_to_stderr = [](
  807. spv_message_level_t
  808. , const char*
  809. , const spv_position_t&
  810. , const char* m
  811. )
  812. {
  813. bx::printf("Error: %s\n", m);
  814. };
  815. opt.SetMessageConsumer(print_msg_to_stderr);
  816. opt.RegisterLegalizationPasses();
  817. spvtools::ValidatorOptions validatorOptions;
  818. validatorOptions.SetBeforeHlslLegalization(true);
  819. if (!opt.Run(
  820. spirv.data()
  821. , spirv.size()
  822. , &spirv
  823. , validatorOptions
  824. , false
  825. ) )
  826. {
  827. compiled = false;
  828. }
  829. else
  830. {
  831. bx::Error err;
  832. bx::WriterI* writer = bx::getDebugOut();
  833. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  834. disassemble(writer, &reader, &err);
  835. spirv_cross::CompilerReflection refl(spirv);
  836. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  837. // Loop through the separate_images, and extract the uniform names:
  838. for (auto &resource : resourcesrefl.separate_images)
  839. {
  840. std::string name = refl.get_name(resource.id);
  841. if (name.size() > 7
  842. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  843. {
  844. std::string uniform_name = name.substr(0, name.length() - 7);
  845. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  846. auto imageType = refl.get_type(resource.base_type_id).image;
  847. auto componentType = refl.get_type(imageType.type).basetype;
  848. bool isCompareSampler = false;
  849. for (auto& sampler : resourcesrefl.separate_samplers)
  850. {
  851. if (binding_index + 16 == refl.get_decoration(sampler.id, spv::Decoration::DecorationBinding))
  852. {
  853. std::string samplerName = refl.get_name(sampler.id);
  854. isCompareSampler = refl.variable_is_depth_or_compare(sampler.id) || samplerName.find("Comparison") != std::string::npos;
  855. break;
  856. }
  857. }
  858. Uniform un;
  859. un.name = uniform_name;
  860. if (isCompareSampler)
  861. un.type = UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | BGFX_UNIFORM_COMPAREBIT | UniformType::Sampler);
  862. else
  863. un.type = UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | UniformType::Sampler);
  864. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType));
  865. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed));
  866. un.regIndex = binding_index;
  867. un.regCount = 0; // unused
  868. uniforms.push_back(un);
  869. }
  870. }
  871. // Loop through the separate_images, and extract the uniform names:
  872. for (auto &resource : resourcesrefl.storage_images)
  873. {
  874. std::string name = refl.get_name(resource.id);
  875. if (name.size() > 7
  876. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  877. {
  878. std::string uniform_name = name.substr(0, name.length() - 7);
  879. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  880. auto imageType = refl.get_type(resource.base_type_id).image;
  881. auto componentType = refl.get_type(imageType.type).basetype;
  882. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  883. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  884. ? UniformType::Enum(BGFX_UNIFORM_READONLYBIT | UniformType::End)
  885. : UniformType::End;
  886. Uniform un;
  887. un.name = uniform_name;
  888. un.type = type;
  889. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType));
  890. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed));
  891. un.regIndex = binding_index;
  892. un.regCount = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; // for descriptor type
  893. uniforms.push_back(un);
  894. }
  895. }
  896. // Loop through the storage buffer, and extract the uniform names:
  897. for (auto& resource : resourcesrefl.storage_buffers)
  898. {
  899. std::string name = refl.get_name(resource.id);
  900. for (auto& uniform : uniforms)
  901. {
  902. if (!bx::strFind(uniform.name.c_str(), name.c_str()).isEmpty())
  903. {
  904. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  905. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  906. ? UniformType::Enum(BGFX_UNIFORM_READONLYBIT | UniformType::End)
  907. : UniformType::End;
  908. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  909. uniform.name = name;
  910. uniform.type = UniformType::End;
  911. uniform.regIndex = binding_index;
  912. uniform.regCount = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  913. break;
  914. }
  915. }
  916. }
  917. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  918. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  919. {
  920. if (g_verbose)
  921. {
  922. glslang::SpirvToolsDisassemble(std::cout, spirv);
  923. }
  924. spirv_cross::CompilerMSL msl(std::move(spirv));
  925. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  926. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  927. if (!entryPoints.empty() )
  928. {
  929. msl.rename_entry_point(
  930. entryPoints[0].name
  931. , "xlatMtlMain"
  932. , entryPoints[0].execution_model
  933. );
  934. }
  935. for (auto &resource : resources.uniform_buffers)
  936. {
  937. msl.set_name(resource.id, "_mtl_u");
  938. }
  939. for (auto &resource : resources.storage_buffers)
  940. {
  941. unsigned binding = msl.get_decoration(resource.id, spv::DecorationBinding);
  942. msl.set_decoration(resource.id, spv::DecorationBinding, binding + 1);
  943. }
  944. for (auto &resource : resources.separate_images)
  945. {
  946. std::string name = msl.get_name(resource.id);
  947. if (name.size() > 7
  948. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  949. {
  950. msl.set_name(resource.id, name.substr(0, name.length() - 7));
  951. }
  952. }
  953. std::string source = msl.compile();
  954. if ('c' == _options.shaderType)
  955. {
  956. for (int i = 0; i < 3; ++i)
  957. {
  958. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  959. bx::write(_writer, dim);
  960. }
  961. }
  962. uint32_t shaderSize = (uint32_t)source.size();
  963. bx::write(_writer, shaderSize);
  964. bx::write(_writer, source.c_str(), shaderSize);
  965. uint8_t nul = 0;
  966. bx::write(_writer, nul);
  967. }
  968. else
  969. {
  970. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  971. bx::write(_writer, shaderSize);
  972. bx::write(_writer, spirv.data(), shaderSize);
  973. uint8_t nul = 0;
  974. bx::write(_writer, nul);
  975. }
  976. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  977. bx::write(_writer, numAttr);
  978. for (uint8_t ii = 0; ii < numAttr; ++ii)
  979. {
  980. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  981. if (bgfx::Attrib::Count != attr)
  982. {
  983. bx::write(_writer, bgfx::attribToId(attr) );
  984. }
  985. else
  986. {
  987. bx::write(_writer, uint16_t(UINT16_MAX) );
  988. }
  989. }
  990. bx::write(_writer, size);
  991. }
  992. }
  993. }
  994. delete program;
  995. delete shader;
  996. glslang::FinalizeProcess();
  997. return compiled && linked && validated;
  998. }
  999. } // namespace spirv
  1000. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  1001. {
  1002. return spirv::compile(_options, _version, _code, _writer, true);
  1003. }
  1004. } // namespace bgfx