shaderc.cpp 70 KB

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