shaderc.cpp 44 KB

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