shaderc.cpp 63 KB

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