shaderc.cpp 41 KB

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