shaderc.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  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. #include <bx/commandline.h>
  7. #include <bx/filepath.h>
  8. #define MAX_TAGS 256
  9. extern "C"
  10. {
  11. #include <fpp.h>
  12. } // extern "C"
  13. #define BGFX_SHADER_BIN_VERSION 9
  14. #define BGFX_CHUNK_MAGIC_CSH BX_MAKEFOURCC('C', 'S', 'H', BGFX_SHADER_BIN_VERSION)
  15. #define BGFX_CHUNK_MAGIC_FSH BX_MAKEFOURCC('F', 'S', 'H', BGFX_SHADER_BIN_VERSION)
  16. #define BGFX_CHUNK_MAGIC_VSH BX_MAKEFOURCC('V', 'S', 'H', BGFX_SHADER_BIN_VERSION)
  17. #define BGFX_SHADERC_VERSION_MAJOR 1
  18. #define BGFX_SHADERC_VERSION_MINOR 17
  19. namespace bgfx
  20. {
  21. bool g_verbose = false;
  22. static const char* s_ARB_shader_texture_lod[] =
  23. {
  24. "texture2DLod",
  25. "texture2DArrayLod", // BK - interacts with ARB_texture_array.
  26. "texture2DProjLod",
  27. "texture2DGrad",
  28. "texture2DProjGrad",
  29. "texture3DLod",
  30. "texture3DProjLod",
  31. "texture3DGrad",
  32. "texture3DProjGrad",
  33. "textureCubeLod",
  34. "textureCubeGrad",
  35. "shadow2DLod",
  36. "shadow2DProjLod",
  37. NULL
  38. // "texture1DLod",
  39. // "texture1DProjLod",
  40. // "shadow1DLod",
  41. // "shadow1DProjLod",
  42. };
  43. static const char* s_EXT_shader_texture_lod[] =
  44. {
  45. "texture2DLod",
  46. "texture2DProjLod",
  47. "textureCubeLod",
  48. "texture2DGrad",
  49. "texture2DProjGrad",
  50. "textureCubeGrad",
  51. NULL
  52. };
  53. static const char* s_EXT_shadow_samplers[] =
  54. {
  55. "shadow2D",
  56. "shadow2DProj",
  57. "sampler2DShadow",
  58. NULL
  59. };
  60. static const char* s_OES_standard_derivatives[] =
  61. {
  62. "dFdx",
  63. "dFdy",
  64. "fwidth",
  65. NULL
  66. };
  67. static const char* s_OES_texture_3D[] =
  68. {
  69. "texture3D",
  70. "texture3DProj",
  71. "texture3DLod",
  72. "texture3DProjLod",
  73. NULL
  74. };
  75. static const char* s_EXT_gpu_shader4[] =
  76. {
  77. "gl_VertexID",
  78. "gl_InstanceID",
  79. NULL
  80. };
  81. static const char* s_ARB_gpu_shader5[] =
  82. {
  83. "bitfieldReverse",
  84. "floatBitsToInt",
  85. "floatBitsToUint",
  86. "intBitsToFloat",
  87. "uintBitsToFloat",
  88. NULL
  89. };
  90. static const char* s_ARB_shading_language_packing[] =
  91. {
  92. "packHalf2x16",
  93. "unpackHalf2x16",
  94. NULL
  95. };
  96. static const char* s_130[] =
  97. {
  98. "uint",
  99. "uint2",
  100. "uint3",
  101. "uint4",
  102. "isampler2D",
  103. "usampler2D",
  104. "isampler3D",
  105. "usampler3D",
  106. "isamplerCube",
  107. "usamplerCube",
  108. NULL
  109. };
  110. static const char* s_textureArray[] =
  111. {
  112. "sampler2DArray",
  113. "texture2DArray",
  114. "texture2DArrayLod",
  115. "shadow2DArray",
  116. NULL
  117. };
  118. static const char* s_ARB_texture_multisample[] =
  119. {
  120. "sampler2DMS",
  121. "isampler2DMS",
  122. "usampler2DMS",
  123. NULL
  124. };
  125. static const char* s_texelFetch[] =
  126. {
  127. "texelFetch",
  128. "texelFetchOffset",
  129. NULL
  130. };
  131. const char* s_uniformTypeName[] =
  132. {
  133. "int", "int",
  134. NULL, NULL,
  135. "vec4", "float4",
  136. "mat3", "float3x3",
  137. "mat4", "float4x4",
  138. };
  139. BX_STATIC_ASSERT(BX_COUNTOF(s_uniformTypeName) == UniformType::Count*2);
  140. static const char* s_allowedVertexShaderInputs[] =
  141. {
  142. "a_position",
  143. "a_normal",
  144. "a_tangent",
  145. "a_bitangent",
  146. "a_color0",
  147. "a_color1",
  148. "a_color2",
  149. "a_color3",
  150. "a_indices",
  151. "a_weight",
  152. "a_texcoord0",
  153. "a_texcoord1",
  154. "a_texcoord2",
  155. "a_texcoord3",
  156. "a_texcoord4",
  157. "a_texcoord5",
  158. "a_texcoord6",
  159. "a_texcoord7",
  160. "i_data0",
  161. "i_data1",
  162. "i_data2",
  163. "i_data3",
  164. "i_data4",
  165. NULL
  166. };
  167. Options::Options()
  168. : shaderType(' ')
  169. , disasm(false)
  170. , raw(false)
  171. , preprocessOnly(false)
  172. , depends(false)
  173. , debugInformation(false)
  174. , avoidFlowControl(false)
  175. , noPreshader(false)
  176. , partialPrecision(false)
  177. , preferFlowControl(false)
  178. , backwardsCompatibility(false)
  179. , warningsAreErrors(false)
  180. , keepIntermediate(false)
  181. , optimize(false)
  182. , optimizationLevel(3)
  183. {
  184. }
  185. void Options::dump()
  186. {
  187. BX_TRACE("Options:\n"
  188. "\t shaderType: %c\n"
  189. "\t platform: %s\n"
  190. "\t profile: %s\n"
  191. "\t inputFile: %s\n"
  192. "\t outputFile: %s\n"
  193. "\t disasm: %s\n"
  194. "\t raw: %s\n"
  195. "\t preprocessOnly: %s\n"
  196. "\t depends: %s\n"
  197. "\t debugInformation: %s\n"
  198. "\t avoidFlowControl: %s\n"
  199. "\t noPreshader: %s\n"
  200. "\t partialPrecision: %s\n"
  201. "\t preferFlowControl: %s\n"
  202. "\t backwardsCompatibility: %s\n"
  203. "\t warningsAreErrors: %s\n"
  204. "\t keepIntermediate: %s\n"
  205. "\t optimize: %s\n"
  206. "\t optimizationLevel: %d\n"
  207. , shaderType
  208. , platform.c_str()
  209. , profile.c_str()
  210. , inputFilePath.c_str()
  211. , outputFilePath.c_str()
  212. , disasm ? "true" : "false"
  213. , raw ? "true" : "false"
  214. , preprocessOnly ? "true" : "false"
  215. , depends ? "true" : "false"
  216. , debugInformation ? "true" : "false"
  217. , avoidFlowControl ? "true" : "false"
  218. , noPreshader ? "true" : "false"
  219. , partialPrecision ? "true" : "false"
  220. , preferFlowControl ? "true" : "false"
  221. , backwardsCompatibility ? "true" : "false"
  222. , warningsAreErrors ? "true" : "false"
  223. , keepIntermediate ? "true" : "false"
  224. , optimize ? "true" : "false"
  225. , optimizationLevel
  226. );
  227. for (size_t ii = 0; ii < includeDirs.size(); ++ii)
  228. {
  229. BX_TRACE("\t include :%s\n", includeDirs[ii].c_str());
  230. }
  231. for (size_t ii = 0; ii < defines.size(); ++ii)
  232. {
  233. BX_TRACE("\t define :%s\n", defines[ii].c_str());
  234. }
  235. for (size_t ii = 0; ii < dependencies.size(); ++ii)
  236. {
  237. BX_TRACE("\t dependency :%s\n", dependencies[ii].c_str());
  238. }
  239. }
  240. const char* interpolationDx11(const char* _glsl)
  241. {
  242. if (0 == bx::strCmp(_glsl, "smooth") )
  243. {
  244. return "linear";
  245. }
  246. else if (0 == bx::strCmp(_glsl, "flat") )
  247. {
  248. return "nointerpolation";
  249. }
  250. return _glsl; // centroid, noperspective
  251. }
  252. const char* getUniformTypeName(UniformType::Enum _enum)
  253. {
  254. uint32_t idx = _enum & ~(kUniformFragmentBit|kUniformSamplerBit);
  255. if (idx < UniformType::Count)
  256. {
  257. return s_uniformTypeName[idx];
  258. }
  259. return "Unknown uniform type?!";
  260. }
  261. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  262. {
  263. for (uint32_t ii = 0; ii < UniformType::Count*2; ++ii)
  264. {
  265. if (NULL != s_uniformTypeName[ii]
  266. && 0 == bx::strCmp(_name, s_uniformTypeName[ii]) )
  267. {
  268. return UniformType::Enum(ii/2);
  269. }
  270. }
  271. return UniformType::Count;
  272. }
  273. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  274. {
  275. va_list argList;
  276. va_start(argList, _format);
  277. char temp[2048];
  278. char* out = temp;
  279. int32_t max = sizeof(temp);
  280. int32_t len = bx::vsnprintf(out, max, _format, argList);
  281. if (len > max)
  282. {
  283. out = (char*)alloca(len);
  284. len = bx::vsnprintf(out, len, _format, argList);
  285. }
  286. len = bx::write(_writer, out, len);
  287. va_end(argList);
  288. return len;
  289. }
  290. class Bin2cWriter : public bx::FileWriter
  291. {
  292. public:
  293. Bin2cWriter(const bx::StringView& _name)
  294. : m_name(_name)
  295. {
  296. }
  297. virtual ~Bin2cWriter()
  298. {
  299. }
  300. virtual void close() override
  301. {
  302. generate();
  303. return bx::FileWriter::close();
  304. }
  305. virtual int32_t write(const void* _data, int32_t _size, bx::Error*) override
  306. {
  307. const char* data = (const char*)_data;
  308. m_buffer.insert(m_buffer.end(), data, data+_size);
  309. return _size;
  310. }
  311. private:
  312. void generate()
  313. {
  314. #define HEX_DUMP_WIDTH 16
  315. #define HEX_DUMP_SPACE_WIDTH 96
  316. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  317. const uint8_t* data = &m_buffer[0];
  318. uint32_t size = (uint32_t)m_buffer.size();
  319. outf("static const uint8_t %.*s[%d] =\n{\n", m_name.getLength(), m_name.getPtr(), size);
  320. if (NULL != data)
  321. {
  322. char hex[HEX_DUMP_SPACE_WIDTH+1];
  323. char ascii[HEX_DUMP_WIDTH+1];
  324. uint32_t hexPos = 0;
  325. uint32_t asciiPos = 0;
  326. for (uint32_t ii = 0; ii < size; ++ii)
  327. {
  328. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  329. hexPos += 6;
  330. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' && data[asciiPos] != '\t' ? data[asciiPos] : '.';
  331. asciiPos++;
  332. if (HEX_DUMP_WIDTH == asciiPos)
  333. {
  334. ascii[asciiPos] = '\0';
  335. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  336. data += asciiPos;
  337. hexPos = 0;
  338. asciiPos = 0;
  339. }
  340. }
  341. if (0 != asciiPos)
  342. {
  343. ascii[asciiPos] = '\0';
  344. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  345. }
  346. }
  347. outf("};\n");
  348. #undef HEX_DUMP_WIDTH
  349. #undef HEX_DUMP_SPACE_WIDTH
  350. #undef HEX_DUMP_FORMAT
  351. }
  352. int32_t outf(const char* _format, ...)
  353. {
  354. va_list argList;
  355. va_start(argList, _format);
  356. char temp[2048];
  357. char* out = temp;
  358. int32_t max = sizeof(temp);
  359. int32_t len = bx::vsnprintf(out, max, _format, argList);
  360. if (len > max)
  361. {
  362. out = (char*)alloca(len);
  363. len = bx::vsnprintf(out, len, _format, argList);
  364. }
  365. bx::Error err;
  366. int32_t size = bx::FileWriter::write(out, len, &err);
  367. va_end(argList);
  368. return size;
  369. }
  370. bx::StringView m_name;
  371. typedef std::vector<uint8_t> Buffer;
  372. Buffer m_buffer;
  373. };
  374. struct Varying
  375. {
  376. std::string m_precision;
  377. std::string m_interpolation;
  378. std::string m_name;
  379. std::string m_type;
  380. std::string m_init;
  381. std::string m_semantics;
  382. };
  383. typedef std::unordered_map<std::string, Varying> VaryingMap;
  384. class File
  385. {
  386. public:
  387. File()
  388. : m_data(NULL)
  389. , m_size(0)
  390. {
  391. }
  392. ~File()
  393. {
  394. delete [] m_data;
  395. }
  396. void load(const bx::FilePath& _filePath)
  397. {
  398. bx::FileReader reader;
  399. if (bx::open(&reader, _filePath) )
  400. {
  401. m_size = (uint32_t)bx::getSize(&reader);
  402. m_data = new char[m_size+1];
  403. m_size = (uint32_t)bx::read(&reader, m_data, m_size);
  404. bx::close(&reader);
  405. if (m_data[0] == '\xef'
  406. && m_data[1] == '\xbb'
  407. && m_data[2] == '\xbf')
  408. {
  409. bx::memMove(m_data, &m_data[3], m_size-3);
  410. m_size -= 3;
  411. }
  412. m_data[m_size] = '\0';
  413. }
  414. }
  415. const char* getData() const
  416. {
  417. return m_data;
  418. }
  419. uint32_t getSize() const
  420. {
  421. return m_size;
  422. }
  423. private:
  424. char* m_data;
  425. uint32_t m_size;
  426. };
  427. char* strInsert(char* _str, const char* _insert)
  428. {
  429. uint32_t len = bx::strLen(_insert);
  430. bx::memMove(&_str[len], _str, bx::strLen(_str) );
  431. bx::memCopy(_str, _insert, len);
  432. return _str + len;
  433. }
  434. void strReplace(char* _str, const char* _find, const char* _replace)
  435. {
  436. const int32_t len = bx::strLen(_find);
  437. char* replace = (char*)alloca(len+1);
  438. bx::strCopy(replace, len+1, _replace);
  439. for (int32_t ii = bx::strLen(replace); ii < len; ++ii)
  440. {
  441. replace[ii] = ' ';
  442. }
  443. replace[len] = '\0';
  444. BX_ASSERT(len >= bx::strLen(_replace), "");
  445. for (bx::StringView ptr = bx::strFind(_str, _find)
  446. ; !ptr.isEmpty()
  447. ; ptr = bx::strFind(ptr.getPtr() + len, _find)
  448. )
  449. {
  450. bx::memCopy(const_cast<char*>(ptr.getPtr() ), replace, len);
  451. }
  452. }
  453. void strNormalizeEol(char* _str)
  454. {
  455. strReplace(_str, "\r\n", "\n");
  456. strReplace(_str, "\r", "\n");
  457. }
  458. void printCode(const char* _code, int32_t _line, int32_t _start, int32_t _end, int32_t _column)
  459. {
  460. bx::printf("Code:\n---\n");
  461. bx::LineReader reader(_code);
  462. for (int32_t line = 1; !reader.isDone() && line < _end; ++line)
  463. {
  464. bx::StringView strLine = reader.next();
  465. if (line >= _start)
  466. {
  467. if (_line == line)
  468. {
  469. bx::printf("\n");
  470. bx::printf(">>> %3d: %.*s\n", line, strLine.getLength(), strLine.getPtr() );
  471. if (-1 != _column)
  472. {
  473. bx::printf(">>> %3d: %*s\n", _column, _column, "^");
  474. }
  475. bx::printf("\n");
  476. }
  477. else
  478. {
  479. bx::printf(" %3d: %.*s\n", line, strLine.getLength(), strLine.getPtr() );
  480. }
  481. }
  482. }
  483. bx::printf("---\n");
  484. }
  485. void writeFile(const char* _filePath, const void* _data, int32_t _size)
  486. {
  487. bx::FileWriter out;
  488. if (bx::open(&out, _filePath) )
  489. {
  490. bx::write(&out, _data, _size);
  491. bx::close(&out);
  492. }
  493. }
  494. struct Preprocessor
  495. {
  496. Preprocessor(const char* _filePath, bool _essl)
  497. : m_tagptr(m_tags)
  498. , m_scratchPos(0)
  499. , m_fgetsPos(0)
  500. {
  501. m_tagptr->tag = FPPTAG_USERDATA;
  502. m_tagptr->data = this;
  503. m_tagptr++;
  504. m_tagptr->tag = FPPTAG_DEPENDS;
  505. m_tagptr->data = (void*)fppDepends;
  506. m_tagptr++;
  507. m_tagptr->tag = FPPTAG_INPUT;
  508. m_tagptr->data = (void*)fppInput;
  509. m_tagptr++;
  510. m_tagptr->tag = FPPTAG_OUTPUT;
  511. m_tagptr->data = (void*)fppOutput;
  512. m_tagptr++;
  513. m_tagptr->tag = FPPTAG_ERROR;
  514. m_tagptr->data = (void*)fppError;
  515. m_tagptr++;
  516. m_tagptr->tag = FPPTAG_SHOWVERSION;
  517. m_tagptr->data = (void*)0;
  518. m_tagptr++;
  519. m_tagptr->tag = FPPTAG_LINE;
  520. m_tagptr->data = (void*)0;
  521. m_tagptr++;
  522. m_tagptr->tag = FPPTAG_INPUT_NAME;
  523. m_tagptr->data = scratch(_filePath);
  524. m_tagptr++;
  525. if (!_essl)
  526. {
  527. m_default = "#define lowp\n#define mediump\n#define highp\n";
  528. }
  529. }
  530. void setDefine(const char* _define)
  531. {
  532. m_tagptr->tag = FPPTAG_DEFINE;
  533. m_tagptr->data = scratch(_define);
  534. m_tagptr++;
  535. }
  536. void setDefaultDefine(const char* _name)
  537. {
  538. char temp[1024];
  539. bx::snprintf(temp, BX_COUNTOF(temp)
  540. , "#ifndef %s\n"
  541. "# define %s 0\n"
  542. "#endif // %s\n"
  543. "\n"
  544. , _name
  545. , _name
  546. , _name
  547. );
  548. m_default += temp;
  549. }
  550. void writef(const char* _format, ...)
  551. {
  552. va_list argList;
  553. va_start(argList, _format);
  554. bx::stringPrintfVargs(m_default, _format, argList);
  555. va_end(argList);
  556. }
  557. void addInclude(const char* _includeDir)
  558. {
  559. char* start = scratch(_includeDir);
  560. for (bx::StringView split = bx::strFind(start, ';')
  561. ; !split.isEmpty()
  562. ; split = bx::strFind(start, ';')
  563. )
  564. {
  565. *const_cast<char*>(split.getPtr() ) = '\0';
  566. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  567. m_tagptr->data = start;
  568. m_tagptr++;
  569. start = const_cast<char*>(split.getPtr() ) + 1;
  570. }
  571. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  572. m_tagptr->data = start;
  573. m_tagptr++;
  574. }
  575. void addDependency(const char* _fileName)
  576. {
  577. m_depends += " \\\n ";
  578. m_depends += _fileName;
  579. }
  580. bool run(const char* _input)
  581. {
  582. m_fgetsPos = 0;
  583. m_preprocessed.clear();
  584. m_input = m_default;
  585. m_input += "\n\n";
  586. int32_t len = bx::strLen(_input)+1;
  587. char* temp = new char[len];
  588. bx::StringView normalized = bx::normalizeEolLf(temp, len, _input);
  589. std::string str;
  590. str.assign(normalized.getPtr(), normalized.getTerm() );
  591. m_input += str;
  592. delete [] temp;
  593. fppTag* tagptr = m_tagptr;
  594. tagptr->tag = FPPTAG_END;
  595. tagptr->data = 0;
  596. tagptr++;
  597. int result = fppPreProcess(m_tags);
  598. return 0 == result;
  599. }
  600. char* fgets(char* _buffer, int _size)
  601. {
  602. int ii = 0;
  603. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  604. {
  605. _buffer[ii++] = ch;
  606. if (ch == '\n' || ii == _size)
  607. {
  608. _buffer[ii] = '\0';
  609. m_fgetsPos++;
  610. return _buffer;
  611. }
  612. }
  613. return NULL;
  614. }
  615. static void fppDepends(char* _fileName, void* _userData)
  616. {
  617. Preprocessor* thisClass = (Preprocessor*)_userData;
  618. thisClass->addDependency(_fileName);
  619. }
  620. static char* fppInput(char* _buffer, int _size, void* _userData)
  621. {
  622. Preprocessor* thisClass = (Preprocessor*)_userData;
  623. return thisClass->fgets(_buffer, _size);
  624. }
  625. static void fppOutput(int _ch, void* _userData)
  626. {
  627. Preprocessor* thisClass = (Preprocessor*)_userData;
  628. thisClass->m_preprocessed += char(_ch);
  629. }
  630. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  631. {
  632. bx::vprintf(_format, _vargs);
  633. }
  634. char* scratch(const char* _str)
  635. {
  636. char* result = &m_scratch[m_scratchPos];
  637. bx::strCopy(result, uint32_t(sizeof(m_scratch)-m_scratchPos), _str);
  638. m_scratchPos += (uint32_t)bx::strLen(_str)+1;
  639. return result;
  640. }
  641. fppTag m_tags[MAX_TAGS];
  642. fppTag* m_tagptr;
  643. std::string m_depends;
  644. std::string m_default;
  645. std::string m_input;
  646. std::string m_preprocessed;
  647. char m_scratch[16<<10];
  648. uint32_t m_scratchPos;
  649. uint32_t m_fgetsPos;
  650. };
  651. typedef std::vector<std::string> InOut;
  652. uint32_t parseInOut(InOut& _inout, const bx::StringView& _str)
  653. {
  654. uint32_t hash = 0;
  655. bx::StringView str = bx::strLTrimSpace(_str);
  656. if (!str.isEmpty() )
  657. {
  658. bx::StringView delim;
  659. do
  660. {
  661. delim = bx::strFind(str, ',');
  662. if (delim.isEmpty() )
  663. {
  664. delim = bx::strFind(str, ' ');
  665. }
  666. const bx::StringView token(bx::strRTrim(bx::StringView(str.getPtr(), delim.getPtr() ), " ") );
  667. if (!token.isEmpty() )
  668. {
  669. _inout.push_back(std::string(token.getPtr(), token.getTerm() ) );
  670. str = bx::strLTrimSpace(bx::StringView(delim.getPtr() + 1, str.getTerm() ) );
  671. }
  672. }
  673. while (!delim.isEmpty() );
  674. std::sort(_inout.begin(), _inout.end() );
  675. bx::HashMurmur2A murmur;
  676. murmur.begin();
  677. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  678. {
  679. murmur.add(it->c_str(), (uint32_t)it->size() );
  680. }
  681. hash = murmur.end();
  682. }
  683. return hash;
  684. }
  685. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  686. {
  687. char find[32];
  688. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  689. char replace[32];
  690. bx::snprintf(replace, sizeof(replace), "bgfx_FragData%d", _idx);
  691. strReplace(_data, find, replace);
  692. _preprocessor.writef(
  693. " \\\n\t%sout vec4 bgfx_FragData%d : SV_TARGET%d"
  694. , _comma ? ", " : " "
  695. , _idx
  696. , _idx
  697. );
  698. }
  699. void voidFragData(char* _data, uint32_t _idx)
  700. {
  701. char find[32];
  702. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  703. strReplace(_data, find, "bgfx_VoidFrag");
  704. }
  705. bx::StringView baseName(const bx::StringView& _filePath)
  706. {
  707. bx::FilePath fp(_filePath);
  708. return bx::strFind(_filePath, fp.getBaseName() );
  709. }
  710. // c - compute
  711. // d - domain
  712. // f - fragment
  713. // g - geometry
  714. // h - hull
  715. // v - vertex
  716. //
  717. // OpenGL #version Features Direct3D Features Shader Model
  718. // 2.1 120 vf 9.0 vf 2.0
  719. // 3.0 130
  720. // 3.1 140
  721. // 3.2 150 vgf
  722. // 3.3 330 10.0 vgf 4.0
  723. // 4.0 400 vhdgf
  724. // 4.1 410
  725. // 4.2 420 11.0 vhdgf+c 5.0
  726. // 4.3 430 vhdgf+c
  727. // 4.4 440
  728. //
  729. // SPIR-V profile naming convention:
  730. // spirv<SPIR-V version>-<Vulkan version>
  731. //
  732. // SPIR-V version | Vulkan version | shaderc encoding
  733. // 1.0 | 1.0 | 1010
  734. // 1.3 | 1.1 | 1311
  735. // 1.4 | 1.1 | 1411
  736. // 1.5 | 1.2 | 1512
  737. void help(const char* _error = NULL)
  738. {
  739. if (NULL != _error)
  740. {
  741. bx::printf("Error:\n%s\n\n", _error);
  742. }
  743. bx::printf(
  744. "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  745. "Copyright 2011-2020 Branimir Karadzic. All rights reserved.\n"
  746. "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n\n"
  747. , BGFX_SHADERC_VERSION_MAJOR
  748. , BGFX_SHADERC_VERSION_MINOR
  749. , BGFX_API_VERSION
  750. );
  751. bx::printf(
  752. "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  753. "\n"
  754. "Options:\n"
  755. " -h, --help Help.\n"
  756. " -v, --version Version information only.\n"
  757. " -f <file path> Input file path.\n"
  758. " -i <include path> Include path (for multiple paths use -i multiple times).\n"
  759. " -o <file path> Output file path.\n"
  760. " --bin2c [array name] Generate C header file. If array name is not specified base file name will be used as name.\n"
  761. " --depends Generate makefile style depends file.\n"
  762. " --platform <platform> Target platform.\n"
  763. " android\n"
  764. " asm.js\n"
  765. " ios\n"
  766. " linux\n"
  767. " orbis\n"
  768. " osx\n"
  769. " windows\n"
  770. " -p, --profile <profile> Shader model (default GLSL).\n"
  771. " s_3\n"
  772. " s_4\n"
  773. " s_4_0_level\n"
  774. " s_5\n"
  775. " metal\n"
  776. " pssl\n"
  777. " spirv Alias for spirv10-10. \n"
  778. " spirv10-10\n"
  779. " spirv13-11\n"
  780. " spirv14-11\n"
  781. " spirv15-12\n"
  782. " --preprocess Preprocess only.\n"
  783. " --define <defines> Add defines to preprocessor (semicolon separated).\n"
  784. " --raw Do not process shader. No preprocessor, and no glsl-optimizer (GLSL only).\n"
  785. " --type <type> Shader type (vertex, fragment)\n"
  786. " --varyingdef <file path> Path to varying.def.sc file.\n"
  787. " --verbose Verbose.\n"
  788. "\n"
  789. "Options (DX9 and DX11 only):\n"
  790. "\n"
  791. " --debug Debug information.\n"
  792. " --disasm Disassemble compiled shader.\n"
  793. " -O <level> Optimization level (0, 1, 2, 3).\n"
  794. " --Werror Treat warnings as errors.\n"
  795. "\n"
  796. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  797. );
  798. }
  799. bx::StringView nextWord(bx::StringView& _parse)
  800. {
  801. bx::StringView word = bx::strWord(bx::strLTrimSpace(_parse) );
  802. _parse = bx::strLTrimSpace(bx::StringView(word.getTerm(), _parse.getTerm() ) );
  803. return word;
  804. }
  805. bool compileShader(const char* _varying, const char* _comment, char* _shader, uint32_t _shaderLen, Options& _options, bx::FileWriter* _writer)
  806. {
  807. uint32_t glsl = 0;
  808. uint32_t essl = 0;
  809. uint32_t hlsl = 0;
  810. uint32_t d3d = 11;
  811. uint32_t metal = 0;
  812. uint32_t pssl = 0;
  813. uint32_t spirv = 0;
  814. const char* profile = _options.profile.c_str();
  815. if ('\0' != profile[0])
  816. {
  817. if (0 == bx::strCmp(&profile[1], "s_4_0_level", 11) )
  818. {
  819. hlsl = 2;
  820. }
  821. else if (0 == bx::strCmp(&profile[1], "s_3", 3) )
  822. {
  823. hlsl = 3;
  824. d3d = 9;
  825. }
  826. else if (0 == bx::strCmp(&profile[1], "s_4", 3) )
  827. {
  828. hlsl = 4;
  829. }
  830. else if (0 == bx::strCmp(&profile[1], "s_5", 3) )
  831. {
  832. hlsl = 5;
  833. }
  834. else if (0 == bx::strCmp(profile, "metal") )
  835. {
  836. metal = 1;
  837. }
  838. else if (0 == bx::strCmp(profile, "pssl") )
  839. {
  840. pssl = 1;
  841. }
  842. else if (0 == bx::strCmp(profile, "spirv13-11") )
  843. {
  844. spirv = 1311;
  845. }
  846. else if (0 == bx::strCmp(profile, "spirv14-11") )
  847. {
  848. spirv = 1411;
  849. }
  850. else if (0 == bx::strCmp(profile, "spirv15-12") )
  851. {
  852. spirv = 1512;
  853. }
  854. else if (0 == bx::strCmp(profile, "spirv10-10")
  855. || 0 == bx::strCmp(profile, "spirv") )
  856. {
  857. spirv = 1010;
  858. }
  859. else
  860. {
  861. bx::fromString(&glsl, profile);
  862. }
  863. }
  864. else
  865. {
  866. essl = 2;
  867. }
  868. Preprocessor preprocessor(_options.inputFilePath.c_str(), 0 != essl);
  869. for (size_t ii = 0; ii < _options.includeDirs.size(); ++ii)
  870. {
  871. preprocessor.addInclude(_options.includeDirs[ii].c_str() );
  872. }
  873. for (size_t ii = 0; ii < _options.defines.size(); ++ii)
  874. {
  875. preprocessor.setDefine(_options.defines[ii].c_str() );
  876. }
  877. for (size_t ii = 0; ii < _options.dependencies.size(); ++ii)
  878. {
  879. preprocessor.addDependency(_options.dependencies[ii].c_str() );
  880. }
  881. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  882. preprocessor.setDefaultDefine("BX_PLATFORM_EMSCRIPTEN");
  883. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  884. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  885. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  886. preprocessor.setDefaultDefine("BX_PLATFORM_PS4");
  887. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  888. preprocessor.setDefaultDefine("BX_PLATFORM_XBOXONE");
  889. // preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_ESSL");
  890. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  891. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  892. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_METAL");
  893. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_PSSL");
  894. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_SPIRV");
  895. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_COMPUTE");
  896. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  897. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  898. char glslDefine[128];
  899. bx::snprintf(glslDefine, BX_COUNTOF(glslDefine)
  900. , "BGFX_SHADER_LANGUAGE_GLSL=%d"
  901. , essl ? 1 : glsl
  902. );
  903. char hlslDefine[128];
  904. if (0 != hlsl)
  905. {
  906. bx::snprintf(hlslDefine, BX_COUNTOF(hlslDefine)
  907. , "BGFX_SHADER_LANGUAGE_HLSL=%d"
  908. , hlsl);
  909. }
  910. const char* platform = _options.platform.c_str();
  911. if (0 == bx::strCmpI(platform, "android") )
  912. {
  913. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  914. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  915. }
  916. else if (0 == bx::strCmpI(platform, "asm.js") )
  917. {
  918. preprocessor.setDefine("BX_PLATFORM_EMSCRIPTEN=1");
  919. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  920. }
  921. else if (0 == bx::strCmpI(platform, "ios") )
  922. {
  923. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  924. if (metal)
  925. {
  926. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_METAL=1");
  927. }
  928. else
  929. {
  930. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  931. }
  932. }
  933. else if (0 == bx::strCmpI(platform, "linux") )
  934. {
  935. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  936. if (0 != spirv)
  937. {
  938. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  939. }
  940. else
  941. {
  942. preprocessor.setDefine(glslDefine);
  943. }
  944. }
  945. else if (0 == bx::strCmpI(platform, "osx") )
  946. {
  947. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  948. if (!metal)
  949. {
  950. preprocessor.setDefine(glslDefine);
  951. }
  952. char temp[256];
  953. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_METAL=%d", metal);
  954. preprocessor.setDefine(temp);
  955. }
  956. else if (0 == bx::strCmpI(platform, "windows") )
  957. {
  958. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  959. if (0 != hlsl)
  960. {
  961. preprocessor.setDefine(hlslDefine);
  962. }
  963. else if (0 != glsl
  964. || 0 != essl)
  965. {
  966. preprocessor.setDefine(glslDefine);
  967. }
  968. else if (0 != spirv)
  969. {
  970. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  971. }
  972. }
  973. else if (0 == bx::strCmpI(platform, "orbis") )
  974. {
  975. preprocessor.setDefine("BX_PLATFORM_PS4=1");
  976. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_PSSL=1");
  977. preprocessor.setDefine("lit=lit_reserved");
  978. }
  979. else
  980. {
  981. if (0 != hlsl)
  982. {
  983. preprocessor.setDefine(hlslDefine);
  984. }
  985. else if (0 != glsl
  986. || 0 != essl)
  987. {
  988. preprocessor.setDefine(glslDefine);
  989. }
  990. else if (0 != spirv)
  991. {
  992. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  993. }
  994. }
  995. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  996. switch (_options.shaderType)
  997. {
  998. case 'c':
  999. preprocessor.setDefine("BGFX_SHADER_TYPE_COMPUTE=1");
  1000. break;
  1001. case 'f':
  1002. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1003. break;
  1004. case 'v':
  1005. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1006. break;
  1007. default:
  1008. bx::printf("Unknown type: %c?!", _options.shaderType);
  1009. return false;
  1010. }
  1011. bool compiled = false;
  1012. VaryingMap varyingMap;
  1013. bx::StringView parse(_varying);
  1014. bx::StringView term(parse);
  1015. bool usesInterpolationQualifiers = false;
  1016. while (!parse.isEmpty() )
  1017. {
  1018. parse = bx::strLTrimSpace(parse);
  1019. bx::StringView eol = bx::strFind(parse, ';');
  1020. if (eol.isEmpty() )
  1021. {
  1022. eol = bx::strFindEol(parse);
  1023. }
  1024. if (!eol.isEmpty() )
  1025. {
  1026. eol.set(eol.getPtr() + 1, parse.getTerm() );
  1027. bx::StringView precision;
  1028. bx::StringView interpolation;
  1029. bx::StringView typen = nextWord(parse);
  1030. if (0 == bx::strCmp(typen, "lowp", 4)
  1031. || 0 == bx::strCmp(typen, "mediump", 7)
  1032. || 0 == bx::strCmp(typen, "highp", 5) )
  1033. {
  1034. precision = typen;
  1035. typen = nextWord(parse);
  1036. }
  1037. if (0 == bx::strCmp(typen, "flat", 4)
  1038. || 0 == bx::strCmp(typen, "smooth", 6)
  1039. || 0 == bx::strCmp(typen, "noperspective", 13)
  1040. || 0 == bx::strCmp(typen, "centroid", 8) )
  1041. {
  1042. if ('f' == _options.shaderType
  1043. || 0 != glsl
  1044. || 0 != essl)
  1045. {
  1046. interpolation = typen;
  1047. usesInterpolationQualifiers = true;
  1048. }
  1049. typen = nextWord(parse);
  1050. }
  1051. bx::StringView name = nextWord(parse);
  1052. bx::StringView column = bx::strSubstr(parse, 0, 1);
  1053. bx::StringView semantics;
  1054. if (0 == bx::strCmp(column, ":", 1) )
  1055. {
  1056. parse = bx::strLTrimSpace(bx::StringView(parse.getPtr() + 1, parse.getTerm() ) );
  1057. semantics = nextWord(parse);
  1058. }
  1059. bx::StringView assign = bx::strSubstr(parse, 0, 1);
  1060. bx::StringView init;
  1061. if (0 == bx::strCmp(assign, "=", 1))
  1062. {
  1063. parse = bx::strLTrimSpace(bx::StringView(parse.getPtr() + 1, parse.getTerm() ) );
  1064. init.set(parse.getPtr(), eol.getPtr() );
  1065. }
  1066. if (!typen.isEmpty()
  1067. && !name.isEmpty()
  1068. && !semantics.isEmpty() )
  1069. {
  1070. Varying var;
  1071. if (!precision.isEmpty() )
  1072. {
  1073. var.m_precision.assign(precision.getPtr(), precision.getTerm() );
  1074. }
  1075. if (!interpolation.isEmpty() )
  1076. {
  1077. var.m_interpolation.assign(interpolation.getPtr(), interpolation.getTerm() );
  1078. }
  1079. var.m_type.assign(typen.getPtr(), typen.getTerm() );
  1080. var.m_name.assign(name.getPtr(), name.getTerm() );
  1081. var.m_semantics.assign(semantics.getPtr(), semantics.getTerm() );
  1082. if (d3d == 9
  1083. && var.m_semantics == "BITANGENT")
  1084. {
  1085. var.m_semantics = "BINORMAL";
  1086. }
  1087. if (!init.isEmpty() )
  1088. {
  1089. var.m_init.assign(init.getPtr(), init.getTerm() );
  1090. }
  1091. varyingMap.insert(std::make_pair(var.m_name, var) );
  1092. }
  1093. parse = bx::strLTrimSpace(bx::strFindNl(bx::StringView(eol.getPtr(), term.getTerm() ) ) );
  1094. }
  1095. }
  1096. bool raw = _options.raw;
  1097. InOut shaderInputs;
  1098. InOut shaderOutputs;
  1099. uint32_t inputHash = 0;
  1100. uint32_t outputHash = 0;
  1101. char* data;
  1102. char* input;
  1103. {
  1104. data = _shader;
  1105. uint32_t size = _shaderLen;
  1106. const size_t padding = 16384;
  1107. if (!raw)
  1108. {
  1109. // To avoid commented code being recognized as used feature,
  1110. // first preprocess pass is used to strip all comments before
  1111. // substituting code.
  1112. bool ok = preprocessor.run(data);
  1113. delete [] data;
  1114. if (!ok)
  1115. {
  1116. return false;
  1117. }
  1118. size = (uint32_t)preprocessor.m_preprocessed.size();
  1119. data = new char[size+padding+1];
  1120. bx::memCopy(data, preprocessor.m_preprocessed.c_str(), size);
  1121. bx::memSet(&data[size], 0, padding+1);
  1122. }
  1123. strNormalizeEol(data);
  1124. input = const_cast<char*>(bx::strLTrimSpace(data).getPtr() );
  1125. while (input[0] == '$')
  1126. {
  1127. bx::StringView str = bx::strLTrimSpace(input+1);
  1128. bx::StringView eol = bx::strFindEol(str);
  1129. bx::StringView nl = bx::strFindNl(eol);
  1130. input = const_cast<char*>(nl.getPtr() );
  1131. if (0 == bx::strCmp(str, "input", 5) )
  1132. {
  1133. str = bx::StringView(str.getPtr() + 5, str.getTerm() );
  1134. bx::StringView comment = bx::strFind(str, "//");
  1135. eol = !comment.isEmpty() && comment.getPtr() < eol.getPtr() ? comment.getPtr() : eol;
  1136. inputHash = parseInOut(shaderInputs, bx::StringView(str.getPtr(), eol.getPtr() ) );
  1137. }
  1138. else if (0 == bx::strCmp(str, "output", 6) )
  1139. {
  1140. str = bx::StringView(str.getPtr() + 6, str.getTerm() );
  1141. bx::StringView comment = bx::strFind(str, "//");
  1142. eol = !comment.isEmpty() && comment.getPtr() < eol.getPtr() ? comment.getPtr() : eol;
  1143. outputHash = parseInOut(shaderOutputs, bx::StringView(str.getPtr(), eol.getPtr() ) );
  1144. }
  1145. else if (0 == bx::strCmp(str, "raw", 3) )
  1146. {
  1147. raw = true;
  1148. str = bx::StringView(str.getPtr() + 3, str.getTerm() );
  1149. }
  1150. input = const_cast<char*>(bx::strLTrimSpace(input).getPtr() );
  1151. }
  1152. }
  1153. bool invalidShaderAttribute = false;
  1154. if ('v' == _options.shaderType)
  1155. {
  1156. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1157. {
  1158. if (bx::findIdentifierMatch(it->c_str(), s_allowedVertexShaderInputs).isEmpty() )
  1159. {
  1160. invalidShaderAttribute = true;
  1161. bx::printf(
  1162. "Invalid vertex shader input attribute '%s'.\n"
  1163. "\n"
  1164. "Valid input attributes:\n"
  1165. " a_position, a_normal, a_tangent, a_bitangent, a_color0, a_color1, a_color2, a_color3, a_indices, a_weight,\n"
  1166. " a_texcoord0, a_texcoord1, a_texcoord2, a_texcoord3, a_texcoord4, a_texcoord5, a_texcoord6, a_texcoord7,\n"
  1167. " i_data0, i_data1, i_data2, i_data3, i_data4.\n"
  1168. "\n"
  1169. , it->c_str() );
  1170. break;
  1171. }
  1172. }
  1173. }
  1174. if (invalidShaderAttribute)
  1175. {
  1176. }
  1177. else if (raw)
  1178. {
  1179. if ('f' == _options.shaderType)
  1180. {
  1181. bx::write(_writer, BGFX_CHUNK_MAGIC_FSH);
  1182. }
  1183. else if ('v' == _options.shaderType)
  1184. {
  1185. bx::write(_writer, BGFX_CHUNK_MAGIC_VSH);
  1186. }
  1187. else
  1188. {
  1189. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1190. }
  1191. bx::write(_writer, inputHash);
  1192. bx::write(_writer, outputHash);
  1193. }
  1194. if (raw)
  1195. {
  1196. if (0 != glsl)
  1197. {
  1198. bx::write(_writer, uint16_t(0) );
  1199. uint32_t shaderSize = (uint32_t)bx::strLen(input);
  1200. bx::write(_writer, shaderSize);
  1201. bx::write(_writer, input, shaderSize);
  1202. bx::write(_writer, uint8_t(0) );
  1203. compiled = true;
  1204. }
  1205. else if (0 != pssl)
  1206. {
  1207. compiled = compilePSSLShader(_options, 0, input, _writer);
  1208. }
  1209. else
  1210. {
  1211. compiled = compileHLSLShader(_options, d3d, input, _writer);
  1212. }
  1213. }
  1214. else if ('c' == _options.shaderType) // Compute
  1215. {
  1216. bx::StringView entry = bx::strFind(input, "void main()");
  1217. if (entry.isEmpty() )
  1218. {
  1219. bx::printf("Shader entry point 'void main()' is not found.\n");
  1220. }
  1221. else
  1222. {
  1223. if (0 != glsl
  1224. || 0 != essl)
  1225. {
  1226. }
  1227. else
  1228. {
  1229. if (0 != pssl)
  1230. {
  1231. preprocessor.writef(getPsslPreamble() );
  1232. }
  1233. preprocessor.writef(
  1234. "#define lowp\n"
  1235. "#define mediump\n"
  1236. "#define highp\n"
  1237. "#define ivec2 int2\n"
  1238. "#define ivec3 int3\n"
  1239. "#define ivec4 int4\n"
  1240. "#define uvec2 uint2\n"
  1241. "#define uvec3 uint3\n"
  1242. "#define uvec4 uint4\n"
  1243. "#define vec2 float2\n"
  1244. "#define vec3 float3\n"
  1245. "#define vec4 float4\n"
  1246. "#define mat2 float2x2\n"
  1247. "#define mat3 float3x3\n"
  1248. "#define mat4 float4x4\n"
  1249. );
  1250. *const_cast<char*>(entry.getPtr() + 4) = '_';
  1251. preprocessor.writef("#define void_main()");
  1252. preprocessor.writef(" \\\n\tvoid main(");
  1253. uint32_t arg = 0;
  1254. const bool hasLocalInvocationID = !bx::strFind(input, "gl_LocalInvocationID").isEmpty();
  1255. const bool hasLocalInvocationIndex = !bx::strFind(input, "gl_LocalInvocationIndex").isEmpty();
  1256. const bool hasGlobalInvocationID = !bx::strFind(input, "gl_GlobalInvocationID").isEmpty();
  1257. const bool hasWorkGroupID = !bx::strFind(input, "gl_WorkGroupID").isEmpty();
  1258. if (hasLocalInvocationID)
  1259. {
  1260. preprocessor.writef(
  1261. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1262. , arg++ > 0 ? ", " : " "
  1263. );
  1264. }
  1265. if (hasLocalInvocationIndex)
  1266. {
  1267. preprocessor.writef(
  1268. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1269. , arg++ > 0 ? ", " : " "
  1270. );
  1271. }
  1272. if (hasGlobalInvocationID)
  1273. {
  1274. preprocessor.writef(
  1275. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1276. , arg++ > 0 ? ", " : " "
  1277. );
  1278. }
  1279. if (hasWorkGroupID)
  1280. {
  1281. preprocessor.writef(
  1282. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1283. , arg++ > 0 ? ", " : " "
  1284. );
  1285. }
  1286. preprocessor.writef(
  1287. " \\\n\t)\n"
  1288. );
  1289. }
  1290. if (preprocessor.run(input) )
  1291. {
  1292. if (_options.preprocessOnly)
  1293. {
  1294. bx::write(_writer, preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1295. return true;
  1296. }
  1297. {
  1298. std::string code;
  1299. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1300. bx::write(_writer, uint32_t(0) );
  1301. bx::write(_writer, outputHash);
  1302. if (0 != glsl
  1303. || 0 != essl)
  1304. {
  1305. if (essl)
  1306. {
  1307. bx::stringPrintf(code, "#version 310 es\n");
  1308. }
  1309. else
  1310. {
  1311. bx::stringPrintf(code, "#version %d\n", glsl == 0 ? 430 : glsl);
  1312. }
  1313. #if 1
  1314. code += preprocessor.m_preprocessed;
  1315. bx::write(_writer, uint16_t(0) );
  1316. uint32_t shaderSize = (uint32_t)code.size();
  1317. bx::write(_writer, shaderSize);
  1318. bx::write(_writer, code.c_str(), shaderSize);
  1319. bx::write(_writer, uint8_t(0) );
  1320. compiled = true;
  1321. #else
  1322. code += _comment;
  1323. code += preprocessor.m_preprocessed;
  1324. compiled = compileGLSLShader(cmdLine, essl, code, writer);
  1325. #endif // 0
  1326. }
  1327. else
  1328. {
  1329. code += _comment;
  1330. code += preprocessor.m_preprocessed;
  1331. if (0 != metal)
  1332. {
  1333. compiled = compileMetalShader(_options, BX_MAKEFOURCC('M', 'T', 'L', 0), code, _writer);
  1334. }
  1335. else if (0 != spirv)
  1336. {
  1337. compiled = compileSPIRVShader(_options, spirv, code, _writer);
  1338. }
  1339. else if (0 != pssl)
  1340. {
  1341. compiled = compilePSSLShader(_options, 0, code, _writer);
  1342. }
  1343. else
  1344. {
  1345. compiled = compileHLSLShader(_options, d3d, code, _writer);
  1346. }
  1347. }
  1348. }
  1349. if (compiled)
  1350. {
  1351. if (_options.depends)
  1352. {
  1353. std::string ofp = _options.outputFilePath;
  1354. ofp += ".d";
  1355. bx::FileWriter writer;
  1356. if (bx::open(&writer, ofp.c_str() ) )
  1357. {
  1358. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  1359. bx::close(&writer);
  1360. }
  1361. }
  1362. }
  1363. }
  1364. }
  1365. }
  1366. else // Vertex/Fragment
  1367. {
  1368. bx::StringView shader(input);
  1369. bx::StringView entry = bx::strFind(shader, "void main()");
  1370. if (entry.isEmpty() )
  1371. {
  1372. bx::printf("Shader entry point 'void main()' is not found.\n");
  1373. }
  1374. else
  1375. {
  1376. if (0 != glsl
  1377. || 0 != essl)
  1378. {
  1379. if (0 == essl)
  1380. {
  1381. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1382. // not as GLSL language 1.2 specs shadow2D/Proj.
  1383. preprocessor.writef(
  1384. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1385. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1386. );
  1387. }
  1388. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1389. {
  1390. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1391. if (varyingIt != varyingMap.end() )
  1392. {
  1393. const Varying& var = varyingIt->second;
  1394. const char* name = var.m_name.c_str();
  1395. if (0 == bx::strCmp(name, "a_", 2)
  1396. || 0 == bx::strCmp(name, "i_", 2) )
  1397. {
  1398. preprocessor.writef(
  1399. "attribute %s %s %s %s;\n"
  1400. , var.m_precision.c_str()
  1401. , var.m_interpolation.c_str()
  1402. , var.m_type.c_str()
  1403. , name
  1404. );
  1405. }
  1406. else
  1407. {
  1408. preprocessor.writef(
  1409. "%s varying %s %s %s;\n"
  1410. , var.m_interpolation.c_str()
  1411. , var.m_precision.c_str()
  1412. , var.m_type.c_str()
  1413. , name
  1414. );
  1415. }
  1416. }
  1417. }
  1418. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1419. {
  1420. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1421. if (varyingIt != varyingMap.end() )
  1422. {
  1423. const Varying& var = varyingIt->second;
  1424. preprocessor.writef("%s varying %s %s;\n"
  1425. , var.m_interpolation.c_str()
  1426. , var.m_type.c_str()
  1427. , var.m_name.c_str()
  1428. );
  1429. }
  1430. }
  1431. }
  1432. else
  1433. {
  1434. if (0 != pssl)
  1435. {
  1436. preprocessor.writef(getPsslPreamble() );
  1437. }
  1438. preprocessor.writef(
  1439. "#define lowp\n"
  1440. "#define mediump\n"
  1441. "#define highp\n"
  1442. "#define ivec2 int2\n"
  1443. "#define ivec3 int3\n"
  1444. "#define ivec4 int4\n"
  1445. "#define uvec2 uint2\n"
  1446. "#define uvec3 uint3\n"
  1447. "#define uvec4 uint4\n"
  1448. "#define vec2 float2\n"
  1449. "#define vec3 float3\n"
  1450. "#define vec4 float4\n"
  1451. "#define mat2 float2x2\n"
  1452. "#define mat3 float3x3\n"
  1453. "#define mat4 float4x4\n"
  1454. );
  1455. if (hlsl != 0
  1456. && hlsl < 4)
  1457. {
  1458. preprocessor.writef(
  1459. "#define centroid\n"
  1460. "#define flat\n"
  1461. "#define noperspective\n"
  1462. "#define smooth\n"
  1463. );
  1464. }
  1465. *const_cast<char*>(entry.getPtr() + 4) = '_';
  1466. if ('f' == _options.shaderType)
  1467. {
  1468. bx::StringView insert = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1469. if (!insert.isEmpty() )
  1470. {
  1471. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\nvec4 bgfx_VoidFrag = vec4_splat(0.0);\n");
  1472. }
  1473. const bool hasFragColor = !bx::strFind(input, "gl_FragColor").isEmpty();
  1474. const bool hasFragCoord = !bx::strFind(input, "gl_FragCoord").isEmpty() || hlsl > 3 || hlsl == 2;
  1475. const bool hasFragDepth = !bx::strFind(input, "gl_FragDepth").isEmpty();
  1476. const bool hasFrontFacing = !bx::strFind(input, "gl_FrontFacing").isEmpty();
  1477. const bool hasPrimitiveId = !bx::strFind(input, "gl_PrimitiveID").isEmpty();
  1478. bool hasFragData[8] = {};
  1479. uint32_t numFragData = 0;
  1480. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1481. {
  1482. char temp[32];
  1483. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  1484. hasFragData[ii] = !bx::strFind(input, temp).isEmpty();
  1485. numFragData += hasFragData[ii];
  1486. }
  1487. if (0 == numFragData)
  1488. {
  1489. // GL errors when both gl_FragColor and gl_FragData is used.
  1490. // This will trigger the same error with HLSL compiler too.
  1491. preprocessor.writef("#define gl_FragColor bgfx_FragData0\n");
  1492. // If it has gl_FragData or gl_FragColor, color target at
  1493. // index 0 exists, otherwise shader is not modifying color
  1494. // targets.
  1495. hasFragData[0] |= hasFragColor || d3d < 11;
  1496. if (!insert.isEmpty()
  1497. && d3d < 11
  1498. && !hasFragColor)
  1499. {
  1500. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\ngl_FragColor = bgfx_VoidFrag;\n");
  1501. }
  1502. }
  1503. preprocessor.writef("#define void_main()");
  1504. preprocessor.writef(" \\\n\tvoid main(");
  1505. uint32_t arg = 0;
  1506. if (hasFragCoord)
  1507. {
  1508. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1509. ++arg;
  1510. }
  1511. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1512. {
  1513. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1514. if (varyingIt != varyingMap.end() )
  1515. {
  1516. const Varying& var = varyingIt->second;
  1517. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  1518. , arg++ > 0 ? ", " : " "
  1519. , interpolationDx11(var.m_interpolation.c_str() )
  1520. , var.m_type.c_str()
  1521. , var.m_name.c_str()
  1522. , var.m_semantics.c_str()
  1523. );
  1524. }
  1525. }
  1526. const uint32_t maxRT = d3d > 9 ? BX_COUNTOF(hasFragData) : 4;
  1527. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1528. {
  1529. if (ii < maxRT)
  1530. {
  1531. if (hasFragData[ii])
  1532. {
  1533. addFragData(preprocessor, input, ii, arg++ > 0);
  1534. }
  1535. }
  1536. else
  1537. {
  1538. voidFragData(input, ii);
  1539. }
  1540. }
  1541. if (hasFragDepth)
  1542. {
  1543. preprocessor.writef(
  1544. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1545. , arg++ > 0 ? ", " : " "
  1546. );
  1547. }
  1548. if (hasFrontFacing)
  1549. {
  1550. if (hlsl == 3)
  1551. {
  1552. preprocessor.writef(
  1553. " \\\n\t%sfloat __vface : VFACE"
  1554. , arg++ > 0 ? ", " : " "
  1555. );
  1556. }
  1557. else
  1558. {
  1559. preprocessor.writef(
  1560. " \\\n\t%sbool gl_FrontFacing : SV_IsFrontFace"
  1561. , arg++ > 0 ? ", " : " "
  1562. );
  1563. }
  1564. }
  1565. if (hasPrimitiveId)
  1566. {
  1567. if (hlsl > 3)
  1568. {
  1569. preprocessor.writef(
  1570. " \\\n\t%suint gl_PrimitiveID : SV_PrimitiveID"
  1571. , arg++ > 0 ? ", " : " "
  1572. );
  1573. }
  1574. else
  1575. {
  1576. bx::printf("gl_PrimitiveID builtin is not supported by this D3D9 HLSL.\n");
  1577. return false;
  1578. }
  1579. }
  1580. preprocessor.writef(
  1581. " \\\n\t)\n"
  1582. );
  1583. if (hasFrontFacing)
  1584. {
  1585. if (hlsl == 3)
  1586. {
  1587. preprocessor.writef(
  1588. "#define gl_FrontFacing (__vface >= 0.0)\n"
  1589. );
  1590. }
  1591. }
  1592. }
  1593. else if ('v' == _options.shaderType)
  1594. {
  1595. const bool hasVertexId = !bx::strFind(input, "gl_VertexID").isEmpty();
  1596. const bool hasInstanceId = !bx::strFind(input, "gl_InstanceID").isEmpty();
  1597. bx::StringView brace = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1598. if (!brace.isEmpty() )
  1599. {
  1600. bx::StringView block = bx::strFindBlock(bx::StringView(brace.getPtr(), shader.getTerm() ), '{', '}');
  1601. if (!block.isEmpty() )
  1602. {
  1603. strInsert(const_cast<char*>(block.getTerm()-1), "__RETURN__;\n");
  1604. }
  1605. }
  1606. preprocessor.writef(
  1607. "struct Output\n"
  1608. "{\n"
  1609. "\tvec4 gl_Position : SV_POSITION;\n"
  1610. "#define gl_Position _varying_.gl_Position\n"
  1611. );
  1612. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1613. {
  1614. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1615. if (varyingIt != varyingMap.end() )
  1616. {
  1617. const Varying& var = varyingIt->second;
  1618. preprocessor.writef(
  1619. "\t%s %s %s : %s;\n"
  1620. , interpolationDx11(var.m_interpolation.c_str() )
  1621. , var.m_type.c_str()
  1622. , var.m_name.c_str()
  1623. , var.m_semantics.c_str()
  1624. );
  1625. preprocessor.writef(
  1626. "#define %s _varying_.%s\n"
  1627. , var.m_name.c_str()
  1628. , var.m_name.c_str()
  1629. );
  1630. }
  1631. }
  1632. preprocessor.writef(
  1633. "};\n"
  1634. );
  1635. preprocessor.writef("#define void_main() \\\n");
  1636. preprocessor.writef("Output main(");
  1637. uint32_t arg = 0;
  1638. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1639. {
  1640. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1641. if (varyingIt != varyingMap.end() )
  1642. {
  1643. const Varying& var = varyingIt->second;
  1644. preprocessor.writef(
  1645. " \\\n\t%s%s %s : %s"
  1646. , arg++ > 0 ? ", " : ""
  1647. , var.m_type.c_str()
  1648. , var.m_name.c_str()
  1649. , var.m_semantics.c_str()
  1650. );
  1651. }
  1652. }
  1653. if (hasVertexId)
  1654. {
  1655. if (d3d > 9)
  1656. {
  1657. preprocessor.writef(
  1658. " \\\n\t%suint gl_VertexID : SV_VertexID"
  1659. , arg++ > 0 ? ", " : " "
  1660. );
  1661. }
  1662. else
  1663. {
  1664. bx::printf("gl_VertexID builtin is not supported by this D3D9 HLSL.\n");
  1665. return false;
  1666. }
  1667. }
  1668. if (hasInstanceId)
  1669. {
  1670. if (d3d > 9)
  1671. {
  1672. preprocessor.writef(
  1673. " \\\n\t%suint gl_InstanceID : SV_InstanceID"
  1674. , arg++ > 0 ? ", " : " "
  1675. );
  1676. }
  1677. else
  1678. {
  1679. bx::printf("gl_InstanceID builtin is not supported by this D3D9 HLSL.\n");
  1680. return false;
  1681. }
  1682. }
  1683. preprocessor.writef(
  1684. ") \\\n"
  1685. "{ \\\n"
  1686. "\tOutput _varying_;"
  1687. );
  1688. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1689. {
  1690. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1691. if (varyingIt != varyingMap.end() )
  1692. {
  1693. const Varying& var = varyingIt->second;
  1694. preprocessor.writef(" \\\n\t%s", var.m_name.c_str() );
  1695. if (!var.m_init.empty() )
  1696. {
  1697. preprocessor.writef(" = %s", var.m_init.c_str() );
  1698. }
  1699. preprocessor.writef(";");
  1700. }
  1701. }
  1702. preprocessor.writef(
  1703. "\n#define __RETURN__ \\\n"
  1704. "\t} \\\n"
  1705. );
  1706. preprocessor.writef(
  1707. "\treturn _varying_"
  1708. );
  1709. }
  1710. }
  1711. if (preprocessor.run(input) )
  1712. {
  1713. //BX_TRACE("Input file: %s", filePath);
  1714. //BX_TRACE("Output file: %s", outFilePath);
  1715. if (_options.preprocessOnly)
  1716. {
  1717. if (0 != glsl)
  1718. {
  1719. if (essl != 0)
  1720. {
  1721. writef(_writer
  1722. , "#ifdef GL_ES\n"
  1723. "precision highp float;\n"
  1724. "#endif // GL_ES\n\n"
  1725. );
  1726. }
  1727. }
  1728. bx::write(_writer, preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1729. return true;
  1730. }
  1731. {
  1732. std::string code;
  1733. if ('f' == _options.shaderType)
  1734. {
  1735. bx::write(_writer, BGFX_CHUNK_MAGIC_FSH);
  1736. bx::write(_writer, inputHash);
  1737. bx::write(_writer, uint32_t(0) );
  1738. }
  1739. else if ('v' == _options.shaderType)
  1740. {
  1741. bx::write(_writer, BGFX_CHUNK_MAGIC_VSH);
  1742. bx::write(_writer, uint32_t(0) );
  1743. bx::write(_writer, outputHash);
  1744. }
  1745. else
  1746. {
  1747. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1748. bx::write(_writer, uint32_t(0) );
  1749. bx::write(_writer, outputHash);
  1750. }
  1751. if (0 != glsl
  1752. || 0 != essl)
  1753. {
  1754. const bx::StringView preprocessedInput(preprocessor.m_preprocessed.c_str() );
  1755. if (!bx::strFind(preprocessedInput, "layout(std430").isEmpty()
  1756. || !bx::strFind(preprocessedInput, "image2D").isEmpty()
  1757. || (_options.shaderType == 'f'
  1758. && (!bx::strFind(preprocessedInput, "floatBitsToUint").isEmpty() ||
  1759. !bx::strFind(preprocessedInput, "floatBitsToInt").isEmpty() ||
  1760. !bx::strFind(preprocessedInput, "intBitsToFloat").isEmpty() ||
  1761. !bx::strFind(preprocessedInput, "uintBitsToFloat").isEmpty()
  1762. ) )
  1763. )
  1764. {
  1765. glsl = 430;
  1766. }
  1767. if (glsl < 400)
  1768. {
  1769. const bool usesTextureLod = false
  1770. || !bx::findIdentifierMatch(input, s_ARB_shader_texture_lod).isEmpty()
  1771. || !bx::findIdentifierMatch(input, s_EXT_shader_texture_lod).isEmpty()
  1772. ;
  1773. const bool usesGpuShader5 = true
  1774. && _options.shaderType != 'f'
  1775. && !bx::findIdentifierMatch(input, s_ARB_gpu_shader5).isEmpty()
  1776. ;
  1777. const bool usesInstanceID = !bx::findIdentifierMatch(input, "gl_InstanceID").isEmpty();
  1778. const bool usesGpuShader4 = !bx::findIdentifierMatch(input, s_EXT_gpu_shader4).isEmpty();
  1779. const bool usesTexelFetch = !bx::findIdentifierMatch(input, s_texelFetch).isEmpty();
  1780. const bool usesTextureMS = !bx::findIdentifierMatch(input, s_ARB_texture_multisample).isEmpty();
  1781. const bool usesTextureArray = !bx::findIdentifierMatch(input, s_textureArray).isEmpty();
  1782. const bool usesPacking = !bx::findIdentifierMatch(input, s_ARB_shading_language_packing).isEmpty();
  1783. if (0 == essl)
  1784. {
  1785. const bool need130 = (120 == glsl && (false
  1786. || !bx::findIdentifierMatch(input, s_130).isEmpty()
  1787. || usesInterpolationQualifiers
  1788. || usesTexelFetch
  1789. ) );
  1790. bx::stringPrintf(code, "#version %s\n", need130 ? "130" : _options.profile.c_str());
  1791. glsl = 130;
  1792. if (need130)
  1793. {
  1794. bx::stringPrintf(code, "#define varying %s\n"
  1795. , 'f' == _options.shaderType ? "in" : "out"
  1796. );
  1797. }
  1798. if (usesInstanceID)
  1799. {
  1800. bx::stringPrintf(code
  1801. , "#extension GL_ARB_draw_instanced : enable\n"
  1802. );
  1803. }
  1804. if (usesGpuShader4)
  1805. {
  1806. bx::stringPrintf(code
  1807. , "#extension GL_EXT_gpu_shader4 : enable\n"
  1808. );
  1809. }
  1810. if (usesGpuShader5)
  1811. {
  1812. bx::stringPrintf(code
  1813. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1814. );
  1815. }
  1816. if (usesPacking)
  1817. {
  1818. bx::stringPrintf(code
  1819. , "#extension GL_ARB_shading_language_packing : enable\n"
  1820. );
  1821. }
  1822. bool ARB_shader_texture_lod = false;
  1823. bool EXT_shader_texture_lod = false;
  1824. if (usesTextureLod)
  1825. {
  1826. if ('f' == _options.shaderType)
  1827. {
  1828. ARB_shader_texture_lod = true;
  1829. bx::stringPrintf(code
  1830. , "#extension GL_ARB_shader_texture_lod : enable\n"
  1831. );
  1832. }
  1833. else
  1834. {
  1835. EXT_shader_texture_lod = true;
  1836. bx::stringPrintf(code
  1837. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1838. );
  1839. }
  1840. }
  1841. if (usesTextureMS)
  1842. {
  1843. bx::stringPrintf(code
  1844. , "#extension GL_ARB_texture_multisample : enable\n"
  1845. );
  1846. }
  1847. if (usesTextureArray)
  1848. {
  1849. bx::stringPrintf(code
  1850. , "#extension GL_EXT_texture_array : enable\n"
  1851. );
  1852. }
  1853. if (130 > glsl)
  1854. {
  1855. bx::stringPrintf(code,
  1856. "#define ivec2 vec2\n"
  1857. "#define ivec3 vec3\n"
  1858. "#define ivec4 vec4\n"
  1859. );
  1860. }
  1861. if (ARB_shader_texture_lod)
  1862. {
  1863. bx::stringPrintf(code,
  1864. "#define texture2DProjLod texture2DProjLodARB\n"
  1865. "#define texture2DGrad texture2DGradARB\n"
  1866. "#define texture2DProjGrad texture2DProjGradARB\n"
  1867. "#define textureCubeGrad textureCubeGradARB\n"
  1868. );
  1869. }
  1870. else if (EXT_shader_texture_lod)
  1871. {
  1872. bx::stringPrintf(code,
  1873. "#define texture2DProjLod texture2DProjLodEXT\n"
  1874. "#define texture2DGrad texture2DGradEXT\n"
  1875. "#define texture2DProjGrad texture2DProjGradEXT\n"
  1876. "#define textureCubeGrad textureCubeGradEXT\n"
  1877. );
  1878. }
  1879. if (need130)
  1880. {
  1881. bx::stringPrintf(code
  1882. , "#define bgfxShadow2D(_sampler, _coord) vec4_splat(texture(_sampler, _coord))\n"
  1883. "#define bgfxShadow2DProj(_sampler, _coord) vec4_splat(textureProj(_sampler, _coord))\n"
  1884. );
  1885. }
  1886. else
  1887. {
  1888. bx::stringPrintf(code
  1889. , "#define bgfxShadow2D shadow2D\n"
  1890. "#define bgfxShadow2DProj shadow2DProj\n"
  1891. );
  1892. }
  1893. }
  1894. else
  1895. {
  1896. if (usesInterpolationQualifiers)
  1897. {
  1898. bx::stringPrintf(code, "#version 300 es\n");
  1899. bx::stringPrintf(code, "#define attribute in\n");
  1900. bx::stringPrintf(code, "#define varying %s\n"
  1901. , 'f' == _options.shaderType ? "in" : "out"
  1902. );
  1903. }
  1904. else if (essl == 2)
  1905. {
  1906. code +=
  1907. "mat2 transpose(mat2 _mtx)\n"
  1908. "{\n"
  1909. " vec2 v0 = _mtx[0];\n"
  1910. " vec2 v1 = _mtx[1];\n"
  1911. "\n"
  1912. " return mat2(\n"
  1913. " vec2(v0.x, v1.x)\n"
  1914. " , vec2(v0.y, v1.y)\n"
  1915. " );\n"
  1916. "}\n"
  1917. "\n"
  1918. "mat3 transpose(mat3 _mtx)\n"
  1919. "{\n"
  1920. " vec3 v0 = _mtx[0];\n"
  1921. " vec3 v1 = _mtx[1];\n"
  1922. " vec3 v2 = _mtx[2];\n"
  1923. "\n"
  1924. " return mat3(\n"
  1925. " vec3(v0.x, v1.x, v2.x)\n"
  1926. " , vec3(v0.y, v1.y, v2.y)\n"
  1927. " , vec3(v0.z, v1.z, v2.z)\n"
  1928. " );\n"
  1929. "}\n"
  1930. "\n"
  1931. "mat4 transpose(mat4 _mtx)\n"
  1932. "{\n"
  1933. " vec4 v0 = _mtx[0];\n"
  1934. " vec4 v1 = _mtx[1];\n"
  1935. " vec4 v2 = _mtx[2];\n"
  1936. " vec4 v3 = _mtx[3];\n"
  1937. "\n"
  1938. " return mat4(\n"
  1939. " vec4(v0.x, v1.x, v2.x, v3.x)\n"
  1940. " , vec4(v0.y, v1.y, v2.y, v3.y)\n"
  1941. " , vec4(v0.z, v1.z, v2.z, v3.z)\n"
  1942. " , vec4(v0.w, v1.w, v2.w, v3.w)\n"
  1943. " );\n"
  1944. "}\n"
  1945. ;
  1946. }
  1947. // Pretend that all extensions are available.
  1948. // This will be stripped later.
  1949. if (usesTextureLod)
  1950. {
  1951. bx::stringPrintf(code
  1952. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1953. "#define texture2DLod texture2DLodEXT\n"
  1954. "#define texture2DGrad texture2DGradEXT\n"
  1955. "#define texture2DProjLod texture2DProjLodEXT\n"
  1956. "#define texture2DProjGrad texture2DProjGradEXT\n"
  1957. "#define textureCubeLod textureCubeLodEXT\n"
  1958. "#define textureCubeGrad textureCubeGradEXT\n"
  1959. );
  1960. }
  1961. if (!bx::findIdentifierMatch(input, s_OES_standard_derivatives).isEmpty() )
  1962. {
  1963. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  1964. }
  1965. if (!bx::findIdentifierMatch(input, s_OES_texture_3D).isEmpty() )
  1966. {
  1967. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  1968. }
  1969. if (!bx::findIdentifierMatch(input, s_EXT_shadow_samplers).isEmpty() )
  1970. {
  1971. bx::stringPrintf(code
  1972. , "#extension GL_EXT_shadow_samplers : enable\n"
  1973. "#define shadow2D shadow2DEXT\n"
  1974. "#define shadow2DProj shadow2DProjEXT\n"
  1975. );
  1976. }
  1977. if (usesGpuShader5)
  1978. {
  1979. bx::stringPrintf(code
  1980. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1981. );
  1982. }
  1983. if (usesPacking)
  1984. {
  1985. bx::stringPrintf(code
  1986. , "#extension GL_ARB_shading_language_packing : enable\n"
  1987. );
  1988. }
  1989. if (!bx::findIdentifierMatch(input, "gl_FragDepth").isEmpty() )
  1990. {
  1991. bx::stringPrintf(code
  1992. , "#extension GL_EXT_frag_depth : enable\n"
  1993. "#define gl_FragDepth gl_FragDepthEXT\n"
  1994. );
  1995. }
  1996. if (usesTextureArray)
  1997. {
  1998. bx::stringPrintf(code
  1999. , "#extension GL_EXT_texture_array : enable\n"
  2000. );
  2001. }
  2002. bx::stringPrintf(code
  2003. , "#define ivec2 vec2\n"
  2004. "#define ivec3 vec3\n"
  2005. "#define ivec4 vec4\n"
  2006. "#define uvec2 vec2\n"
  2007. "#define uvec3 vec3\n"
  2008. "#define uvec4 vec4\n"
  2009. );
  2010. }
  2011. }
  2012. else
  2013. {
  2014. bx::stringPrintf(code, "#version %d\n", glsl);
  2015. bx::stringPrintf(code
  2016. , "#define texture2DLod textureLod\n"
  2017. "#define texture2DGrad textureGrad\n"
  2018. "#define texture2DProjLod textureProjLod\n"
  2019. "#define texture2DProjGrad textureProjGrad\n"
  2020. "#define textureCubeLod textureLod\n"
  2021. "#define textureCubeGrad textureGrad\n"
  2022. "#define texture3D texture\n"
  2023. );
  2024. bx::stringPrintf(code, "#define attribute in\n");
  2025. bx::stringPrintf(code, "#define varying %s\n"
  2026. , 'f' == _options.shaderType ? "in" : "out"
  2027. );
  2028. bx::stringPrintf(code
  2029. , "#define bgfxShadow2D(_sampler, _coord) vec4_splat(texture(_sampler, _coord))\n"
  2030. "#define bgfxShadow2DProj(_sampler, _coord) vec4_splat(textureProj(_sampler, _coord))\n"
  2031. );
  2032. }
  2033. if (glsl > 400)
  2034. {
  2035. code += preprocessor.m_preprocessed;
  2036. bx::write(_writer, uint16_t(0) );
  2037. uint32_t shaderSize = (uint32_t)code.size();
  2038. bx::write(_writer, shaderSize);
  2039. bx::write(_writer, code.c_str(), shaderSize);
  2040. bx::write(_writer, uint8_t(0) );
  2041. compiled = true;
  2042. }
  2043. else
  2044. {
  2045. code += _comment;
  2046. code += preprocessor.m_preprocessed;
  2047. compiled = compileGLSLShader(_options, metal ? BX_MAKEFOURCC('M', 'T', 'L', 0) : essl, code, _writer);
  2048. }
  2049. }
  2050. else
  2051. {
  2052. code += _comment;
  2053. code += preprocessor.m_preprocessed;
  2054. if (0 != metal)
  2055. {
  2056. compiled = compileMetalShader(_options, BX_MAKEFOURCC('M', 'T', 'L', 0), code, _writer);
  2057. }
  2058. else if (0 != spirv)
  2059. {
  2060. compiled = compileSPIRVShader(_options, spirv, code, _writer);
  2061. }
  2062. else if (0 != pssl)
  2063. {
  2064. compiled = compilePSSLShader(_options, 0, code, _writer);
  2065. }
  2066. else
  2067. {
  2068. compiled = compileHLSLShader(_options, d3d, code, _writer);
  2069. }
  2070. }
  2071. }
  2072. if (compiled)
  2073. {
  2074. if (_options.depends)
  2075. {
  2076. std::string ofp = _options.outputFilePath + ".d";
  2077. bx::FileWriter writer;
  2078. if (bx::open(&writer, ofp.c_str() ) )
  2079. {
  2080. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  2081. bx::close(&writer);
  2082. }
  2083. }
  2084. }
  2085. }
  2086. }
  2087. }
  2088. delete [] data;
  2089. return compiled;
  2090. }
  2091. int compileShader(int _argc, const char* _argv[])
  2092. {
  2093. bx::CommandLine cmdLine(_argc, _argv);
  2094. if (cmdLine.hasArg('v', "version") )
  2095. {
  2096. bx::printf(
  2097. "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  2098. , BGFX_SHADERC_VERSION_MAJOR
  2099. , BGFX_SHADERC_VERSION_MINOR
  2100. , BGFX_API_VERSION
  2101. );
  2102. return bx::kExitSuccess;
  2103. }
  2104. if (cmdLine.hasArg('h', "help") )
  2105. {
  2106. help();
  2107. return bx::kExitFailure;
  2108. }
  2109. g_verbose = cmdLine.hasArg("verbose");
  2110. const char* filePath = cmdLine.findOption('f');
  2111. if (NULL == filePath)
  2112. {
  2113. help("Shader file name must be specified.");
  2114. return bx::kExitFailure;
  2115. }
  2116. const char* outFilePath = cmdLine.findOption('o');
  2117. if (NULL == outFilePath)
  2118. {
  2119. help("Output file name must be specified.");
  2120. return bx::kExitFailure;
  2121. }
  2122. const char* type = cmdLine.findOption('\0', "type");
  2123. if (NULL == type)
  2124. {
  2125. help("Must specify shader type.");
  2126. return bx::kExitFailure;
  2127. }
  2128. Options options;
  2129. options.inputFilePath = filePath;
  2130. options.outputFilePath = outFilePath;
  2131. options.shaderType = bx::toLower(type[0]);
  2132. options.disasm = cmdLine.hasArg('\0', "disasm");
  2133. const char* platform = cmdLine.findOption('\0', "platform");
  2134. if (NULL == platform)
  2135. {
  2136. platform = "";
  2137. }
  2138. options.platform = platform;
  2139. options.raw = cmdLine.hasArg('\0', "raw");
  2140. const char* profile = cmdLine.findOption('p', "profile");
  2141. if ( NULL != profile)
  2142. {
  2143. options.profile = profile;
  2144. }
  2145. {
  2146. options.debugInformation = cmdLine.hasArg('\0', "debug");
  2147. options.avoidFlowControl = cmdLine.hasArg('\0', "avoid-flow-control");
  2148. options.noPreshader = cmdLine.hasArg('\0', "no-preshader");
  2149. options.partialPrecision = cmdLine.hasArg('\0', "partial-precision");
  2150. options.preferFlowControl = cmdLine.hasArg('\0', "prefer-flow-control");
  2151. options.backwardsCompatibility = cmdLine.hasArg('\0', "backwards-compatibility");
  2152. options.warningsAreErrors = cmdLine.hasArg('\0', "Werror");
  2153. options.keepIntermediate = cmdLine.hasArg('\0', "keep-intermediate");
  2154. uint32_t optimization = 3;
  2155. if (cmdLine.hasArg(optimization, 'O') )
  2156. {
  2157. options.optimize = true;
  2158. options.optimizationLevel = optimization;
  2159. }
  2160. }
  2161. bx::StringView bin2c;
  2162. if (cmdLine.hasArg("bin2c") )
  2163. {
  2164. const char* bin2cArg = cmdLine.findOption("bin2c");
  2165. if (NULL != bin2cArg)
  2166. {
  2167. bin2c.set(bin2cArg);
  2168. }
  2169. else
  2170. {
  2171. bin2c = baseName(outFilePath);
  2172. if (!bin2c.isEmpty() )
  2173. {
  2174. char* temp = (char*)alloca(bin2c.getLength()+1);
  2175. for (uint32_t ii = 0, num = bin2c.getLength(); ii < num; ++ii)
  2176. {
  2177. char ch = bin2c.getPtr()[ii];
  2178. if (bx::isAlphaNum(ch) )
  2179. {
  2180. temp[ii] = ch;
  2181. }
  2182. else
  2183. {
  2184. temp[ii] = '_';
  2185. }
  2186. }
  2187. temp[bin2c.getLength()] = '\0';
  2188. bin2c = temp;
  2189. }
  2190. }
  2191. }
  2192. options.depends = cmdLine.hasArg("depends");
  2193. options.preprocessOnly = cmdLine.hasArg("preprocess");
  2194. const char* includeDir = cmdLine.findOption('i');
  2195. BX_TRACE("depends: %d", options.depends);
  2196. BX_TRACE("preprocessOnly: %d", options.preprocessOnly);
  2197. BX_TRACE("includeDir: %s", includeDir);
  2198. for (int ii = 1; NULL != includeDir; ++ii)
  2199. {
  2200. options.includeDirs.push_back(includeDir);
  2201. includeDir = cmdLine.findOption(ii, 'i');
  2202. }
  2203. std::string dir;
  2204. {
  2205. bx::FilePath fp(filePath);
  2206. bx::StringView path(fp.getPath() );
  2207. dir.assign(path.getPtr(), path.getTerm() );
  2208. options.includeDirs.push_back(dir);
  2209. }
  2210. const char* defines = cmdLine.findOption("define");
  2211. while (NULL != defines
  2212. && '\0' != *defines)
  2213. {
  2214. defines = bx::strLTrimSpace(defines).getPtr();
  2215. bx::StringView eol = bx::strFind(defines, ';');
  2216. std::string define(defines, eol.getPtr() );
  2217. options.defines.push_back(define.c_str() );
  2218. defines = ';' == *eol.getPtr() ? eol.getPtr()+1 : eol.getPtr();
  2219. }
  2220. std::string commandLineComment = "// shaderc command line:\n//";
  2221. for (int32_t ii = 0, num = cmdLine.getNum(); ii < num; ++ii)
  2222. {
  2223. commandLineComment += " ";
  2224. commandLineComment += cmdLine.get(ii);
  2225. }
  2226. commandLineComment += "\n\n";
  2227. bool compiled = false;
  2228. bx::FileReader reader;
  2229. if (!bx::open(&reader, filePath) )
  2230. {
  2231. bx::printf("Unable to open file '%s'.\n", filePath);
  2232. }
  2233. else
  2234. {
  2235. const char* varying = NULL;
  2236. File attribdef;
  2237. if ('c' != options.shaderType)
  2238. {
  2239. std::string defaultVarying = dir + "varying.def.sc";
  2240. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  2241. attribdef.load(varyingdef);
  2242. varying = attribdef.getData();
  2243. if (NULL != varying
  2244. && *varying != '\0')
  2245. {
  2246. options.dependencies.push_back(varyingdef);
  2247. }
  2248. else
  2249. {
  2250. bx::printf("ERROR: Failed to parse varying def file: \"%s\" No input/output semantics will be generated in the code!\n", varyingdef);
  2251. }
  2252. }
  2253. const size_t padding = 16384;
  2254. uint32_t size = (uint32_t)bx::getSize(&reader);
  2255. char* data = new char[size+padding+1];
  2256. size = (uint32_t)bx::read(&reader, data, size);
  2257. if (data[0] == '\xef'
  2258. && data[1] == '\xbb'
  2259. && data[2] == '\xbf')
  2260. {
  2261. bx::memMove(data, &data[3], size-3);
  2262. size -= 3;
  2263. }
  2264. // Compiler generates "error X3000: syntax error: unexpected end of file"
  2265. // if input doesn't have empty line at EOF.
  2266. data[size] = '\n';
  2267. bx::memSet(&data[size+1], 0, padding);
  2268. bx::close(&reader);
  2269. bx::FileWriter* writer = NULL;
  2270. if (!bin2c.isEmpty() )
  2271. {
  2272. writer = new Bin2cWriter(bin2c);
  2273. }
  2274. else
  2275. {
  2276. writer = new bx::FileWriter;
  2277. }
  2278. if (!bx::open(writer, outFilePath) )
  2279. {
  2280. bx::printf("Unable to open output file '%s'.", outFilePath);
  2281. return bx::kExitFailure;
  2282. }
  2283. compiled = compileShader(varying, commandLineComment.c_str(), data, size, options, writer);
  2284. bx::close(writer);
  2285. delete writer;
  2286. }
  2287. if (compiled)
  2288. {
  2289. return bx::kExitSuccess;
  2290. }
  2291. bx::remove(outFilePath);
  2292. bx::printf("Failed to build shader.\n");
  2293. return bx::kExitFailure;
  2294. }
  2295. } // namespace bgfx
  2296. int main(int _argc, const char* _argv[])
  2297. {
  2298. return bgfx::compileShader(_argc, _argv);
  2299. }