shaderc.cpp 59 KB

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