shaderc.cpp 55 KB

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