shaderc.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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, "Error %s\n%s\n", _code.c_str(), glslopt_get_log(shader) );
  168. glslopt_cleanup(ctx);
  169. return false;
  170. }
  171. const char* optimizedShader = glslopt_get_output(shader);
  172. FILE* out = fopen(_outFilePath, "wb");
  173. if (NULL == out)
  174. {
  175. fprintf(stderr, "Unable to open output file '%s'.", _outFilePath);
  176. glslopt_cleanup(ctx);
  177. return false;
  178. }
  179. Stream stream(out);
  180. stream.write("precision highp float;\n\n");
  181. stream.write(optimizedShader, strlen(optimizedShader) );
  182. uint8_t nul = 0;
  183. stream.write(nul);
  184. stream.close();
  185. fclose(out);
  186. glslopt_cleanup(ctx);
  187. return true;
  188. }
  189. bool compileHLSLShader(CommandLine& _cmdLine, const std::string& _code, const char* _outFilePath)
  190. {
  191. #if BX_PLATFORM_WINDOWS
  192. const char* profile = _cmdLine.findOption('p');
  193. if (NULL == profile)
  194. {
  195. printf("Shader profile must be specified.\n");
  196. return false;
  197. }
  198. bool bigEndian = _cmdLine.hasArg('\0', "xbox360");
  199. uint32_t flags = 0;
  200. flags |= _cmdLine.hasArg('\0', "debug") ? D3DXSHADER_DEBUG : 0;
  201. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
  202. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
  203. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
  204. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
  205. uint32_t optimization = 3;
  206. if (_cmdLine.hasArg(optimization, 'O') )
  207. {
  208. optimization = bx::uint32_min(optimization, countof(s_optimizationLevel)-1);
  209. flags |= s_optimizationLevel[optimization];
  210. }
  211. else
  212. {
  213. flags |= D3DXSHADER_SKIPOPTIMIZATION;
  214. }
  215. BX_TRACE("Profile: %s", profile);
  216. BX_TRACE("Flags: 0x%08x", flags);
  217. BX_TRACE("Big Endian: %s", bigEndian?"true":"false");
  218. LPD3DXBUFFER code;
  219. LPD3DXBUFFER errorMsg;
  220. LPD3DXCONSTANTTABLE constantTable;
  221. HRESULT hr = D3DXCompileShader(_code.c_str()
  222. , _code.size()
  223. , NULL
  224. , NULL
  225. , "main"
  226. , profile
  227. , flags
  228. , &code
  229. , &errorMsg
  230. , &constantTable
  231. );
  232. if (FAILED(hr) )
  233. {
  234. fprintf(stderr, "0x%08x: %s\n", hr, errorMsg->GetBufferPointer() );
  235. return false;
  236. }
  237. D3DXCONSTANTTABLE_DESC desc;
  238. hr = constantTable->GetDesc(&desc);
  239. if (FAILED(hr) )
  240. {
  241. fprintf(stderr, "Error 0x%08x\n", hr);
  242. return false;
  243. }
  244. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  245. BX_TRACE("Num constants: %d", desc.Constants);
  246. BX_TRACE("# cl ty RxC S By Name");
  247. UniformArray uniforms;
  248. for (uint32_t ii = 0; ii < desc.Constants; ++ii)
  249. {
  250. D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
  251. D3DXCONSTANT_DESC constDesc;
  252. uint32_t count;
  253. constantTable->GetConstantDesc(handle, &constDesc, &count);
  254. BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
  255. , ii
  256. , constDesc.Class
  257. , constDesc.Type
  258. , constDesc.Rows
  259. , constDesc.Columns
  260. , constDesc.StructMembers
  261. , constDesc.Bytes
  262. , constDesc.Name
  263. , constDesc.Elements
  264. , constDesc.RegisterIndex
  265. , constDesc.RegisterCount
  266. );
  267. ConstantType::Enum type = findConstantType(constDesc);
  268. if (ConstantType::Count != type)
  269. {
  270. Uniform un;
  271. un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
  272. un.type = type;
  273. un.num = constDesc.Elements;
  274. un.regIndex = constDesc.RegisterIndex;
  275. un.regCount = constDesc.RegisterCount;
  276. uniforms.push_back(un);
  277. }
  278. }
  279. FILE* out = fopen(_outFilePath, "wb");
  280. if (NULL == out)
  281. {
  282. fprintf(stderr, "Unable to open output file '%s'.", _outFilePath);
  283. return false;
  284. }
  285. Stream stream(out, bigEndian);
  286. uint16_t count = (uint16_t)uniforms.size();
  287. stream.write(count);
  288. uint32_t fragmentBit = profile[0] == 'p' ? ConstantType::FragmentBit : 0;
  289. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  290. {
  291. const Uniform& un = *it;
  292. uint8_t nameSize = (uint8_t)un.name.size();
  293. stream.write(nameSize);
  294. stream.write(un.name.c_str(), nameSize);
  295. stream.write<uint8_t>(un.type|fragmentBit);
  296. stream.write(un.num);
  297. stream.write(un.regIndex);
  298. stream.write(un.regCount);
  299. BX_TRACE("%s, %s, %d, %d, %d"
  300. , un.name.c_str()
  301. , s_constantTypeName[un.type]
  302. , un.num
  303. , un.regIndex
  304. , un.regCount
  305. );
  306. }
  307. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  308. stream.write(shaderSize);
  309. stream.write(code->GetBufferPointer(), shaderSize);
  310. uint8_t nul = 0;
  311. stream.write(nul);
  312. stream.close();
  313. fclose(out);
  314. if (NULL != code)
  315. {
  316. code->Release();
  317. }
  318. if (NULL != errorMsg)
  319. {
  320. errorMsg->Release();
  321. }
  322. if (NULL != constantTable)
  323. {
  324. constantTable->Release();
  325. }
  326. return true;
  327. #else
  328. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  329. return false;
  330. #endif // BX_PLATFORM_WINDOWS
  331. }
  332. struct Preprocessor
  333. {
  334. Preprocessor(const char* _filePath)
  335. : m_tagptr(m_tags)
  336. , m_scratchPos(0)
  337. , m_fgetsPos(0)
  338. {
  339. m_filePath = scratch(_filePath);
  340. m_tagptr->tag = FPPTAG_USERDATA;
  341. m_tagptr->data = this;
  342. m_tagptr++;
  343. m_tagptr->tag = FPPTAG_INPUT;
  344. m_tagptr->data = (void*)fppInput;
  345. m_tagptr++;
  346. m_tagptr->tag = FPPTAG_OUTPUT;
  347. m_tagptr->data = (void*)fppOutput;
  348. m_tagptr++;
  349. m_tagptr->tag = FPPTAG_ERROR;
  350. m_tagptr->data = (void*)fppError;
  351. m_tagptr++;
  352. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  353. m_tagptr->data = (void*)0;
  354. m_tagptr++;
  355. m_tagptr->tag = FPPTAG_LINE;
  356. m_tagptr->data = (void*)0;
  357. m_tagptr++;
  358. m_tagptr->tag = FPPTAG_INPUT_NAME;
  359. m_tagptr->data = m_filePath;
  360. m_tagptr++;
  361. m_default = "#define lowp\n#define mediump\n#define highp\n";
  362. }
  363. void setDefine(const char* _define)
  364. {
  365. m_tagptr->tag = FPPTAG_DEFINE;
  366. m_tagptr->data = scratch(_define);
  367. m_tagptr++;
  368. }
  369. void setDefaultDefine(const char* _name)
  370. {
  371. char temp[1024];
  372. _snprintf(temp, countof(temp)
  373. , "#ifndef %s\n"
  374. "# define %s 0\n"
  375. "#endif // %s\n"
  376. "\n"
  377. , _name
  378. , _name
  379. , _name
  380. );
  381. m_default += temp;
  382. }
  383. bool run()
  384. {
  385. m_fgetsPos = 0;
  386. FILE* file = fopen(m_filePath, "r");
  387. long int size = fsize(file);
  388. char* input = new char[size+1];
  389. fread(input, size, 1, file);
  390. input[size] = '\0';
  391. m_input = m_default;
  392. m_input += input;
  393. fclose(file);
  394. fppTag* tagptr = m_tagptr;
  395. tagptr->tag = FPPTAG_END;
  396. tagptr->data = 0;
  397. tagptr++;
  398. int result = fppPreProcess(m_tags);
  399. return 0 == result;
  400. }
  401. char* fgets(char* _buffer, int _size)
  402. {
  403. int ii = 0;
  404. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  405. {
  406. _buffer[ii++] = ch;
  407. if (ch == '\n' || ii == _size)
  408. {
  409. _buffer[ii] = '\0';
  410. m_fgetsPos++;
  411. return _buffer;
  412. }
  413. }
  414. return NULL;
  415. }
  416. static char* fppInput(char* _buffer, int _size, void* _userData)
  417. {
  418. Preprocessor* thisClass = (Preprocessor*)_userData;
  419. return thisClass->fgets(_buffer, _size);
  420. }
  421. static void fppOutput(int _ch, void* _userData)
  422. {
  423. Preprocessor* thisClass = (Preprocessor*)_userData;
  424. thisClass->m_preprocessed += _ch;
  425. }
  426. static void fppError(void* _userData, char* _format, va_list _vargs)
  427. {
  428. vfprintf(stderr, _format, _vargs);
  429. }
  430. char* scratch(const char* _str)
  431. {
  432. char* result = &m_scratch[m_scratchPos];
  433. strcpy(result, _str);
  434. m_scratchPos += strlen(_str)+1;
  435. return result;
  436. }
  437. fppTag m_tags[MAX_TAGS];
  438. fppTag* m_tagptr;
  439. char* m_filePath;
  440. std::string m_default;
  441. std::string m_input;
  442. std::string m_preprocessed;
  443. char m_scratch[16<<10];
  444. uint32_t m_scratchPos;
  445. uint32_t m_fgetsPos;
  446. };
  447. int main(int _argc, const char* _argv[])
  448. {
  449. CommandLine cmdLine(_argc, _argv);
  450. const char* filePath = cmdLine.findOption('f');
  451. if (NULL == filePath)
  452. {
  453. fprintf(stderr, "Shader file name must be specified.\n");
  454. return EXIT_FAILURE;
  455. }
  456. const char* outFilePath = cmdLine.findOption('o');
  457. if (NULL == outFilePath)
  458. {
  459. fprintf(stderr, "Output file name must be specified.\n");
  460. return EXIT_FAILURE;
  461. }
  462. const char* type = cmdLine.findOption('\0', "type");
  463. if (NULL == type)
  464. {
  465. fprintf(stderr, "Must specify shader type.");
  466. return EXIT_FAILURE;
  467. }
  468. const char* platform = cmdLine.findOption('\0', "platform");
  469. if (NULL == platform)
  470. {
  471. fprintf(stderr, "Must specify platform.\n");
  472. return EXIT_FAILURE;
  473. }
  474. bool preprocessOnly = cmdLine.hasArg("preprocess");
  475. Preprocessor preprocessor(filePath);
  476. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  477. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  478. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  479. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  480. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  481. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  482. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  483. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  484. bool glsl = false;
  485. if (0 == _stricmp(platform, "android") )
  486. {
  487. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  488. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  489. glsl = true;
  490. }
  491. else if (0 == _stricmp(platform, "nacl") )
  492. {
  493. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  494. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  495. glsl = true;
  496. }
  497. else if (0 == _stricmp(platform, "windows") )
  498. {
  499. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  500. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=1");
  501. }
  502. else if (0 == _stricmp(platform, "xbox360") )
  503. {
  504. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  505. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=1");
  506. }
  507. else
  508. {
  509. fprintf(stderr, "Unknown platform %s?!", platform);
  510. return EXIT_FAILURE;
  511. }
  512. if (0 == _stricmp(type, "fragment") )
  513. {
  514. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  515. }
  516. else
  517. {
  518. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  519. }
  520. if (preprocessor.run() )
  521. {
  522. BX_TRACE("Input file: %s", filePath);
  523. BX_TRACE("Output file: %s", outFilePath);
  524. if (preprocessOnly)
  525. {
  526. FILE* out = fopen(outFilePath, "wb");
  527. if (NULL == out)
  528. {
  529. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  530. return false;
  531. }
  532. Stream stream(out);
  533. if (glsl)
  534. {
  535. stream.write("precision highp float;\n\n");
  536. }
  537. stream.write(preprocessor.m_preprocessed.c_str(), preprocessor.m_preprocessed.size() );
  538. stream.close();
  539. fclose(out);
  540. return EXIT_SUCCESS;
  541. }
  542. if (glsl)
  543. {
  544. if (compileGLSLShader(cmdLine, preprocessor.m_preprocessed, outFilePath) )
  545. {
  546. return EXIT_SUCCESS;
  547. }
  548. }
  549. else
  550. {
  551. if (compileHLSLShader(cmdLine, preprocessor.m_preprocessed, outFilePath) )
  552. {
  553. return EXIT_SUCCESS;
  554. }
  555. }
  556. }
  557. fprintf(stderr, "Failed to build shader.\n");
  558. return EXIT_FAILURE;
  559. }