shaderc.cpp 40 KB

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