shaderc.cpp 63 KB

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