shaderc.cpp 46 KB

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