shaderc.cpp 72 KB

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