shaderc.cpp 62 KB

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