shaderc_metal.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*
  2. * Copyright 2011-2021 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("-Wattributes") // warning: attribute ignored
  10. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wdeprecated-declarations") // warning: ‘MSLVertexAttr’ is deprecated
  11. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits") // warning: comparison of unsigned expression in ‘< 0’ is always false
  12. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow") // warning: declaration of 'userData' shadows a member of 'glslang::TShader::Includer::IncludeResult'
  13. #define ENABLE_OPT 1
  14. #include <ShaderLang.h>
  15. #include <ResourceLimits.h>
  16. #include <SPIRV/SPVRemapper.h>
  17. #include <SPIRV/GlslangToSpv.h>
  18. #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
  19. #include <spirv_msl.hpp>
  20. #include <spirv_reflect.hpp>
  21. #include <spirv-tools/optimizer.hpp>
  22. BX_PRAGMA_DIAGNOSTIC_POP()
  23. namespace bgfx
  24. {
  25. struct TinyStlAllocator
  26. {
  27. static void* static_allocate(size_t _bytes);
  28. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  29. };
  30. } // namespace bgfx
  31. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  32. #include <tinystl/allocator.h>
  33. #include <tinystl/string.h>
  34. #include <tinystl/unordered_map.h>
  35. #include <tinystl/vector.h>
  36. namespace stl = tinystl;
  37. #include "../../src/shader.h"
  38. namespace bgfx { namespace metal
  39. {
  40. const TBuiltInResource resourceLimits =
  41. {
  42. 32, // MaxLights
  43. 6, // MaxClipPlanes
  44. 32, // MaxTextureUnits
  45. 32, // MaxTextureCoords
  46. 64, // MaxVertexAttribs
  47. 4096, // MaxVertexUniformComponents
  48. 64, // MaxVaryingFloats
  49. 32, // MaxVertexTextureImageUnits
  50. 80, // MaxCombinedTextureImageUnits
  51. 32, // MaxTextureImageUnits
  52. 4096, // MaxFragmentUniformComponents
  53. 32, // MaxDrawBuffers
  54. 128, // MaxVertexUniformVectors
  55. 8, // MaxVaryingVectors
  56. 16, // MaxFragmentUniformVectors
  57. 16, // MaxVertexOutputVectors
  58. 15, // MaxFragmentInputVectors
  59. -8, // MinProgramTexelOffset
  60. 7, // MaxProgramTexelOffset
  61. 8, // MaxClipDistances
  62. 65535, // MaxComputeWorkGroupCountX
  63. 65535, // MaxComputeWorkGroupCountY
  64. 65535, // MaxComputeWorkGroupCountZ
  65. 1024, // MaxComputeWorkGroupSizeX
  66. 1024, // MaxComputeWorkGroupSizeY
  67. 64, // MaxComputeWorkGroupSizeZ
  68. 1024, // MaxComputeUniformComponents
  69. 16, // MaxComputeTextureImageUnits
  70. 8, // MaxComputeImageUniforms
  71. 8, // MaxComputeAtomicCounters
  72. 1, // MaxComputeAtomicCounterBuffers
  73. 60, // MaxVaryingComponents
  74. 64, // MaxVertexOutputComponents
  75. 64, // MaxGeometryInputComponents
  76. 128, // MaxGeometryOutputComponents
  77. 128, // MaxFragmentInputComponents
  78. 8, // MaxImageUnits
  79. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  80. 8, // MaxCombinedShaderOutputResources
  81. 0, // MaxImageSamples
  82. 0, // MaxVertexImageUniforms
  83. 0, // MaxTessControlImageUniforms
  84. 0, // MaxTessEvaluationImageUniforms
  85. 0, // MaxGeometryImageUniforms
  86. 8, // MaxFragmentImageUniforms
  87. 8, // MaxCombinedImageUniforms
  88. 16, // MaxGeometryTextureImageUnits
  89. 256, // MaxGeometryOutputVertices
  90. 1024, // MaxGeometryTotalOutputComponents
  91. 1024, // MaxGeometryUniformComponents
  92. 64, // MaxGeometryVaryingComponents
  93. 128, // MaxTessControlInputComponents
  94. 128, // MaxTessControlOutputComponents
  95. 16, // MaxTessControlTextureImageUnits
  96. 1024, // MaxTessControlUniformComponents
  97. 4096, // MaxTessControlTotalOutputComponents
  98. 128, // MaxTessEvaluationInputComponents
  99. 128, // MaxTessEvaluationOutputComponents
  100. 16, // MaxTessEvaluationTextureImageUnits
  101. 1024, // MaxTessEvaluationUniformComponents
  102. 120, // MaxTessPatchComponents
  103. 32, // MaxPatchVertices
  104. 64, // MaxTessGenLevel
  105. 16, // MaxViewports
  106. 0, // MaxVertexAtomicCounters
  107. 0, // MaxTessControlAtomicCounters
  108. 0, // MaxTessEvaluationAtomicCounters
  109. 0, // MaxGeometryAtomicCounters
  110. 8, // MaxFragmentAtomicCounters
  111. 8, // MaxCombinedAtomicCounters
  112. 1, // MaxAtomicCounterBindings
  113. 0, // MaxVertexAtomicCounterBuffers
  114. 0, // MaxTessControlAtomicCounterBuffers
  115. 0, // MaxTessEvaluationAtomicCounterBuffers
  116. 0, // MaxGeometryAtomicCounterBuffers
  117. 1, // MaxFragmentAtomicCounterBuffers
  118. 1, // MaxCombinedAtomicCounterBuffers
  119. 16384, // MaxAtomicCounterBufferSize
  120. 4, // MaxTransformFeedbackBuffers
  121. 64, // MaxTransformFeedbackInterleavedComponents
  122. 8, // MaxCullDistances
  123. 8, // MaxCombinedClipAndCullDistances
  124. 4, // MaxSamples
  125. 0, // maxMeshOutputVerticesNV
  126. 0, // maxMeshOutputPrimitivesNV
  127. 0, // maxMeshWorkGroupSizeX_NV
  128. 0, // maxMeshWorkGroupSizeY_NV
  129. 0, // maxMeshWorkGroupSizeZ_NV
  130. 0, // maxTaskWorkGroupSizeX_NV
  131. 0, // maxTaskWorkGroupSizeY_NV
  132. 0, // maxTaskWorkGroupSizeZ_NV
  133. 0, // maxMeshViewCountNV
  134. 0, // maxDualSourceDrawBuffersEXT
  135. { // limits
  136. true, // nonInductiveForLoops
  137. true, // whileLoops
  138. true, // doWhileLoops
  139. true, // generalUniformIndexing
  140. true, // generalAttributeMatrixVectorIndexing
  141. true, // generalVaryingIndexing
  142. true, // generalSamplerIndexing
  143. true, // generalVariableIndexing
  144. true, // generalConstantMatrixVectorIndexing
  145. },
  146. };
  147. static EShLanguage getLang(char _p)
  148. {
  149. switch (_p)
  150. {
  151. case 'c': return EShLangCompute;
  152. case 'f': return EShLangFragment;
  153. case 'v': return EShLangVertex;
  154. default: return EShLangCount;
  155. }
  156. }
  157. static const char* s_attribName[] =
  158. {
  159. "a_position",
  160. "a_normal",
  161. "a_tangent",
  162. "a_bitangent",
  163. "a_color0",
  164. "a_color1",
  165. "a_color2",
  166. "a_color3",
  167. "a_indices",
  168. "a_weight",
  169. "a_texcoord0",
  170. "a_texcoord1",
  171. "a_texcoord2",
  172. "a_texcoord3",
  173. "a_texcoord4",
  174. "a_texcoord5",
  175. "a_texcoord6",
  176. "a_texcoord7",
  177. };
  178. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  179. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  180. {
  181. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  182. {
  183. if (0 == bx::strCmp(s_attribName[ii], _name) )
  184. {
  185. return bgfx::Attrib::Enum(ii);
  186. }
  187. }
  188. return bgfx::Attrib::Count;
  189. }
  190. static const char* s_samplerTypes[] =
  191. {
  192. "BgfxSampler2D",
  193. "BgfxISampler2D",
  194. "BgfxUSampler2D",
  195. "BgfxSampler2DArray",
  196. "BgfxSampler2DShadow",
  197. "BgfxSampler2DArrayShadow",
  198. "BgfxSampler3D",
  199. "BgfxISampler3D",
  200. "BgfxUSampler3D",
  201. "BgfxSamplerCube",
  202. "BgfxSamplerCubeShadow",
  203. "BgfxSampler2DMS",
  204. };
  205. static uint16_t writeUniformArray(bx::WriterI* _writer, const UniformArray& uniforms, bool isFragmentShader)
  206. {
  207. uint16_t size = 0;
  208. bx::ErrorAssert err;
  209. uint16_t count = uint16_t(uniforms.size());
  210. bx::write(_writer, count, &err);
  211. uint32_t fragmentBit = isFragmentShader ? kUniformFragmentBit : 0;
  212. for (uint16_t ii = 0; ii < count; ++ii)
  213. {
  214. const Uniform& un = uniforms[ii];
  215. size += un.regCount*16;
  216. uint8_t nameSize = (uint8_t)un.name.size();
  217. bx::write(_writer, nameSize, &err);
  218. bx::write(_writer, un.name.c_str(), nameSize, &err);
  219. bx::write(_writer, uint8_t(un.type | fragmentBit), &err);
  220. bx::write(_writer, un.num, &err);
  221. bx::write(_writer, un.regIndex, &err);
  222. bx::write(_writer, un.regCount, &err);
  223. bx::write(_writer, un.texComponent, &err);
  224. bx::write(_writer, un.texDimension, &err);
  225. bx::write(_writer, un.texFormat, &err);
  226. BX_TRACE("%s, %s, %d, %d, %d"
  227. , un.name.c_str()
  228. , getUniformTypeName(un.type)
  229. , un.num
  230. , un.regIndex
  231. , un.regCount
  232. );
  233. }
  234. return size;
  235. }
  236. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  237. {
  238. BX_UNUSED(_version);
  239. glslang::InitializeProcess();
  240. EShLanguage stage = getLang(_options.shaderType);
  241. if (EShLangCount == stage)
  242. {
  243. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  244. return false;
  245. }
  246. glslang::TProgram* program = new glslang::TProgram;
  247. glslang::TShader* shader = new glslang::TShader(stage);
  248. EShMessages messages = EShMessages(0
  249. | EShMsgDefault
  250. | EShMsgReadHlsl
  251. | EShMsgVulkanRules
  252. | EShMsgSpvRules
  253. );
  254. shader->setEntryPoint("main");
  255. shader->setAutoMapBindings(true);
  256. const int textureBindingOffset = 16;
  257. shader->setShiftBinding(glslang::EResTexture, textureBindingOffset);
  258. shader->setShiftBinding(glslang::EResSampler, textureBindingOffset);
  259. shader->setShiftBinding(glslang::EResImage, textureBindingOffset);
  260. const char* shaderStrings[] = { _code.c_str() };
  261. shader->setStrings(
  262. shaderStrings
  263. , BX_COUNTOF(shaderStrings)
  264. );
  265. bool compiled = shader->parse(&resourceLimits
  266. , 110
  267. , false
  268. , messages
  269. );
  270. bool linked = false;
  271. bool validated = true;
  272. if (!compiled)
  273. {
  274. const char* log = shader->getInfoLog();
  275. if (NULL != log)
  276. {
  277. int32_t source = 0;
  278. int32_t line = 0;
  279. int32_t column = 0;
  280. int32_t start = 0;
  281. int32_t end = INT32_MAX;
  282. bx::StringView err = bx::strFind(log, "ERROR:");
  283. bool found = false;
  284. if (!err.isEmpty() )
  285. {
  286. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  287. if (found)
  288. {
  289. ++line;
  290. }
  291. }
  292. if (found)
  293. {
  294. start = bx::uint32_imax(1, line-10);
  295. end = start + 20;
  296. }
  297. printCode(_code.c_str(), line, start, end, column);
  298. bx::printf("%s\n", log);
  299. }
  300. }
  301. else
  302. {
  303. program->addShader(shader);
  304. linked = true
  305. && program->link(messages)
  306. && program->mapIO()
  307. ;
  308. if (!linked)
  309. {
  310. const char* log = program->getInfoLog();
  311. if (NULL != log)
  312. {
  313. bx::printf("%s\n", log);
  314. }
  315. }
  316. else
  317. {
  318. program->buildReflection();
  319. if (_firstPass)
  320. {
  321. // first time through, we just find unused uniforms and get rid of them
  322. std::string output;
  323. bx::Error err;
  324. bx::LineReader reader(_code.c_str() );
  325. while (!reader.isDone() )
  326. {
  327. bx::StringView strLine = reader.next();
  328. bx::StringView str = strFind(strLine, "uniform ");
  329. if (!str.isEmpty() )
  330. {
  331. // If the line declares a uniform, merge all next
  332. // lines until we encounter a semicolon.
  333. bx::StringView lineEnd = strFind(strLine, ";");
  334. while (lineEnd.isEmpty() && !reader.isDone()) {
  335. bx::StringView nextLine = reader.next();
  336. strLine.set(strLine.getPtr(), nextLine.getTerm());
  337. lineEnd = strFind(nextLine, ";");
  338. }
  339. bool found = false;
  340. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  341. {
  342. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  343. {
  344. found = true;
  345. break;
  346. }
  347. }
  348. if (!found)
  349. {
  350. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  351. {
  352. // matching lines like: uniform u_name;
  353. // we want to replace "uniform" with "static" so that it's no longer
  354. // included in the uniform blob that the application must upload
  355. // we can't just remove them, because unused functions might still reference
  356. // them and cause a compile error when they're gone
  357. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  358. {
  359. found = true;
  360. break;
  361. }
  362. }
  363. }
  364. if (!found)
  365. {
  366. output.append(strLine.getPtr(), str.getPtr() );
  367. output += "static ";
  368. output.append(str.getTerm(), strLine.getTerm() );
  369. output += "\n";
  370. }
  371. else
  372. {
  373. output.append(strLine.getPtr(), strLine.getTerm() );
  374. output += "\n";
  375. }
  376. }
  377. else
  378. {
  379. output.append(strLine.getPtr(), strLine.getTerm() );
  380. output += "\n";
  381. }
  382. }
  383. // recompile with the unused uniforms converted to statics
  384. delete program;
  385. delete shader;
  386. return compile(_options, _version, output.c_str(), _writer, false);
  387. }
  388. UniformArray uniforms;
  389. {
  390. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  391. for (uint16_t ii = 0; ii < count; ++ii)
  392. {
  393. Uniform un;
  394. un.name = program->getUniformName(ii);
  395. un.num = uint8_t(program->getUniformArraySize(ii) );
  396. const uint32_t offset = program->getUniformBufferOffset(ii);
  397. un.regIndex = uint16_t(offset);
  398. un.regCount = un.num;
  399. switch (program->getUniformType(ii) )
  400. {
  401. case 0x1404: // GL_INT:
  402. un.type = UniformType::Sampler;
  403. break;
  404. case 0x8B52: // GL_FLOAT_VEC4:
  405. un.type = UniformType::Vec4;
  406. break;
  407. case 0x8B5B: // GL_FLOAT_MAT3:
  408. un.type = UniformType::Mat3;
  409. un.regCount *= 3;
  410. break;
  411. case 0x8B5C: // GL_FLOAT_MAT4:
  412. un.type = UniformType::Mat4;
  413. un.regCount *= 4;
  414. break;
  415. default:
  416. un.type = UniformType::End;
  417. break;
  418. }
  419. uniforms.push_back(un);
  420. }
  421. }
  422. if (g_verbose)
  423. {
  424. program->dumpReflection();
  425. }
  426. BX_UNUSED(spv::MemorySemanticsAllMemory);
  427. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  428. std::vector<uint32_t> spirv;
  429. glslang::SpvOptions options;
  430. options.disableOptimizer = false;
  431. glslang::GlslangToSpv(*intermediate, spirv, &options);
  432. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  433. auto print_msg_to_stderr = [](
  434. spv_message_level_t
  435. , const char*
  436. , const spv_position_t&
  437. , const char* m
  438. )
  439. {
  440. bx::printf("Error: %s\n", m);
  441. };
  442. opt.SetMessageConsumer(print_msg_to_stderr);
  443. opt.RegisterLegalizationPasses();
  444. spvtools::ValidatorOptions validatorOptions;
  445. validatorOptions.SetBeforeHlslLegalization(true);
  446. if (!opt.Run(
  447. spirv.data()
  448. , spirv.size()
  449. , &spirv
  450. , validatorOptions
  451. , false
  452. ) )
  453. {
  454. compiled = false;
  455. }
  456. else
  457. {
  458. if (g_verbose)
  459. {
  460. glslang::SpirvToolsDisassemble(std::cout, spirv, SPV_ENV_VULKAN_1_0);
  461. }
  462. spirv_cross::CompilerReflection refl(spirv);
  463. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  464. // Loop through the separate_images, and extract the uniform names:
  465. for (auto &resource : resourcesrefl.separate_images)
  466. {
  467. std::string name = refl.get_name(resource.id);
  468. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture"))
  469. {
  470. name = name.substr(0, name.length() - 7);
  471. }
  472. Uniform un;
  473. un.name = name;
  474. un.type = UniformType::Sampler;
  475. un.num = 0; // needed?
  476. un.regIndex = 0; // needed?
  477. un.regCount = 0; // needed?
  478. uniforms.push_back(un);
  479. }
  480. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  481. bx::Error err;
  482. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  483. {
  484. spirv_cross::CompilerMSL msl(std::move(spirv) );
  485. auto executionModel = msl.get_execution_model();
  486. spirv_cross::MSLResourceBinding newBinding;
  487. newBinding.stage = executionModel;
  488. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  489. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  490. if (!entryPoints.empty() )
  491. msl.rename_entry_point(entryPoints[0].name, "xlatMtlMain", entryPoints[0].execution_model);
  492. for (auto &resource : resources.uniform_buffers)
  493. {
  494. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  495. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  496. newBinding.desc_set = set;
  497. newBinding.binding = binding;
  498. newBinding.msl_buffer = 0;
  499. msl.add_msl_resource_binding( newBinding );
  500. msl.set_name(resource.id, "_mtl_u");
  501. }
  502. for (auto &resource : resources.storage_buffers)
  503. {
  504. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  505. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  506. newBinding.desc_set = set;
  507. newBinding.binding = binding;
  508. newBinding.msl_buffer = binding + 1;
  509. msl.add_msl_resource_binding( newBinding );
  510. }
  511. for (auto &resource : resources.separate_samplers)
  512. {
  513. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  514. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  515. newBinding.desc_set = set;
  516. newBinding.binding = binding;
  517. newBinding.msl_texture = binding - textureBindingOffset;
  518. newBinding.msl_sampler = binding - textureBindingOffset;
  519. msl.add_msl_resource_binding( newBinding );
  520. }
  521. for (auto &resource : resources.separate_images)
  522. {
  523. std::string name = msl.get_name(resource.id);
  524. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  525. {
  526. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  527. }
  528. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  529. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  530. newBinding.desc_set = set;
  531. newBinding.binding = binding;
  532. newBinding.msl_texture = binding - textureBindingOffset;
  533. newBinding.msl_sampler = binding - textureBindingOffset;
  534. msl.add_msl_resource_binding( newBinding );
  535. }
  536. for (auto &resource : resources.storage_images)
  537. {
  538. std::string name = msl.get_name(resource.id);
  539. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  540. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  541. newBinding.desc_set = set;
  542. newBinding.binding = binding;
  543. newBinding.msl_texture = binding - textureBindingOffset;
  544. newBinding.msl_sampler = binding - textureBindingOffset;
  545. msl.add_msl_resource_binding( newBinding );
  546. }
  547. std::string source = msl.compile();
  548. if ('c' == _options.shaderType)
  549. {
  550. for (int i = 0; i < 3; ++i)
  551. {
  552. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  553. bx::write(_writer, dim, &err);
  554. }
  555. }
  556. uint32_t shaderSize = (uint32_t)source.size();
  557. bx::write(_writer, shaderSize, &err);
  558. bx::write(_writer, source.c_str(), shaderSize, &err);
  559. uint8_t nul = 0;
  560. bx::write(_writer, nul, &err);
  561. }
  562. else
  563. {
  564. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  565. bx::write(_writer, shaderSize, &err);
  566. bx::write(_writer, spirv.data(), shaderSize, &err);
  567. uint8_t nul = 0;
  568. bx::write(_writer, nul, &err);
  569. }
  570. //
  571. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  572. bx::write(_writer, numAttr, &err);
  573. for (uint8_t ii = 0; ii < numAttr; ++ii)
  574. {
  575. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  576. if (bgfx::Attrib::Count != attr)
  577. {
  578. bx::write(_writer, bgfx::attribToId(attr), &err);
  579. }
  580. else
  581. {
  582. bx::write(_writer, uint16_t(UINT16_MAX), &err);
  583. }
  584. }
  585. bx::write(_writer, size, &err);
  586. }
  587. }
  588. }
  589. delete program;
  590. delete shader;
  591. glslang::FinalizeProcess();
  592. return compiled && linked && validated;
  593. }
  594. } // namespace metal
  595. bool compileMetalShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  596. {
  597. return metal::compile(_options, _version, _code, _writer, true);
  598. }
  599. } // namespace bgfx