shaderc.cpp 41 KB

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