2
0

shaderc_spirv.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. /*
  2. * Copyright 2011-2018 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. BX_PRAGMA_DIAGNOSTIC_POP()
  16. namespace bgfx
  17. {
  18. static bx::DefaultAllocator s_allocator;
  19. bx::AllocatorI* g_allocator = &s_allocator;
  20. struct TinyStlAllocator
  21. {
  22. static void* static_allocate(size_t _bytes);
  23. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  24. };
  25. void* TinyStlAllocator::static_allocate(size_t _bytes)
  26. {
  27. return BX_ALLOC(g_allocator, _bytes);
  28. }
  29. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  30. {
  31. if (NULL != _ptr)
  32. {
  33. BX_FREE(g_allocator, _ptr);
  34. }
  35. }
  36. } // namespace bgfx
  37. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  38. #include <tinystl/allocator.h>
  39. #include <tinystl/string.h>
  40. #include <tinystl/unordered_map.h>
  41. #include <tinystl/vector.h>
  42. namespace stl = tinystl;
  43. #include "../../src/shader_spirv.h"
  44. namespace bgfx { namespace spirv
  45. {
  46. const TBuiltInResource resourceLimits =
  47. {
  48. 32, // MaxLights
  49. 6, // MaxClipPlanes
  50. 32, // MaxTextureUnits
  51. 32, // MaxTextureCoords
  52. 64, // MaxVertexAttribs
  53. 4096, // MaxVertexUniformComponents
  54. 64, // MaxVaryingFloats
  55. 32, // MaxVertexTextureImageUnits
  56. 80, // MaxCombinedTextureImageUnits
  57. 32, // MaxTextureImageUnits
  58. 4096, // MaxFragmentUniformComponents
  59. 32, // MaxDrawBuffers
  60. 128, // MaxVertexUniformVectors
  61. 8, // MaxVaryingVectors
  62. 16, // MaxFragmentUniformVectors
  63. 16, // MaxVertexOutputVectors
  64. 15, // MaxFragmentInputVectors
  65. -8, // MinProgramTexelOffset
  66. 7, // MaxProgramTexelOffset
  67. 8, // MaxClipDistances
  68. 65535, // MaxComputeWorkGroupCountX
  69. 65535, // MaxComputeWorkGroupCountY
  70. 65535, // MaxComputeWorkGroupCountZ
  71. 1024, // MaxComputeWorkGroupSizeX
  72. 1024, // MaxComputeWorkGroupSizeY
  73. 64, // MaxComputeWorkGroupSizeZ
  74. 1024, // MaxComputeUniformComponents
  75. 16, // MaxComputeTextureImageUnits
  76. 8, // MaxComputeImageUniforms
  77. 8, // MaxComputeAtomicCounters
  78. 1, // MaxComputeAtomicCounterBuffers
  79. 60, // MaxVaryingComponents
  80. 64, // MaxVertexOutputComponents
  81. 64, // MaxGeometryInputComponents
  82. 128, // MaxGeometryOutputComponents
  83. 128, // MaxFragmentInputComponents
  84. 8, // MaxImageUnits
  85. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  86. 8, // MaxCombinedShaderOutputResources
  87. 0, // MaxImageSamples
  88. 0, // MaxVertexImageUniforms
  89. 0, // MaxTessControlImageUniforms
  90. 0, // MaxTessEvaluationImageUniforms
  91. 0, // MaxGeometryImageUniforms
  92. 8, // MaxFragmentImageUniforms
  93. 8, // MaxCombinedImageUniforms
  94. 16, // MaxGeometryTextureImageUnits
  95. 256, // MaxGeometryOutputVertices
  96. 1024, // MaxGeometryTotalOutputComponents
  97. 1024, // MaxGeometryUniformComponents
  98. 64, // MaxGeometryVaryingComponents
  99. 128, // MaxTessControlInputComponents
  100. 128, // MaxTessControlOutputComponents
  101. 16, // MaxTessControlTextureImageUnits
  102. 1024, // MaxTessControlUniformComponents
  103. 4096, // MaxTessControlTotalOutputComponents
  104. 128, // MaxTessEvaluationInputComponents
  105. 128, // MaxTessEvaluationOutputComponents
  106. 16, // MaxTessEvaluationTextureImageUnits
  107. 1024, // MaxTessEvaluationUniformComponents
  108. 120, // MaxTessPatchComponents
  109. 32, // MaxPatchVertices
  110. 64, // MaxTessGenLevel
  111. 16, // MaxViewports
  112. 0, // MaxVertexAtomicCounters
  113. 0, // MaxTessControlAtomicCounters
  114. 0, // MaxTessEvaluationAtomicCounters
  115. 0, // MaxGeometryAtomicCounters
  116. 8, // MaxFragmentAtomicCounters
  117. 8, // MaxCombinedAtomicCounters
  118. 1, // MaxAtomicCounterBindings
  119. 0, // MaxVertexAtomicCounterBuffers
  120. 0, // MaxTessControlAtomicCounterBuffers
  121. 0, // MaxTessEvaluationAtomicCounterBuffers
  122. 0, // MaxGeometryAtomicCounterBuffers
  123. 1, // MaxFragmentAtomicCounterBuffers
  124. 1, // MaxCombinedAtomicCounterBuffers
  125. 16384, // MaxAtomicCounterBufferSize
  126. 4, // MaxTransformFeedbackBuffers
  127. 64, // MaxTransformFeedbackInterleavedComponents
  128. 8, // MaxCullDistances
  129. 8, // MaxCombinedClipAndCullDistances
  130. 4, // MaxSamples
  131. 0, // maxMeshOutputVerticesNV;
  132. 0, // maxMeshOutputPrimitivesNV;
  133. 0, // maxMeshWorkGroupSizeX_NV;
  134. 0, // maxMeshWorkGroupSizeY_NV;
  135. 0, // maxMeshWorkGroupSizeZ_NV;
  136. 0, // maxTaskWorkGroupSizeX_NV;
  137. 0, // maxTaskWorkGroupSizeY_NV;
  138. 0, // maxTaskWorkGroupSizeZ_NV;
  139. 0, // maxMeshViewCountNV
  140. { // limits
  141. true, // nonInductiveForLoops
  142. true, // whileLoops
  143. true, // doWhileLoops
  144. true, // generalUniformIndexing
  145. true, // generalAttributeMatrixVectorIndexing
  146. true, // generalVaryingIndexing
  147. true, // generalSamplerIndexing
  148. true, // generalVariableIndexing
  149. true, // generalConstantMatrixVectorIndexing
  150. },
  151. };
  152. bool printAsm(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  153. {
  154. BX_UNUSED(_userData);
  155. char temp[512];
  156. toString(temp, sizeof(temp), _instruction);
  157. BX_TRACE("%5d: %s", _offset, temp);
  158. return true;
  159. }
  160. struct SpvReflection
  161. {
  162. struct TypeId
  163. {
  164. enum Enum
  165. {
  166. Void,
  167. Bool,
  168. Int32,
  169. Int64,
  170. Uint32,
  171. Uint64,
  172. Float,
  173. Double,
  174. Vector,
  175. Matrix,
  176. Count
  177. };
  178. TypeId()
  179. : baseType(Enum::Count)
  180. , type(Enum::Count)
  181. , numComponents(0)
  182. {
  183. }
  184. Enum baseType;
  185. Enum type;
  186. uint32_t numComponents;
  187. stl::string toString()
  188. {
  189. stl::string result;
  190. switch (type)
  191. {
  192. case Float:
  193. result.append("float");
  194. break;
  195. case Vector:
  196. bx::stringPrintf(result, "vec%d"
  197. , numComponents
  198. );
  199. break;
  200. case Matrix:
  201. bx::stringPrintf(result, "mat%d"
  202. , numComponents
  203. );
  204. default:
  205. break;
  206. }
  207. return result;
  208. }
  209. };
  210. struct Id
  211. {
  212. struct Variable
  213. {
  214. Variable()
  215. : decoration(SpvDecoration::Count)
  216. , builtin(SpvBuiltin::Count)
  217. , storageClass(SpvStorageClass::Count)
  218. , location(UINT32_MAX)
  219. , offset(UINT32_MAX)
  220. , type(UINT32_MAX)
  221. {
  222. }
  223. stl::string name;
  224. SpvDecoration::Enum decoration;
  225. SpvBuiltin::Enum builtin;
  226. SpvStorageClass::Enum storageClass;
  227. uint32_t location;
  228. uint32_t offset;
  229. uint32_t type;
  230. };
  231. typedef stl::vector<Variable> MemberArray;
  232. Variable var;
  233. MemberArray members;
  234. };
  235. typedef stl::unordered_map<uint32_t, TypeId> TypeIdMap;
  236. typedef stl::unordered_map<uint32_t, Id> IdMap;
  237. TypeIdMap typeIdMap;
  238. IdMap idMap;
  239. stl::string getTypeName(uint32_t _typeId)
  240. {
  241. return getTypeId(_typeId).toString();
  242. }
  243. Id& getId(uint32_t _id)
  244. {
  245. IdMap::iterator it = idMap.find(_id);
  246. if (it == idMap.end() )
  247. {
  248. Id id;
  249. stl::pair<IdMap::iterator, bool> result = idMap.insert(stl::make_pair(_id, id) );
  250. it = result.first;
  251. }
  252. return it->second;
  253. }
  254. Id::Variable& get(uint32_t _id, uint32_t _idx)
  255. {
  256. Id& id = getId(_id);
  257. id.members.resize(bx::uint32_max(_idx+1, uint32_t(id.members.size() ) ) );
  258. return id.members[_idx];
  259. }
  260. TypeId& getTypeId(uint32_t _id)
  261. {
  262. TypeIdMap::iterator it = typeIdMap.find(_id);
  263. if (it == typeIdMap.end() )
  264. {
  265. TypeId id;
  266. stl::pair<TypeIdMap::iterator, bool> result = typeIdMap.insert(stl::make_pair(_id, id) );
  267. it = result.first;
  268. }
  269. return it->second;
  270. }
  271. void update(uint32_t _id, const stl::string& _name)
  272. {
  273. getId(_id).var.name = _name;
  274. }
  275. BX_NO_INLINE void update(Id::Variable& _variable, SpvDecoration::Enum _decoration, uint32_t _literal)
  276. {
  277. _variable.decoration = _decoration;
  278. switch (_decoration)
  279. {
  280. case SpvDecoration::Location:
  281. _variable.location = _literal;
  282. break;
  283. case SpvDecoration::Offset:
  284. _variable.offset = _literal;
  285. break;
  286. case SpvDecoration::BuiltIn:
  287. _variable.builtin = SpvBuiltin::Enum(_literal);
  288. break;
  289. default:
  290. break;
  291. }
  292. }
  293. BX_NO_INLINE void update(Id::Variable& _variable, uint32_t _type, SpvStorageClass::Enum _storageClass)
  294. {
  295. _variable.type = _type;
  296. _variable.storageClass = _storageClass;
  297. }
  298. void update(uint32_t _id, SpvDecoration::Enum _decoration, uint32_t _literal)
  299. {
  300. update(getId(_id).var, _decoration, _literal);
  301. }
  302. void update(uint32_t _id, uint32_t _type, SpvStorageClass::Enum _storageClass)
  303. {
  304. update(getId(_id).var, _type, _storageClass);
  305. }
  306. void update(uint32_t _id, uint32_t _idx, const stl::string& _name)
  307. {
  308. Id::Variable& var = get(_id, _idx);
  309. var.name = _name;
  310. }
  311. BX_NO_INLINE void update(uint32_t _id, uint32_t _idx, SpvDecoration::Enum _decoration, uint32_t _literal)
  312. {
  313. update(get(_id, _idx), _decoration, _literal);
  314. }
  315. void update(uint32_t _id, TypeId::Enum _type)
  316. {
  317. TypeId& type = getTypeId(_id);
  318. type.type = _type;
  319. }
  320. void update(uint32_t _id, TypeId::Enum _type, uint32_t _baseTypeId, uint32_t _numComonents)
  321. {
  322. TypeId& type = getTypeId(_id);
  323. type.type = _type;
  324. type.baseType = getTypeId(_baseTypeId).type;
  325. type.numComponents = _numComonents;
  326. }
  327. };
  328. bool spvParse(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  329. {
  330. BX_UNUSED(_offset);
  331. SpvReflection* spv = (SpvReflection*)_userData;
  332. switch (_instruction.opcode)
  333. {
  334. case SpvOpcode::Name:
  335. spv->update(_instruction.result
  336. , _instruction.operand[0].literalString
  337. );
  338. break;
  339. case SpvOpcode::Decorate:
  340. spv->update(_instruction.operand[0].data
  341. , SpvDecoration::Enum(_instruction.operand[1].data)
  342. , _instruction.operand[2].data
  343. );
  344. break;
  345. case SpvOpcode::MemberName:
  346. spv->update(_instruction.result
  347. , _instruction.operand[0].data
  348. , _instruction.operand[1].literalString
  349. );
  350. break;
  351. case SpvOpcode::MemberDecorate:
  352. spv->update(_instruction.operand[0].data
  353. , _instruction.operand[1].data
  354. , SpvDecoration::Enum(_instruction.operand[2].data)
  355. , _instruction.operand[3].data
  356. );
  357. break;
  358. case SpvOpcode::Variable:
  359. spv->update(_instruction.result
  360. , _instruction.type
  361. , SpvStorageClass::Enum(_instruction.operand[0].data)
  362. );
  363. break;
  364. case SpvOpcode::TypeVoid:
  365. spv->update(_instruction.result, SpvReflection::TypeId::Void);
  366. break;
  367. case SpvOpcode::TypeBool:
  368. spv->update(_instruction.result, SpvReflection::TypeId::Bool);
  369. break;
  370. case SpvOpcode::TypeInt:
  371. spv->update(_instruction.result
  372. , 32 == _instruction.operand[0].data
  373. ? 0 == _instruction.operand[1].data
  374. ? SpvReflection::TypeId::Uint32
  375. : SpvReflection::TypeId::Int32
  376. : 0 == _instruction.operand[1].data
  377. ? SpvReflection::TypeId::Uint64
  378. : SpvReflection::TypeId::Int64
  379. );
  380. break;
  381. case SpvOpcode::TypeFloat:
  382. spv->update(_instruction.result
  383. , 32 == _instruction.operand[0].data
  384. ? SpvReflection::TypeId::Float
  385. : SpvReflection::TypeId::Double
  386. );
  387. break;
  388. case SpvOpcode::TypeVector:
  389. spv->update(_instruction.result
  390. , SpvReflection::TypeId::Vector
  391. , _instruction.operand[0].data
  392. , _instruction.operand[1].data
  393. );
  394. break;
  395. case SpvOpcode::TypeMatrix:
  396. spv->update(_instruction.result
  397. , SpvReflection::TypeId::Matrix
  398. , _instruction.operand[0].data
  399. , _instruction.operand[1].data
  400. );
  401. break;
  402. case SpvOpcode::TypeImage:
  403. case SpvOpcode::TypeSampler:
  404. case SpvOpcode::TypeSampledImage:
  405. break;
  406. case SpvOpcode::TypeStruct:
  407. for (uint32_t ii = 0, num = _instruction.numOperands; ii < num; ++ii)
  408. {
  409. SpvReflection::Id::Variable& var = spv->get(_instruction.result, ii);
  410. var.type = _instruction.operand[ii].data;
  411. }
  412. break;
  413. default:
  414. break;
  415. }
  416. return true;
  417. }
  418. #define DBG(...) // bx::debugPrintf(__VA_ARGS__)
  419. void disassemble(bx::WriterI* _writer, bx::ReaderSeekerI* _reader, bx::Error* _err)
  420. {
  421. BX_UNUSED(_writer);
  422. uint32_t magic;
  423. bx::peek(_reader, magic);
  424. SpvReflection spvx;
  425. if (magic == SPV_CHUNK_HEADER)
  426. {
  427. SpirV spirv;
  428. read(_reader, spirv, _err);
  429. parse(spirv.shader, spvParse, &spvx, _err);
  430. for (SpvReflection::IdMap::const_iterator it = spvx.idMap.begin(), itEnd = spvx.idMap.end(); it != itEnd; ++it)
  431. {
  432. const SpvReflection::Id& id = it->second;
  433. uint32_t num = uint32_t(id.members.size() );
  434. if (0 < num
  435. && 0 != bx::strCmp(id.var.name.c_str(), "gl_PerVertex") )
  436. {
  437. DBG("%3d: %s %d %s\n"
  438. , it->first
  439. , id.var.name.c_str()
  440. , id.var.location
  441. , getName(id.var.storageClass)
  442. );
  443. DBG("{\n");
  444. for (uint32_t ii = 0; ii < num; ++ii)
  445. {
  446. const SpvReflection::Id::Variable& var = id.members[ii];
  447. DBG("\t\t%s %s %d %s\n"
  448. , spvx.getTypeName(var.type).c_str()
  449. , var.name.c_str()
  450. , var.offset
  451. , getName(var.storageClass)
  452. );
  453. BX_UNUSED(var);
  454. }
  455. DBG("}\n");
  456. }
  457. }
  458. }
  459. }
  460. static EShLanguage getLang(char _p)
  461. {
  462. switch (_p)
  463. {
  464. case 'c': return EShLangCompute;
  465. case 'f': return EShLangFragment;
  466. case 'v': return EShLangVertex;
  467. default: return EShLangCount;
  468. }
  469. }
  470. // static void printError(spv_message_level_t, const char*, const spv_position_t&, const char* _message)
  471. // {
  472. // fprintf(stderr, "%s\n", _message);
  473. // }
  474. static const char* s_attribName[] =
  475. {
  476. "a_position",
  477. "a_normal",
  478. "a_tangent",
  479. "a_bitangent",
  480. "a_color0",
  481. "a_color1",
  482. "a_color2",
  483. "a_color3",
  484. "a_indices",
  485. "a_weight",
  486. "a_texcoord0",
  487. "a_texcoord1",
  488. "a_texcoord2",
  489. "a_texcoord3",
  490. "a_texcoord4",
  491. "a_texcoord5",
  492. "a_texcoord6",
  493. "a_texcoord7",
  494. };
  495. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  496. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  497. {
  498. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  499. {
  500. if (0 == bx::strCmp(s_attribName[ii], _name) )
  501. {
  502. return bgfx::Attrib::Enum(ii);
  503. }
  504. }
  505. return bgfx::Attrib::Count;
  506. }
  507. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  508. {
  509. BX_UNUSED(_version);
  510. glslang::InitializeProcess();
  511. glslang::TProgram* program = new glslang::TProgram;
  512. EShLanguage stage = getLang(_options.shaderType);
  513. if (EShLangCount == stage)
  514. {
  515. fprintf(stderr, "Error: Unknown shader type '%c'.\n", _options.shaderType);
  516. return false;
  517. }
  518. glslang::TShader* shader = new glslang::TShader(stage);
  519. EShMessages messages = EShMessages(0
  520. | EShMsgDefault
  521. | EShMsgReadHlsl
  522. | EShMsgVulkanRules
  523. | EShMsgSpvRules
  524. );
  525. shader->setEntryPoint("main");
  526. const char* shaderStrings[] = { _code.c_str() };
  527. shader->setStrings(
  528. shaderStrings
  529. , BX_COUNTOF(shaderStrings)
  530. );
  531. bool compiled = shader->parse(&resourceLimits
  532. , 110
  533. , false
  534. , messages
  535. );
  536. bool linked = false;
  537. bool validated = true;
  538. if (!compiled)
  539. {
  540. const char* log = shader->getInfoLog();
  541. if (NULL != log)
  542. {
  543. int32_t source = 0;
  544. int32_t line = 0;
  545. int32_t column = 0;
  546. int32_t start = 0;
  547. int32_t end = INT32_MAX;
  548. bx::StringView err = bx::strFind(log, "ERROR:");
  549. bool found = false;
  550. if (!err.isEmpty() )
  551. {
  552. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  553. if (found)
  554. {
  555. ++line;
  556. }
  557. }
  558. if (found)
  559. {
  560. start = bx::uint32_imax(1, line-10);
  561. end = start + 20;
  562. }
  563. printCode(_code.c_str(), line, start, end, column);
  564. fprintf(stderr, "%s\n", log);
  565. }
  566. }
  567. else
  568. {
  569. program->addShader(shader);
  570. linked = true
  571. && program->link(messages)
  572. && program->mapIO()
  573. ;
  574. if (!linked)
  575. {
  576. const char* log = program->getInfoLog();
  577. if (NULL != log)
  578. {
  579. fprintf(stderr, "%s\n", log);
  580. }
  581. }
  582. else
  583. {
  584. uint16_t size = 0;
  585. program->buildReflection();
  586. if (_firstPass)
  587. {
  588. const size_t strLength = bx::strLen("uniform");
  589. // first time through, we just find unused uniforms and get rid of them
  590. std::string output;
  591. bx::Error err;
  592. LineReader reader(_code.c_str() );
  593. while (err.isOk() )
  594. {
  595. char str[4096];
  596. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  597. if (err.isOk() )
  598. {
  599. std::string strLine(str, len);
  600. size_t index = strLine.find("uniform ");
  601. if (index != std::string::npos)
  602. {
  603. bool found = false;
  604. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  605. {
  606. // matching lines like: uniform u_name;
  607. // we want to replace "uniform" with "static" so that it's no longer
  608. // included in the uniform blob that the application must upload
  609. // we can't just remove them, because unused functions might still reference
  610. // them and cause a compile error when they're gone
  611. if (!bx::findIdentifierMatch(strLine.c_str(), program->getUniformName(ii) ).isEmpty() )
  612. {
  613. found = true;
  614. break;
  615. }
  616. }
  617. if (!found)
  618. {
  619. strLine = strLine.replace(index, strLength, "static");
  620. }
  621. }
  622. output += strLine;
  623. }
  624. }
  625. // recompile with the unused uniforms converted to statics
  626. return compile(_options, _version, output.c_str(), _writer, false);
  627. }
  628. {
  629. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  630. bx::write(_writer, count);
  631. uint32_t fragmentBit = _options.shaderType == 'f' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  632. for (uint16_t ii = 0; ii < count; ++ii)
  633. {
  634. Uniform un;
  635. un.name = program->getUniformName(ii);
  636. un.num = uint8_t(program->getUniformArraySize(ii) );
  637. const uint32_t offset = program->getUniformBufferOffset(ii);
  638. un.regIndex = uint16_t(offset);
  639. un.regCount = un.num;
  640. switch (program->getUniformType(ii))
  641. {
  642. case 0x1404: // GL_INT:
  643. un.type = UniformType::Int1;
  644. break;
  645. case 0x8B52: // GL_FLOAT_VEC4:
  646. un.type = UniformType::Vec4;
  647. break;
  648. case 0x8B5B: // GL_FLOAT_MAT3:
  649. un.type = UniformType::Mat3;
  650. un.regCount *= 3;
  651. break;
  652. case 0x8B5C: // GL_FLOAT_MAT4:
  653. un.type = UniformType::Mat4;
  654. un.regCount *= 4;
  655. break;
  656. default:
  657. un.type = UniformType::End;
  658. break;
  659. }
  660. size += un.regCount*16;
  661. uint8_t nameSize = (uint8_t)un.name.size();
  662. bx::write(_writer, nameSize);
  663. bx::write(_writer, un.name.c_str(), nameSize);
  664. bx::write(_writer, uint8_t(un.type | fragmentBit));
  665. bx::write(_writer, un.num);
  666. bx::write(_writer, un.regIndex);
  667. bx::write(_writer, un.regCount);
  668. BX_TRACE("%s, %s, %d, %d, %d"
  669. , un.name.c_str()
  670. , getUniformTypeName(un.type)
  671. , un.num
  672. , un.regIndex
  673. , un.regCount
  674. );
  675. }
  676. }
  677. if (g_verbose)
  678. {
  679. program->dumpReflection();
  680. }
  681. BX_UNUSED(spv::MemorySemanticsAllMemory);
  682. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  683. std::vector<uint32_t> spirv;
  684. glslang::SpvOptions options;
  685. options.disableOptimizer = false;
  686. glslang::GlslangToSpv(*intermediate, spirv, &options);
  687. bx::Error err;
  688. bx::WriterI* writer = bx::getDebugOut();
  689. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  690. disassemble(writer, &reader, &err);
  691. uint32_t shaderSize = (uint32_t)spirv.size()*sizeof(uint32_t);
  692. bx::write(_writer, shaderSize);
  693. bx::write(_writer, spirv.data(), shaderSize);
  694. uint8_t nul = 0;
  695. bx::write(_writer, nul);
  696. //
  697. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  698. bx::write(_writer, numAttr);
  699. for (uint8_t ii = 0; ii < numAttr; ++ii)
  700. {
  701. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  702. if (bgfx::Attrib::Count != attr)
  703. {
  704. bx::write(_writer, bgfx::attribToId(attr) );
  705. }
  706. else
  707. {
  708. bx::write(_writer, uint16_t(UINT16_MAX) );
  709. }
  710. }
  711. bx::write(_writer, size);
  712. }
  713. }
  714. delete program;
  715. delete shader;
  716. glslang::FinalizeProcess();
  717. return compiled && linked && validated;
  718. }
  719. } // namespace spirv
  720. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  721. {
  722. return spirv::compile(_options, _version, _code, _writer, true);
  723. }
  724. } // namespace bgfx