shaderc_glsl.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Copyright 2011-2023 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include "shaderc.h"
  6. #include "glsl_optimizer.h"
  7. namespace bgfx { namespace glsl
  8. {
  9. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  10. {
  11. char ch = _options.shaderType;
  12. const glslopt_shader_type type = ch == 'f'
  13. ? kGlslOptShaderFragment
  14. : (ch == 'c' ? kGlslOptShaderCompute : kGlslOptShaderVertex);
  15. glslopt_target target = kGlslTargetOpenGL;
  16. if(_version == BX_MAKEFOURCC('M', 'T', 'L', 0))
  17. {
  18. target = kGlslTargetMetal;
  19. } else if(_version < 0x80000000) {
  20. target = kGlslTargetOpenGL;
  21. }
  22. else {
  23. _version &= ~0x80000000;
  24. target = (_version >= 300) ? kGlslTargetOpenGLES30 : kGlslTargetOpenGLES20;
  25. }
  26. glslopt_ctx* ctx = glslopt_initialize(target);
  27. glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
  28. if (!glslopt_get_status(shader) )
  29. {
  30. const char* log = glslopt_get_log(shader);
  31. int32_t source = 0;
  32. int32_t line = 0;
  33. int32_t column = 0;
  34. int32_t start = 0;
  35. int32_t end = INT32_MAX;
  36. bool found = false
  37. || 3 == sscanf(log, "%u:%u(%u):", &source, &line, &column)
  38. || 2 == sscanf(log, "(%u,%u):", &line, &column)
  39. ;
  40. if (found
  41. && 0 != line)
  42. {
  43. start = bx::uint32_imax(1, line-10);
  44. end = start + 20;
  45. }
  46. printCode(_code.c_str(), line, start, end, column);
  47. bx::printf("Error: %s\n", log);
  48. glslopt_shader_delete(shader);
  49. glslopt_cleanup(ctx);
  50. return false;
  51. }
  52. const char* optimizedShader = glslopt_get_output(shader);
  53. std::string out;
  54. // Trim all directives.
  55. while ('#' == *optimizedShader)
  56. {
  57. optimizedShader = bx::strFindNl(optimizedShader).getPtr();
  58. }
  59. out.append(optimizedShader, strlen(optimizedShader));
  60. optimizedShader = out.c_str();
  61. {
  62. char* code = const_cast<char*>(optimizedShader);
  63. strReplace(code, "gl_FragDepthEXT", "gl_FragDepth");
  64. strReplace(code, "textureLodEXT", "texture2DLod");
  65. strReplace(code, "textureGradEXT", "texture2DGrad");
  66. strReplace(code, "texture2DLodARB", "texture2DLod");
  67. strReplace(code, "texture2DLodEXT", "texture2DLod");
  68. strReplace(code, "texture2DGradARB", "texture2DGrad");
  69. strReplace(code, "texture2DGradEXT", "texture2DGrad");
  70. strReplace(code, "textureCubeLodARB", "textureCubeLod");
  71. strReplace(code, "textureCubeLodEXT", "textureCubeLod");
  72. strReplace(code, "textureCubeGradARB", "textureCubeGrad");
  73. strReplace(code, "textureCubeGradEXT", "textureCubeGrad");
  74. strReplace(code, "texture2DProjLodARB", "texture2DProjLod");
  75. strReplace(code, "texture2DProjLodEXT", "texture2DProjLod");
  76. strReplace(code, "texture2DProjGradARB", "texture2DProjGrad");
  77. strReplace(code, "texture2DProjGradEXT", "texture2DProjGrad");
  78. strReplace(code, "shadow2DARB", "shadow2D");
  79. strReplace(code, "shadow2DEXT", "shadow2D");
  80. strReplace(code, "shadow2DProjARB", "shadow2DProj");
  81. strReplace(code, "shadow2DProjEXT", "shadow2DProj");
  82. }
  83. UniformArray uniforms;
  84. if (target != kGlslTargetMetal)
  85. {
  86. bx::StringView parse(optimizedShader);
  87. while (!parse.isEmpty() )
  88. {
  89. parse = bx::strLTrimSpace(parse);
  90. bx::StringView eol = bx::strFind(parse, ';');
  91. if (!eol.isEmpty() )
  92. {
  93. bx::StringView qualifier = nextWord(parse);
  94. if (0 == bx::strCmp(qualifier, "precision", 9) )
  95. {
  96. // skip precision
  97. parse.set(eol.getPtr() + 1, parse.getTerm() );
  98. continue;
  99. }
  100. if (0 == bx::strCmp(qualifier, "attribute", 9)
  101. || 0 == bx::strCmp(qualifier, "varying", 7)
  102. || 0 == bx::strCmp(qualifier, "in", 2)
  103. || 0 == bx::strCmp(qualifier, "out", 3)
  104. )
  105. {
  106. // skip attributes and varyings.
  107. parse.set(eol.getPtr() + 1, parse.getTerm() );
  108. continue;
  109. }
  110. if (0 == bx::strCmp(qualifier, "flat", 4)
  111. || 0 == bx::strCmp(qualifier, "smooth", 6)
  112. || 0 == bx::strCmp(qualifier, "noperspective", 13)
  113. || 0 == bx::strCmp(qualifier, "centroid", 8)
  114. )
  115. {
  116. // skip interpolation qualifiers
  117. parse.set(eol.getPtr() + 1, parse.getTerm() );
  118. continue;
  119. }
  120. if (0 == bx::strCmp(parse, "tmpvar", 6) )
  121. {
  122. // skip temporaries
  123. parse.set(eol.getPtr() + 1, parse.getTerm() );
  124. continue;
  125. }
  126. if (0 != bx::strCmp(qualifier, "uniform", 7) )
  127. {
  128. // end if there is no uniform keyword.
  129. parse.clear();
  130. continue;
  131. }
  132. bx::StringView precision;
  133. bx::StringView typen = nextWord(parse);
  134. if (0 == bx::strCmp(typen, "lowp", 4)
  135. || 0 == bx::strCmp(typen, "mediump", 7)
  136. || 0 == bx::strCmp(typen, "highp", 5) )
  137. {
  138. precision = typen;
  139. typen = nextWord(parse);
  140. }
  141. BX_UNUSED(precision);
  142. char uniformType[256];
  143. if (0 == bx::strCmp(typen, "sampler", 7)
  144. || 0 == bx::strCmp(typen, "isampler", 8)
  145. || 0 == bx::strCmp(typen, "usampler", 8) )
  146. {
  147. bx::strCopy(uniformType, BX_COUNTOF(uniformType), "int");
  148. }
  149. else
  150. {
  151. bx::strCopy(uniformType, BX_COUNTOF(uniformType), typen);
  152. }
  153. bx::StringView name = nextWord(parse);
  154. uint8_t num = 1;
  155. bx::StringView array = bx::strSubstr(parse, 0, 1);
  156. if (0 == bx::strCmp(array, "[", 1) )
  157. {
  158. parse = bx::strLTrimSpace(bx::StringView(parse.getPtr() + 1, parse.getTerm() ) );
  159. uint32_t tmp;
  160. bx::fromString(&tmp, parse);
  161. num = uint8_t(tmp);
  162. }
  163. Uniform un;
  164. un.type = nameToUniformTypeEnum(uniformType);
  165. if (UniformType::Count != un.type)
  166. {
  167. un.name.assign(name.getPtr(), name.getTerm());
  168. BX_TRACE("name: %s (type %d, num %d)", un.name.c_str(), un.type, num);
  169. un.num = num;
  170. un.regIndex = 0;
  171. un.regCount = num;
  172. switch (un.type)
  173. {
  174. case UniformType::Mat3:
  175. un.regCount *= 3;
  176. break;
  177. case UniformType::Mat4:
  178. un.regCount *= 4;
  179. break;
  180. default:
  181. break;
  182. }
  183. uniforms.push_back(un);
  184. }
  185. parse = bx::strLTrimSpace(bx::strFindNl(bx::StringView(eol.getPtr(), parse.getTerm() ) ) );
  186. }
  187. }
  188. }
  189. else
  190. {
  191. const bx::StringView optShader(optimizedShader);
  192. bx::StringView parse = bx::strFind(optimizedShader, "struct xlatMtlShaderUniform {");
  193. bx::StringView end = parse;
  194. if (!parse.isEmpty() )
  195. {
  196. parse.set(parse.getPtr() + bx::strLen("struct xlatMtlShaderUniform {"), optShader.getTerm() );
  197. end = bx::strFind(parse, "};");
  198. }
  199. while ( parse.getPtr() < end.getPtr()
  200. && !parse.isEmpty() )
  201. {
  202. parse.set(bx::strLTrimSpace(parse).getPtr(), optShader.getTerm() );
  203. const bx::StringView eol = bx::strFind(parse, ';');
  204. if (!eol.isEmpty() )
  205. {
  206. const char* typen = parse.getPtr();
  207. char uniformType[256];
  208. parse = bx::strWord(parse);
  209. bx::strCopy(uniformType, parse.getLength()+1, typen);
  210. parse.set(parse.getPtr()+parse.getLength(),optShader.getTerm());
  211. const char* name = bx::strLTrimSpace(parse).getPtr();
  212. parse.set(name, optShader.getTerm() );
  213. char uniformName[256];
  214. uint8_t num = 1;
  215. bx::StringView array = bx::strFind(bx::StringView(name, int32_t(eol.getPtr()-parse.getPtr() ) ), "[");
  216. if (!array.isEmpty() )
  217. {
  218. bx::strCopy(uniformName, int32_t(array.getPtr()-name+1), name);
  219. char arraySize[32];
  220. bx::StringView arrayEnd = bx::strFind(bx::StringView(array.getPtr(), int32_t(eol.getPtr()-array.getPtr() ) ), "]");
  221. bx::strCopy(arraySize, int32_t(arrayEnd.getPtr()-array.getPtr() ), array.getPtr()+1);
  222. uint32_t tmp;
  223. bx::fromString(&tmp, arraySize);
  224. num = uint8_t(tmp);
  225. }
  226. else
  227. {
  228. bx::strCopy(uniformName, int32_t(eol.getPtr()-name+1), name);
  229. }
  230. Uniform un;
  231. un.type = nameToUniformTypeEnum(uniformType);
  232. if (UniformType::Count != un.type)
  233. {
  234. BX_TRACE("name: %s (type %d, num %d)", uniformName, un.type, num);
  235. un.name = uniformName;
  236. un.num = num;
  237. un.regIndex = 0;
  238. un.regCount = num;
  239. uniforms.push_back(un);
  240. }
  241. parse = eol.getPtr() + 1;
  242. }
  243. }
  244. bx::StringView mainEntry("xlatMtlShaderOutput xlatMtlMain (");
  245. parse = bx::strFind(optimizedShader, mainEntry);
  246. end = parse;
  247. if (!parse.isEmpty())
  248. {
  249. parse.set(parse.getPtr() + mainEntry.getLength(), optShader.getTerm());
  250. end = bx::strFind(parse, "{");
  251. }
  252. while (parse.getPtr() < end.getPtr()
  253. && !parse.isEmpty())
  254. {
  255. parse.set(bx::strLTrimSpace(parse).getPtr(), optShader.getTerm());
  256. const bx::StringView textureNameMark("[[texture(");
  257. const bx::StringView textureName = bx::strFind(parse, textureNameMark);
  258. if (!textureName.isEmpty())
  259. {
  260. Uniform un;
  261. un.type = nameToUniformTypeEnum("int"); // int for sampler
  262. const char* varNameEnd = textureName.getPtr() - 1;
  263. parse.set(parse.getPtr(), varNameEnd - 1);
  264. const char* varNameBeg = parse.getPtr();
  265. for (int ii = parse.getLength() - 1; 0 <= ii; --ii)
  266. {
  267. if (varNameBeg[ii] == ' ')
  268. {
  269. parse.set(varNameBeg + ii + 1, varNameEnd);
  270. break;
  271. }
  272. }
  273. char uniformName[256];
  274. bx::strCopy(uniformName, parse.getLength() + 1, parse);
  275. un.name = uniformName;
  276. const char* regIndexBeg = textureName.getPtr() + textureNameMark.getLength();
  277. bx::StringView regIndex = bx::strFind(regIndexBeg, ")");
  278. regIndex.set(regIndexBeg, regIndex.getPtr());
  279. uint32_t tmp;
  280. bx::fromString(&tmp, regIndex);
  281. un.regIndex = uint16_t(tmp);
  282. un.num = 1;
  283. un.regCount = 1;
  284. uniforms.push_back(un);
  285. parse = regIndex.getPtr() + 1;
  286. }
  287. else
  288. {
  289. parse = textureName;
  290. }
  291. }
  292. }
  293. bx::ErrorAssert err;
  294. uint16_t count = (uint16_t)uniforms.size();
  295. bx::write(_writer, count, &err);
  296. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  297. {
  298. const Uniform& un = *it;
  299. uint8_t nameSize = (uint8_t)un.name.size();
  300. bx::write(_writer, nameSize, &err);
  301. bx::write(_writer, un.name.c_str(), nameSize, &err);
  302. uint8_t uniformType = uint8_t(un.type);
  303. bx::write(_writer, uniformType, &err);
  304. bx::write(_writer, un.num, &err);
  305. bx::write(_writer, un.regIndex, &err);
  306. bx::write(_writer, un.regCount, &err);
  307. bx::write(_writer, un.texComponent, &err);
  308. bx::write(_writer, un.texDimension, &err);
  309. bx::write(_writer, un.texFormat, &err);
  310. BX_TRACE("%s, %s, %d, %d, %d"
  311. , un.name.c_str()
  312. , getUniformTypeName(un.type)
  313. , un.num
  314. , un.regIndex
  315. , un.regCount
  316. );
  317. }
  318. uint32_t shaderSize = (uint32_t)bx::strLen(optimizedShader);
  319. bx::write(_writer, shaderSize, &err);
  320. bx::write(_writer, optimizedShader, shaderSize, &err);
  321. uint8_t nul = 0;
  322. bx::write(_writer, nul, &err);
  323. if (_options.disasm )
  324. {
  325. std::string disasmfp = _options.outputFilePath + ".disasm";
  326. writeFile(disasmfp.c_str(), optimizedShader, shaderSize);
  327. }
  328. glslopt_shader_delete(shader);
  329. glslopt_cleanup(ctx);
  330. return true;
  331. }
  332. } // namespace glsl
  333. bool compileGLSLShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  334. {
  335. return glsl::compile(_options, _version, _code, _writer);
  336. }
  337. } // namespace bgfx