shaderc_metal.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. uint16_t count = static_cast<uint16_t>(uniforms.size() );
  209. bx::write(_writer, count);
  210. uint32_t fragmentBit = isFragmentShader ? kUniformFragmentBit : 0;
  211. for (uint16_t ii = 0; ii < count; ++ii)
  212. {
  213. const Uniform& un = uniforms[ii];
  214. size += un.regCount*16;
  215. uint8_t nameSize = (uint8_t)un.name.size();
  216. bx::write(_writer, nameSize);
  217. bx::write(_writer, un.name.c_str(), nameSize);
  218. bx::write(_writer, uint8_t(un.type | fragmentBit) );
  219. bx::write(_writer, un.num);
  220. bx::write(_writer, un.regIndex);
  221. bx::write(_writer, un.regCount);
  222. bx::write(_writer, un.texComponent);
  223. bx::write(_writer, un.texDimension);
  224. bx::write(_writer, un.texFormat);
  225. BX_TRACE("%s, %s, %d, %d, %d"
  226. , un.name.c_str()
  227. , getUniformTypeName(un.type)
  228. , un.num
  229. , un.regIndex
  230. , un.regCount
  231. );
  232. }
  233. return size;
  234. }
  235. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  236. {
  237. BX_UNUSED(_version);
  238. glslang::InitializeProcess();
  239. EShLanguage stage = getLang(_options.shaderType);
  240. if (EShLangCount == stage)
  241. {
  242. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  243. return false;
  244. }
  245. glslang::TProgram* program = new glslang::TProgram;
  246. glslang::TShader* shader = new glslang::TShader(stage);
  247. EShMessages messages = EShMessages(0
  248. | EShMsgDefault
  249. | EShMsgReadHlsl
  250. | EShMsgVulkanRules
  251. | EShMsgSpvRules
  252. );
  253. shader->setEntryPoint("main");
  254. shader->setAutoMapBindings(true);
  255. const int textureBindingOffset = 16;
  256. shader->setShiftBinding(glslang::EResTexture, textureBindingOffset);
  257. shader->setShiftBinding(glslang::EResSampler, textureBindingOffset);
  258. shader->setShiftBinding(glslang::EResImage, textureBindingOffset);
  259. const char* shaderStrings[] = { _code.c_str() };
  260. shader->setStrings(
  261. shaderStrings
  262. , BX_COUNTOF(shaderStrings)
  263. );
  264. bool compiled = shader->parse(&resourceLimits
  265. , 110
  266. , false
  267. , messages
  268. );
  269. bool linked = false;
  270. bool validated = true;
  271. if (!compiled)
  272. {
  273. const char* log = shader->getInfoLog();
  274. if (NULL != log)
  275. {
  276. int32_t source = 0;
  277. int32_t line = 0;
  278. int32_t column = 0;
  279. int32_t start = 0;
  280. int32_t end = INT32_MAX;
  281. bx::StringView err = bx::strFind(log, "ERROR:");
  282. bool found = false;
  283. if (!err.isEmpty() )
  284. {
  285. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  286. if (found)
  287. {
  288. ++line;
  289. }
  290. }
  291. if (found)
  292. {
  293. start = bx::uint32_imax(1, line-10);
  294. end = start + 20;
  295. }
  296. printCode(_code.c_str(), line, start, end, column);
  297. bx::printf("%s\n", log);
  298. }
  299. }
  300. else
  301. {
  302. program->addShader(shader);
  303. linked = true
  304. && program->link(messages)
  305. && program->mapIO()
  306. ;
  307. if (!linked)
  308. {
  309. const char* log = program->getInfoLog();
  310. if (NULL != log)
  311. {
  312. bx::printf("%s\n", log);
  313. }
  314. }
  315. else
  316. {
  317. program->buildReflection();
  318. if (_firstPass)
  319. {
  320. // first time through, we just find unused uniforms and get rid of them
  321. std::string output;
  322. bx::Error err;
  323. bx::LineReader reader(_code.c_str() );
  324. while (!reader.isDone() )
  325. {
  326. bx::StringView strLine = reader.next();
  327. bx::StringView str = strFind(strLine, "uniform ");
  328. if (!str.isEmpty() )
  329. {
  330. // If the line declares a uniform, merge all next
  331. // lines until we encounter a semicolon.
  332. bx::StringView lineEnd = strFind(strLine, ";");
  333. while (lineEnd.isEmpty() && !reader.isDone()) {
  334. bx::StringView nextLine = reader.next();
  335. strLine.set(strLine.getPtr(), nextLine.getTerm());
  336. lineEnd = strFind(nextLine, ";");
  337. }
  338. bool found = false;
  339. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  340. {
  341. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  342. {
  343. found = true;
  344. break;
  345. }
  346. }
  347. if (!found)
  348. {
  349. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  350. {
  351. // matching lines like: uniform u_name;
  352. // we want to replace "uniform" with "static" so that it's no longer
  353. // included in the uniform blob that the application must upload
  354. // we can't just remove them, because unused functions might still reference
  355. // them and cause a compile error when they're gone
  356. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  357. {
  358. found = true;
  359. break;
  360. }
  361. }
  362. }
  363. if (!found)
  364. {
  365. output.append(strLine.getPtr(), str.getPtr() );
  366. output += "static ";
  367. output.append(str.getTerm(), strLine.getTerm() );
  368. output += "\n";
  369. }
  370. else
  371. {
  372. output.append(strLine.getPtr(), strLine.getTerm() );
  373. output += "\n";
  374. }
  375. }
  376. else
  377. {
  378. output.append(strLine.getPtr(), strLine.getTerm() );
  379. output += "\n";
  380. }
  381. }
  382. // recompile with the unused uniforms converted to statics
  383. delete program;
  384. delete shader;
  385. return compile(_options, _version, output.c_str(), _writer, false);
  386. }
  387. UniformArray uniforms;
  388. {
  389. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  390. for (uint16_t ii = 0; ii < count; ++ii)
  391. {
  392. Uniform un;
  393. un.name = program->getUniformName(ii);
  394. un.num = uint8_t(program->getUniformArraySize(ii) );
  395. const uint32_t offset = program->getUniformBufferOffset(ii);
  396. un.regIndex = uint16_t(offset);
  397. un.regCount = un.num;
  398. switch (program->getUniformType(ii) )
  399. {
  400. case 0x1404: // GL_INT:
  401. un.type = UniformType::Sampler;
  402. break;
  403. case 0x8B52: // GL_FLOAT_VEC4:
  404. un.type = UniformType::Vec4;
  405. break;
  406. case 0x8B5B: // GL_FLOAT_MAT3:
  407. un.type = UniformType::Mat3;
  408. un.regCount *= 3;
  409. break;
  410. case 0x8B5C: // GL_FLOAT_MAT4:
  411. un.type = UniformType::Mat4;
  412. un.regCount *= 4;
  413. break;
  414. default:
  415. un.type = UniformType::End;
  416. break;
  417. }
  418. uniforms.push_back(un);
  419. }
  420. }
  421. if (g_verbose)
  422. {
  423. program->dumpReflection();
  424. }
  425. BX_UNUSED(spv::MemorySemanticsAllMemory);
  426. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  427. std::vector<uint32_t> spirv;
  428. glslang::SpvOptions options;
  429. options.disableOptimizer = false;
  430. glslang::GlslangToSpv(*intermediate, spirv, &options);
  431. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  432. auto print_msg_to_stderr = [](
  433. spv_message_level_t
  434. , const char*
  435. , const spv_position_t&
  436. , const char* m
  437. )
  438. {
  439. bx::printf("Error: %s\n", m);
  440. };
  441. opt.SetMessageConsumer(print_msg_to_stderr);
  442. opt.RegisterLegalizationPasses();
  443. spvtools::ValidatorOptions validatorOptions;
  444. validatorOptions.SetBeforeHlslLegalization(true);
  445. if (!opt.Run(
  446. spirv.data()
  447. , spirv.size()
  448. , &spirv
  449. , validatorOptions
  450. , false
  451. ) )
  452. {
  453. compiled = false;
  454. }
  455. else
  456. {
  457. if (g_verbose)
  458. {
  459. glslang::SpirvToolsDisassemble(std::cout, spirv, SPV_ENV_VULKAN_1_0);
  460. }
  461. spirv_cross::CompilerReflection refl(spirv);
  462. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  463. // Loop through the separate_images, and extract the uniform names:
  464. for (auto &resource : resourcesrefl.separate_images)
  465. {
  466. std::string name = refl.get_name(resource.id);
  467. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture"))
  468. {
  469. name = name.substr(0, name.length() - 7);
  470. }
  471. Uniform un;
  472. un.name = name;
  473. un.type = UniformType::Sampler;
  474. un.num = 0; // needed?
  475. un.regIndex = 0; // needed?
  476. un.regCount = 0; // needed?
  477. uniforms.push_back(un);
  478. }
  479. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  480. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  481. {
  482. spirv_cross::CompilerMSL msl(std::move(spirv) );
  483. auto executionModel = msl.get_execution_model();
  484. spirv_cross::MSLResourceBinding newBinding;
  485. newBinding.stage = executionModel;
  486. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  487. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  488. if (!entryPoints.empty() )
  489. msl.rename_entry_point(entryPoints[0].name, "xlatMtlMain", entryPoints[0].execution_model);
  490. for (auto &resource : resources.uniform_buffers)
  491. {
  492. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  493. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  494. newBinding.desc_set = set;
  495. newBinding.binding = binding;
  496. newBinding.msl_buffer = 0;
  497. msl.add_msl_resource_binding( newBinding );
  498. msl.set_name(resource.id, "_mtl_u");
  499. }
  500. for (auto &resource : resources.storage_buffers)
  501. {
  502. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  503. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  504. newBinding.desc_set = set;
  505. newBinding.binding = binding;
  506. newBinding.msl_buffer = binding + 1;
  507. msl.add_msl_resource_binding( newBinding );
  508. }
  509. for (auto &resource : resources.separate_samplers)
  510. {
  511. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  512. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  513. newBinding.desc_set = set;
  514. newBinding.binding = binding;
  515. newBinding.msl_texture = binding - textureBindingOffset;
  516. newBinding.msl_sampler = binding - textureBindingOffset;
  517. msl.add_msl_resource_binding( newBinding );
  518. }
  519. for (auto &resource : resources.separate_images)
  520. {
  521. std::string name = msl.get_name(resource.id);
  522. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  523. {
  524. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  525. }
  526. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  527. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  528. newBinding.desc_set = set;
  529. newBinding.binding = binding;
  530. newBinding.msl_texture = binding - textureBindingOffset;
  531. newBinding.msl_sampler = binding - textureBindingOffset;
  532. msl.add_msl_resource_binding( newBinding );
  533. }
  534. for (auto &resource : resources.storage_images)
  535. {
  536. std::string name = msl.get_name(resource.id);
  537. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  538. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  539. newBinding.desc_set = set;
  540. newBinding.binding = binding;
  541. newBinding.msl_texture = binding - textureBindingOffset;
  542. newBinding.msl_sampler = binding - textureBindingOffset;
  543. msl.add_msl_resource_binding( newBinding );
  544. }
  545. std::string source = msl.compile();
  546. if ('c' == _options.shaderType)
  547. {
  548. for (int i = 0; i < 3; ++i)
  549. {
  550. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  551. bx::write(_writer, dim);
  552. }
  553. }
  554. uint32_t shaderSize = (uint32_t)source.size();
  555. bx::write(_writer, shaderSize);
  556. bx::write(_writer, source.c_str(), shaderSize);
  557. uint8_t nul = 0;
  558. bx::write(_writer, nul);
  559. }
  560. else
  561. {
  562. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  563. bx::write(_writer, shaderSize);
  564. bx::write(_writer, spirv.data(), shaderSize);
  565. uint8_t nul = 0;
  566. bx::write(_writer, nul);
  567. }
  568. //
  569. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  570. bx::write(_writer, numAttr);
  571. for (uint8_t ii = 0; ii < numAttr; ++ii)
  572. {
  573. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  574. if (bgfx::Attrib::Count != attr)
  575. {
  576. bx::write(_writer, bgfx::attribToId(attr) );
  577. }
  578. else
  579. {
  580. bx::write(_writer, uint16_t(UINT16_MAX) );
  581. }
  582. }
  583. bx::write(_writer, size);
  584. }
  585. }
  586. }
  587. delete program;
  588. delete shader;
  589. glslang::FinalizeProcess();
  590. return compiled && linked && validated;
  591. }
  592. } // namespace metal
  593. bool compileMetalShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  594. {
  595. return metal::compile(_options, _version, _code, _writer, true);
  596. }
  597. } // namespace bgfx