shaderc.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /*
  2. * Copyright 2011-2012 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <stdio.h>
  6. #include <stdint.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <string>
  10. #include <vector>
  11. #include "glsl_optimizer.h"
  12. #define MAX_TAGS 256
  13. extern "C" {
  14. # include <fpp.h>
  15. } // extern "C"
  16. #if 0
  17. # define BX_TRACE(_format, ...) fprintf(stderr, "" _format "\n", ##__VA_ARGS__)
  18. #endif // DEBUG
  19. #define BX_NAMESPACE 1
  20. #include <bx/bx.h>
  21. #if BX_PLATFORM_LINUX
  22. # define _stricmp strcasecmp
  23. #endif // BX_PLATFORM_LINUX
  24. #include <bx/commandline.h>
  25. #include <bx/countof.h>
  26. #include <bx/endian.h>
  27. #include <bx/uint32_t.h>
  28. #if BX_PLATFORM_WINDOWS
  29. # include <d3dx9.h>
  30. #endif // BX_PLATFORM_WINDOWS
  31. long int fsize(FILE* _file)
  32. {
  33. long int pos = ftell(_file);
  34. fseek(_file, 0L, SEEK_END);
  35. long int size = ftell(_file);
  36. fseek(_file, pos, SEEK_SET);
  37. return size;
  38. }
  39. struct ConstantType
  40. {
  41. enum Enum
  42. {
  43. Uniform1i,
  44. Uniform1f,
  45. End,
  46. Uniform1iv,
  47. Uniform1fv,
  48. Uniform2fv,
  49. Uniform3fv,
  50. Uniform4fv,
  51. Uniform3x3fv,
  52. Uniform4x4fv,
  53. Count,
  54. TypeMask = 0x7f,
  55. FragmentBit = 0x80
  56. };
  57. };
  58. static const char* s_constantTypeName[ConstantType::Count] =
  59. {
  60. "int",
  61. "float",
  62. NULL,
  63. "int",
  64. "float",
  65. "float2",
  66. "float3",
  67. "float4",
  68. "float3x3",
  69. "float4x4",
  70. };
  71. struct Uniform
  72. {
  73. std::string name;
  74. ConstantType::Enum type;
  75. uint8_t num;
  76. uint16_t regIndex;
  77. uint16_t regCount;
  78. };
  79. typedef std::vector<Uniform> UniformArray;
  80. #if BX_PLATFORM_WINDOWS
  81. struct ConstRemap
  82. {
  83. ConstantType::Enum id;
  84. D3DXPARAMETER_CLASS paramClass;
  85. D3DXPARAMETER_TYPE paramType;
  86. uint32_t paramBytes;
  87. };
  88. static const ConstRemap s_constRemap[7] =
  89. {
  90. { ConstantType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 4 },
  91. { ConstantType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 4 },
  92. { ConstantType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 8 },
  93. { ConstantType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 12 },
  94. { ConstantType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 16 },
  95. { ConstantType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 36 },
  96. { ConstantType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 64 },
  97. };
  98. ConstantType::Enum findConstantType(const D3DXCONSTANT_DESC& constDesc)
  99. {
  100. uint32_t count = sizeof(s_constRemap)/sizeof(ConstRemap);
  101. for (uint32_t ii = 0; ii < count; ++ii)
  102. {
  103. const ConstRemap& remap = s_constRemap[ii];
  104. if (remap.paramClass == constDesc.Class
  105. && remap.paramType == constDesc.Type
  106. && (constDesc.Bytes%remap.paramBytes) == 0)
  107. {
  108. return remap.id;
  109. }
  110. }
  111. return ConstantType::Count;
  112. }
  113. static uint32_t s_optimizationLevel[4] =
  114. {
  115. D3DXSHADER_OPTIMIZATION_LEVEL0,
  116. D3DXSHADER_OPTIMIZATION_LEVEL1,
  117. D3DXSHADER_OPTIMIZATION_LEVEL2,
  118. D3DXSHADER_OPTIMIZATION_LEVEL3,
  119. };
  120. #endif // BX_PLATFORM_WINDOWS
  121. class Stream
  122. {
  123. public:
  124. Stream(FILE* _file, bool _bigEndian = false)
  125. : m_file(_file)
  126. , m_bigEndian(_bigEndian)
  127. {
  128. }
  129. ~Stream()
  130. {
  131. }
  132. void close()
  133. {
  134. m_file = NULL;
  135. }
  136. void write(const char* _str)
  137. {
  138. if (NULL != m_file)
  139. {
  140. fwrite(_str, strlen(_str), 1, m_file);
  141. }
  142. }
  143. void write(const void* _data, size_t _size)
  144. {
  145. if (NULL != m_file)
  146. {
  147. fwrite(_data, _size, 1, m_file);
  148. }
  149. }
  150. template<typename Ty>
  151. void write(Ty _value)
  152. {
  153. Ty temp = m_bigEndian ? bx::bigEndian<Ty>(_value) : _value;
  154. write(&temp, sizeof(Ty) );
  155. }
  156. private:
  157. FILE* m_file;
  158. bool m_bigEndian;
  159. };
  160. bool compileGLSLShader(CommandLine& _cmdLine, const std::string& _code, const char* _outFilePath)
  161. {
  162. const glslopt_shader_type type = (0 == _stricmp(_cmdLine.findOption('\0', "type"), "fragment") ) ? kGlslOptShaderFragment : kGlslOptShaderVertex;
  163. glslopt_ctx* ctx = glslopt_initialize(false);
  164. glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
  165. if( !glslopt_get_status(shader) )
  166. {
  167. fprintf(stderr, "Code:\n---\n%s\n---\n", _code.c_str() );
  168. fprintf(stderr, "Error: %s\n", glslopt_get_log(shader) );
  169. glslopt_cleanup(ctx);
  170. return false;
  171. }
  172. const char* optimizedShader = glslopt_get_output(shader);
  173. FILE* out = fopen(_outFilePath, "wb");
  174. if (NULL == out)
  175. {
  176. fprintf(stderr, "Unable to open output file '%s'.", _outFilePath);
  177. glslopt_cleanup(ctx);
  178. return false;
  179. }
  180. Stream stream(out);
  181. stream.write("precision highp float;\n\n");
  182. stream.write(optimizedShader, strlen(optimizedShader) );
  183. uint8_t nul = 0;
  184. stream.write(nul);
  185. stream.close();
  186. fclose(out);
  187. glslopt_cleanup(ctx);
  188. return true;
  189. }
  190. bool compileHLSLShader(CommandLine& _cmdLine, const std::string& _code, const char* _outFilePath)
  191. {
  192. #if BX_PLATFORM_WINDOWS
  193. const char* profile = _cmdLine.findOption('p');
  194. if (NULL == profile)
  195. {
  196. printf("Shader profile must be specified.\n");
  197. return false;
  198. }
  199. bool bigEndian = _cmdLine.hasArg('\0', "xbox360");
  200. uint32_t flags = 0;
  201. flags |= _cmdLine.hasArg('\0', "debug") ? D3DXSHADER_DEBUG : 0;
  202. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
  203. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
  204. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
  205. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
  206. uint32_t optimization = 3;
  207. if (_cmdLine.hasArg(optimization, 'O') )
  208. {
  209. optimization = bx::uint32_min(optimization, countof(s_optimizationLevel)-1);
  210. flags |= s_optimizationLevel[optimization];
  211. }
  212. else
  213. {
  214. flags |= D3DXSHADER_SKIPOPTIMIZATION;
  215. }
  216. BX_TRACE("Profile: %s", profile);
  217. BX_TRACE("Flags: 0x%08x", flags);
  218. BX_TRACE("Big Endian: %s", bigEndian?"true":"false");
  219. LPD3DXBUFFER code;
  220. LPD3DXBUFFER errorMsg;
  221. LPD3DXCONSTANTTABLE constantTable;
  222. HRESULT hr = D3DXCompileShader(_code.c_str()
  223. , _code.size()
  224. , NULL
  225. , NULL
  226. , "main"
  227. , profile
  228. , flags
  229. , &code
  230. , &errorMsg
  231. , &constantTable
  232. );
  233. if (FAILED(hr) )
  234. {
  235. fprintf(stderr, "Code:\n---\n%s\n---\n", _code.c_str() );
  236. fprintf(stderr, "Error: 0x%08x %s\n", hr, errorMsg->GetBufferPointer() );
  237. return false;
  238. }
  239. D3DXCONSTANTTABLE_DESC desc;
  240. hr = constantTable->GetDesc(&desc);
  241. if (FAILED(hr) )
  242. {
  243. fprintf(stderr, "Error 0x%08x\n", hr);
  244. return false;
  245. }
  246. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  247. BX_TRACE("Num constants: %d", desc.Constants);
  248. BX_TRACE("# cl ty RxC S By Name");
  249. UniformArray uniforms;
  250. for (uint32_t ii = 0; ii < desc.Constants; ++ii)
  251. {
  252. D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
  253. D3DXCONSTANT_DESC constDesc;
  254. uint32_t count;
  255. constantTable->GetConstantDesc(handle, &constDesc, &count);
  256. BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
  257. , ii
  258. , constDesc.Class
  259. , constDesc.Type
  260. , constDesc.Rows
  261. , constDesc.Columns
  262. , constDesc.StructMembers
  263. , constDesc.Bytes
  264. , constDesc.Name
  265. , constDesc.Elements
  266. , constDesc.RegisterIndex
  267. , constDesc.RegisterCount
  268. );
  269. ConstantType::Enum type = findConstantType(constDesc);
  270. if (ConstantType::Count != type)
  271. {
  272. Uniform un;
  273. un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
  274. un.type = type;
  275. un.num = constDesc.Elements;
  276. un.regIndex = constDesc.RegisterIndex;
  277. un.regCount = constDesc.RegisterCount;
  278. uniforms.push_back(un);
  279. }
  280. }
  281. FILE* out = fopen(_outFilePath, "wb");
  282. if (NULL == out)
  283. {
  284. fprintf(stderr, "Unable to open output file '%s'.", _outFilePath);
  285. return false;
  286. }
  287. Stream stream(out, bigEndian);
  288. uint16_t count = (uint16_t)uniforms.size();
  289. stream.write(count);
  290. uint32_t fragmentBit = profile[0] == 'p' ? ConstantType::FragmentBit : 0;
  291. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  292. {
  293. const Uniform& un = *it;
  294. uint8_t nameSize = (uint8_t)un.name.size();
  295. stream.write(nameSize);
  296. stream.write(un.name.c_str(), nameSize);
  297. stream.write<uint8_t>(un.type|fragmentBit);
  298. stream.write(un.num);
  299. stream.write(un.regIndex);
  300. stream.write(un.regCount);
  301. BX_TRACE("%s, %s, %d, %d, %d"
  302. , un.name.c_str()
  303. , s_constantTypeName[un.type]
  304. , un.num
  305. , un.regIndex
  306. , un.regCount
  307. );
  308. }
  309. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  310. stream.write(shaderSize);
  311. stream.write(code->GetBufferPointer(), shaderSize);
  312. uint8_t nul = 0;
  313. stream.write(nul);
  314. stream.close();
  315. fclose(out);
  316. if (NULL != code)
  317. {
  318. code->Release();
  319. }
  320. if (NULL != errorMsg)
  321. {
  322. errorMsg->Release();
  323. }
  324. if (NULL != constantTable)
  325. {
  326. constantTable->Release();
  327. }
  328. return true;
  329. #else
  330. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  331. return false;
  332. #endif // BX_PLATFORM_WINDOWS
  333. }
  334. struct Preprocessor
  335. {
  336. Preprocessor(const char* _filePath)
  337. : m_tagptr(m_tags)
  338. , m_scratchPos(0)
  339. , m_fgetsPos(0)
  340. {
  341. m_filePath = scratch(_filePath);
  342. m_tagptr->tag = FPPTAG_USERDATA;
  343. m_tagptr->data = this;
  344. m_tagptr++;
  345. m_tagptr->tag = FPPTAG_INPUT;
  346. m_tagptr->data = (void*)fppInput;
  347. m_tagptr++;
  348. m_tagptr->tag = FPPTAG_OUTPUT;
  349. m_tagptr->data = (void*)fppOutput;
  350. m_tagptr++;
  351. m_tagptr->tag = FPPTAG_ERROR;
  352. m_tagptr->data = (void*)fppError;
  353. m_tagptr++;
  354. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  355. m_tagptr->data = (void*)0;
  356. m_tagptr++;
  357. m_tagptr->tag = FPPTAG_LINE;
  358. m_tagptr->data = (void*)0;
  359. m_tagptr++;
  360. m_tagptr->tag = FPPTAG_INPUT_NAME;
  361. m_tagptr->data = m_filePath;
  362. m_tagptr++;
  363. m_default = "#define lowp\n#define mediump\n#define highp\n";
  364. }
  365. void setDefine(const char* _define)
  366. {
  367. m_tagptr->tag = FPPTAG_DEFINE;
  368. m_tagptr->data = scratch(_define);
  369. m_tagptr++;
  370. }
  371. void setDefaultDefine(const char* _name)
  372. {
  373. char temp[1024];
  374. _snprintf(temp, countof(temp)
  375. , "#ifndef %s\n"
  376. "# define %s 0\n"
  377. "#endif // %s\n"
  378. "\n"
  379. , _name
  380. , _name
  381. , _name
  382. );
  383. m_default += temp;
  384. }
  385. bool run()
  386. {
  387. m_fgetsPos = 0;
  388. FILE* file = fopen(m_filePath, "r");
  389. long int size = fsize(file);
  390. char* input = new char[size+1];
  391. size = fread(input, 1, size, file);
  392. input[size] = '\0';
  393. fclose(file);
  394. m_input = m_default;
  395. m_input += input;
  396. fppTag* tagptr = m_tagptr;
  397. tagptr->tag = FPPTAG_END;
  398. tagptr->data = 0;
  399. tagptr++;
  400. int result = fppPreProcess(m_tags);
  401. return 0 == result;
  402. }
  403. char* fgets(char* _buffer, int _size)
  404. {
  405. int ii = 0;
  406. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  407. {
  408. _buffer[ii++] = ch;
  409. if (ch == '\n' || ii == _size)
  410. {
  411. _buffer[ii] = '\0';
  412. m_fgetsPos++;
  413. return _buffer;
  414. }
  415. }
  416. return NULL;
  417. }
  418. static char* fppInput(char* _buffer, int _size, void* _userData)
  419. {
  420. Preprocessor* thisClass = (Preprocessor*)_userData;
  421. return thisClass->fgets(_buffer, _size);
  422. }
  423. static void fppOutput(int _ch, void* _userData)
  424. {
  425. Preprocessor* thisClass = (Preprocessor*)_userData;
  426. thisClass->m_preprocessed += _ch;
  427. }
  428. static void fppError(void* _userData, char* _format, va_list _vargs)
  429. {
  430. vfprintf(stderr, _format, _vargs);
  431. }
  432. char* scratch(const char* _str)
  433. {
  434. char* result = &m_scratch[m_scratchPos];
  435. strcpy(result, _str);
  436. m_scratchPos += strlen(_str)+1;
  437. return result;
  438. }
  439. fppTag m_tags[MAX_TAGS];
  440. fppTag* m_tagptr;
  441. char* m_filePath;
  442. std::string m_default;
  443. std::string m_input;
  444. std::string m_preprocessed;
  445. char m_scratch[16<<10];
  446. uint32_t m_scratchPos;
  447. uint32_t m_fgetsPos;
  448. };
  449. int main(int _argc, const char* _argv[])
  450. {
  451. CommandLine cmdLine(_argc, _argv);
  452. const char* filePath = cmdLine.findOption('f');
  453. if (NULL == filePath)
  454. {
  455. fprintf(stderr, "Shader file name must be specified.\n");
  456. return EXIT_FAILURE;
  457. }
  458. const char* outFilePath = cmdLine.findOption('o');
  459. if (NULL == outFilePath)
  460. {
  461. fprintf(stderr, "Output file name must be specified.\n");
  462. return EXIT_FAILURE;
  463. }
  464. const char* type = cmdLine.findOption('\0', "type");
  465. if (NULL == type)
  466. {
  467. fprintf(stderr, "Must specify shader type.");
  468. return EXIT_FAILURE;
  469. }
  470. const char* platform = cmdLine.findOption('\0', "platform");
  471. if (NULL == platform)
  472. {
  473. fprintf(stderr, "Must specify platform.\n");
  474. return EXIT_FAILURE;
  475. }
  476. bool preprocessOnly = cmdLine.hasArg("preprocess");
  477. Preprocessor preprocessor(filePath);
  478. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  479. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  480. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  481. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  482. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  483. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  484. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  485. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  486. bool glsl = false;
  487. if (0 == _stricmp(platform, "android") )
  488. {
  489. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  490. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  491. glsl = true;
  492. }
  493. else if (0 == _stricmp(platform, "nacl") )
  494. {
  495. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  496. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  497. glsl = true;
  498. }
  499. else if (0 == _stricmp(platform, "windows") )
  500. {
  501. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  502. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=1");
  503. }
  504. else if (0 == _stricmp(platform, "xbox360") )
  505. {
  506. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  507. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=1");
  508. }
  509. else
  510. {
  511. fprintf(stderr, "Unknown platform %s?!", platform);
  512. return EXIT_FAILURE;
  513. }
  514. switch (tolower(type[0]) )
  515. {
  516. case 'f':
  517. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  518. break;
  519. case 'v':
  520. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  521. break;
  522. default:
  523. fprintf(stderr, "Unknown type: %s?!", type);
  524. return EXIT_FAILURE;
  525. }
  526. if (preprocessor.run() )
  527. {
  528. BX_TRACE("Input file: %s", filePath);
  529. BX_TRACE("Output file: %s", outFilePath);
  530. if (preprocessOnly)
  531. {
  532. FILE* out = fopen(outFilePath, "wb");
  533. if (NULL == out)
  534. {
  535. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  536. return false;
  537. }
  538. Stream stream(out);
  539. if (glsl)
  540. {
  541. stream.write("precision highp float;\n\n");
  542. }
  543. stream.write(preprocessor.m_preprocessed.c_str(), preprocessor.m_preprocessed.size() );
  544. stream.close();
  545. fclose(out);
  546. return EXIT_SUCCESS;
  547. }
  548. if (glsl)
  549. {
  550. if (compileGLSLShader(cmdLine, preprocessor.m_preprocessed, outFilePath) )
  551. {
  552. return EXIT_SUCCESS;
  553. }
  554. }
  555. else
  556. {
  557. if (compileHLSLShader(cmdLine, preprocessor.m_preprocessed, outFilePath) )
  558. {
  559. return EXIT_SUCCESS;
  560. }
  561. }
  562. }
  563. fprintf(stderr, "Failed to build shader.\n");
  564. return EXIT_FAILURE;
  565. }