shaderc.cpp 45 KB

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