shaderc.cpp 47 KB

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