shaderc.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  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. bool usesInterpolationQualifiers = false;
  885. while (NULL != parse
  886. && '\0' != *parse)
  887. {
  888. parse = bx::strws(parse);
  889. const char* eol = bx::strFind(parse, ';');
  890. if (NULL == eol)
  891. {
  892. eol = bx::streol(parse);
  893. }
  894. if (NULL != eol)
  895. {
  896. const char* precision = NULL;
  897. const char* interpolation = NULL;
  898. const char* typen = parse;
  899. if (0 == bx::strCmp(typen, "lowp", 4)
  900. || 0 == bx::strCmp(typen, "mediump", 7)
  901. || 0 == bx::strCmp(typen, "highp", 5) )
  902. {
  903. precision = typen;
  904. typen = parse = bx::strws(bx::strSkipWord(parse) );
  905. }
  906. if (0 == bx::strCmp(typen, "flat", 4)
  907. || 0 == bx::strCmp(typen, "smooth", 6)
  908. || 0 == bx::strCmp(typen, "noperspective", 13)
  909. || 0 == bx::strCmp(typen, "centroid", 8) )
  910. {
  911. interpolation = typen;
  912. typen = parse = bx::strws(bx::strSkipWord(parse) );
  913. usesInterpolationQualifiers = true;
  914. }
  915. const char* name = parse = bx::strws(bx::strSkipWord(parse) );
  916. const char* column = parse = bx::strws(bx::strSkipWord(parse) );
  917. const char* semantics = parse = bx::strws( (*parse == ':' ? ++parse : parse) );
  918. const char* assign = parse = bx::strws(bx::strSkipWord(parse) );
  919. const char* init = parse = bx::strws( (*parse == '=' ? ++parse : parse) );
  920. if (typen < eol
  921. && name < eol
  922. && column < eol
  923. && ':' == *column
  924. && semantics < eol)
  925. {
  926. Varying var;
  927. if (NULL != precision)
  928. {
  929. var.m_precision.assign(precision, bx::strSkipWord(precision)-precision);
  930. }
  931. if (NULL != interpolation)
  932. {
  933. var.m_interpolation.assign(interpolation, bx::strSkipWord(interpolation)-interpolation);
  934. }
  935. var.m_type.assign(typen, bx::strSkipWord(typen)-typen);
  936. var.m_name.assign(name, bx::strSkipWord(name)-name);
  937. var.m_semantics.assign(semantics, bx::strSkipWord(semantics)-semantics);
  938. if (d3d == 9
  939. && var.m_semantics == "BITANGENT")
  940. {
  941. var.m_semantics = "BINORMAL";
  942. }
  943. if (assign < eol
  944. && '=' == *assign
  945. && init < eol)
  946. {
  947. var.m_init.assign(init, eol-init);
  948. }
  949. varyingMap.insert(std::make_pair(var.m_name, var) );
  950. }
  951. parse = bx::strws(bx::strnl(eol) );
  952. }
  953. }
  954. bool raw = _options.raw;
  955. InOut shaderInputs;
  956. InOut shaderOutputs;
  957. uint32_t inputHash = 0;
  958. uint32_t outputHash = 0;
  959. char* data;
  960. char* input;
  961. {
  962. data = _shader;
  963. uint32_t size = _shaderLen;
  964. const size_t padding = 4096;
  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. bx::memCopy(data, preprocessor.m_preprocessed.c_str(), size);
  975. bx::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 == bx::strCmp(str, "input", 5) )
  986. {
  987. str += 5;
  988. const char* comment = bx::strFind(str, "//");
  989. eol = NULL != comment && comment < eol ? comment : eol;
  990. inputHash = parseInOut(shaderInputs, str, eol);
  991. }
  992. else if (0 == bx::strCmp(str, "output", 6) )
  993. {
  994. str += 6;
  995. const char* comment = bx::strFind(str, "//");
  996. eol = NULL != comment && comment < eol ? comment : eol;
  997. outputHash = parseInOut(shaderOutputs, str, eol);
  998. }
  999. else if (0 == bx::strCmp(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. if ('f' == _options.shaderType)
  1010. {
  1011. bx::write(_writer, BGFX_CHUNK_MAGIC_FSH);
  1012. bx::write(_writer, inputHash);
  1013. }
  1014. else if ('v' == _options.shaderType)
  1015. {
  1016. bx::write(_writer, BGFX_CHUNK_MAGIC_VSH);
  1017. bx::write(_writer, outputHash);
  1018. }
  1019. else
  1020. {
  1021. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1022. bx::write(_writer, outputHash);
  1023. }
  1024. if (0 != glsl)
  1025. {
  1026. bx::write(_writer, uint16_t(0) );
  1027. uint32_t shaderSize = (uint32_t)bx::strLen(input);
  1028. bx::write(_writer, shaderSize);
  1029. bx::write(_writer, input, shaderSize);
  1030. bx::write(_writer, uint8_t(0) );
  1031. compiled = true;
  1032. }
  1033. else if (0 != pssl)
  1034. {
  1035. compiled = compilePSSLShader(_options, 0, input, _writer);
  1036. }
  1037. else
  1038. {
  1039. compiled = compileHLSLShader(_options, d3d, input, _writer);
  1040. }
  1041. }
  1042. else if ('c' == _options.shaderType) // Compute
  1043. {
  1044. char* entry = const_cast<char*>(bx::strFind(input, "void main()") );
  1045. if (NULL == entry)
  1046. {
  1047. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1048. }
  1049. else
  1050. {
  1051. if (0 != glsl
  1052. || 0 != essl
  1053. || 0 != metal)
  1054. {
  1055. }
  1056. else
  1057. {
  1058. preprocessor.writef(
  1059. "#define lowp\n"
  1060. "#define mediump\n"
  1061. "#define highp\n"
  1062. "#define ivec2 int2\n"
  1063. "#define ivec3 int3\n"
  1064. "#define ivec4 int4\n"
  1065. "#define uvec2 uint2\n"
  1066. "#define uvec3 uint3\n"
  1067. "#define uvec4 uint4\n"
  1068. "#define vec2 float2\n"
  1069. "#define vec3 float3\n"
  1070. "#define vec4 float4\n"
  1071. "#define mat2 float2x2\n"
  1072. "#define mat3 float3x3\n"
  1073. "#define mat4 float4x4\n"
  1074. );
  1075. entry[4] = '_';
  1076. preprocessor.writef("#define void_main()");
  1077. preprocessor.writef(" \\\n\tvoid main(");
  1078. uint32_t arg = 0;
  1079. const bool hasLocalInvocationID = NULL != bx::strFind(input, "gl_LocalInvocationID");
  1080. const bool hasLocalInvocationIndex = NULL != bx::strFind(input, "gl_LocalInvocationIndex");
  1081. const bool hasGlobalInvocationID = NULL != bx::strFind(input, "gl_GlobalInvocationID");
  1082. const bool hasWorkGroupID = NULL != bx::strFind(input, "gl_WorkGroupID");
  1083. if (hasLocalInvocationID)
  1084. {
  1085. preprocessor.writef(
  1086. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1087. , arg++ > 0 ? ", " : " "
  1088. );
  1089. }
  1090. if (hasLocalInvocationIndex)
  1091. {
  1092. preprocessor.writef(
  1093. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1094. , arg++ > 0 ? ", " : " "
  1095. );
  1096. }
  1097. if (hasGlobalInvocationID)
  1098. {
  1099. preprocessor.writef(
  1100. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1101. , arg++ > 0 ? ", " : " "
  1102. );
  1103. }
  1104. if (hasWorkGroupID)
  1105. {
  1106. preprocessor.writef(
  1107. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1108. , arg++ > 0 ? ", " : " "
  1109. );
  1110. }
  1111. preprocessor.writef(
  1112. " \\\n\t)\n"
  1113. );
  1114. }
  1115. if (preprocessor.run(input) )
  1116. {
  1117. //BX_TRACE("Input file: %s", filePath);
  1118. //BX_TRACE("Output file: %s", outFilePath);
  1119. if (_options.preprocessOnly)
  1120. {
  1121. bx::write(_writer, preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1122. return true;
  1123. }
  1124. {
  1125. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1126. bx::write(_writer, outputHash);
  1127. if (0 != glsl
  1128. || 0 != essl)
  1129. {
  1130. std::string code;
  1131. if (essl)
  1132. {
  1133. bx::stringPrintf(code, "#version 310 es\n");
  1134. }
  1135. else
  1136. {
  1137. bx::stringPrintf(code, "#version %d\n", glsl == 0 ? 430 : glsl);
  1138. }
  1139. code += preprocessor.m_preprocessed;
  1140. #if 1
  1141. bx::write(_writer, uint16_t(0) );
  1142. uint32_t shaderSize = (uint32_t)code.size();
  1143. bx::write(_writer, shaderSize);
  1144. bx::write(_writer, code.c_str(), shaderSize);
  1145. bx::write(_writer, uint8_t(0) );
  1146. compiled = true;
  1147. #else
  1148. compiled = compileGLSLShader(cmdLine, essl, code, writer);
  1149. #endif // 0
  1150. }
  1151. else if (0 != spirv)
  1152. {
  1153. compiled = compileSPIRVShader(_options, 0, preprocessor.m_preprocessed, _writer);
  1154. }
  1155. else if (0 != pssl)
  1156. {
  1157. compiled = compilePSSLShader(_options, 0, preprocessor.m_preprocessed, _writer);
  1158. }
  1159. else
  1160. {
  1161. compiled = compileHLSLShader(_options, d3d, preprocessor.m_preprocessed, _writer);
  1162. }
  1163. }
  1164. if (compiled)
  1165. {
  1166. if (_options.depends)
  1167. {
  1168. std::string ofp = _options.outputFilePath;
  1169. ofp += ".d";
  1170. bx::FileWriter writer;
  1171. if (bx::open(&writer, ofp.c_str() ) )
  1172. {
  1173. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  1174. bx::close(&writer);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. }
  1180. }
  1181. else // Vertex/Fragment
  1182. {
  1183. char* entry = const_cast<char*>(bx::strFind(input, "void main()") );
  1184. if (NULL == entry)
  1185. {
  1186. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1187. }
  1188. else
  1189. {
  1190. if (0 != glsl
  1191. || 0 != essl
  1192. || 0 != metal)
  1193. {
  1194. if (0 == essl)
  1195. {
  1196. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1197. // not as GLSL language 1.2 specs shadow2D/Proj.
  1198. preprocessor.writef(
  1199. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1200. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1201. );
  1202. }
  1203. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1204. {
  1205. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1206. if (varyingIt != varyingMap.end() )
  1207. {
  1208. const Varying& var = varyingIt->second;
  1209. const char* name = var.m_name.c_str();
  1210. if (0 == bx::strCmp(name, "a_", 2)
  1211. || 0 == bx::strCmp(name, "i_", 2) )
  1212. {
  1213. preprocessor.writef("attribute %s %s %s %s;\n"
  1214. , var.m_precision.c_str()
  1215. , var.m_interpolation.c_str()
  1216. , var.m_type.c_str()
  1217. , name
  1218. );
  1219. }
  1220. else
  1221. {
  1222. preprocessor.writef("%s varying %s %s %s;\n"
  1223. , var.m_interpolation.c_str()
  1224. , var.m_precision.c_str()
  1225. , var.m_type.c_str()
  1226. , name
  1227. );
  1228. }
  1229. }
  1230. }
  1231. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1232. {
  1233. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1234. if (varyingIt != varyingMap.end() )
  1235. {
  1236. const Varying& var = varyingIt->second;
  1237. preprocessor.writef("%s varying %s %s;\n"
  1238. , var.m_interpolation.c_str()
  1239. , var.m_type.c_str()
  1240. , var.m_name.c_str()
  1241. );
  1242. }
  1243. }
  1244. }
  1245. else
  1246. {
  1247. preprocessor.writef(
  1248. "#define lowp\n"
  1249. "#define mediump\n"
  1250. "#define highp\n"
  1251. "#define ivec2 int2\n"
  1252. "#define ivec3 int3\n"
  1253. "#define ivec4 int4\n"
  1254. "#define uvec2 uint2\n"
  1255. "#define uvec3 uint3\n"
  1256. "#define uvec4 uint4\n"
  1257. "#define vec2 float2\n"
  1258. "#define vec3 float3\n"
  1259. "#define vec4 float4\n"
  1260. "#define mat2 float2x2\n"
  1261. "#define mat3 float3x3\n"
  1262. "#define mat4 float4x4\n"
  1263. );
  1264. if (hlsl != 0
  1265. && hlsl < 4)
  1266. {
  1267. preprocessor.writef(
  1268. "#define centroid\n"
  1269. "#define flat\n"
  1270. "#define noperspective\n"
  1271. "#define smooth\n"
  1272. );
  1273. }
  1274. entry[4] = '_';
  1275. if ('f' == _options.shaderType)
  1276. {
  1277. const char* insert = bx::strFind(entry, "{");
  1278. if (NULL != insert)
  1279. {
  1280. insert = strInsert(const_cast<char*>(insert+1), "\nvec4 bgfx_VoidFrag = vec4_splat(0.0);\n");
  1281. }
  1282. const bool hasFragColor = NULL != bx::strFind(input, "gl_FragColor");
  1283. const bool hasFragCoord = NULL != bx::strFind(input, "gl_FragCoord") || hlsl > 3 || hlsl == 2;
  1284. const bool hasFragDepth = NULL != bx::strFind(input, "gl_FragDepth");
  1285. const bool hasFrontFacing = NULL != bx::strFind(input, "gl_FrontFacing");
  1286. const bool hasPrimitiveId = NULL != bx::strFind(input, "gl_PrimitiveID");
  1287. bool hasFragData[8] = {};
  1288. uint32_t numFragData = 0;
  1289. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1290. {
  1291. char temp[32];
  1292. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  1293. hasFragData[ii] = NULL != bx::strFind(input, temp);
  1294. numFragData += hasFragData[ii];
  1295. }
  1296. if (0 == numFragData)
  1297. {
  1298. // GL errors when both gl_FragColor and gl_FragData is used.
  1299. // This will trigger the same error with HLSL compiler too.
  1300. preprocessor.writef("#define gl_FragColor gl_FragData_0_\n");
  1301. // If it has gl_FragData or gl_FragColor, color target at
  1302. // index 0 exists, otherwise shader is not modifying color
  1303. // targets.
  1304. hasFragData[0] |= hasFragColor || d3d < 11;
  1305. if (NULL != insert
  1306. && d3d < 11
  1307. && !hasFragColor)
  1308. {
  1309. insert = strInsert(const_cast<char*>(insert+1), "\ngl_FragColor = bgfx_VoidFrag;\n");
  1310. }
  1311. }
  1312. preprocessor.writef("#define void_main()");
  1313. preprocessor.writef(" \\\n\tvoid main(");
  1314. uint32_t arg = 0;
  1315. if (hasFragCoord)
  1316. {
  1317. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1318. ++arg;
  1319. }
  1320. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1321. {
  1322. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1323. if (varyingIt != varyingMap.end() )
  1324. {
  1325. const Varying& var = varyingIt->second;
  1326. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  1327. , arg++ > 0 ? ", " : " "
  1328. , interpolationDx11(var.m_interpolation.c_str() )
  1329. , var.m_type.c_str()
  1330. , var.m_name.c_str()
  1331. , var.m_semantics.c_str()
  1332. );
  1333. }
  1334. }
  1335. const uint32_t maxRT = d3d > 9 ? BX_COUNTOF(hasFragData) : 4;
  1336. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1337. {
  1338. if (ii < maxRT)
  1339. {
  1340. if (hasFragData[ii])
  1341. {
  1342. addFragData(preprocessor, input, ii, arg++ > 0);
  1343. }
  1344. }
  1345. else
  1346. {
  1347. voidFragData(input, ii);
  1348. }
  1349. }
  1350. if (hasFragDepth)
  1351. {
  1352. preprocessor.writef(
  1353. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1354. , arg++ > 0 ? ", " : " "
  1355. );
  1356. }
  1357. if (hasFrontFacing
  1358. && hlsl >= 3)
  1359. {
  1360. preprocessor.writef(
  1361. " \\\n\t%sfloat __vface : VFACE"
  1362. , arg++ > 0 ? ", " : " "
  1363. );
  1364. }
  1365. if (hasPrimitiveId)
  1366. {
  1367. if (d3d > 9)
  1368. {
  1369. preprocessor.writef(
  1370. " \\\n\t%suint gl_PrimitiveID : SV_PrimitiveID"
  1371. , arg++ > 0 ? ", " : " "
  1372. );
  1373. }
  1374. else
  1375. {
  1376. fprintf(stderr, "gl_PrimitiveID builtin is not supported by this D3D9 HLSL.\n");
  1377. return false;
  1378. }
  1379. }
  1380. preprocessor.writef(
  1381. " \\\n\t)\n"
  1382. );
  1383. if (hasFrontFacing)
  1384. {
  1385. if (hlsl >= 3)
  1386. {
  1387. preprocessor.writef(
  1388. "#define gl_FrontFacing (__vface <= 0.0)\n"
  1389. );
  1390. }
  1391. else
  1392. {
  1393. preprocessor.writef(
  1394. "#define gl_FrontFacing false\n"
  1395. );
  1396. }
  1397. }
  1398. }
  1399. else if ('v' == _options.shaderType)
  1400. {
  1401. const bool hasVertexId = NULL != bx::strFind(input, "gl_VertexID");
  1402. const bool hasInstanceId = NULL != bx::strFind(input, "gl_InstanceID");
  1403. const char* brace = bx::strFind(entry, "{");
  1404. if (NULL != brace)
  1405. {
  1406. const char* end = bx::strmb(brace, '{', '}');
  1407. if (NULL != end)
  1408. {
  1409. strInsert(const_cast<char*>(end), "__RETURN__;\n");
  1410. }
  1411. }
  1412. preprocessor.writef(
  1413. "struct Output\n"
  1414. "{\n"
  1415. "\tvec4 gl_Position : SV_POSITION;\n"
  1416. "#define gl_Position _varying_.gl_Position\n"
  1417. );
  1418. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1419. {
  1420. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1421. if (varyingIt != varyingMap.end() )
  1422. {
  1423. const Varying& var = varyingIt->second;
  1424. preprocessor.writef(
  1425. "\t%s %s %s : %s;\n"
  1426. , interpolationDx11(var.m_interpolation.c_str() )
  1427. , var.m_type.c_str()
  1428. , var.m_name.c_str()
  1429. , var.m_semantics.c_str()
  1430. );
  1431. preprocessor.writef(
  1432. "#define %s _varying_.%s\n"
  1433. , var.m_name.c_str()
  1434. , var.m_name.c_str()
  1435. );
  1436. }
  1437. }
  1438. preprocessor.writef(
  1439. "};\n"
  1440. );
  1441. preprocessor.writef("#define void_main() \\\n");
  1442. preprocessor.writef("Output main(");
  1443. uint32_t arg = 0;
  1444. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1445. {
  1446. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1447. if (varyingIt != varyingMap.end() )
  1448. {
  1449. const Varying& var = varyingIt->second;
  1450. preprocessor.writef(
  1451. " \\\n\t%s%s %s : %s"
  1452. , arg++ > 0 ? ", " : ""
  1453. , var.m_type.c_str()
  1454. , var.m_name.c_str()
  1455. , var.m_semantics.c_str()
  1456. );
  1457. }
  1458. }
  1459. if (hasVertexId)
  1460. {
  1461. if (d3d > 9)
  1462. {
  1463. preprocessor.writef(
  1464. " \\\n\t%suint gl_VertexID : SV_VertexID"
  1465. , arg++ > 0 ? ", " : " "
  1466. );
  1467. }
  1468. else
  1469. {
  1470. fprintf(stderr, "gl_VertexID builtin is not supported by this D3D9 HLSL.\n");
  1471. return false;
  1472. }
  1473. }
  1474. if (hasInstanceId)
  1475. {
  1476. if (d3d > 9)
  1477. {
  1478. preprocessor.writef(
  1479. " \\\n\t%suint gl_InstanceID : SV_InstanceID"
  1480. , arg++ > 0 ? ", " : " "
  1481. );
  1482. }
  1483. else
  1484. {
  1485. fprintf(stderr, "gl_InstanceID builtin is not supported by this D3D9 HLSL.\n");
  1486. return false;
  1487. }
  1488. }
  1489. preprocessor.writef(
  1490. ") \\\n"
  1491. "{ \\\n"
  1492. "\tOutput _varying_;"
  1493. );
  1494. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1495. {
  1496. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1497. if (varyingIt != varyingMap.end() )
  1498. {
  1499. const Varying& var = varyingIt->second;
  1500. preprocessor.writef(" \\\n\t%s", var.m_name.c_str() );
  1501. if (!var.m_init.empty() )
  1502. {
  1503. preprocessor.writef(" = %s", var.m_init.c_str() );
  1504. }
  1505. preprocessor.writef(";");
  1506. }
  1507. }
  1508. preprocessor.writef(
  1509. "\n#define __RETURN__ \\\n"
  1510. "\t} \\\n"
  1511. );
  1512. if (hlsl != 0
  1513. && hlsl <= 3)
  1514. {
  1515. // preprocessor.writef(
  1516. // "\tgl_Position.xy += u_viewTexel.xy * gl_Position.w; \\\n"
  1517. // );
  1518. }
  1519. preprocessor.writef(
  1520. "\treturn _varying_"
  1521. );
  1522. }
  1523. }
  1524. if (preprocessor.run(input) )
  1525. {
  1526. //BX_TRACE("Input file: %s", filePath);
  1527. //BX_TRACE("Output file: %s", outFilePath);
  1528. if (_options.preprocessOnly)
  1529. {
  1530. if (0 != glsl)
  1531. {
  1532. if (essl != 0)
  1533. {
  1534. writef(_writer
  1535. , "#ifdef GL_ES\n"
  1536. "precision highp float;\n"
  1537. "#endif // GL_ES\n\n"
  1538. );
  1539. }
  1540. }
  1541. bx::write(_writer, preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1542. return true;
  1543. }
  1544. {
  1545. if ('f' == _options.shaderType)
  1546. {
  1547. bx::write(_writer, BGFX_CHUNK_MAGIC_FSH);
  1548. bx::write(_writer, inputHash);
  1549. }
  1550. else if ('v' == _options.shaderType)
  1551. {
  1552. bx::write(_writer, BGFX_CHUNK_MAGIC_VSH);
  1553. bx::write(_writer, outputHash);
  1554. }
  1555. else
  1556. {
  1557. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1558. bx::write(_writer, outputHash);
  1559. }
  1560. if (0 != glsl
  1561. || 0 != essl
  1562. || 0 != metal)
  1563. {
  1564. std::string code;
  1565. if (NULL != bx::strFind(preprocessor.m_preprocessed.c_str(), "layout(std430") )
  1566. {
  1567. glsl = 430;
  1568. }
  1569. if (glsl < 400)
  1570. {
  1571. const bool usesTextureLod = false
  1572. || !!bx::findIdentifierMatch(input, s_ARB_shader_texture_lod)
  1573. || !!bx::findIdentifierMatch(input, s_EXT_shader_texture_lod)
  1574. ;
  1575. const bool usesInstanceID = !!bx::strFind(input, "gl_InstanceID");
  1576. const bool usesGpuShader4 = !!bx::findIdentifierMatch(input, s_EXT_gpu_shader4);
  1577. const bool usesGpuShader5 = !!bx::findIdentifierMatch(input, s_ARB_gpu_shader5);
  1578. const bool usesTexelFetch = !!bx::findIdentifierMatch(input, s_texelFetch);
  1579. const bool usesTextureMS = !!bx::findIdentifierMatch(input, s_ARB_texture_multisample);
  1580. const bool usesTextureArray = !!bx::findIdentifierMatch(input, s_textureArray);
  1581. const bool usesPacking = !!bx::findIdentifierMatch(input, s_ARB_shading_language_packing);
  1582. if (0 == essl)
  1583. {
  1584. const bool need130 = 120 == glsl && (false
  1585. || bx::findIdentifierMatch(input, s_130)
  1586. || usesInterpolationQualifiers
  1587. || usesTexelFetch
  1588. );
  1589. if (0 != metal)
  1590. {
  1591. bx::stringPrintf(code, "#version 120\n");
  1592. }
  1593. else
  1594. {
  1595. bx::stringPrintf(code, "#version %s\n", need130 ? "130" : _options.profile.c_str());
  1596. glsl = 130;
  1597. }
  1598. if (need130)
  1599. {
  1600. bx::stringPrintf(code, "#define varying %s\n"
  1601. , 'f' == _options.shaderType ? "in" : "out"
  1602. );
  1603. }
  1604. if (usesInstanceID)
  1605. {
  1606. bx::stringPrintf(code
  1607. , "#extension GL_ARB_draw_instanced : enable\n"
  1608. );
  1609. }
  1610. if (usesGpuShader4)
  1611. {
  1612. bx::stringPrintf(code
  1613. , "#extension GL_EXT_gpu_shader4 : enable\n"
  1614. );
  1615. }
  1616. if (usesGpuShader5)
  1617. {
  1618. bx::stringPrintf(code
  1619. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1620. );
  1621. }
  1622. if (usesPacking)
  1623. {
  1624. bx::stringPrintf(code
  1625. , "#extension GL_ARB_shading_language_packing : enable\n"
  1626. );
  1627. }
  1628. bool ARB_shader_texture_lod = false;
  1629. bool EXT_shader_texture_lod = false;
  1630. if (usesTextureLod)
  1631. {
  1632. if ('f' == _options.shaderType)
  1633. {
  1634. ARB_shader_texture_lod = true;
  1635. bx::stringPrintf(code
  1636. , "#extension GL_ARB_shader_texture_lod : enable\n"
  1637. );
  1638. }
  1639. else
  1640. {
  1641. EXT_shader_texture_lod = true;
  1642. bx::stringPrintf(code
  1643. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1644. );
  1645. }
  1646. }
  1647. if (usesTextureMS)
  1648. {
  1649. bx::stringPrintf(code
  1650. , "#extension GL_ARB_texture_multisample : enable\n"
  1651. );
  1652. }
  1653. if (usesTextureArray)
  1654. {
  1655. bx::stringPrintf(code
  1656. , "#extension GL_EXT_texture_array : enable\n"
  1657. );
  1658. }
  1659. if (130 > glsl)
  1660. {
  1661. bx::stringPrintf(code,
  1662. "#define ivec2 vec2\n"
  1663. "#define ivec3 vec3\n"
  1664. "#define ivec4 vec4\n"
  1665. );
  1666. }
  1667. if (ARB_shader_texture_lod)
  1668. {
  1669. bx::stringPrintf(code,
  1670. "#define texture2DProjLod texture2DProjLodARB\n"
  1671. "#define texture2DGrad texture2DGradARB\n"
  1672. "#define texture2DProjGrad texture2DProjGradARB\n"
  1673. "#define textureCubeGrad textureCubeGradARB\n"
  1674. );
  1675. }
  1676. else if (EXT_shader_texture_lod)
  1677. {
  1678. bx::stringPrintf(code,
  1679. "#define texture2DProjLod texture2DProjLodEXT\n"
  1680. "#define texture2DGrad texture2DGradEXT\n"
  1681. "#define texture2DProjGrad texture2DProjGradEXT\n"
  1682. "#define textureCubeGrad textureCubeGradEXT\n"
  1683. );
  1684. }
  1685. if (need130)
  1686. {
  1687. bx::stringPrintf(code
  1688. , "#define bgfxShadow2D(_sampler, _coord) vec4_splat(texture(_sampler, _coord))\n"
  1689. "#define bgfxShadow2DProj(_sampler, _coord) vec4_splat(textureProj(_sampler, _coord))\n"
  1690. );
  1691. }
  1692. else
  1693. {
  1694. bx::stringPrintf(code
  1695. , "#define bgfxShadow2D shadow2D\n"
  1696. "#define bgfxShadow2DProj shadow2DProj\n"
  1697. );
  1698. }
  1699. }
  1700. else
  1701. {
  1702. if (usesInterpolationQualifiers)
  1703. {
  1704. bx::stringPrintf(code, "#version 300 es\n");
  1705. bx::stringPrintf(code, "#define attribute in\n");
  1706. bx::stringPrintf(code, "#define varying %s\n"
  1707. , 'f' == _options.shaderType ? "in" : "out"
  1708. );
  1709. }
  1710. // Pretend that all extensions are available.
  1711. // This will be stripped later.
  1712. if (usesTextureLod)
  1713. {
  1714. bx::stringPrintf(code
  1715. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1716. "#define texture2DLod texture2DLodEXT\n"
  1717. "#define texture2DGrad texture2DGradEXT\n"
  1718. "#define texture2DProjLod texture2DProjLodEXT\n"
  1719. "#define texture2DProjGrad texture2DProjGradEXT\n"
  1720. "#define textureCubeLod textureCubeLodEXT\n"
  1721. "#define textureCubeGrad textureCubeGradEXT\n"
  1722. );
  1723. }
  1724. if (NULL != bx::findIdentifierMatch(input, s_OES_standard_derivatives) )
  1725. {
  1726. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  1727. }
  1728. if (NULL != bx::findIdentifierMatch(input, s_OES_texture_3D) )
  1729. {
  1730. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  1731. }
  1732. if (NULL != bx::findIdentifierMatch(input, s_EXT_shadow_samplers) )
  1733. {
  1734. bx::stringPrintf(code
  1735. , "#extension GL_EXT_shadow_samplers : enable\n"
  1736. "#define shadow2D shadow2DEXT\n"
  1737. "#define shadow2DProj shadow2DProjEXT\n"
  1738. );
  1739. }
  1740. if (usesGpuShader5)
  1741. {
  1742. bx::stringPrintf(code
  1743. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1744. );
  1745. }
  1746. if (usesPacking)
  1747. {
  1748. bx::stringPrintf(code
  1749. , "#extension GL_ARB_shading_language_packing : enable\n"
  1750. );
  1751. }
  1752. if (NULL != bx::findIdentifierMatch(input, "gl_FragDepth") )
  1753. {
  1754. bx::stringPrintf(code
  1755. , "#extension GL_EXT_frag_depth : enable\n"
  1756. "#define gl_FragDepth gl_FragDepthEXT\n"
  1757. );
  1758. }
  1759. if (usesTextureArray)
  1760. {
  1761. bx::stringPrintf(code
  1762. , "#extension GL_EXT_texture_array : enable\n"
  1763. );
  1764. }
  1765. bx::stringPrintf(code
  1766. , "#define ivec2 vec2\n"
  1767. "#define ivec3 vec3\n"
  1768. "#define ivec4 vec4\n"
  1769. );
  1770. }
  1771. }
  1772. else
  1773. {
  1774. bx::stringPrintf(code, "#version %d\n", glsl);
  1775. bx::stringPrintf(code
  1776. , "#define texture2DLod textureLod\n"
  1777. "#define texture2DGrad textureGrad\n"
  1778. "#define texture2DProjLod textureProjLod\n"
  1779. "#define texture2DProjGrad textureProjGrad\n"
  1780. "#define textureCubeLod textureLod\n"
  1781. "#define textureCubeGrad textureGrad\n"
  1782. );
  1783. }
  1784. code += preprocessor.m_preprocessed;
  1785. if (glsl > 400)
  1786. {
  1787. bx::write(_writer, uint16_t(0) );
  1788. uint32_t shaderSize = (uint32_t)code.size();
  1789. bx::write(_writer, shaderSize);
  1790. bx::write(_writer, code.c_str(), shaderSize);
  1791. bx::write(_writer, uint8_t(0) );
  1792. compiled = true;
  1793. }
  1794. else
  1795. {
  1796. compiled = compileGLSLShader(_options
  1797. , metal ? BX_MAKEFOURCC('M', 'T', 'L', 0) : essl
  1798. , code
  1799. , _writer
  1800. );
  1801. }
  1802. }
  1803. else if (0 != spirv)
  1804. {
  1805. compiled = compileSPIRVShader(_options
  1806. , 0
  1807. , preprocessor.m_preprocessed
  1808. , _writer
  1809. );
  1810. }
  1811. else if (0 != pssl)
  1812. {
  1813. compiled = compilePSSLShader(_options
  1814. , 0
  1815. , preprocessor.m_preprocessed
  1816. , _writer
  1817. );
  1818. }
  1819. else
  1820. {
  1821. compiled = compileHLSLShader(_options
  1822. , d3d
  1823. , preprocessor.m_preprocessed
  1824. , _writer
  1825. );
  1826. }
  1827. }
  1828. if (compiled)
  1829. {
  1830. if (_options.depends)
  1831. {
  1832. std::string ofp = _options.outputFilePath + ".d";
  1833. bx::FileWriter writer;
  1834. if (bx::open(&writer, ofp.c_str() ) )
  1835. {
  1836. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  1837. bx::close(&writer);
  1838. }
  1839. }
  1840. }
  1841. }
  1842. }
  1843. }
  1844. delete [] data;
  1845. return compiled;
  1846. }
  1847. int compileShader(int _argc, const char* _argv[])
  1848. {
  1849. bx::CommandLine cmdLine(_argc, _argv);
  1850. if (cmdLine.hasArg('v', "version") )
  1851. {
  1852. fprintf(stderr
  1853. , "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  1854. , BGFX_SHADERC_VERSION_MAJOR
  1855. , BGFX_SHADERC_VERSION_MINOR
  1856. , BGFX_API_VERSION
  1857. );
  1858. return bx::kExitSuccess;
  1859. }
  1860. if (cmdLine.hasArg('h', "help") )
  1861. {
  1862. help();
  1863. return bx::kExitFailure;
  1864. }
  1865. g_verbose = cmdLine.hasArg("verbose");
  1866. const char* filePath = cmdLine.findOption('f');
  1867. if (NULL == filePath)
  1868. {
  1869. help("Shader file name must be specified.");
  1870. return bx::kExitFailure;
  1871. }
  1872. const char* outFilePath = cmdLine.findOption('o');
  1873. if (NULL == outFilePath)
  1874. {
  1875. help("Output file name must be specified.");
  1876. return bx::kExitFailure;
  1877. }
  1878. const char* type = cmdLine.findOption('\0', "type");
  1879. if (NULL == type)
  1880. {
  1881. help("Must specify shader type.");
  1882. return bx::kExitFailure;
  1883. }
  1884. Options options;
  1885. options.inputFilePath = filePath;
  1886. options.outputFilePath = outFilePath;
  1887. options.shaderType = bx::toLower(type[0]);
  1888. options.disasm = cmdLine.hasArg('\0', "disasm");
  1889. const char* platform = cmdLine.findOption('\0', "platform");
  1890. if (NULL == platform)
  1891. {
  1892. platform = "";
  1893. }
  1894. options.platform = platform;
  1895. options.raw = cmdLine.hasArg('\0', "raw");
  1896. const char* profile = cmdLine.findOption('p', "profile");
  1897. if ( NULL != profile)
  1898. {
  1899. options.profile = profile;
  1900. }
  1901. { // hlsl only
  1902. options.debugInformation = cmdLine.hasArg('\0', "debug");
  1903. options.avoidFlowControl = cmdLine.hasArg('\0', "avoid-flow-control");
  1904. options.noPreshader = cmdLine.hasArg('\0', "no-preshader");
  1905. options.partialPrecision = cmdLine.hasArg('\0', "partial-precision");
  1906. options.preferFlowControl = cmdLine.hasArg('\0', "prefer-flow-control");
  1907. options.backwardsCompatibility = cmdLine.hasArg('\0', "backwards-compatibility");
  1908. options.warningsAreErrors = cmdLine.hasArg('\0', "Werror");
  1909. uint32_t optimization = 3;
  1910. if (cmdLine.hasArg(optimization, 'O') )
  1911. {
  1912. options.optimize = true;
  1913. options.optimizationLevel = optimization;
  1914. }
  1915. }
  1916. const char* bin2c = NULL;
  1917. if (cmdLine.hasArg("bin2c") )
  1918. {
  1919. bin2c = cmdLine.findOption("bin2c");
  1920. if (NULL == bin2c)
  1921. {
  1922. bin2c = baseName(outFilePath);
  1923. uint32_t len = (uint32_t)bx::strLen(bin2c);
  1924. char* temp = (char*)alloca(len+1);
  1925. for (char *out = temp; *bin2c != '\0';)
  1926. {
  1927. char ch = *bin2c++;
  1928. if (isalnum(ch) )
  1929. {
  1930. *out++ = ch;
  1931. }
  1932. else
  1933. {
  1934. *out++ = '_';
  1935. }
  1936. }
  1937. temp[len] = '\0';
  1938. bin2c = temp;
  1939. }
  1940. }
  1941. options.depends = cmdLine.hasArg("depends");
  1942. options.preprocessOnly = cmdLine.hasArg("preprocess");
  1943. const char* includeDir = cmdLine.findOption('i');
  1944. BX_TRACE("depends: %d", options.depends);
  1945. BX_TRACE("preprocessOnly: %d", options.preprocessOnly);
  1946. BX_TRACE("includeDir: %s", includeDir);
  1947. for (int ii = 1; NULL != includeDir; ++ii)
  1948. {
  1949. options.includeDirs.push_back(includeDir);
  1950. includeDir = cmdLine.findOption(ii, 'i');
  1951. }
  1952. std::string dir;
  1953. {
  1954. const char* base = baseName(filePath);
  1955. if (base != filePath)
  1956. {
  1957. dir.assign(filePath, base-filePath);
  1958. options.includeDirs.push_back(dir.c_str());
  1959. }
  1960. }
  1961. const char* defines = cmdLine.findOption("define");
  1962. while (NULL != defines
  1963. && '\0' != *defines)
  1964. {
  1965. defines = bx::strws(defines);
  1966. const char* eol = bx::strFind(defines, ';');
  1967. if (NULL == eol)
  1968. {
  1969. eol = defines + bx::strLen(defines);
  1970. }
  1971. std::string define(defines, eol);
  1972. options.defines.push_back(define.c_str() );
  1973. defines = ';' == *eol ? eol+1 : eol;
  1974. }
  1975. bool compiled = false;
  1976. bx::FileReader reader;
  1977. if (!bx::open(&reader, filePath) )
  1978. {
  1979. fprintf(stderr, "Unable to open file '%s'.\n", filePath);
  1980. }
  1981. else
  1982. {
  1983. std::string defaultVarying = dir + "varying.def.sc";
  1984. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  1985. File attribdef(varyingdef);
  1986. const char* parse = attribdef.getData();
  1987. if (NULL != parse
  1988. && *parse != '\0')
  1989. {
  1990. options.dependencies.push_back(varyingdef);
  1991. }
  1992. else
  1993. {
  1994. fprintf(stderr, "ERROR: Failed to parse varying def file: \"%s\" No input/output semantics will be generated in the code!\n", varyingdef);
  1995. }
  1996. const size_t padding = 4096;
  1997. uint32_t size = (uint32_t)bx::getSize(&reader);
  1998. char* data = new char[size+padding+1];
  1999. size = (uint32_t)bx::read(&reader, data, size);
  2000. if (data[0] == '\xef'
  2001. && data[1] == '\xbb'
  2002. && data[2] == '\xbf')
  2003. {
  2004. bx::memMove(data, &data[3], size-3);
  2005. size -= 3;
  2006. }
  2007. // Compiler generates "error X3000: syntax error: unexpected end of file"
  2008. // if input doesn't have empty line at EOF.
  2009. data[size] = '\n';
  2010. bx::memSet(&data[size+1], 0, padding);
  2011. bx::close(&reader);
  2012. bx::FileWriter* writer = NULL;
  2013. if (NULL != bin2c)
  2014. {
  2015. writer = new Bin2cWriter(bin2c);
  2016. }
  2017. else
  2018. {
  2019. writer = new bx::FileWriter;
  2020. }
  2021. if (!bx::open(writer, outFilePath) )
  2022. {
  2023. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2024. return bx::kExitFailure;
  2025. }
  2026. if ( compileShader(attribdef.getData(), data, size, options, writer) )
  2027. compiled = true;
  2028. bx::close(writer);
  2029. delete writer;
  2030. }
  2031. if (compiled)
  2032. {
  2033. return bx::kExitSuccess;
  2034. }
  2035. remove(outFilePath);
  2036. fprintf(stderr, "Failed to build shader.\n");
  2037. return bx::kExitFailure;
  2038. }
  2039. } // namespace bgfx
  2040. int main(int _argc, const char* _argv[])
  2041. {
  2042. return bgfx::compileShader(_argc, _argv);
  2043. }