shaderc.cpp 41 KB

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