shaderc.cpp 63 KB

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