shaderc.cpp 41 KB

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