shaderc.cpp 60 KB

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