shaderc.cpp 45 KB

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