shaderc.cpp 45 KB

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