shaderc.cpp 44 KB

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