2
0

shaderc.cpp 80 KB

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