shaderc.cpp 77 KB

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