shaderc.cpp 73 KB

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