shaderc.cpp 40 KB

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