shaderc.cpp 59 KB

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