shaderc.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247
  1. /*
  2. * Copyright 2011-2014 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #ifndef SHADERC_DEBUG
  6. # define SHADERC_DEBUG 0
  7. #endif // SHADERC_DEBUG
  8. #define _BX_TRACE(_format, ...) \
  9. do { \
  10. fprintf(stderr, BX_FILE_LINE_LITERAL "" _format "\n", ##__VA_ARGS__); \
  11. } while(0)
  12. #define _BX_WARN(_condition, _format, ...) \
  13. do { \
  14. if (!(_condition) ) \
  15. { \
  16. BX_TRACE("WARN " _format, ##__VA_ARGS__); \
  17. } \
  18. } while(0)
  19. #define _BX_CHECK(_condition, _format, ...) \
  20. do { \
  21. if (!(_condition) ) \
  22. { \
  23. BX_TRACE("CHECK " _format, ##__VA_ARGS__); \
  24. bx::debugBreak(); \
  25. } \
  26. } while(0)
  27. #if SHADERC_DEBUG
  28. # define BX_TRACE _BX_TRACE
  29. # define BX_WARN _BX_WARN
  30. # define BX_CHECK _BX_CHECK
  31. #endif // DEBUG
  32. #include <bx/bx.h>
  33. #include <bx/debug.h>
  34. #define NOMINMAX
  35. #include <alloca.h>
  36. #include <stdio.h>
  37. #include <stdint.h>
  38. #include <stdlib.h>
  39. #include <string.h>
  40. #include <algorithm>
  41. #include <string>
  42. #include <vector>
  43. #include <unordered_map>
  44. #define MAX_TAGS 256
  45. extern "C"
  46. {
  47. #include <fpp.h>
  48. } // extern "C"
  49. #define BGFX_CHUNK_MAGIC_VSH BX_MAKEFOURCC('V', 'S', 'H', 0x1)
  50. #define BGFX_CHUNK_MAGIC_FSH BX_MAKEFOURCC('F', 'S', 'H', 0x1)
  51. #include <bx/commandline.h>
  52. #include <bx/endian.h>
  53. #include <bx/uint32_t.h>
  54. #include <bx/readerwriter.h>
  55. #include <bx/string.h>
  56. #include <bx/hash.h>
  57. #include "glsl_optimizer.h"
  58. #if BX_PLATFORM_WINDOWS
  59. # include <sal.h>
  60. # define __D3DX9MATH_INL__ // not used and MinGW complains about type-punning
  61. # include <d3dx9.h>
  62. # include <d3dcompiler.h>
  63. #endif // BX_PLATFORM_WINDOWS
  64. long int fsize(FILE* _file)
  65. {
  66. long int pos = ftell(_file);
  67. fseek(_file, 0L, SEEK_END);
  68. long int size = ftell(_file);
  69. fseek(_file, pos, SEEK_SET);
  70. return size;
  71. }
  72. struct Attrib
  73. {
  74. enum Enum
  75. {
  76. Position = 0,
  77. Normal,
  78. Tangent,
  79. Color0,
  80. Color1,
  81. Indices,
  82. Weight,
  83. TexCoord0,
  84. TexCoord1,
  85. TexCoord2,
  86. TexCoord3,
  87. TexCoord4,
  88. TexCoord5,
  89. TexCoord6,
  90. TexCoord7,
  91. Count,
  92. };
  93. };
  94. static const char* s_ARB_shader_texture_lod[] =
  95. {
  96. "texture2DLod",
  97. "texture2DProjLod",
  98. "texture3DLod",
  99. "texture3DProjLod",
  100. "textureCubeLod",
  101. "shadow2DLod",
  102. "shadow2DProjLod",
  103. NULL
  104. // "texture1DLod",
  105. // "texture1DProjLod",
  106. // "shadow1DLod",
  107. // "shadow1DProjLod",
  108. };
  109. static const char* s_EXT_shadow_samplers[] =
  110. {
  111. "shadow2D",
  112. "shadow2DProj",
  113. "sampler2DShadow",
  114. NULL
  115. };
  116. static const char* s_OES_standard_derivatives[] =
  117. {
  118. "dFdx",
  119. "dFdy",
  120. "fwidth",
  121. NULL
  122. };
  123. static const char* s_OES_texture_3D[] =
  124. {
  125. "texture3D",
  126. "texture3DProj",
  127. "texture3DLod",
  128. "texture3DProjLod",
  129. NULL
  130. };
  131. struct RemapInputSemantic
  132. {
  133. Attrib::Enum m_attr;
  134. const char* m_name;
  135. uint8_t m_index;
  136. };
  137. static const RemapInputSemantic s_remapInputSemantic[Attrib::Count+1] =
  138. {
  139. { Attrib::Position, "POSITION", 0 },
  140. { Attrib::Normal, "NORMAL", 0 },
  141. { Attrib::Tangent, "TANGENT", 0 },
  142. { Attrib::Color0, "COLOR", 0 },
  143. { Attrib::Color1, "COLOR", 1 },
  144. { Attrib::Indices, "BLENDINDICES", 0 },
  145. { Attrib::Weight, "BLENDWEIGHT", 0 },
  146. { Attrib::TexCoord0, "TEXCOORD", 0 },
  147. { Attrib::TexCoord1, "TEXCOORD", 1 },
  148. { Attrib::TexCoord2, "TEXCOORD", 2 },
  149. { Attrib::TexCoord3, "TEXCOORD", 3 },
  150. { Attrib::TexCoord4, "TEXCOORD", 4 },
  151. { Attrib::TexCoord5, "TEXCOORD", 5 },
  152. { Attrib::TexCoord6, "TEXCOORD", 6 },
  153. { Attrib::TexCoord7, "TEXCOORD", 7 },
  154. { Attrib::Count, "", 0 },
  155. };
  156. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  157. {
  158. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  159. {
  160. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  161. if (0 == strcmp(ris.m_name, _name)
  162. && ris.m_index == _index)
  163. {
  164. return ris;
  165. }
  166. }
  167. return s_remapInputSemantic[Attrib::Count];
  168. }
  169. struct ConstantType
  170. {
  171. enum Enum
  172. {
  173. Uniform1i,
  174. Uniform1f,
  175. End,
  176. Uniform1iv,
  177. Uniform1fv,
  178. Uniform2fv,
  179. Uniform3fv,
  180. Uniform4fv,
  181. Uniform3x3fv,
  182. Uniform4x4fv,
  183. Count,
  184. };
  185. };
  186. #define BGFX_UNIFORM_FRAGMENTBIT UINT8_C(0x10)
  187. const char* s_constantTypeName[ConstantType::Count] =
  188. {
  189. "int",
  190. "float",
  191. NULL,
  192. "int",
  193. "float",
  194. "float2",
  195. "float3",
  196. "float4",
  197. "float3x3",
  198. "float4x4",
  199. };
  200. struct Uniform
  201. {
  202. std::string name;
  203. ConstantType::Enum type;
  204. uint8_t num;
  205. uint16_t regIndex;
  206. uint16_t regCount;
  207. };
  208. typedef std::vector<Uniform> UniformArray;
  209. #if BX_PLATFORM_WINDOWS
  210. struct ConstRemapDx9
  211. {
  212. ConstantType::Enum id;
  213. D3DXPARAMETER_CLASS paramClass;
  214. D3DXPARAMETER_TYPE paramType;
  215. uint32_t paramBytes;
  216. };
  217. static const ConstRemapDx9 s_constRemapDx9[7] =
  218. {
  219. { ConstantType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 4 },
  220. { ConstantType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 4 },
  221. { ConstantType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 8 },
  222. { ConstantType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 12 },
  223. { ConstantType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 16 },
  224. { ConstantType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 36 },
  225. { ConstantType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 64 },
  226. };
  227. ConstantType::Enum findConstantTypeDx9(const D3DXCONSTANT_DESC& constDesc)
  228. {
  229. uint32_t count = sizeof(s_constRemapDx9)/sizeof(ConstRemapDx9);
  230. for (uint32_t ii = 0; ii < count; ++ii)
  231. {
  232. const ConstRemapDx9& remap = s_constRemapDx9[ii];
  233. if (remap.paramClass == constDesc.Class
  234. && remap.paramType == constDesc.Type
  235. && (constDesc.Bytes%remap.paramBytes) == 0)
  236. {
  237. return remap.id;
  238. }
  239. }
  240. return ConstantType::Count;
  241. }
  242. static uint32_t s_optimizationLevelDx9[4] =
  243. {
  244. D3DXSHADER_OPTIMIZATION_LEVEL0,
  245. D3DXSHADER_OPTIMIZATION_LEVEL1,
  246. D3DXSHADER_OPTIMIZATION_LEVEL2,
  247. D3DXSHADER_OPTIMIZATION_LEVEL3,
  248. };
  249. struct ConstRemapDx11
  250. {
  251. ConstantType::Enum id;
  252. D3D_SHADER_VARIABLE_CLASS paramClass;
  253. D3D_SHADER_VARIABLE_TYPE paramType;
  254. uint32_t paramBytes;
  255. };
  256. static const ConstRemapDx11 s_constRemapDx11[7] =
  257. {
  258. { ConstantType::Uniform1iv, D3D_SVC_SCALAR, D3D_SVT_INT, 4 },
  259. { ConstantType::Uniform1fv, D3D_SVC_SCALAR, D3D_SVT_FLOAT, 4 },
  260. { ConstantType::Uniform2fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 8 },
  261. { ConstantType::Uniform3fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 12 },
  262. { ConstantType::Uniform4fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 16 },
  263. { ConstantType::Uniform3x3fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 36 },
  264. { ConstantType::Uniform4x4fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 64 },
  265. };
  266. ConstantType::Enum findConstantTypeDx11(const D3D11_SHADER_TYPE_DESC& constDesc, uint32_t _size)
  267. {
  268. uint32_t count = sizeof(s_constRemapDx11)/sizeof(ConstRemapDx9);
  269. for (uint32_t ii = 0; ii < count; ++ii)
  270. {
  271. const ConstRemapDx11& remap = s_constRemapDx11[ii];
  272. if (remap.paramClass == constDesc.Class
  273. && remap.paramType == constDesc.Type
  274. && (_size%remap.paramBytes) == 0)
  275. {
  276. return remap.id;
  277. }
  278. }
  279. return ConstantType::Count;
  280. }
  281. static uint32_t s_optimizationLevelDx11[4] =
  282. {
  283. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  284. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  285. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  286. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  287. };
  288. #endif // BX_PLATFORM_WINDOWS
  289. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  290. {
  291. va_list argList;
  292. va_start(argList, _format);
  293. char temp[2048];
  294. char* out = temp;
  295. int32_t max = sizeof(temp);
  296. int32_t len = bx::vsnprintf(out, max, _format, argList);
  297. if (len > max)
  298. {
  299. out = (char*)alloca(len);
  300. len = bx::vsnprintf(out, len, _format, argList);
  301. }
  302. len = bx::write(_writer, out, len);
  303. va_end(argList);
  304. return len;
  305. }
  306. class Bin2cWriter : public bx::CrtFileWriter
  307. {
  308. public:
  309. Bin2cWriter(const char* _name)
  310. : m_name(_name)
  311. {
  312. }
  313. virtual ~Bin2cWriter()
  314. {
  315. }
  316. virtual int32_t close() BX_OVERRIDE
  317. {
  318. generate();
  319. return bx::CrtFileWriter::close();
  320. }
  321. virtual int32_t write(const void* _data, int32_t _size) BX_OVERRIDE
  322. {
  323. const char* data = (const char*)_data;
  324. m_buffer.insert(m_buffer.end(), data, data+_size);
  325. return _size;
  326. }
  327. private:
  328. void generate()
  329. {
  330. #define HEX_DUMP_WIDTH 16
  331. #define HEX_DUMP_SPACE_WIDTH 96
  332. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  333. const uint8_t* data = &m_buffer[0];
  334. uint32_t size = (uint32_t)m_buffer.size();
  335. outf("static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size);
  336. if (NULL != data)
  337. {
  338. char hex[HEX_DUMP_SPACE_WIDTH+1];
  339. char ascii[HEX_DUMP_WIDTH+1];
  340. uint32_t hexPos = 0;
  341. uint32_t asciiPos = 0;
  342. for (uint32_t ii = 0; ii < size; ++ii)
  343. {
  344. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  345. hexPos += 6;
  346. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
  347. asciiPos++;
  348. if (HEX_DUMP_WIDTH == asciiPos)
  349. {
  350. ascii[asciiPos] = '\0';
  351. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  352. data += asciiPos;
  353. hexPos = 0;
  354. asciiPos = 0;
  355. }
  356. }
  357. if (0 != asciiPos)
  358. {
  359. ascii[asciiPos] = '\0';
  360. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  361. }
  362. }
  363. outf("};\n");
  364. #undef HEX_DUMP_WIDTH
  365. #undef HEX_DUMP_SPACE_WIDTH
  366. #undef HEX_DUMP_FORMAT
  367. }
  368. int32_t outf(const char* _format, ...)
  369. {
  370. va_list argList;
  371. va_start(argList, _format);
  372. char temp[2048];
  373. char* out = temp;
  374. int32_t max = sizeof(temp);
  375. int32_t len = bx::vsnprintf(out, max, _format, argList);
  376. if (len > max)
  377. {
  378. out = (char*)alloca(len);
  379. len = bx::vsnprintf(out, len, _format, argList);
  380. }
  381. int32_t size = bx::CrtFileWriter::write(out, len);
  382. va_end(argList);
  383. return size;
  384. }
  385. std::string m_filePath;
  386. std::string m_name;
  387. typedef std::vector<uint8_t> Buffer;
  388. Buffer m_buffer;
  389. };
  390. struct Varying
  391. {
  392. std::string m_precision;
  393. std::string m_name;
  394. std::string m_type;
  395. std::string m_init;
  396. std::string m_semantics;
  397. };
  398. typedef std::unordered_map<std::string, Varying> VaryingMap;
  399. class File
  400. {
  401. public:
  402. File(const char* _filePath)
  403. : m_data(NULL)
  404. {
  405. FILE* file = fopen(_filePath, "r");
  406. if (NULL != file)
  407. {
  408. m_size = fsize(file);
  409. m_data = new char[m_size+1];
  410. m_size = (uint32_t)fread(m_data, 1, m_size, file);
  411. m_data[m_size] = '\0';
  412. fclose(file);
  413. }
  414. }
  415. ~File()
  416. {
  417. delete [] m_data;
  418. }
  419. const char* getData() const
  420. {
  421. return m_data;
  422. }
  423. uint32_t getSize() const
  424. {
  425. return m_size;
  426. }
  427. private:
  428. char* m_data;
  429. uint32_t m_size;
  430. };
  431. void strins(char* _str, const char* _insert)
  432. {
  433. size_t len = strlen(_insert);
  434. memmove(&_str[len], _str, strlen(_str) );
  435. memcpy(_str, _insert, len);
  436. }
  437. void strreplace(char* _str, const char* _find, const char* _replace)
  438. {
  439. const size_t len = strlen(_find);
  440. char* replace = (char*)alloca(len+1);
  441. bx::strlcpy(replace, _replace, len+1);
  442. for (uint32_t ii = strlen(replace); ii < len; ++ii)
  443. {
  444. replace[ii] = ' ';
  445. }
  446. replace[len] = '\0';
  447. BX_CHECK(len >= strlen(_replace), "");
  448. for (char* ptr = strstr(_str, _find); NULL != ptr; ptr = strstr(ptr + len, _find) )
  449. {
  450. memcpy(ptr, replace, len);
  451. }
  452. }
  453. class LineReader
  454. {
  455. public:
  456. LineReader(const char* _str)
  457. : m_str(_str)
  458. , m_pos(0)
  459. , m_size( (uint32_t)strlen(_str) )
  460. {
  461. }
  462. std::string getLine()
  463. {
  464. const char* str = &m_str[m_pos];
  465. skipLine();
  466. const char* eol = &m_str[m_pos];
  467. std::string tmp;
  468. tmp.assign(str, eol-str);
  469. return tmp;
  470. }
  471. bool isEof() const
  472. {
  473. return m_str[m_pos] == '\0';
  474. }
  475. void skipLine()
  476. {
  477. const char* str = &m_str[m_pos];
  478. const char* nl = bx::strnl(str);
  479. m_pos += (uint32_t)(nl - str);
  480. }
  481. const char* m_str;
  482. uint32_t m_pos;
  483. uint32_t m_size;
  484. };
  485. void printCode(const char* _code, int32_t _line = 0, int32_t _start = 0, int32_t _end = INT32_MAX)
  486. {
  487. fprintf(stderr, "Code:\n---\n");
  488. LineReader lr(_code);
  489. for (int32_t line = 1; !lr.isEof() && line < _end; ++line)
  490. {
  491. if (line >= _start)
  492. {
  493. fprintf(stderr, "%s%3d: %s", _line == line ? ">>> " : " ", line, lr.getLine().c_str() );
  494. }
  495. else
  496. {
  497. lr.skipLine();
  498. }
  499. }
  500. fprintf(stderr, "---\n");
  501. }
  502. void writeFile(const char* _filePath, const void* _data, int32_t _size)
  503. {
  504. bx::CrtFileWriter out;
  505. if (0 == out.open(_filePath) )
  506. {
  507. out.write(_data, _size);
  508. out.close();
  509. }
  510. }
  511. bool compileGLSLShader(bx::CommandLine& _cmdLine, uint32_t _gles, const std::string& _code, bx::WriterI* _writer)
  512. {
  513. const glslopt_shader_type type = tolower(_cmdLine.findOption('\0', "type")[0]) == 'f' ? kGlslOptShaderFragment : kGlslOptShaderVertex;
  514. glslopt_target target = kGlslTargetOpenGL;
  515. switch (_gles)
  516. {
  517. case 2:
  518. target = kGlslTargetOpenGLES20;
  519. break;
  520. case 3:
  521. target = kGlslTargetOpenGLES30;
  522. break;
  523. default:
  524. target = kGlslTargetOpenGL;
  525. break;
  526. }
  527. glslopt_ctx* ctx = glslopt_initialize(target);
  528. glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
  529. if (!glslopt_get_status(shader) )
  530. {
  531. const char* log = glslopt_get_log(shader);
  532. int32_t source = 0;
  533. int32_t line = 0;
  534. int32_t column = 0;
  535. int32_t start = 0;
  536. int32_t end = INT32_MAX;
  537. if (3 == sscanf(log, "%u:%u(%u):", &source, &line, &column)
  538. && 0 != line)
  539. {
  540. start = bx::uint32_imax(1, line-10);
  541. end = start + 20;
  542. }
  543. printCode(_code.c_str(), line, start, end);
  544. fprintf(stderr, "Error: %s\n", log);
  545. glslopt_cleanup(ctx);
  546. return false;
  547. }
  548. const char* optimizedShader = glslopt_get_output(shader);
  549. // Trim all directives.
  550. while ('#' == *optimizedShader)
  551. {
  552. optimizedShader = bx::strnl(optimizedShader);
  553. }
  554. if (0 != _gles)
  555. {
  556. char* shader = const_cast<char*>(optimizedShader);
  557. strreplace(shader, "gl_FragDepthEXT", "gl_FragDepth");
  558. strreplace(shader, "texture2DLodEXT", "texture2DLod");
  559. strreplace(shader, "texture2DProjLodEXT", "texture2DProjLod");
  560. strreplace(shader, "textureCubeLodEXT", "textureCubeLod");
  561. strreplace(shader, "texture2DGradEXT", "texture2DGrad");
  562. strreplace(shader, "texture2DProjGradEXT", "texture2DProjGrad");
  563. strreplace(shader, "textureCubeGradEXT", "textureCubeGrad");
  564. strreplace(shader, "shadow2DEXT", "shadow2D");
  565. strreplace(shader, "shadow2DProjEXT", "shadow2DProj");
  566. }
  567. bx::write(_writer, optimizedShader, (int32_t)strlen(optimizedShader) );
  568. uint8_t nul = 0;
  569. bx::write(_writer, nul);
  570. glslopt_cleanup(ctx);
  571. return true;
  572. }
  573. bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  574. {
  575. #if BX_PLATFORM_WINDOWS
  576. const char* profile = _cmdLine.findOption('p', "profile");
  577. if (NULL == profile)
  578. {
  579. fprintf(stderr, "Shader profile must be specified.\n");
  580. return false;
  581. }
  582. bool debug = _cmdLine.hasArg('\0', "debug");
  583. uint32_t flags = 0;
  584. flags |= debug ? D3DXSHADER_DEBUG : 0;
  585. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
  586. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
  587. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
  588. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
  589. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  590. bool werror = _cmdLine.hasArg('\0', "Werror");
  591. uint32_t optimization = 3;
  592. if (_cmdLine.hasArg(optimization, 'O') )
  593. {
  594. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx9)-1);
  595. flags |= s_optimizationLevelDx9[optimization];
  596. }
  597. else
  598. {
  599. flags |= D3DXSHADER_SKIPOPTIMIZATION;
  600. }
  601. BX_TRACE("Profile: %s", profile);
  602. BX_TRACE("Flags: 0x%08x", flags);
  603. LPD3DXBUFFER code;
  604. LPD3DXBUFFER errorMsg;
  605. LPD3DXCONSTANTTABLE constantTable;
  606. HRESULT hr;
  607. // Output preprocessed shader so that HLSL can be debugged via GPA
  608. // or PIX. Compiling through memory won't embed preprocessed shader
  609. // file path.
  610. if (debug)
  611. {
  612. std::string hlslfp = _cmdLine.findOption('o');
  613. hlslfp += ".hlsl";
  614. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  615. hr = D3DXCompileShaderFromFileA(hlslfp.c_str()
  616. , NULL
  617. , NULL
  618. , "main"
  619. , profile
  620. , flags
  621. , &code
  622. , &errorMsg
  623. , &constantTable
  624. );
  625. }
  626. else
  627. {
  628. hr = D3DXCompileShader(_code.c_str()
  629. , (uint32_t)_code.size()
  630. , NULL
  631. , NULL
  632. , "main"
  633. , profile
  634. , flags
  635. , &code
  636. , &errorMsg
  637. , &constantTable
  638. );
  639. }
  640. if (FAILED(hr)
  641. || (werror && NULL != errorMsg) )
  642. {
  643. const char* log = (const char*)errorMsg->GetBufferPointer();
  644. char source[1024];
  645. int32_t line = 0;
  646. int32_t column = 0;
  647. int32_t start = 0;
  648. int32_t end = INT32_MAX;
  649. if (3 == sscanf(log, "%[^(](%u,%u):", source, &line, &column)
  650. && 0 != line)
  651. {
  652. start = bx::uint32_imax(1, line-10);
  653. end = start + 20;
  654. }
  655. printCode(_code.c_str(), line, start, end);
  656. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  657. errorMsg->Release();
  658. return false;
  659. }
  660. D3DXCONSTANTTABLE_DESC desc;
  661. hr = constantTable->GetDesc(&desc);
  662. if (FAILED(hr) )
  663. {
  664. fprintf(stderr, "Error 0x%08x\n", (uint32_t)hr);
  665. return false;
  666. }
  667. BX_TRACE("Creator: %s 0x%08x", desc.Creator, (uint32_t /*mingw warning*/)desc.Version);
  668. BX_TRACE("Num constants: %d", desc.Constants);
  669. BX_TRACE("# cl ty RxC S By Name");
  670. UniformArray uniforms;
  671. for (uint32_t ii = 0; ii < desc.Constants; ++ii)
  672. {
  673. D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
  674. D3DXCONSTANT_DESC constDesc;
  675. uint32_t count;
  676. constantTable->GetConstantDesc(handle, &constDesc, &count);
  677. BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
  678. , ii
  679. , constDesc.Class
  680. , constDesc.Type
  681. , constDesc.Rows
  682. , constDesc.Columns
  683. , constDesc.StructMembers
  684. , constDesc.Bytes
  685. , constDesc.Name
  686. , constDesc.Elements
  687. , constDesc.RegisterIndex
  688. , constDesc.RegisterCount
  689. );
  690. ConstantType::Enum type = findConstantTypeDx9(constDesc);
  691. if (ConstantType::Count != type)
  692. {
  693. Uniform un;
  694. un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
  695. un.type = type;
  696. un.num = constDesc.Elements;
  697. un.regIndex = constDesc.RegisterIndex;
  698. un.regCount = constDesc.RegisterCount;
  699. uniforms.push_back(un);
  700. }
  701. }
  702. uint16_t count = (uint16_t)uniforms.size();
  703. bx::write(_writer, count);
  704. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  705. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  706. {
  707. const Uniform& un = *it;
  708. uint8_t nameSize = (uint8_t)un.name.size();
  709. bx::write(_writer, nameSize);
  710. bx::write(_writer, un.name.c_str(), nameSize);
  711. uint8_t type = un.type|fragmentBit;
  712. bx::write(_writer, type);
  713. bx::write(_writer, un.num);
  714. bx::write(_writer, un.regIndex);
  715. bx::write(_writer, un.regCount);
  716. BX_TRACE("%s, %s, %d, %d, %d"
  717. , un.name.c_str()
  718. , s_constantTypeName[un.type]
  719. , un.num
  720. , un.regIndex
  721. , un.regCount
  722. );
  723. }
  724. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  725. bx::write(_writer, shaderSize);
  726. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  727. uint8_t nul = 0;
  728. bx::write(_writer, nul);
  729. if (_cmdLine.hasArg('\0', "disasm") )
  730. {
  731. LPD3DXBUFFER disasm;
  732. D3DXDisassembleShader( (const DWORD*)code->GetBufferPointer()
  733. , false
  734. , NULL
  735. , &disasm
  736. );
  737. if (NULL != disasm)
  738. {
  739. std::string disasmfp = _cmdLine.findOption('o');
  740. disasmfp += ".disasm";
  741. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), disasm->GetBufferSize() );
  742. disasm->Release();
  743. }
  744. }
  745. if (NULL != code)
  746. {
  747. code->Release();
  748. }
  749. if (NULL != errorMsg)
  750. {
  751. errorMsg->Release();
  752. }
  753. if (NULL != constantTable)
  754. {
  755. constantTable->Release();
  756. }
  757. return true;
  758. #else
  759. BX_UNUSED(_cmdLine, _code, _writer);
  760. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  761. return false;
  762. #endif // BX_PLATFORM_WINDOWS
  763. }
  764. bool compileHLSLShaderDx11(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  765. {
  766. #if BX_PLATFORM_WINDOWS
  767. const char* profile = _cmdLine.findOption('p', "profile");
  768. if (NULL == profile)
  769. {
  770. fprintf(stderr, "Shader profile must be specified.\n");
  771. return false;
  772. }
  773. bool debug = _cmdLine.hasArg('\0', "debug");
  774. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  775. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  776. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  777. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
  778. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  779. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  780. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  781. bool werror = _cmdLine.hasArg('\0', "Werror");
  782. if (werror)
  783. {
  784. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  785. }
  786. uint32_t optimization = 3;
  787. if (_cmdLine.hasArg(optimization, 'O') )
  788. {
  789. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx11)-1);
  790. flags |= s_optimizationLevelDx11[optimization];
  791. }
  792. else
  793. {
  794. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  795. }
  796. BX_TRACE("Profile: %s", profile);
  797. BX_TRACE("Flags: 0x%08x", flags);
  798. ID3DBlob* code;
  799. ID3DBlob* errorMsg;
  800. // Output preprocessed shader so that HLSL can be debugged via GPA
  801. // or PIX. Compiling through memory won't embed preprocessed shader
  802. // file path.
  803. std::string hlslfp;
  804. if (debug)
  805. {
  806. hlslfp = _cmdLine.findOption('o');
  807. hlslfp += ".hlsl";
  808. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  809. }
  810. HRESULT hr = D3DCompile(_code.c_str()
  811. , _code.size()
  812. , hlslfp.c_str()
  813. , NULL
  814. , NULL
  815. , "main"
  816. , profile
  817. , flags
  818. , 0
  819. , &code
  820. , &errorMsg
  821. );
  822. if (FAILED(hr)
  823. || (werror && NULL != errorMsg) )
  824. {
  825. const char* log = (char*)errorMsg->GetBufferPointer();
  826. int32_t line = 0;
  827. int32_t column = 0;
  828. int32_t start = 0;
  829. int32_t end = INT32_MAX;
  830. if (2 == sscanf(log, "(%u,%u):", &line, &column)
  831. && 0 != line)
  832. {
  833. start = bx::uint32_imax(1, line-10);
  834. end = start + 20;
  835. }
  836. printCode(_code.c_str(), line, start, end);
  837. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  838. errorMsg->Release();
  839. return false;
  840. }
  841. UniformArray uniforms;
  842. ID3D11ShaderReflection* reflect = NULL;
  843. hr = D3DReflect(code->GetBufferPointer()
  844. , code->GetBufferSize()
  845. , IID_ID3D11ShaderReflection
  846. , (void**)&reflect
  847. );
  848. if (FAILED(hr) )
  849. {
  850. fprintf(stderr, "Error: 0x%08x\n", (uint32_t)hr);
  851. return false;
  852. }
  853. D3D11_SHADER_DESC desc;
  854. hr = reflect->GetDesc(&desc);
  855. if (FAILED(hr) )
  856. {
  857. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr);
  858. return false;
  859. }
  860. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  861. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  862. BX_TRACE("Input:");
  863. uint8_t attrMask[Attrib::Count];
  864. memset(attrMask, 0, sizeof(attrMask) );
  865. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  866. {
  867. D3D11_SIGNATURE_PARAMETER_DESC spd;
  868. reflect->GetInputParameterDesc(ii, &spd);
  869. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  870. , ii
  871. , spd.SemanticName
  872. , spd.SemanticIndex
  873. , spd.SystemValueType
  874. , spd.ComponentType
  875. , spd.Mask
  876. , spd.Register
  877. );
  878. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
  879. if (ris.m_attr != Attrib::Count)
  880. {
  881. attrMask[ris.m_attr] = 0xff;
  882. }
  883. }
  884. bx::write(_writer, attrMask, sizeof(attrMask) );
  885. BX_TRACE("Output:");
  886. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  887. {
  888. D3D11_SIGNATURE_PARAMETER_DESC spd;
  889. reflect->GetOutputParameterDesc(ii, &spd);
  890. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  891. }
  892. uint16_t size = 0;
  893. for (uint32_t ii = 0; ii < bx::uint32_min(1, desc.ConstantBuffers); ++ii)
  894. {
  895. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  896. D3D11_SHADER_BUFFER_DESC bufferDesc;
  897. hr = cbuffer->GetDesc(&bufferDesc);
  898. size = (uint16_t)bufferDesc.Size;
  899. if (SUCCEEDED(hr) )
  900. {
  901. BX_TRACE("%s, %d, vars %d, size %d"
  902. , bufferDesc.Name
  903. , bufferDesc.Type
  904. , bufferDesc.Variables
  905. , bufferDesc.Size
  906. );
  907. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  908. {
  909. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  910. ID3D11ShaderReflectionType* type = var->GetType();
  911. D3D11_SHADER_VARIABLE_DESC varDesc;
  912. hr = var->GetDesc(&varDesc);
  913. if (SUCCEEDED(hr) )
  914. {
  915. D3D11_SHADER_TYPE_DESC constDesc;
  916. hr = type->GetDesc(&constDesc);
  917. if (SUCCEEDED(hr) )
  918. {
  919. ConstantType::Enum type = findConstantTypeDx11(constDesc, varDesc.Size);
  920. if (ConstantType::Count != type
  921. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  922. {
  923. Uniform un;
  924. un.name = varDesc.Name;
  925. un.type = type;
  926. un.num = constDesc.Elements;
  927. un.regIndex = varDesc.StartOffset;
  928. un.regCount = BX_ALIGN_16(varDesc.Size)/16;
  929. uniforms.push_back(un);
  930. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d"
  931. , varDesc.Name
  932. , varDesc.StartOffset
  933. , varDesc.Size
  934. , varDesc.uFlags
  935. , type
  936. );
  937. }
  938. }
  939. }
  940. }
  941. }
  942. }
  943. BX_TRACE("Bound:");
  944. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  945. {
  946. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  947. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  948. if (SUCCEEDED(hr) )
  949. {
  950. // if (bindDesc.Type == D3D_SIT_SAMPLER)
  951. {
  952. BX_TRACE("\t%s, %d, %d, %d"
  953. , bindDesc.Name
  954. , bindDesc.Type
  955. , bindDesc.BindPoint
  956. , bindDesc.BindCount
  957. );
  958. }
  959. }
  960. }
  961. uint16_t count = (uint16_t)uniforms.size();
  962. bx::write(_writer, count);
  963. bx::write(_writer, size);
  964. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  965. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  966. {
  967. const Uniform& un = *it;
  968. uint8_t nameSize = (uint8_t)un.name.size();
  969. bx::write(_writer, nameSize);
  970. bx::write(_writer, un.name.c_str(), nameSize);
  971. uint8_t type = un.type|fragmentBit;
  972. bx::write(_writer, type);
  973. bx::write(_writer, un.num);
  974. bx::write(_writer, un.regIndex);
  975. bx::write(_writer, un.regCount);
  976. BX_TRACE("%s, %s, %d, %d, %d"
  977. , un.name.c_str()
  978. , s_constantTypeName[un.type]
  979. , un.num
  980. , un.regIndex
  981. , un.regCount
  982. );
  983. }
  984. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  985. bx::write(_writer, shaderSize);
  986. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  987. uint8_t nul = 0;
  988. bx::write(_writer, nul);
  989. if (_cmdLine.hasArg('\0', "disasm") )
  990. {
  991. ID3DBlob* disasm;
  992. D3DDisassemble(code->GetBufferPointer()
  993. , code->GetBufferSize()
  994. , 0
  995. , NULL
  996. , &disasm
  997. );
  998. if (NULL != disasm)
  999. {
  1000. std::string disasmfp = _cmdLine.findOption('o');
  1001. disasmfp += ".disasm";
  1002. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  1003. disasm->Release();
  1004. }
  1005. }
  1006. if (NULL != reflect)
  1007. {
  1008. reflect->Release();
  1009. }
  1010. if (NULL != errorMsg)
  1011. {
  1012. errorMsg->Release();
  1013. }
  1014. code->Release();
  1015. return true;
  1016. #else
  1017. BX_UNUSED(_cmdLine, _code, _writer);
  1018. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  1019. return false;
  1020. #endif // BX_PLATFORM_WINDOWS
  1021. }
  1022. struct Preprocessor
  1023. {
  1024. Preprocessor(const char* _filePath, bool _gles, const char* _includeDir = NULL)
  1025. : m_tagptr(m_tags)
  1026. , m_scratchPos(0)
  1027. , m_fgetsPos(0)
  1028. {
  1029. m_tagptr->tag = FPPTAG_USERDATA;
  1030. m_tagptr->data = this;
  1031. m_tagptr++;
  1032. m_tagptr->tag = FPPTAG_DEPENDS;
  1033. m_tagptr->data = (void*)fppDepends;
  1034. m_tagptr++;
  1035. m_tagptr->tag = FPPTAG_INPUT;
  1036. m_tagptr->data = (void*)fppInput;
  1037. m_tagptr++;
  1038. m_tagptr->tag = FPPTAG_OUTPUT;
  1039. m_tagptr->data = (void*)fppOutput;
  1040. m_tagptr++;
  1041. m_tagptr->tag = FPPTAG_ERROR;
  1042. m_tagptr->data = (void*)fppError;
  1043. m_tagptr++;
  1044. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  1045. m_tagptr->data = (void*)0;
  1046. m_tagptr++;
  1047. m_tagptr->tag = FPPTAG_LINE;
  1048. m_tagptr->data = (void*)0;
  1049. m_tagptr++;
  1050. m_tagptr->tag = FPPTAG_INPUT_NAME;
  1051. m_tagptr->data = scratch(_filePath);
  1052. m_tagptr++;
  1053. if (NULL != _includeDir)
  1054. {
  1055. addInclude(_includeDir);
  1056. }
  1057. if (!_gles)
  1058. {
  1059. m_default = "#define lowp\n#define mediump\n#define highp\n";
  1060. }
  1061. }
  1062. void setDefine(const char* _define)
  1063. {
  1064. m_tagptr->tag = FPPTAG_DEFINE;
  1065. m_tagptr->data = scratch(_define);
  1066. m_tagptr++;
  1067. }
  1068. void setDefaultDefine(const char* _name)
  1069. {
  1070. char temp[1024];
  1071. bx::snprintf(temp, BX_COUNTOF(temp)
  1072. , "#ifndef %s\n"
  1073. "# define %s 0\n"
  1074. "#endif // %s\n"
  1075. "\n"
  1076. , _name
  1077. , _name
  1078. , _name
  1079. );
  1080. m_default += temp;
  1081. }
  1082. void writef(const char* _format, ...)
  1083. {
  1084. va_list argList;
  1085. va_start(argList, _format);
  1086. bx::stringPrintfVargs(m_default, _format, argList);
  1087. va_end(argList);
  1088. }
  1089. void addInclude(const char* _includeDir)
  1090. {
  1091. char* start = scratch(_includeDir);
  1092. for (char* split = strchr(start, ';'); NULL != split; split = strchr(start, ';'))
  1093. {
  1094. *split = '\0';
  1095. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1096. m_tagptr->data = start;
  1097. m_tagptr++;
  1098. start = split + 1;
  1099. }
  1100. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1101. m_tagptr->data = start;
  1102. m_tagptr++;
  1103. }
  1104. void addDependency(const char* _fileName)
  1105. {
  1106. m_depends += " \\\n ";
  1107. m_depends += _fileName;
  1108. }
  1109. bool run(const char* _input)
  1110. {
  1111. m_fgetsPos = 0;
  1112. m_preprocessed.clear();
  1113. m_input = m_default;
  1114. m_input += "\n\n";
  1115. size_t len = strlen(_input)+1;
  1116. char* temp = new char[len];
  1117. bx::eolLF(temp, len, _input);
  1118. m_input += temp;
  1119. delete [] temp;
  1120. fppTag* tagptr = m_tagptr;
  1121. tagptr->tag = FPPTAG_END;
  1122. tagptr->data = 0;
  1123. tagptr++;
  1124. int result = fppPreProcess(m_tags);
  1125. return 0 == result;
  1126. }
  1127. char* fgets(char* _buffer, int _size)
  1128. {
  1129. int ii = 0;
  1130. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  1131. {
  1132. _buffer[ii++] = ch;
  1133. if (ch == '\n' || ii == _size)
  1134. {
  1135. _buffer[ii] = '\0';
  1136. m_fgetsPos++;
  1137. return _buffer;
  1138. }
  1139. }
  1140. return NULL;
  1141. }
  1142. static void fppDepends(char* _fileName, void* _userData)
  1143. {
  1144. Preprocessor* thisClass = (Preprocessor*)_userData;
  1145. thisClass->addDependency(_fileName);
  1146. }
  1147. static char* fppInput(char* _buffer, int _size, void* _userData)
  1148. {
  1149. Preprocessor* thisClass = (Preprocessor*)_userData;
  1150. return thisClass->fgets(_buffer, _size);
  1151. }
  1152. static void fppOutput(int _ch, void* _userData)
  1153. {
  1154. Preprocessor* thisClass = (Preprocessor*)_userData;
  1155. thisClass->m_preprocessed += _ch;
  1156. }
  1157. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  1158. {
  1159. vfprintf(stderr, _format, _vargs);
  1160. }
  1161. char* scratch(const char* _str)
  1162. {
  1163. char* result = &m_scratch[m_scratchPos];
  1164. strcpy(result, _str);
  1165. m_scratchPos += (uint32_t)strlen(_str)+1;
  1166. return result;
  1167. }
  1168. fppTag m_tags[MAX_TAGS];
  1169. fppTag* m_tagptr;
  1170. std::string m_depends;
  1171. std::string m_default;
  1172. std::string m_input;
  1173. std::string m_preprocessed;
  1174. char m_scratch[16<<10];
  1175. uint32_t m_scratchPos;
  1176. uint32_t m_fgetsPos;
  1177. };
  1178. const char* baseName(const char* _filePath)
  1179. {
  1180. const char* bs = strrchr(_filePath, '\\');
  1181. const char* fs = strrchr(_filePath, '/');
  1182. const char* column = strrchr(_filePath, ':');
  1183. const char* basename = std::max(std::max(bs, fs), column);
  1184. if (NULL != basename)
  1185. {
  1186. return basename+1;
  1187. }
  1188. return _filePath;
  1189. }
  1190. typedef std::vector<std::string> InOut;
  1191. uint32_t parseInOut(InOut& _inout, const char* _str, const char* _eol)
  1192. {
  1193. uint32_t hash = 0;
  1194. _str = bx::strws(_str);
  1195. if (_str < _eol)
  1196. {
  1197. const char* delim;
  1198. do
  1199. {
  1200. delim = strpbrk(_str, " ,");
  1201. if (NULL != delim)
  1202. {
  1203. delim = delim > _eol ? _eol : delim;
  1204. std::string token;
  1205. token.assign(_str, delim-_str);
  1206. _inout.push_back(token);
  1207. _str = bx::strws(delim + 1);
  1208. }
  1209. }
  1210. while (delim < _eol && _str < _eol && NULL != delim);
  1211. std::sort(_inout.begin(), _inout.end() );
  1212. bx::HashMurmur2A murmur;
  1213. murmur.begin();
  1214. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  1215. {
  1216. murmur.add(it->c_str(), (uint32_t)it->size() );
  1217. }
  1218. hash = murmur.end();
  1219. }
  1220. return hash;
  1221. }
  1222. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  1223. {
  1224. char find[32];
  1225. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  1226. char replace[32];
  1227. bx::snprintf(replace, sizeof(replace), "gl_FragData_%d_", _idx);
  1228. strreplace(_data, find, replace);
  1229. _preprocessor.writef(
  1230. " \\\n\t%sout vec4 gl_FragData_%d_ : SV_TARGET%d"
  1231. , _comma ? ", " : " "
  1232. , _idx
  1233. , _idx
  1234. );
  1235. }
  1236. // c - compute
  1237. // d - domain
  1238. // f - fragment
  1239. // g - geometry
  1240. // h - hull
  1241. // v - vertex
  1242. //
  1243. // OpenGL #version Features Direct3D Features Shader Model
  1244. // 2.1 120 vf 9.0 vf 2.0
  1245. // 3.0 130
  1246. // 3.1 140
  1247. // 3.2 150 vgf
  1248. // 3.3 330 10.0 vgf 4.0
  1249. // 4.0 400 vhdgf
  1250. // 4.1 410
  1251. // 4.2 420 11.0 vhdgf+c 5.0
  1252. // 4.3 430 vhdgf+c
  1253. void help(const char* _error = NULL)
  1254. {
  1255. if (NULL != _error)
  1256. {
  1257. fprintf(stderr, "Error:\n%s\n\n", _error);
  1258. }
  1259. fprintf(stderr
  1260. , "shaderc, bgfx shader compiler tool\n"
  1261. "Copyright 2011-2014 Branimir Karadzic. All rights reserved.\n"
  1262. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  1263. );
  1264. fprintf(stderr
  1265. , "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  1266. "\n"
  1267. "Options:\n"
  1268. " -f <file path> Input file path.\n"
  1269. " -i <include path> Include path (for multiple paths use semicolon).\n"
  1270. " -o <file path> Output file path.\n"
  1271. " --bin2c <file path> Generate C header file.\n"
  1272. " --depends <file path> Generate makefile style depends file.\n"
  1273. " --platform <platform> Target platform.\n"
  1274. " android\n"
  1275. " ios\n"
  1276. " linux\n"
  1277. " nacl\n"
  1278. " osx\n"
  1279. " windows\n"
  1280. " --type <type> Shader type (vertex, fragment)\n"
  1281. " --varyingdef <file path> Path to varying.def.sc file.\n"
  1282. "\n"
  1283. "Options (DX9 and DX11 only):\n"
  1284. "\n"
  1285. " --debug Debug information.\n"
  1286. " --disasm Disassemble compiled shader.\n"
  1287. " -p, --profile <profile> Shader model (f.e. ps_3_0).\n"
  1288. " -O <level> Optimization level (0, 1, 2, 3).\n"
  1289. " --Werror Treat warnings as errors.\n"
  1290. "\n"
  1291. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  1292. );
  1293. }
  1294. int main(int _argc, const char* _argv[])
  1295. {
  1296. bx::CommandLine cmdLine(_argc, _argv);
  1297. if (cmdLine.hasArg('h', "help") )
  1298. {
  1299. help();
  1300. return EXIT_FAILURE;
  1301. }
  1302. const char* filePath = cmdLine.findOption('f');
  1303. if (NULL == filePath)
  1304. {
  1305. help("Shader file name must be specified.");
  1306. return EXIT_FAILURE;
  1307. }
  1308. const char* outFilePath = cmdLine.findOption('o');
  1309. if (NULL == outFilePath)
  1310. {
  1311. help("Output file name must be specified.");
  1312. return EXIT_FAILURE;
  1313. }
  1314. const char* type = cmdLine.findOption('\0', "type");
  1315. if (NULL == type)
  1316. {
  1317. help("Must specify shader type.");
  1318. return EXIT_FAILURE;
  1319. }
  1320. const char* platform = cmdLine.findOption('\0', "platform");
  1321. if (NULL == platform)
  1322. {
  1323. help("Must specify platform.");
  1324. return EXIT_FAILURE;
  1325. }
  1326. uint32_t gles = 0;
  1327. uint32_t hlsl = 2;
  1328. const char* profile = cmdLine.findOption('p', "profile");
  1329. if (NULL != profile)
  1330. {
  1331. if (0 == strncmp(&profile[1], "s_3", 3) )
  1332. {
  1333. hlsl = 3;
  1334. }
  1335. else if (0 == strncmp(&profile[1], "s_4", 3) )
  1336. {
  1337. hlsl = 4;
  1338. }
  1339. else if (0 == strncmp(&profile[1], "s_5", 3) )
  1340. {
  1341. hlsl = 5;
  1342. }
  1343. }
  1344. else
  1345. {
  1346. gles = 2;
  1347. }
  1348. const char* bin2c = NULL;
  1349. if (cmdLine.hasArg("bin2c") )
  1350. {
  1351. bin2c = cmdLine.findOption("bin2c");
  1352. if (NULL == bin2c)
  1353. {
  1354. bin2c = baseName(outFilePath);
  1355. uint32_t len = (uint32_t)strlen(bin2c);
  1356. char* temp = (char*)alloca(len+1);
  1357. for (char *out = temp; *bin2c != '\0';)
  1358. {
  1359. char ch = *bin2c++;
  1360. if (isalnum(ch) )
  1361. {
  1362. *out++ = ch;
  1363. }
  1364. else
  1365. {
  1366. *out++ = '_';
  1367. }
  1368. }
  1369. temp[len] = '\0';
  1370. bin2c = temp;
  1371. }
  1372. }
  1373. bool depends = cmdLine.hasArg("depends");
  1374. bool preprocessOnly = cmdLine.hasArg("preprocess");
  1375. const char* includeDir = cmdLine.findOption('i');
  1376. Preprocessor preprocessor(filePath, 0 != gles, includeDir);
  1377. std::string dir;
  1378. {
  1379. const char* base = baseName(filePath);
  1380. if (base != filePath)
  1381. {
  1382. dir.assign(filePath, base-filePath);
  1383. preprocessor.addInclude(dir.c_str() );
  1384. }
  1385. }
  1386. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  1387. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  1388. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  1389. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  1390. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  1391. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  1392. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  1393. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  1394. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  1395. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  1396. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  1397. bool glsl = false;
  1398. if (0 == bx::stricmp(platform, "android") )
  1399. {
  1400. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  1401. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1402. glsl = true;
  1403. }
  1404. else if (0 == bx::stricmp(platform, "ios") )
  1405. {
  1406. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1407. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1408. glsl = true;
  1409. }
  1410. else if (0 == bx::stricmp(platform, "linux") )
  1411. {
  1412. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  1413. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1414. glsl = true;
  1415. }
  1416. else if (0 == bx::stricmp(platform, "nacl") )
  1417. {
  1418. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  1419. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1420. glsl = true;
  1421. }
  1422. else if (0 == bx::stricmp(platform, "osx") )
  1423. {
  1424. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  1425. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1426. glsl = true;
  1427. }
  1428. else if (0 == bx::stricmp(platform, "windows") )
  1429. {
  1430. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  1431. char temp[256];
  1432. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  1433. preprocessor.setDefine(temp);
  1434. }
  1435. else if (0 == bx::stricmp(platform, "xbox360") )
  1436. {
  1437. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  1438. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=3");
  1439. }
  1440. else
  1441. {
  1442. fprintf(stderr, "Unknown platform %s?!", platform);
  1443. return EXIT_FAILURE;
  1444. }
  1445. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  1446. bool fragment = false;
  1447. switch (tolower(type[0]) )
  1448. {
  1449. case 'f':
  1450. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1451. fragment = true;
  1452. break;
  1453. case 'v':
  1454. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1455. break;
  1456. default:
  1457. fprintf(stderr, "Unknown type: %s?!", type);
  1458. return EXIT_FAILURE;
  1459. }
  1460. FILE* file = fopen(filePath, "r");
  1461. if (NULL != file)
  1462. {
  1463. VaryingMap varyingMap;
  1464. std::string defaultVarying = dir + "varying.def.sc";
  1465. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  1466. File attribdef(varyingdef);
  1467. const char* parse = attribdef.getData();
  1468. if (NULL != parse
  1469. && *parse != '\0')
  1470. {
  1471. preprocessor.addDependency(varyingdef);
  1472. }
  1473. while (NULL != parse
  1474. && *parse != '\0')
  1475. {
  1476. parse = bx::strws(parse);
  1477. const char* eol = strchr(parse, ';');
  1478. if (NULL != eol)
  1479. {
  1480. const char* precision = NULL;
  1481. const char* type = parse;
  1482. if (0 == strncmp(type, "lowp", 4)
  1483. || 0 == strncmp(type, "mediump", 7)
  1484. || 0 == strncmp(type, "highp", 5) )
  1485. {
  1486. precision = type;
  1487. type = parse = bx::strws(bx::strword(parse) );
  1488. }
  1489. const char* name = parse = bx::strws(bx::strword(parse) );
  1490. const char* column = parse = bx::strws(bx::strword(parse) );
  1491. const char* semantics = parse = bx::strws(bx::strnws(parse) );
  1492. const char* assign = parse = bx::strws(bx::strword(parse) );
  1493. const char* init = parse = bx::strws(bx::strnws(parse) );
  1494. if (type < eol
  1495. && name < eol
  1496. && column < eol
  1497. && ':' == *column
  1498. && semantics < eol)
  1499. {
  1500. Varying var;
  1501. if (NULL != precision)
  1502. {
  1503. var.m_precision.assign(precision, bx::strword(precision)-precision);
  1504. }
  1505. var.m_type.assign(type, bx::strword(type)-type);
  1506. var.m_name.assign(name, bx::strword(name)-name);
  1507. var.m_semantics.assign(semantics, bx::strword(semantics)-semantics);
  1508. if (assign < eol
  1509. && '=' == *assign
  1510. && init < eol)
  1511. {
  1512. var.m_init.assign(init, eol-init);
  1513. }
  1514. varyingMap.insert(std::make_pair(var.m_name, var) );
  1515. }
  1516. parse = bx::strnl(eol);
  1517. }
  1518. }
  1519. char* data;
  1520. {
  1521. const size_t padding = 16;
  1522. uint32_t size = (uint32_t)fsize(file);
  1523. data = new char[size+padding+1];
  1524. size = (uint32_t)fread(data, 1, size, file);
  1525. // Compiler generates "error X3000: syntax error: unexpected end of file"
  1526. // if input doesn't have empty line at EOF.
  1527. data[size] = '\n';
  1528. memset(&data[size+1], 0, padding);
  1529. fclose(file);
  1530. // To avoid commented code being recognized as used feature,
  1531. // first preprocess pass is used to strip all comments before
  1532. // substituting code.
  1533. preprocessor.run(data);
  1534. delete [] data;
  1535. size = preprocessor.m_preprocessed.size();
  1536. data = new char[size+padding+1];
  1537. memcpy(data, preprocessor.m_preprocessed.c_str(), size);
  1538. memset(&data[size], 0, padding+1);
  1539. }
  1540. char* entry = strstr(data, "void main()");
  1541. if (NULL == entry)
  1542. {
  1543. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1544. }
  1545. else
  1546. {
  1547. InOut shaderInputs;
  1548. InOut shaderOutputs;
  1549. uint32_t inputHash = 0;
  1550. uint32_t outputHash = 0;
  1551. const char* input = data;
  1552. while (input[0] == '$')
  1553. {
  1554. const char* str = input+1;
  1555. const char* eol = bx::streol(str);
  1556. const char* nl = bx::strnl(eol);
  1557. input = nl;
  1558. if (0 == strncmp(str, "input", 5) )
  1559. {
  1560. str += 5;
  1561. const char* comment = strstr(str, "//");
  1562. eol = NULL != comment && comment < eol ? comment : eol;
  1563. inputHash = parseInOut(shaderInputs, str, eol);
  1564. }
  1565. else if (0 == strncmp(str, "output", 6) )
  1566. {
  1567. str += 6;
  1568. const char* comment = strstr(str, "//");
  1569. eol = NULL != comment && comment < eol ? comment : eol;
  1570. outputHash = parseInOut(shaderOutputs, str, eol);
  1571. }
  1572. }
  1573. if (glsl)
  1574. {
  1575. preprocessor.writef(
  1576. "#define ivec2 vec2\n"
  1577. "#define ivec3 vec3\n"
  1578. "#define ivec4 vec4\n"
  1579. );
  1580. if (0 == gles)
  1581. {
  1582. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1583. // not as GLSL language 1.2 specs shadow2D/Proj.
  1584. preprocessor.writef(
  1585. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1586. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1587. );
  1588. }
  1589. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1590. {
  1591. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1592. if (varyingIt != varyingMap.end() )
  1593. {
  1594. const Varying& var = varyingIt->second;
  1595. const char* name = var.m_name.c_str();
  1596. if (0 == strncmp(name, "a_", 2)
  1597. || 0 == strncmp(name, "i_", 2) )
  1598. {
  1599. preprocessor.writef("attribute %s %s %s;\n"
  1600. , var.m_precision.c_str()
  1601. , var.m_type.c_str()
  1602. , name
  1603. );
  1604. }
  1605. else
  1606. {
  1607. preprocessor.writef("varying %s %s %s;\n"
  1608. , var.m_precision.c_str()
  1609. , var.m_type.c_str()
  1610. , name
  1611. );
  1612. }
  1613. }
  1614. }
  1615. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1616. {
  1617. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1618. if (varyingIt != varyingMap.end() )
  1619. {
  1620. const Varying& var = varyingIt->second;
  1621. preprocessor.writef("varying %s %s;\n", var.m_type.c_str(), var.m_name.c_str() );
  1622. }
  1623. }
  1624. }
  1625. else
  1626. {
  1627. preprocessor.writef(
  1628. "#define lowp\n"
  1629. "#define mediump\n"
  1630. "#define highp\n"
  1631. "#define ivec2 int2\n"
  1632. "#define ivec3 int3\n"
  1633. "#define ivec4 int4\n"
  1634. "#define vec2 float2\n"
  1635. "#define vec3 float3\n"
  1636. "#define vec4 float4\n"
  1637. "#define mat2 float2x2\n"
  1638. "#define mat3 float3x3\n"
  1639. "#define mat4 float4x4\n"
  1640. );
  1641. entry[4] = '_';
  1642. if (fragment)
  1643. {
  1644. const bool hasFragCoord = NULL != strstr(data, "gl_FragCoord") || hlsl > 3;
  1645. const bool hasFragDepth = NULL != strstr(data, "gl_FragDepth");
  1646. const bool hasFrontFacing = NULL != strstr(data, "gl_FrontFacing");
  1647. const bool hasFragData0 = NULL != strstr(data, "gl_FragData[0]");
  1648. const bool hasFragData1 = NULL != strstr(data, "gl_FragData[1]");
  1649. const bool hasFragData2 = NULL != strstr(data, "gl_FragData[2]");
  1650. const bool hasFragData3 = NULL != strstr(data, "gl_FragData[3]");
  1651. if (!hasFragData0
  1652. && !hasFragData1
  1653. && !hasFragData2
  1654. && !hasFragData3)
  1655. {
  1656. // GL errors when both gl_FragColor and gl_FragData is used.
  1657. // This will trigger the same error with HLSL compiler too.
  1658. preprocessor.writef("#define gl_FragColor gl_FragData_0_\n");
  1659. }
  1660. preprocessor.writef("#define void_main()");
  1661. preprocessor.writef(" \\\n\tvoid main(");
  1662. uint32_t arg = 0;
  1663. if (hasFragCoord)
  1664. {
  1665. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1666. ++arg;
  1667. }
  1668. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1669. {
  1670. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1671. if (varyingIt != varyingMap.end() )
  1672. {
  1673. const Varying& var = varyingIt->second;
  1674. preprocessor.writef(" \\\n\t%s%s %s : %s", arg++ > 0 ? ", " : " ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1675. }
  1676. }
  1677. addFragData(preprocessor, data, 0, arg++ > 0);
  1678. if (hasFragData1)
  1679. {
  1680. addFragData(preprocessor, data, 1, arg++ > 0);
  1681. }
  1682. if (hasFragData2)
  1683. {
  1684. addFragData(preprocessor, data, 2, arg++ > 0);
  1685. }
  1686. if (hasFragData3)
  1687. {
  1688. addFragData(preprocessor, data, 3, arg++ > 0);
  1689. }
  1690. if (hasFragDepth)
  1691. {
  1692. preprocessor.writef(
  1693. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1694. , arg++ > 0 ? ", " : " "
  1695. );
  1696. }
  1697. if (hasFrontFacing)
  1698. {
  1699. preprocessor.writef(
  1700. " \\\n\t%sfloat __vface : VFACE"
  1701. , arg++ > 0 ? ", " : " "
  1702. );
  1703. }
  1704. preprocessor.writef(
  1705. " \\\n\t)\n"
  1706. );
  1707. if (hasFrontFacing)
  1708. {
  1709. preprocessor.writef(
  1710. "#define gl_FrontFacing (__vface <= 0.0)\n"
  1711. );
  1712. }
  1713. }
  1714. else
  1715. {
  1716. const char* brace = strstr(entry, "{");
  1717. if (NULL != brace)
  1718. {
  1719. const char* end = bx::strmb(brace, '{', '}');
  1720. if (NULL != end)
  1721. {
  1722. strins(const_cast<char*>(end), "__RETURN__;\n");
  1723. }
  1724. }
  1725. preprocessor.writef(
  1726. "struct Output\n"
  1727. "{\n"
  1728. "\tvec4 gl_Position : SV_POSITION;\n"
  1729. "#define gl_Position _varying_.gl_Position\n"
  1730. );
  1731. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1732. {
  1733. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1734. if (varyingIt != varyingMap.end() )
  1735. {
  1736. const Varying& var = varyingIt->second;
  1737. preprocessor.writef("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1738. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  1739. }
  1740. }
  1741. preprocessor.writef(
  1742. "};\n"
  1743. );
  1744. preprocessor.writef("#define void_main() \\\n");
  1745. preprocessor.writef("Output main(");
  1746. bool first = true;
  1747. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1748. {
  1749. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1750. if (varyingIt != varyingMap.end() )
  1751. {
  1752. const Varying& var = varyingIt->second;
  1753. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1754. first = false;
  1755. }
  1756. }
  1757. preprocessor.writef(
  1758. ") \\\n"
  1759. "{ \\\n"
  1760. "\tOutput _varying_;"
  1761. );
  1762. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1763. {
  1764. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1765. if (varyingIt != varyingMap.end() )
  1766. {
  1767. const Varying& var = varyingIt->second;
  1768. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  1769. }
  1770. }
  1771. preprocessor.writef(
  1772. "\n#define __RETURN__ \\\n"
  1773. "\t} \\\n"
  1774. "\treturn _varying_"
  1775. );
  1776. }
  1777. }
  1778. if (preprocessor.run(input) )
  1779. {
  1780. BX_TRACE("Input file: %s", filePath);
  1781. BX_TRACE("Output file: %s", outFilePath);
  1782. if (preprocessOnly)
  1783. {
  1784. bx::CrtFileWriter writer;
  1785. if (0 != writer.open(outFilePath) )
  1786. {
  1787. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1788. return EXIT_FAILURE;
  1789. }
  1790. if (glsl)
  1791. {
  1792. const char* profile = cmdLine.findOption('p', "profile");
  1793. if (NULL == profile)
  1794. {
  1795. writef(&writer
  1796. , "#ifdef GL_ES\n"
  1797. "precision highp float;\n"
  1798. "#endif // GL_ES\n\n"
  1799. );
  1800. }
  1801. }
  1802. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1803. writer.close();
  1804. return EXIT_SUCCESS;
  1805. }
  1806. bool compiled = false;
  1807. {
  1808. bx::CrtFileWriter* writer = NULL;
  1809. if (NULL != bin2c)
  1810. {
  1811. writer = new Bin2cWriter(bin2c);
  1812. }
  1813. else
  1814. {
  1815. writer = new bx::CrtFileWriter;
  1816. }
  1817. if (0 != writer->open(outFilePath) )
  1818. {
  1819. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1820. return EXIT_FAILURE;
  1821. }
  1822. if (fragment)
  1823. {
  1824. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  1825. bx::write(writer, inputHash);
  1826. }
  1827. else
  1828. {
  1829. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  1830. bx::write(writer, outputHash);
  1831. }
  1832. if (glsl)
  1833. {
  1834. std::string code;
  1835. bool hasTextureLod = NULL != bx::findIdentifierMatch(data, s_ARB_shader_texture_lod /*EXT_shader_texture_lod*/);
  1836. if (0 == gles)
  1837. {
  1838. bx::stringPrintf(code, "#version %s\n", profile);
  1839. int32_t version = atoi(profile);
  1840. bx::stringPrintf(code
  1841. , "#define bgfxShadow2D shadow2D\n"
  1842. "#define bgfxShadow2DProj shadow2DProj\n"
  1843. );
  1844. if (hasTextureLod
  1845. && 130 > version)
  1846. {
  1847. bx::stringPrintf(code
  1848. , "#extension GL_ARB_shader_texture_lod : enable\n"
  1849. );
  1850. }
  1851. }
  1852. else
  1853. {
  1854. // Pretend that all extensions are available.
  1855. // This will be stripped later.
  1856. if (hasTextureLod)
  1857. {
  1858. bx::stringPrintf(code
  1859. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1860. "#define texture2DLod texture2DLodEXT\n"
  1861. "#define texture2DProjLod texture2DProjLodEXT\n"
  1862. "#define textureCubeLod textureCubeLodEXT\n"
  1863. // "#define texture2DGrad texture2DGradEXT\n"
  1864. // "#define texture2DProjGrad texture2DProjGradEXT\n"
  1865. // "#define textureCubeGrad textureCubeGradEXT\n"
  1866. );
  1867. }
  1868. if (NULL != bx::findIdentifierMatch(data, s_OES_standard_derivatives) )
  1869. {
  1870. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  1871. }
  1872. if (NULL != bx::findIdentifierMatch(data, s_OES_texture_3D) )
  1873. {
  1874. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  1875. }
  1876. if (NULL != bx::findIdentifierMatch(data, s_EXT_shadow_samplers) )
  1877. {
  1878. bx::stringPrintf(code
  1879. , "#extension GL_EXT_shadow_samplers : enable\n"
  1880. "#define shadow2D shadow2DEXT\n"
  1881. "#define shadow2DProj shadow2DProjEXT\n"
  1882. );
  1883. }
  1884. if (NULL != bx::findIdentifierMatch(data, "gl_FragDepth") )
  1885. {
  1886. bx::stringPrintf(code
  1887. , "#extension GL_EXT_frag_depth : enable\n"
  1888. "#define gl_FragDepth gl_FragDepthEXT\n"
  1889. );
  1890. }
  1891. }
  1892. code += preprocessor.m_preprocessed;
  1893. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  1894. }
  1895. else
  1896. {
  1897. if (hlsl > 3)
  1898. {
  1899. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1900. }
  1901. else
  1902. {
  1903. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1904. }
  1905. }
  1906. writer->close();
  1907. delete writer;
  1908. }
  1909. if (compiled)
  1910. {
  1911. if (depends)
  1912. {
  1913. std::string ofp = outFilePath;
  1914. ofp += ".d";
  1915. bx::CrtFileWriter writer;
  1916. if (0 == writer.open(ofp.c_str() ) )
  1917. {
  1918. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1919. writer.close();
  1920. }
  1921. }
  1922. return EXIT_SUCCESS;
  1923. }
  1924. }
  1925. }
  1926. delete [] data;
  1927. }
  1928. remove(outFilePath);
  1929. fprintf(stderr, "Failed to build shader.\n");
  1930. return EXIT_FAILURE;
  1931. }