shaderc.cpp 41 KB

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