shaderc.cpp 48 KB

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