shaderc.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567
  1. /*
  2. * Copyright 2011-2019 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. "texture2DArray",
  113. "texture2DArrayLod",
  114. "shadow2DArray",
  115. NULL
  116. };
  117. static const char* s_ARB_texture_multisample[] =
  118. {
  119. "sampler2DMS",
  120. "isampler2DMS",
  121. "usampler2DMS",
  122. NULL
  123. };
  124. static const char* s_texelFetch[] =
  125. {
  126. "texelFetch",
  127. "texelFetchOffset",
  128. NULL
  129. };
  130. const char* s_uniformTypeName[] =
  131. {
  132. "int", "int",
  133. NULL, NULL,
  134. "vec4", "float4",
  135. "mat3", "float3x3",
  136. "mat4", "float4x4",
  137. };
  138. BX_STATIC_ASSERT(BX_COUNTOF(s_uniformTypeName) == UniformType::Count*2);
  139. static const char* s_allowedVertexShaderInputs[] =
  140. {
  141. "a_position",
  142. "a_normal",
  143. "a_tangent",
  144. "a_bitangent",
  145. "a_color0",
  146. "a_color1",
  147. "a_color2",
  148. "a_color3",
  149. "a_indices",
  150. "a_weight",
  151. "a_texcoord0",
  152. "a_texcoord1",
  153. "a_texcoord2",
  154. "a_texcoord3",
  155. "a_texcoord4",
  156. "a_texcoord5",
  157. "a_texcoord6",
  158. "a_texcoord7",
  159. "i_data0",
  160. "i_data1",
  161. "i_data2",
  162. "i_data3",
  163. "i_data4",
  164. NULL
  165. };
  166. Options::Options()
  167. : shaderType(' ')
  168. , disasm(false)
  169. , raw(false)
  170. , preprocessOnly(false)
  171. , depends(false)
  172. , debugInformation(false)
  173. , avoidFlowControl(false)
  174. , noPreshader(false)
  175. , partialPrecision(false)
  176. , preferFlowControl(false)
  177. , backwardsCompatibility(false)
  178. , warningsAreErrors(false)
  179. , keepIntermediate(false)
  180. , optimize(false)
  181. , optimizationLevel(3)
  182. {
  183. }
  184. void Options::dump()
  185. {
  186. BX_TRACE("Options:\n"
  187. "\t shaderType: %c\n"
  188. "\t platform: %s\n"
  189. "\t profile: %s\n"
  190. "\t inputFile: %s\n"
  191. "\t outputFile: %s\n"
  192. "\t disasm: %s\n"
  193. "\t raw: %s\n"
  194. "\t preprocessOnly: %s\n"
  195. "\t depends: %s\n"
  196. "\t debugInformation: %s\n"
  197. "\t avoidFlowControl: %s\n"
  198. "\t noPreshader: %s\n"
  199. "\t partialPrecision: %s\n"
  200. "\t preferFlowControl: %s\n"
  201. "\t backwardsCompatibility: %s\n"
  202. "\t warningsAreErrors: %s\n"
  203. "\t keepIntermediate: %s\n"
  204. "\t optimize: %s\n"
  205. "\t optimizationLevel: %d\n"
  206. , shaderType
  207. , platform.c_str()
  208. , profile.c_str()
  209. , inputFilePath.c_str()
  210. , outputFilePath.c_str()
  211. , disasm ? "true" : "false"
  212. , raw ? "true" : "false"
  213. , preprocessOnly ? "true" : "false"
  214. , depends ? "true" : "false"
  215. , debugInformation ? "true" : "false"
  216. , avoidFlowControl ? "true" : "false"
  217. , noPreshader ? "true" : "false"
  218. , partialPrecision ? "true" : "false"
  219. , preferFlowControl ? "true" : "false"
  220. , backwardsCompatibility ? "true" : "false"
  221. , warningsAreErrors ? "true" : "false"
  222. , keepIntermediate ? "true" : "false"
  223. , optimize ? "true" : "false"
  224. , optimizationLevel
  225. );
  226. for (size_t ii = 0; ii < includeDirs.size(); ++ii)
  227. {
  228. BX_TRACE("\t include :%s\n", includeDirs[ii].c_str());
  229. }
  230. for (size_t ii = 0; ii < defines.size(); ++ii)
  231. {
  232. BX_TRACE("\t define :%s\n", defines[ii].c_str());
  233. }
  234. for (size_t ii = 0; ii < dependencies.size(); ++ii)
  235. {
  236. BX_TRACE("\t dependency :%s\n", dependencies[ii].c_str());
  237. }
  238. }
  239. const char* interpolationDx11(const char* _glsl)
  240. {
  241. if (0 == bx::strCmp(_glsl, "smooth") )
  242. {
  243. return "linear";
  244. }
  245. else if (0 == bx::strCmp(_glsl, "flat") )
  246. {
  247. return "nointerpolation";
  248. }
  249. return _glsl; // centroid, noperspective
  250. }
  251. const char* getUniformTypeName(UniformType::Enum _enum)
  252. {
  253. uint32_t idx = _enum & ~(BGFX_UNIFORM_FRAGMENTBIT|BGFX_UNIFORM_SAMPLERBIT);
  254. if (idx < UniformType::Count)
  255. {
  256. return s_uniformTypeName[idx];
  257. }
  258. return "Unknown uniform type?!";
  259. }
  260. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  261. {
  262. for (uint32_t ii = 0; ii < UniformType::Count*2; ++ii)
  263. {
  264. if (NULL != s_uniformTypeName[ii]
  265. && 0 == bx::strCmp(_name, s_uniformTypeName[ii]) )
  266. {
  267. return UniformType::Enum(ii/2);
  268. }
  269. }
  270. return UniformType::Count;
  271. }
  272. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  273. {
  274. va_list argList;
  275. va_start(argList, _format);
  276. char temp[2048];
  277. char* out = temp;
  278. int32_t max = sizeof(temp);
  279. int32_t len = bx::vsnprintf(out, max, _format, argList);
  280. if (len > max)
  281. {
  282. out = (char*)alloca(len);
  283. len = bx::vsnprintf(out, len, _format, argList);
  284. }
  285. len = bx::write(_writer, out, len);
  286. va_end(argList);
  287. return len;
  288. }
  289. class Bin2cWriter : public bx::FileWriter
  290. {
  291. public:
  292. Bin2cWriter(const bx::StringView& _name)
  293. : m_name(_name)
  294. {
  295. }
  296. virtual ~Bin2cWriter()
  297. {
  298. }
  299. virtual void close() override
  300. {
  301. generate();
  302. return bx::FileWriter::close();
  303. }
  304. virtual int32_t write(const void* _data, int32_t _size, bx::Error*) override
  305. {
  306. const char* data = (const char*)_data;
  307. m_buffer.insert(m_buffer.end(), data, data+_size);
  308. return _size;
  309. }
  310. private:
  311. void generate()
  312. {
  313. #define HEX_DUMP_WIDTH 16
  314. #define HEX_DUMP_SPACE_WIDTH 96
  315. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  316. const uint8_t* data = &m_buffer[0];
  317. uint32_t size = (uint32_t)m_buffer.size();
  318. outf("static const uint8_t %.*s[%d] =\n{\n", m_name.getLength(), m_name.getPtr(), size);
  319. if (NULL != data)
  320. {
  321. char hex[HEX_DUMP_SPACE_WIDTH+1];
  322. char ascii[HEX_DUMP_WIDTH+1];
  323. uint32_t hexPos = 0;
  324. uint32_t asciiPos = 0;
  325. for (uint32_t ii = 0; ii < size; ++ii)
  326. {
  327. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  328. hexPos += 6;
  329. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' && data[asciiPos] != '\t' ? data[asciiPos] : '.';
  330. asciiPos++;
  331. if (HEX_DUMP_WIDTH == asciiPos)
  332. {
  333. ascii[asciiPos] = '\0';
  334. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  335. data += asciiPos;
  336. hexPos = 0;
  337. asciiPos = 0;
  338. }
  339. }
  340. if (0 != asciiPos)
  341. {
  342. ascii[asciiPos] = '\0';
  343. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  344. }
  345. }
  346. outf("};\n");
  347. #undef HEX_DUMP_WIDTH
  348. #undef HEX_DUMP_SPACE_WIDTH
  349. #undef HEX_DUMP_FORMAT
  350. }
  351. int32_t outf(const char* _format, ...)
  352. {
  353. va_list argList;
  354. va_start(argList, _format);
  355. char temp[2048];
  356. char* out = temp;
  357. int32_t max = sizeof(temp);
  358. int32_t len = bx::vsnprintf(out, max, _format, argList);
  359. if (len > max)
  360. {
  361. out = (char*)alloca(len);
  362. len = bx::vsnprintf(out, len, _format, argList);
  363. }
  364. bx::Error err;
  365. int32_t size = bx::FileWriter::write(out, len, &err);
  366. va_end(argList);
  367. return size;
  368. }
  369. std::string m_filePath;
  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. fprintf(stderr, "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. std::string strLine(str, len);
  471. if (_line == line)
  472. {
  473. fprintf(stderr, "\n");
  474. fprintf(stderr, ">>> %3d: %s", line, strLine.c_str() );
  475. if (-1 != _column)
  476. {
  477. fprintf(stderr, ">>> %3d: %*s\n", _column, _column, "^");
  478. }
  479. fprintf(stderr, "\n");
  480. }
  481. else
  482. {
  483. fprintf(stderr, " %3d: %s", line, strLine.c_str() );
  484. }
  485. }
  486. }
  487. fprintf(stderr, "---\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. vfprintf(stderr, _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. fprintf(stderr, "Error:\n%s\n\n", _error);
  737. }
  738. fprintf(stderr
  739. , "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  740. "Copyright 2011-2019 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. fprintf(stderr
  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. fprintf(stderr, "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. fprintf(stderr
  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. fprintf(stderr, "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. fprintf(stderr, "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("attribute %s %s %s %s;\n"
  1345. , var.m_precision.c_str()
  1346. , var.m_interpolation.c_str()
  1347. , var.m_type.c_str()
  1348. , name
  1349. );
  1350. }
  1351. else
  1352. {
  1353. preprocessor.writef("%s varying %s %s %s;\n"
  1354. , var.m_interpolation.c_str()
  1355. , var.m_precision.c_str()
  1356. , var.m_type.c_str()
  1357. , name
  1358. );
  1359. }
  1360. }
  1361. }
  1362. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1363. {
  1364. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1365. if (varyingIt != varyingMap.end() )
  1366. {
  1367. const Varying& var = varyingIt->second;
  1368. preprocessor.writef("%s varying %s %s;\n"
  1369. , var.m_interpolation.c_str()
  1370. , var.m_type.c_str()
  1371. , var.m_name.c_str()
  1372. );
  1373. }
  1374. }
  1375. }
  1376. else
  1377. {
  1378. if (0 != pssl)
  1379. {
  1380. preprocessor.writef(getPsslPreamble() );
  1381. }
  1382. preprocessor.writef(
  1383. "#define lowp\n"
  1384. "#define mediump\n"
  1385. "#define highp\n"
  1386. "#define ivec2 int2\n"
  1387. "#define ivec3 int3\n"
  1388. "#define ivec4 int4\n"
  1389. "#define uvec2 uint2\n"
  1390. "#define uvec3 uint3\n"
  1391. "#define uvec4 uint4\n"
  1392. "#define vec2 float2\n"
  1393. "#define vec3 float3\n"
  1394. "#define vec4 float4\n"
  1395. "#define mat2 float2x2\n"
  1396. "#define mat3 float3x3\n"
  1397. "#define mat4 float4x4\n"
  1398. );
  1399. if (hlsl != 0
  1400. && hlsl < 4)
  1401. {
  1402. preprocessor.writef(
  1403. "#define centroid\n"
  1404. "#define flat\n"
  1405. "#define noperspective\n"
  1406. "#define smooth\n"
  1407. );
  1408. }
  1409. *const_cast<char*>(entry.getPtr() + 4) = '_';
  1410. if ('f' == _options.shaderType)
  1411. {
  1412. bx::StringView insert = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1413. if (!insert.isEmpty() )
  1414. {
  1415. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\nvec4 bgfx_VoidFrag = vec4_splat(0.0);\n");
  1416. }
  1417. const bool hasFragColor = !bx::strFind(input, "gl_FragColor").isEmpty();
  1418. const bool hasFragCoord = !bx::strFind(input, "gl_FragCoord").isEmpty() || hlsl > 3 || hlsl == 2;
  1419. const bool hasFragDepth = !bx::strFind(input, "gl_FragDepth").isEmpty();
  1420. const bool hasFrontFacing = !bx::strFind(input, "gl_FrontFacing").isEmpty();
  1421. const bool hasPrimitiveId = !bx::strFind(input, "gl_PrimitiveID").isEmpty();
  1422. bool hasFragData[8] = {};
  1423. uint32_t numFragData = 0;
  1424. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1425. {
  1426. char temp[32];
  1427. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  1428. hasFragData[ii] = !bx::strFind(input, temp).isEmpty();
  1429. numFragData += hasFragData[ii];
  1430. }
  1431. if (0 == numFragData)
  1432. {
  1433. // GL errors when both gl_FragColor and gl_FragData is used.
  1434. // This will trigger the same error with HLSL compiler too.
  1435. preprocessor.writef("#define gl_FragColor bgfx_FragData0\n");
  1436. // If it has gl_FragData or gl_FragColor, color target at
  1437. // index 0 exists, otherwise shader is not modifying color
  1438. // targets.
  1439. hasFragData[0] |= hasFragColor || d3d < 11;
  1440. if (!insert.isEmpty()
  1441. && d3d < 11
  1442. && !hasFragColor)
  1443. {
  1444. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\ngl_FragColor = bgfx_VoidFrag;\n");
  1445. }
  1446. }
  1447. preprocessor.writef("#define void_main()");
  1448. preprocessor.writef(" \\\n\tvoid main(");
  1449. uint32_t arg = 0;
  1450. if (hasFragCoord)
  1451. {
  1452. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1453. ++arg;
  1454. }
  1455. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1456. {
  1457. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1458. if (varyingIt != varyingMap.end() )
  1459. {
  1460. const Varying& var = varyingIt->second;
  1461. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  1462. , arg++ > 0 ? ", " : " "
  1463. , interpolationDx11(var.m_interpolation.c_str() )
  1464. , var.m_type.c_str()
  1465. , var.m_name.c_str()
  1466. , var.m_semantics.c_str()
  1467. );
  1468. }
  1469. }
  1470. const uint32_t maxRT = d3d > 9 ? BX_COUNTOF(hasFragData) : 4;
  1471. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1472. {
  1473. if (ii < maxRT)
  1474. {
  1475. if (hasFragData[ii])
  1476. {
  1477. addFragData(preprocessor, input, ii, arg++ > 0);
  1478. }
  1479. }
  1480. else
  1481. {
  1482. voidFragData(input, ii);
  1483. }
  1484. }
  1485. if (hasFragDepth)
  1486. {
  1487. preprocessor.writef(
  1488. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1489. , arg++ > 0 ? ", " : " "
  1490. );
  1491. }
  1492. if (hasFrontFacing)
  1493. {
  1494. if (hlsl == 3)
  1495. {
  1496. preprocessor.writef(
  1497. " \\\n\t%sfloat __vface : VFACE"
  1498. , arg++ > 0 ? ", " : " "
  1499. );
  1500. }
  1501. else
  1502. {
  1503. preprocessor.writef(
  1504. " \\\n\t%sbool gl_FrontFacing : SV_IsFrontFace"
  1505. , arg++ > 0 ? ", " : " "
  1506. );
  1507. }
  1508. }
  1509. if (hasPrimitiveId)
  1510. {
  1511. if (hlsl > 3)
  1512. {
  1513. preprocessor.writef(
  1514. " \\\n\t%suint gl_PrimitiveID : SV_PrimitiveID"
  1515. , arg++ > 0 ? ", " : " "
  1516. );
  1517. }
  1518. else
  1519. {
  1520. fprintf(stderr, "gl_PrimitiveID builtin is not supported by this D3D9 HLSL.\n");
  1521. return false;
  1522. }
  1523. }
  1524. preprocessor.writef(
  1525. " \\\n\t)\n"
  1526. );
  1527. if (hasFrontFacing)
  1528. {
  1529. if (hlsl == 3)
  1530. {
  1531. preprocessor.writef(
  1532. "#define gl_FrontFacing (__vface >= 0.0)\n"
  1533. );
  1534. }
  1535. }
  1536. }
  1537. else if ('v' == _options.shaderType)
  1538. {
  1539. const bool hasVertexId = !bx::strFind(input, "gl_VertexID").isEmpty();
  1540. const bool hasInstanceId = !bx::strFind(input, "gl_InstanceID").isEmpty();
  1541. bx::StringView brace = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1542. if (!brace.isEmpty() )
  1543. {
  1544. bx::StringView block = bx::strFindBlock(bx::StringView(brace.getPtr(), shader.getTerm() ), '{', '}');
  1545. if (!block.isEmpty() )
  1546. {
  1547. strInsert(const_cast<char*>(block.getTerm()-1), "__RETURN__;\n");
  1548. }
  1549. }
  1550. preprocessor.writef(
  1551. "struct Output\n"
  1552. "{\n"
  1553. "\tvec4 gl_Position : SV_POSITION;\n"
  1554. "#define gl_Position _varying_.gl_Position\n"
  1555. );
  1556. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1557. {
  1558. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1559. if (varyingIt != varyingMap.end() )
  1560. {
  1561. const Varying& var = varyingIt->second;
  1562. preprocessor.writef(
  1563. "\t%s %s %s : %s;\n"
  1564. , interpolationDx11(var.m_interpolation.c_str() )
  1565. , var.m_type.c_str()
  1566. , var.m_name.c_str()
  1567. , var.m_semantics.c_str()
  1568. );
  1569. preprocessor.writef(
  1570. "#define %s _varying_.%s\n"
  1571. , var.m_name.c_str()
  1572. , var.m_name.c_str()
  1573. );
  1574. }
  1575. }
  1576. preprocessor.writef(
  1577. "};\n"
  1578. );
  1579. preprocessor.writef("#define void_main() \\\n");
  1580. preprocessor.writef("Output main(");
  1581. uint32_t arg = 0;
  1582. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1583. {
  1584. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1585. if (varyingIt != varyingMap.end() )
  1586. {
  1587. const Varying& var = varyingIt->second;
  1588. preprocessor.writef(
  1589. " \\\n\t%s%s %s : %s"
  1590. , arg++ > 0 ? ", " : ""
  1591. , var.m_type.c_str()
  1592. , var.m_name.c_str()
  1593. , var.m_semantics.c_str()
  1594. );
  1595. }
  1596. }
  1597. if (hasVertexId)
  1598. {
  1599. if (d3d > 9)
  1600. {
  1601. preprocessor.writef(
  1602. " \\\n\t%suint gl_VertexID : SV_VertexID"
  1603. , arg++ > 0 ? ", " : " "
  1604. );
  1605. }
  1606. else
  1607. {
  1608. fprintf(stderr, "gl_VertexID builtin is not supported by this D3D9 HLSL.\n");
  1609. return false;
  1610. }
  1611. }
  1612. if (hasInstanceId)
  1613. {
  1614. if (d3d > 9)
  1615. {
  1616. preprocessor.writef(
  1617. " \\\n\t%suint gl_InstanceID : SV_InstanceID"
  1618. , arg++ > 0 ? ", " : " "
  1619. );
  1620. }
  1621. else
  1622. {
  1623. fprintf(stderr, "gl_InstanceID builtin is not supported by this D3D9 HLSL.\n");
  1624. return false;
  1625. }
  1626. }
  1627. preprocessor.writef(
  1628. ") \\\n"
  1629. "{ \\\n"
  1630. "\tOutput _varying_;"
  1631. );
  1632. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1633. {
  1634. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1635. if (varyingIt != varyingMap.end() )
  1636. {
  1637. const Varying& var = varyingIt->second;
  1638. preprocessor.writef(" \\\n\t%s", var.m_name.c_str() );
  1639. if (!var.m_init.empty() )
  1640. {
  1641. preprocessor.writef(" = %s", var.m_init.c_str() );
  1642. }
  1643. preprocessor.writef(";");
  1644. }
  1645. }
  1646. preprocessor.writef(
  1647. "\n#define __RETURN__ \\\n"
  1648. "\t} \\\n"
  1649. );
  1650. if (hlsl != 0
  1651. && hlsl <= 3)
  1652. {
  1653. // preprocessor.writef(
  1654. // "\tgl_Position.xy += u_viewTexel.xy * gl_Position.w; \\\n"
  1655. // );
  1656. }
  1657. if (0 != spirv)
  1658. {
  1659. preprocessor.writef(
  1660. "\tgl_Position.y = -gl_Position.y; \\\n"
  1661. );
  1662. }
  1663. preprocessor.writef(
  1664. "\treturn _varying_"
  1665. );
  1666. }
  1667. }
  1668. if (preprocessor.run(input) )
  1669. {
  1670. //BX_TRACE("Input file: %s", filePath);
  1671. //BX_TRACE("Output file: %s", outFilePath);
  1672. if (_options.preprocessOnly)
  1673. {
  1674. if (0 != glsl)
  1675. {
  1676. if (essl != 0)
  1677. {
  1678. writef(_writer
  1679. , "#ifdef GL_ES\n"
  1680. "precision highp float;\n"
  1681. "#endif // GL_ES\n\n"
  1682. );
  1683. }
  1684. }
  1685. bx::write(_writer, preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1686. return true;
  1687. }
  1688. {
  1689. std::string code;
  1690. if ('f' == _options.shaderType)
  1691. {
  1692. bx::write(_writer, BGFX_CHUNK_MAGIC_FSH);
  1693. bx::write(_writer, inputHash);
  1694. bx::write(_writer, uint32_t(0) );
  1695. }
  1696. else if ('v' == _options.shaderType)
  1697. {
  1698. bx::write(_writer, BGFX_CHUNK_MAGIC_VSH);
  1699. bx::write(_writer, uint32_t(0) );
  1700. bx::write(_writer, outputHash);
  1701. }
  1702. else
  1703. {
  1704. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1705. bx::write(_writer, uint32_t(0) );
  1706. bx::write(_writer, outputHash);
  1707. }
  1708. if (0 != glsl
  1709. || 0 != essl)
  1710. {
  1711. const bx::StringView preprocessedInput(preprocessor.m_preprocessed.c_str() );
  1712. if (!bx::strFind(preprocessedInput, "layout(std430").isEmpty()
  1713. || !bx::strFind(preprocessedInput, "image2D").isEmpty() )
  1714. {
  1715. glsl = 430;
  1716. }
  1717. if (glsl < 400)
  1718. {
  1719. const bool usesTextureLod = false
  1720. || !bx::findIdentifierMatch(input, s_ARB_shader_texture_lod).isEmpty()
  1721. || !bx::findIdentifierMatch(input, s_EXT_shader_texture_lod).isEmpty()
  1722. ;
  1723. const bool usesInstanceID = !bx::findIdentifierMatch(input, "gl_InstanceID").isEmpty();
  1724. const bool usesGpuShader4 = !bx::findIdentifierMatch(input, s_EXT_gpu_shader4).isEmpty();
  1725. const bool usesGpuShader5 = !bx::findIdentifierMatch(input, s_ARB_gpu_shader5).isEmpty();
  1726. const bool usesTexelFetch = !bx::findIdentifierMatch(input, s_texelFetch).isEmpty();
  1727. const bool usesTextureMS = !bx::findIdentifierMatch(input, s_ARB_texture_multisample).isEmpty();
  1728. const bool usesTextureArray = !bx::findIdentifierMatch(input, s_textureArray).isEmpty();
  1729. const bool usesPacking = !bx::findIdentifierMatch(input, s_ARB_shading_language_packing).isEmpty();
  1730. if (0 == essl)
  1731. {
  1732. const bool need130 = (120 == glsl && (false
  1733. || !bx::findIdentifierMatch(input, s_130).isEmpty()
  1734. || usesInterpolationQualifiers
  1735. || usesTexelFetch
  1736. ) );
  1737. bx::stringPrintf(code, "#version %s\n", need130 ? "130" : _options.profile.c_str());
  1738. glsl = 130;
  1739. if (need130)
  1740. {
  1741. bx::stringPrintf(code, "#define varying %s\n"
  1742. , 'f' == _options.shaderType ? "in" : "out"
  1743. );
  1744. }
  1745. if (usesInstanceID)
  1746. {
  1747. bx::stringPrintf(code
  1748. , "#extension GL_ARB_draw_instanced : enable\n"
  1749. );
  1750. }
  1751. if (usesGpuShader4)
  1752. {
  1753. bx::stringPrintf(code
  1754. , "#extension GL_EXT_gpu_shader4 : enable\n"
  1755. );
  1756. }
  1757. if (usesGpuShader5)
  1758. {
  1759. bx::stringPrintf(code
  1760. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1761. );
  1762. }
  1763. if (usesPacking)
  1764. {
  1765. bx::stringPrintf(code
  1766. , "#extension GL_ARB_shading_language_packing : enable\n"
  1767. );
  1768. }
  1769. bool ARB_shader_texture_lod = false;
  1770. bool EXT_shader_texture_lod = false;
  1771. if (usesTextureLod)
  1772. {
  1773. if ('f' == _options.shaderType)
  1774. {
  1775. ARB_shader_texture_lod = true;
  1776. bx::stringPrintf(code
  1777. , "#extension GL_ARB_shader_texture_lod : enable\n"
  1778. );
  1779. }
  1780. else
  1781. {
  1782. EXT_shader_texture_lod = true;
  1783. bx::stringPrintf(code
  1784. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1785. );
  1786. }
  1787. }
  1788. if (usesTextureMS)
  1789. {
  1790. bx::stringPrintf(code
  1791. , "#extension GL_ARB_texture_multisample : enable\n"
  1792. );
  1793. }
  1794. if (usesTextureArray)
  1795. {
  1796. bx::stringPrintf(code
  1797. , "#extension GL_EXT_texture_array : enable\n"
  1798. );
  1799. }
  1800. if (130 > glsl)
  1801. {
  1802. bx::stringPrintf(code,
  1803. "#define ivec2 vec2\n"
  1804. "#define ivec3 vec3\n"
  1805. "#define ivec4 vec4\n"
  1806. );
  1807. }
  1808. if (ARB_shader_texture_lod)
  1809. {
  1810. bx::stringPrintf(code,
  1811. "#define texture2DProjLod texture2DProjLodARB\n"
  1812. "#define texture2DGrad texture2DGradARB\n"
  1813. "#define texture2DProjGrad texture2DProjGradARB\n"
  1814. "#define textureCubeGrad textureCubeGradARB\n"
  1815. );
  1816. }
  1817. else if (EXT_shader_texture_lod)
  1818. {
  1819. bx::stringPrintf(code,
  1820. "#define texture2DProjLod texture2DProjLodEXT\n"
  1821. "#define texture2DGrad texture2DGradEXT\n"
  1822. "#define texture2DProjGrad texture2DProjGradEXT\n"
  1823. "#define textureCubeGrad textureCubeGradEXT\n"
  1824. );
  1825. }
  1826. if (need130)
  1827. {
  1828. bx::stringPrintf(code
  1829. , "#define bgfxShadow2D(_sampler, _coord) vec4_splat(texture(_sampler, _coord))\n"
  1830. "#define bgfxShadow2DProj(_sampler, _coord) vec4_splat(textureProj(_sampler, _coord))\n"
  1831. );
  1832. }
  1833. else
  1834. {
  1835. bx::stringPrintf(code
  1836. , "#define bgfxShadow2D shadow2D\n"
  1837. "#define bgfxShadow2DProj shadow2DProj\n"
  1838. );
  1839. }
  1840. }
  1841. else
  1842. {
  1843. if (usesInterpolationQualifiers)
  1844. {
  1845. bx::stringPrintf(code, "#version 300 es\n");
  1846. bx::stringPrintf(code, "#define attribute in\n");
  1847. bx::stringPrintf(code, "#define varying %s\n"
  1848. , 'f' == _options.shaderType ? "in" : "out"
  1849. );
  1850. }
  1851. else if (essl == 2)
  1852. {
  1853. code +=
  1854. "mat2 transpose(mat2 _mtx)\n"
  1855. "{\n"
  1856. " vec2 v0 = _mtx[0];\n"
  1857. " vec2 v1 = _mtx[1];\n"
  1858. "\n"
  1859. " return mat2(\n"
  1860. " vec2(v0.x, v1.x)\n"
  1861. " , vec2(v0.y, v1.y)\n"
  1862. " );\n"
  1863. "}\n"
  1864. "\n"
  1865. "mat3 transpose(mat3 _mtx)\n"
  1866. "{\n"
  1867. " vec3 v0 = _mtx[0];\n"
  1868. " vec3 v1 = _mtx[1];\n"
  1869. " vec3 v2 = _mtx[2];\n"
  1870. "\n"
  1871. " return mat3(\n"
  1872. " vec3(v0.x, v1.x, v2.x)\n"
  1873. " , vec3(v0.y, v1.y, v2.y)\n"
  1874. " , vec3(v0.z, v1.z, v2.z)\n"
  1875. " );\n"
  1876. "}\n"
  1877. "\n"
  1878. "mat4 transpose(mat4 _mtx)\n"
  1879. "{\n"
  1880. " vec4 v0 = _mtx[0];\n"
  1881. " vec4 v1 = _mtx[1];\n"
  1882. " vec4 v2 = _mtx[2];\n"
  1883. " vec4 v3 = _mtx[3];\n"
  1884. "\n"
  1885. " return mat4(\n"
  1886. " vec4(v0.x, v1.x, v2.x, v3.x)\n"
  1887. " , vec4(v0.y, v1.y, v2.y, v3.y)\n"
  1888. " , vec4(v0.z, v1.z, v2.z, v3.z)\n"
  1889. " , vec4(v0.w, v1.w, v2.w, v3.w)\n"
  1890. " );\n"
  1891. "}\n"
  1892. ;
  1893. }
  1894. // Pretend that all extensions are available.
  1895. // This will be stripped later.
  1896. if (usesTextureLod)
  1897. {
  1898. bx::stringPrintf(code
  1899. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1900. "#define texture2DLod texture2DLodEXT\n"
  1901. "#define texture2DGrad texture2DGradEXT\n"
  1902. "#define texture2DProjLod texture2DProjLodEXT\n"
  1903. "#define texture2DProjGrad texture2DProjGradEXT\n"
  1904. "#define textureCubeLod textureCubeLodEXT\n"
  1905. "#define textureCubeGrad textureCubeGradEXT\n"
  1906. );
  1907. }
  1908. if (!bx::findIdentifierMatch(input, s_OES_standard_derivatives).isEmpty() )
  1909. {
  1910. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  1911. }
  1912. if (!bx::findIdentifierMatch(input, s_OES_texture_3D).isEmpty() )
  1913. {
  1914. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  1915. }
  1916. if (!bx::findIdentifierMatch(input, s_EXT_shadow_samplers).isEmpty() )
  1917. {
  1918. bx::stringPrintf(code
  1919. , "#extension GL_EXT_shadow_samplers : enable\n"
  1920. "#define shadow2D shadow2DEXT\n"
  1921. "#define shadow2DProj shadow2DProjEXT\n"
  1922. );
  1923. }
  1924. if (usesGpuShader5)
  1925. {
  1926. bx::stringPrintf(code
  1927. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1928. );
  1929. }
  1930. if (usesPacking)
  1931. {
  1932. bx::stringPrintf(code
  1933. , "#extension GL_ARB_shading_language_packing : enable\n"
  1934. );
  1935. }
  1936. if (!bx::findIdentifierMatch(input, "gl_FragDepth").isEmpty() )
  1937. {
  1938. bx::stringPrintf(code
  1939. , "#extension GL_EXT_frag_depth : enable\n"
  1940. "#define gl_FragDepth gl_FragDepthEXT\n"
  1941. );
  1942. }
  1943. if (usesTextureArray)
  1944. {
  1945. bx::stringPrintf(code
  1946. , "#extension GL_EXT_texture_array : enable\n"
  1947. );
  1948. }
  1949. bx::stringPrintf(code
  1950. , "#define ivec2 vec2\n"
  1951. "#define ivec3 vec3\n"
  1952. "#define ivec4 vec4\n"
  1953. "#define uvec2 vec2\n"
  1954. "#define uvec3 vec3\n"
  1955. "#define uvec4 vec4\n"
  1956. );
  1957. }
  1958. }
  1959. else
  1960. {
  1961. bx::stringPrintf(code, "#version %d\n", glsl);
  1962. bx::stringPrintf(code
  1963. , "#define texture2DLod textureLod\n"
  1964. "#define texture2DGrad textureGrad\n"
  1965. "#define texture2DProjLod textureProjLod\n"
  1966. "#define texture2DProjGrad textureProjGrad\n"
  1967. "#define textureCubeLod textureLod\n"
  1968. "#define textureCubeGrad textureGrad\n"
  1969. "#define texture3D texture\n"
  1970. );
  1971. bx::stringPrintf(code, "#define attribute in\n");
  1972. bx::stringPrintf(code, "#define varying %s\n"
  1973. , 'f' == _options.shaderType ? "in" : "out"
  1974. );
  1975. bx::stringPrintf(code
  1976. , "#define bgfxShadow2D(_sampler, _coord) vec4_splat(texture(_sampler, _coord))\n"
  1977. "#define bgfxShadow2DProj(_sampler, _coord) vec4_splat(textureProj(_sampler, _coord))\n"
  1978. );
  1979. }
  1980. if (glsl > 400)
  1981. {
  1982. code += preprocessor.m_preprocessed;
  1983. bx::write(_writer, uint16_t(0) );
  1984. uint32_t shaderSize = (uint32_t)code.size();
  1985. bx::write(_writer, shaderSize);
  1986. bx::write(_writer, code.c_str(), shaderSize);
  1987. bx::write(_writer, uint8_t(0) );
  1988. compiled = true;
  1989. }
  1990. else
  1991. {
  1992. code += _comment;
  1993. code += preprocessor.m_preprocessed;
  1994. compiled = compileGLSLShader(_options, metal ? BX_MAKEFOURCC('M', 'T', 'L', 0) : essl, code, _writer);
  1995. }
  1996. }
  1997. else
  1998. {
  1999. code += _comment;
  2000. code += preprocessor.m_preprocessed;
  2001. if (0 != spirv || 0 != metal)
  2002. {
  2003. compiled = compileSPIRVShader(_options, metal ? BX_MAKEFOURCC('M', 'T', 'L', 0) : 0, code, _writer);
  2004. }
  2005. else if (0 != pssl)
  2006. {
  2007. compiled = compilePSSLShader(_options, 0, code, _writer);
  2008. }
  2009. else
  2010. {
  2011. compiled = compileHLSLShader(_options, d3d, code, _writer);
  2012. }
  2013. }
  2014. }
  2015. if (compiled)
  2016. {
  2017. if (_options.depends)
  2018. {
  2019. std::string ofp = _options.outputFilePath + ".d";
  2020. bx::FileWriter writer;
  2021. if (bx::open(&writer, ofp.c_str() ) )
  2022. {
  2023. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  2024. bx::close(&writer);
  2025. }
  2026. }
  2027. }
  2028. }
  2029. }
  2030. }
  2031. delete [] data;
  2032. return compiled;
  2033. }
  2034. int compileShader(int _argc, const char* _argv[])
  2035. {
  2036. bx::CommandLine cmdLine(_argc, _argv);
  2037. if (cmdLine.hasArg('v', "version") )
  2038. {
  2039. fprintf(stderr
  2040. , "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  2041. , BGFX_SHADERC_VERSION_MAJOR
  2042. , BGFX_SHADERC_VERSION_MINOR
  2043. , BGFX_API_VERSION
  2044. );
  2045. return bx::kExitSuccess;
  2046. }
  2047. if (cmdLine.hasArg('h', "help") )
  2048. {
  2049. help();
  2050. return bx::kExitFailure;
  2051. }
  2052. g_verbose = cmdLine.hasArg("verbose");
  2053. const char* filePath = cmdLine.findOption('f');
  2054. if (NULL == filePath)
  2055. {
  2056. help("Shader file name must be specified.");
  2057. return bx::kExitFailure;
  2058. }
  2059. const char* outFilePath = cmdLine.findOption('o');
  2060. if (NULL == outFilePath)
  2061. {
  2062. help("Output file name must be specified.");
  2063. return bx::kExitFailure;
  2064. }
  2065. const char* type = cmdLine.findOption('\0', "type");
  2066. if (NULL == type)
  2067. {
  2068. help("Must specify shader type.");
  2069. return bx::kExitFailure;
  2070. }
  2071. Options options;
  2072. options.inputFilePath = filePath;
  2073. options.outputFilePath = outFilePath;
  2074. options.shaderType = bx::toLower(type[0]);
  2075. options.disasm = cmdLine.hasArg('\0', "disasm");
  2076. const char* platform = cmdLine.findOption('\0', "platform");
  2077. if (NULL == platform)
  2078. {
  2079. platform = "";
  2080. }
  2081. options.platform = platform;
  2082. options.raw = cmdLine.hasArg('\0', "raw");
  2083. const char* profile = cmdLine.findOption('p', "profile");
  2084. if ( NULL != profile)
  2085. {
  2086. options.profile = profile;
  2087. }
  2088. {
  2089. options.debugInformation = cmdLine.hasArg('\0', "debug");
  2090. options.avoidFlowControl = cmdLine.hasArg('\0', "avoid-flow-control");
  2091. options.noPreshader = cmdLine.hasArg('\0', "no-preshader");
  2092. options.partialPrecision = cmdLine.hasArg('\0', "partial-precision");
  2093. options.preferFlowControl = cmdLine.hasArg('\0', "prefer-flow-control");
  2094. options.backwardsCompatibility = cmdLine.hasArg('\0', "backwards-compatibility");
  2095. options.warningsAreErrors = cmdLine.hasArg('\0', "Werror");
  2096. options.keepIntermediate = cmdLine.hasArg('\0', "keep-intermediate");
  2097. uint32_t optimization = 3;
  2098. if (cmdLine.hasArg(optimization, 'O') )
  2099. {
  2100. options.optimize = true;
  2101. options.optimizationLevel = optimization;
  2102. }
  2103. }
  2104. bx::StringView bin2c;
  2105. if (cmdLine.hasArg("bin2c") )
  2106. {
  2107. const char* bin2cArg = cmdLine.findOption("bin2c");
  2108. if (NULL != bin2cArg)
  2109. {
  2110. bin2c.set(bin2cArg);
  2111. }
  2112. else
  2113. {
  2114. bin2c = baseName(outFilePath);
  2115. if (!bin2c.isEmpty() )
  2116. {
  2117. char* temp = (char*)alloca(bin2c.getLength()+1);
  2118. for (uint32_t ii = 0, num = bin2c.getLength(); ii < num; ++ii)
  2119. {
  2120. char ch = bin2c.getPtr()[ii];
  2121. if (bx::isAlphaNum(ch) )
  2122. {
  2123. temp[ii] = ch;
  2124. }
  2125. else
  2126. {
  2127. temp[ii] = '_';
  2128. }
  2129. }
  2130. temp[bin2c.getLength()] = '\0';
  2131. bin2c = temp;
  2132. }
  2133. }
  2134. }
  2135. options.depends = cmdLine.hasArg("depends");
  2136. options.preprocessOnly = cmdLine.hasArg("preprocess");
  2137. const char* includeDir = cmdLine.findOption('i');
  2138. BX_TRACE("depends: %d", options.depends);
  2139. BX_TRACE("preprocessOnly: %d", options.preprocessOnly);
  2140. BX_TRACE("includeDir: %s", includeDir);
  2141. for (int ii = 1; NULL != includeDir; ++ii)
  2142. {
  2143. options.includeDirs.push_back(includeDir);
  2144. includeDir = cmdLine.findOption(ii, 'i');
  2145. }
  2146. std::string dir;
  2147. {
  2148. bx::FilePath fp(filePath);
  2149. bx::StringView path(fp.getPath() );
  2150. dir.assign(path.getPtr(), path.getTerm() );
  2151. options.includeDirs.push_back(dir);
  2152. }
  2153. const char* defines = cmdLine.findOption("define");
  2154. while (NULL != defines
  2155. && '\0' != *defines)
  2156. {
  2157. defines = bx::strLTrimSpace(defines).getPtr();
  2158. bx::StringView eol = bx::strFind(defines, ';');
  2159. std::string define(defines, eol.getPtr() );
  2160. options.defines.push_back(define.c_str() );
  2161. defines = ';' == *eol.getPtr() ? eol.getPtr()+1 : eol.getPtr();
  2162. }
  2163. std::string commandLineComment = "// shaderc command line:\n//";
  2164. for (int32_t ii = 0, num = cmdLine.getNum(); ii < num; ++ii)
  2165. {
  2166. commandLineComment += " ";
  2167. commandLineComment += cmdLine.get(ii);
  2168. }
  2169. commandLineComment += "\n\n";
  2170. bool compiled = false;
  2171. bx::FileReader reader;
  2172. if (!bx::open(&reader, filePath) )
  2173. {
  2174. fprintf(stderr, "Unable to open file '%s'.\n", filePath);
  2175. }
  2176. else
  2177. {
  2178. const char* varying = NULL;
  2179. File attribdef;
  2180. if ('c' != options.shaderType)
  2181. {
  2182. std::string defaultVarying = dir + "varying.def.sc";
  2183. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  2184. attribdef.load(varyingdef);
  2185. varying = attribdef.getData();
  2186. if (NULL != varying
  2187. && *varying != '\0')
  2188. {
  2189. options.dependencies.push_back(varyingdef);
  2190. }
  2191. else
  2192. {
  2193. fprintf(stderr, "ERROR: Failed to parse varying def file: \"%s\" No input/output semantics will be generated in the code!\n", varyingdef);
  2194. }
  2195. }
  2196. const size_t padding = 16384;
  2197. uint32_t size = (uint32_t)bx::getSize(&reader);
  2198. char* data = new char[size+padding+1];
  2199. size = (uint32_t)bx::read(&reader, data, size);
  2200. if (data[0] == '\xef'
  2201. && data[1] == '\xbb'
  2202. && data[2] == '\xbf')
  2203. {
  2204. bx::memMove(data, &data[3], size-3);
  2205. size -= 3;
  2206. }
  2207. // Compiler generates "error X3000: syntax error: unexpected end of file"
  2208. // if input doesn't have empty line at EOF.
  2209. data[size] = '\n';
  2210. bx::memSet(&data[size+1], 0, padding);
  2211. bx::close(&reader);
  2212. bx::FileWriter* writer = NULL;
  2213. if (!bin2c.isEmpty() )
  2214. {
  2215. writer = new Bin2cWriter(bin2c);
  2216. }
  2217. else
  2218. {
  2219. writer = new bx::FileWriter;
  2220. }
  2221. if (!bx::open(writer, outFilePath) )
  2222. {
  2223. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2224. return bx::kExitFailure;
  2225. }
  2226. compiled = compileShader(varying, commandLineComment.c_str(), data, size, options, writer);
  2227. bx::close(writer);
  2228. delete writer;
  2229. }
  2230. if (compiled)
  2231. {
  2232. return bx::kExitSuccess;
  2233. }
  2234. bx::remove(outFilePath);
  2235. fprintf(stderr, "Failed to build shader.\n");
  2236. return bx::kExitFailure;
  2237. }
  2238. } // namespace bgfx
  2239. int main(int _argc, const char* _argv[])
  2240. {
  2241. return bgfx::compileShader(_argc, _argv);
  2242. }