shaderc.cpp 48 KB

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