shaderc.cpp 41 KB

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