shaderc.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758
  1. /*
  2. * Copyright 2011-2014 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #define _BX_TRACE(_format, ...) \
  6. BX_MACRO_BLOCK_BEGIN \
  7. if (g_verbose) \
  8. { \
  9. fprintf(stderr, BX_FILE_LINE_LITERAL "" _format "\n", ##__VA_ARGS__); \
  10. } \
  11. BX_MACRO_BLOCK_END
  12. #define _BX_WARN(_condition, _format, ...) \
  13. BX_MACRO_BLOCK_BEGIN \
  14. if (!(_condition) ) \
  15. { \
  16. BX_TRACE("WARN " _format, ##__VA_ARGS__); \
  17. } \
  18. BX_MACRO_BLOCK_END
  19. #define _BX_CHECK(_condition, _format, ...) \
  20. BX_MACRO_BLOCK_BEGIN \
  21. if (!(_condition) ) \
  22. { \
  23. BX_TRACE("CHECK " _format, ##__VA_ARGS__); \
  24. bx::debugBreak(); \
  25. } \
  26. BX_MACRO_BLOCK_END
  27. #define BX_TRACE _BX_TRACE
  28. #define BX_WARN _BX_WARN
  29. #define BX_CHECK _BX_CHECK
  30. bool g_verbose = false;
  31. #include <bx/bx.h>
  32. #include <bx/debug.h>
  33. #define NOMINMAX
  34. #include <alloca.h>
  35. #include <stdio.h>
  36. #include <stdint.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <algorithm>
  40. #include <string>
  41. #include <vector>
  42. #include <unordered_map>
  43. #define MAX_TAGS 256
  44. extern "C"
  45. {
  46. #include <fpp.h>
  47. } // extern "C"
  48. #define BGFX_CHUNK_MAGIC_CSH BX_MAKEFOURCC('C', 'S', 'H', 0x0)
  49. #define BGFX_CHUNK_MAGIC_VSH BX_MAKEFOURCC('V', 'S', 'H', 0x2)
  50. #define BGFX_CHUNK_MAGIC_FSH BX_MAKEFOURCC('F', 'S', 'H', 0x2)
  51. #include <bx/commandline.h>
  52. #include <bx/endian.h>
  53. #include <bx/uint32_t.h>
  54. #include <bx/readerwriter.h>
  55. #include <bx/string.h>
  56. #include <bx/hash.h>
  57. #include "glsl_optimizer.h"
  58. #if BX_PLATFORM_WINDOWS
  59. # include <sal.h>
  60. # define __D3DX9MATH_INL__ // not used and MinGW complains about type-punning
  61. # include <d3dx9.h>
  62. # include <d3dcompiler.h>
  63. #endif // BX_PLATFORM_WINDOWS
  64. long int fsize(FILE* _file)
  65. {
  66. long int pos = ftell(_file);
  67. fseek(_file, 0L, SEEK_END);
  68. long int size = ftell(_file);
  69. fseek(_file, pos, SEEK_SET);
  70. return size;
  71. }
  72. struct Attrib
  73. {
  74. enum Enum
  75. {
  76. Position = 0,
  77. Normal,
  78. Tangent,
  79. Color0,
  80. Color1,
  81. Indices,
  82. Weight,
  83. TexCoord0,
  84. TexCoord1,
  85. TexCoord2,
  86. TexCoord3,
  87. TexCoord4,
  88. TexCoord5,
  89. TexCoord6,
  90. TexCoord7,
  91. Count,
  92. };
  93. };
  94. static const char* s_ARB_shader_texture_lod[] =
  95. {
  96. "texture2DLod",
  97. "texture2DProjLod",
  98. "texture3DLod",
  99. "texture3DProjLod",
  100. "textureCubeLod",
  101. "shadow2DLod",
  102. "shadow2DProjLod",
  103. NULL
  104. // "texture1DLod",
  105. // "texture1DProjLod",
  106. // "shadow1DLod",
  107. // "shadow1DProjLod",
  108. };
  109. static const char* s_EXT_shadow_samplers[] =
  110. {
  111. "shadow2D",
  112. "shadow2DProj",
  113. "sampler2DShadow",
  114. NULL
  115. };
  116. static const char* s_OES_standard_derivatives[] =
  117. {
  118. "dFdx",
  119. "dFdy",
  120. "fwidth",
  121. NULL
  122. };
  123. static const char* s_OES_texture_3D[] =
  124. {
  125. "texture3D",
  126. "texture3DProj",
  127. "texture3DLod",
  128. "texture3DProjLod",
  129. NULL
  130. };
  131. struct RemapInputSemantic
  132. {
  133. Attrib::Enum m_attr;
  134. const char* m_name;
  135. uint8_t m_index;
  136. };
  137. static const RemapInputSemantic s_remapInputSemantic[Attrib::Count+1] =
  138. {
  139. { Attrib::Position, "POSITION", 0 },
  140. { Attrib::Normal, "NORMAL", 0 },
  141. { Attrib::Tangent, "TANGENT", 0 },
  142. { Attrib::Color0, "COLOR", 0 },
  143. { Attrib::Color1, "COLOR", 1 },
  144. { Attrib::Indices, "BLENDINDICES", 0 },
  145. { Attrib::Weight, "BLENDWEIGHT", 0 },
  146. { Attrib::TexCoord0, "TEXCOORD", 0 },
  147. { Attrib::TexCoord1, "TEXCOORD", 1 },
  148. { Attrib::TexCoord2, "TEXCOORD", 2 },
  149. { Attrib::TexCoord3, "TEXCOORD", 3 },
  150. { Attrib::TexCoord4, "TEXCOORD", 4 },
  151. { Attrib::TexCoord5, "TEXCOORD", 5 },
  152. { Attrib::TexCoord6, "TEXCOORD", 6 },
  153. { Attrib::TexCoord7, "TEXCOORD", 7 },
  154. { Attrib::Count, "", 0 },
  155. };
  156. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  157. {
  158. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  159. {
  160. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  161. if (0 == strcmp(ris.m_name, _name)
  162. && ris.m_index == _index)
  163. {
  164. return ris;
  165. }
  166. }
  167. return s_remapInputSemantic[Attrib::Count];
  168. }
  169. struct UniformType
  170. {
  171. enum Enum
  172. {
  173. Uniform1i,
  174. Uniform1f,
  175. End,
  176. Uniform1iv,
  177. Uniform1fv,
  178. Uniform2fv,
  179. Uniform3fv,
  180. Uniform4fv,
  181. Uniform3x3fv,
  182. Uniform4x4fv,
  183. Count
  184. };
  185. };
  186. #define BGFX_UNIFORM_FRAGMENTBIT UINT8_C(0x10)
  187. const char* s_uniformTypeName[UniformType::Count] =
  188. {
  189. "int",
  190. "float",
  191. NULL,
  192. "int",
  193. "float",
  194. "vec2",
  195. "vec3",
  196. "vec4",
  197. "mat3",
  198. "mat4",
  199. };
  200. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  201. {
  202. for (uint32_t ii = 0; ii < UniformType::Count; ++ii)
  203. {
  204. if (NULL != s_uniformTypeName[ii]
  205. && 0 == strcmp(_name, s_uniformTypeName[ii]) )
  206. {
  207. return UniformType::Enum(ii);
  208. }
  209. }
  210. return UniformType::Count;
  211. }
  212. struct Uniform
  213. {
  214. std::string name;
  215. UniformType::Enum type;
  216. uint8_t num;
  217. uint16_t regIndex;
  218. uint16_t regCount;
  219. };
  220. typedef std::vector<Uniform> UniformArray;
  221. const char* interpolationDx11(const char* _glsl)
  222. {
  223. if (0 == strcmp(_glsl, "smooth") )
  224. {
  225. return "linear";
  226. }
  227. else if (0 == strcmp(_glsl, "flat") )
  228. {
  229. return "nointerpolation";
  230. }
  231. return _glsl; // noperspective
  232. }
  233. #if BX_PLATFORM_WINDOWS
  234. struct UniformRemapDx9
  235. {
  236. UniformType::Enum id;
  237. D3DXPARAMETER_CLASS paramClass;
  238. D3DXPARAMETER_TYPE paramType;
  239. uint8_t columns;
  240. uint8_t rows;
  241. };
  242. static const UniformRemapDx9 s_constRemapDx9[7] =
  243. {
  244. { UniformType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 0, 0 },
  245. { UniformType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 0, 0 },
  246. { UniformType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
  247. { UniformType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
  248. { UniformType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
  249. { UniformType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 3, 3 },
  250. { UniformType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 4, 4 },
  251. };
  252. UniformType::Enum findUniformTypeDx9(const D3DXCONSTANT_DESC& constDesc)
  253. {
  254. for (uint32_t ii = 0; ii < BX_COUNTOF(s_constRemapDx9); ++ii)
  255. {
  256. const UniformRemapDx9& remap = s_constRemapDx9[ii];
  257. if (remap.paramClass == constDesc.Class
  258. && remap.paramType == constDesc.Type)
  259. {
  260. if (D3DXPC_MATRIX_COLUMNS != constDesc.Class)
  261. {
  262. return remap.id;
  263. }
  264. if (remap.columns == constDesc.Columns
  265. && remap.rows == constDesc.Rows)
  266. {
  267. return remap.id;
  268. }
  269. }
  270. }
  271. return UniformType::Count;
  272. }
  273. static uint32_t s_optimizationLevelDx9[4] =
  274. {
  275. D3DXSHADER_OPTIMIZATION_LEVEL0,
  276. D3DXSHADER_OPTIMIZATION_LEVEL1,
  277. D3DXSHADER_OPTIMIZATION_LEVEL2,
  278. D3DXSHADER_OPTIMIZATION_LEVEL3,
  279. };
  280. struct UniformRemapDx11
  281. {
  282. UniformType::Enum id;
  283. D3D_SHADER_VARIABLE_CLASS paramClass;
  284. D3D_SHADER_VARIABLE_TYPE paramType;
  285. uint8_t columns;
  286. uint8_t rows;
  287. };
  288. static const UniformRemapDx11 s_constRemapDx11[7] =
  289. {
  290. { UniformType::Uniform1iv, D3D_SVC_SCALAR, D3D_SVT_INT, 0, 0 },
  291. { UniformType::Uniform1fv, D3D_SVC_SCALAR, D3D_SVT_FLOAT, 0, 0 },
  292. { UniformType::Uniform2fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  293. { UniformType::Uniform3fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  294. { UniformType::Uniform4fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  295. { UniformType::Uniform3x3fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 3, 3 },
  296. { UniformType::Uniform4x4fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 4, 4 },
  297. };
  298. UniformType::Enum findUniformTypeDx11(const D3D11_SHADER_TYPE_DESC& constDesc)
  299. {
  300. for (uint32_t ii = 0; ii < BX_COUNTOF(s_constRemapDx11); ++ii)
  301. {
  302. const UniformRemapDx11& remap = s_constRemapDx11[ii];
  303. if (remap.paramClass == constDesc.Class
  304. && remap.paramType == constDesc.Type)
  305. {
  306. if (D3D_SVC_MATRIX_COLUMNS != constDesc.Class)
  307. {
  308. return remap.id;
  309. }
  310. if (remap.columns == constDesc.Columns
  311. && remap.rows == constDesc.Rows)
  312. {
  313. return remap.id;
  314. }
  315. }
  316. }
  317. return UniformType::Count;
  318. }
  319. static uint32_t s_optimizationLevelDx11[4] =
  320. {
  321. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  322. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  323. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  324. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  325. };
  326. #endif // BX_PLATFORM_WINDOWS
  327. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  328. {
  329. va_list argList;
  330. va_start(argList, _format);
  331. char temp[2048];
  332. char* out = temp;
  333. int32_t max = sizeof(temp);
  334. int32_t len = bx::vsnprintf(out, max, _format, argList);
  335. if (len > max)
  336. {
  337. out = (char*)alloca(len);
  338. len = bx::vsnprintf(out, len, _format, argList);
  339. }
  340. len = bx::write(_writer, out, len);
  341. va_end(argList);
  342. return len;
  343. }
  344. class Bin2cWriter : public bx::CrtFileWriter
  345. {
  346. public:
  347. Bin2cWriter(const char* _name)
  348. : m_name(_name)
  349. {
  350. }
  351. virtual ~Bin2cWriter()
  352. {
  353. }
  354. virtual int32_t close() BX_OVERRIDE
  355. {
  356. generate();
  357. return bx::CrtFileWriter::close();
  358. }
  359. virtual int32_t write(const void* _data, int32_t _size) BX_OVERRIDE
  360. {
  361. const char* data = (const char*)_data;
  362. m_buffer.insert(m_buffer.end(), data, data+_size);
  363. return _size;
  364. }
  365. private:
  366. void generate()
  367. {
  368. #define HEX_DUMP_WIDTH 16
  369. #define HEX_DUMP_SPACE_WIDTH 96
  370. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  371. const uint8_t* data = &m_buffer[0];
  372. uint32_t size = (uint32_t)m_buffer.size();
  373. outf("static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size);
  374. if (NULL != data)
  375. {
  376. char hex[HEX_DUMP_SPACE_WIDTH+1];
  377. char ascii[HEX_DUMP_WIDTH+1];
  378. uint32_t hexPos = 0;
  379. uint32_t asciiPos = 0;
  380. for (uint32_t ii = 0; ii < size; ++ii)
  381. {
  382. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  383. hexPos += 6;
  384. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
  385. asciiPos++;
  386. if (HEX_DUMP_WIDTH == asciiPos)
  387. {
  388. ascii[asciiPos] = '\0';
  389. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  390. data += asciiPos;
  391. hexPos = 0;
  392. asciiPos = 0;
  393. }
  394. }
  395. if (0 != asciiPos)
  396. {
  397. ascii[asciiPos] = '\0';
  398. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  399. }
  400. }
  401. outf("};\n");
  402. #undef HEX_DUMP_WIDTH
  403. #undef HEX_DUMP_SPACE_WIDTH
  404. #undef HEX_DUMP_FORMAT
  405. }
  406. int32_t outf(const char* _format, ...)
  407. {
  408. va_list argList;
  409. va_start(argList, _format);
  410. char temp[2048];
  411. char* out = temp;
  412. int32_t max = sizeof(temp);
  413. int32_t len = bx::vsnprintf(out, max, _format, argList);
  414. if (len > max)
  415. {
  416. out = (char*)alloca(len);
  417. len = bx::vsnprintf(out, len, _format, argList);
  418. }
  419. int32_t size = bx::CrtFileWriter::write(out, len);
  420. va_end(argList);
  421. return size;
  422. }
  423. std::string m_filePath;
  424. std::string m_name;
  425. typedef std::vector<uint8_t> Buffer;
  426. Buffer m_buffer;
  427. };
  428. struct Varying
  429. {
  430. std::string m_precision;
  431. std::string m_interpolation;
  432. std::string m_name;
  433. std::string m_type;
  434. std::string m_init;
  435. std::string m_semantics;
  436. };
  437. typedef std::unordered_map<std::string, Varying> VaryingMap;
  438. class File
  439. {
  440. public:
  441. File(const char* _filePath)
  442. : m_data(NULL)
  443. {
  444. FILE* file = fopen(_filePath, "r");
  445. if (NULL != file)
  446. {
  447. m_size = fsize(file);
  448. m_data = new char[m_size+1];
  449. m_size = (uint32_t)fread(m_data, 1, m_size, file);
  450. m_data[m_size] = '\0';
  451. fclose(file);
  452. }
  453. }
  454. ~File()
  455. {
  456. delete [] m_data;
  457. }
  458. const char* getData() const
  459. {
  460. return m_data;
  461. }
  462. uint32_t getSize() const
  463. {
  464. return m_size;
  465. }
  466. private:
  467. char* m_data;
  468. uint32_t m_size;
  469. };
  470. void strins(char* _str, const char* _insert)
  471. {
  472. size_t len = strlen(_insert);
  473. memmove(&_str[len], _str, strlen(_str) );
  474. memcpy(_str, _insert, len);
  475. }
  476. void strreplace(char* _str, const char* _find, const char* _replace)
  477. {
  478. const size_t len = strlen(_find);
  479. char* replace = (char*)alloca(len+1);
  480. bx::strlcpy(replace, _replace, len+1);
  481. for (size_t ii = strlen(replace); ii < len; ++ii)
  482. {
  483. replace[ii] = ' ';
  484. }
  485. replace[len] = '\0';
  486. BX_CHECK(len >= strlen(_replace), "");
  487. for (char* ptr = strstr(_str, _find); NULL != ptr; ptr = strstr(ptr + len, _find) )
  488. {
  489. memcpy(ptr, replace, len);
  490. }
  491. }
  492. class LineReader
  493. {
  494. public:
  495. LineReader(const char* _str)
  496. : m_str(_str)
  497. , m_pos(0)
  498. , m_size( (uint32_t)strlen(_str) )
  499. {
  500. }
  501. std::string getLine()
  502. {
  503. const char* str = &m_str[m_pos];
  504. skipLine();
  505. const char* eol = &m_str[m_pos];
  506. std::string tmp;
  507. tmp.assign(str, eol-str);
  508. return tmp;
  509. }
  510. bool isEof() const
  511. {
  512. return m_str[m_pos] == '\0';
  513. }
  514. void skipLine()
  515. {
  516. const char* str = &m_str[m_pos];
  517. const char* nl = bx::strnl(str);
  518. m_pos += (uint32_t)(nl - str);
  519. }
  520. const char* m_str;
  521. uint32_t m_pos;
  522. uint32_t m_size;
  523. };
  524. void printCode(const char* _code, int32_t _line = 0, int32_t _start = 0, int32_t _end = INT32_MAX)
  525. {
  526. fprintf(stderr, "Code:\n---\n");
  527. LineReader lr(_code);
  528. for (int32_t line = 1; !lr.isEof() && line < _end; ++line)
  529. {
  530. if (line >= _start)
  531. {
  532. fprintf(stderr, "%s%3d: %s", _line == line ? ">>> " : " ", line, lr.getLine().c_str() );
  533. }
  534. else
  535. {
  536. lr.skipLine();
  537. }
  538. }
  539. fprintf(stderr, "---\n");
  540. }
  541. void writeFile(const char* _filePath, const void* _data, int32_t _size)
  542. {
  543. bx::CrtFileWriter out;
  544. if (0 == out.open(_filePath) )
  545. {
  546. out.write(_data, _size);
  547. out.close();
  548. }
  549. }
  550. bool compileGLSLShader(bx::CommandLine& _cmdLine, uint32_t _gles, const std::string& _code, bx::WriterI* _writer)
  551. {
  552. char ch = tolower(_cmdLine.findOption('\0', "type")[0]);
  553. const glslopt_shader_type type = ch == 'f'
  554. ? kGlslOptShaderFragment
  555. : (ch == 'c' ? kGlslOptShaderCompute : kGlslOptShaderVertex);
  556. glslopt_target target = kGlslTargetOpenGL;
  557. switch (_gles)
  558. {
  559. case 2:
  560. target = kGlslTargetOpenGLES20;
  561. break;
  562. case 3:
  563. target = kGlslTargetOpenGLES30;
  564. break;
  565. default:
  566. target = kGlslTargetOpenGL;
  567. break;
  568. }
  569. glslopt_ctx* ctx = glslopt_initialize(target);
  570. glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
  571. if (!glslopt_get_status(shader) )
  572. {
  573. const char* log = glslopt_get_log(shader);
  574. int32_t source = 0;
  575. int32_t line = 0;
  576. int32_t column = 0;
  577. int32_t start = 0;
  578. int32_t end = INT32_MAX;
  579. if (3 == sscanf(log, "%u:%u(%u):", &source, &line, &column)
  580. && 0 != line)
  581. {
  582. start = bx::uint32_imax(1, line-10);
  583. end = start + 20;
  584. }
  585. printCode(_code.c_str(), line, start, end);
  586. fprintf(stderr, "Error: %s\n", log);
  587. glslopt_cleanup(ctx);
  588. return false;
  589. }
  590. const char* optimizedShader = glslopt_get_output(shader);
  591. // Trim all directives.
  592. while ('#' == *optimizedShader)
  593. {
  594. optimizedShader = bx::strnl(optimizedShader);
  595. }
  596. if (0 != _gles)
  597. {
  598. char* shader = const_cast<char*>(optimizedShader);
  599. strreplace(shader, "gl_FragDepthEXT", "gl_FragDepth");
  600. strreplace(shader, "texture2DLodEXT", "texture2DLod");
  601. strreplace(shader, "texture2DProjLodEXT", "texture2DProjLod");
  602. strreplace(shader, "textureCubeLodEXT", "textureCubeLod");
  603. strreplace(shader, "texture2DGradEXT", "texture2DGrad");
  604. strreplace(shader, "texture2DProjGradEXT", "texture2DProjGrad");
  605. strreplace(shader, "textureCubeGradEXT", "textureCubeGrad");
  606. strreplace(shader, "shadow2DEXT", "shadow2D");
  607. strreplace(shader, "shadow2DProjEXT", "shadow2DProj");
  608. }
  609. UniformArray uniforms;
  610. {
  611. const char* parse = optimizedShader;
  612. while (NULL != parse
  613. && *parse != '\0')
  614. {
  615. parse = bx::strws(parse);
  616. const char* eol = strchr(parse, ';');
  617. if (NULL != eol)
  618. {
  619. const char* qualifier = parse;
  620. parse = bx::strws(bx::strword(parse) );
  621. if (0 == strncmp(qualifier, "attribute", 9)
  622. || 0 == strncmp(qualifier, "varying", 7) )
  623. {
  624. // skip attributes and varyings.
  625. parse = eol + 1;
  626. continue;
  627. }
  628. if (0 != strncmp(qualifier, "uniform", 7) )
  629. {
  630. // end if there is no uniform keyword.
  631. parse = NULL;
  632. continue;
  633. }
  634. const char* precision = NULL;
  635. const char* type = parse;
  636. if (0 == strncmp(type, "lowp", 4)
  637. || 0 == strncmp(type, "mediump", 7)
  638. || 0 == strncmp(type, "highp", 5) )
  639. {
  640. precision = type;
  641. type = parse = bx::strws(bx::strword(parse) );
  642. }
  643. BX_UNUSED(precision);
  644. char uniformType[256];
  645. parse = bx::strword(parse);
  646. if (0 == strncmp(type, "sampler", 7) )
  647. {
  648. strcpy(uniformType, "int");
  649. }
  650. else
  651. {
  652. bx::strlcpy(uniformType, type, parse-type+1);
  653. }
  654. const char* name = parse = bx::strws(parse);
  655. char uniformName[256];
  656. uint8_t num = 1;
  657. const char* array = bx::strnstr(name, "[", eol-parse);
  658. if (NULL != array)
  659. {
  660. bx::strlcpy(uniformName, name, array-name+1);
  661. char arraySize[32];
  662. const char* end = bx::strnstr(array, "]", eol-array);
  663. bx::strlcpy(arraySize, array+1, end-array);
  664. num = atoi(arraySize);
  665. }
  666. else
  667. {
  668. bx::strlcpy(uniformName, name, eol-name+1);
  669. }
  670. Uniform un;
  671. un.type = nameToUniformTypeEnum(uniformType);
  672. if (UniformType::Count != un.type)
  673. {
  674. BX_TRACE("name: %s (type %d, num %d)", uniformName, un.type, num);
  675. un.name = uniformName;
  676. un.num = num;
  677. un.regIndex = 0;
  678. un.regCount = num;
  679. uniforms.push_back(un);
  680. }
  681. parse = eol + 1;
  682. }
  683. }
  684. }
  685. uint16_t count = (uint16_t)uniforms.size();
  686. bx::write(_writer, count);
  687. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  688. {
  689. const Uniform& un = *it;
  690. uint8_t nameSize = (uint8_t)un.name.size();
  691. bx::write(_writer, nameSize);
  692. bx::write(_writer, un.name.c_str(), nameSize);
  693. uint8_t type = un.type;
  694. bx::write(_writer, type);
  695. bx::write(_writer, un.num);
  696. bx::write(_writer, un.regIndex);
  697. bx::write(_writer, un.regCount);
  698. BX_TRACE("%s, %s, %d, %d, %d"
  699. , un.name.c_str()
  700. , s_uniformTypeName[un.type]
  701. , un.num
  702. , un.regIndex
  703. , un.regCount
  704. );
  705. }
  706. uint32_t shaderSize = (uint32_t)strlen(optimizedShader);
  707. bx::write(_writer, shaderSize);
  708. bx::write(_writer, optimizedShader, shaderSize);
  709. uint8_t nul = 0;
  710. bx::write(_writer, nul);
  711. glslopt_cleanup(ctx);
  712. return true;
  713. }
  714. bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  715. {
  716. #if BX_PLATFORM_WINDOWS
  717. BX_TRACE("DX9");
  718. const char* profile = _cmdLine.findOption('p', "profile");
  719. if (NULL == profile)
  720. {
  721. fprintf(stderr, "Shader profile must be specified.\n");
  722. return false;
  723. }
  724. bool debug = _cmdLine.hasArg('\0', "debug");
  725. uint32_t flags = 0;
  726. flags |= debug ? D3DXSHADER_DEBUG : 0;
  727. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
  728. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
  729. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
  730. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
  731. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  732. bool werror = _cmdLine.hasArg('\0', "Werror");
  733. uint32_t optimization = 3;
  734. if (_cmdLine.hasArg(optimization, 'O') )
  735. {
  736. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx9)-1);
  737. flags |= s_optimizationLevelDx9[optimization];
  738. }
  739. else
  740. {
  741. flags |= D3DXSHADER_SKIPOPTIMIZATION;
  742. }
  743. BX_TRACE("Profile: %s", profile);
  744. BX_TRACE("Flags: 0x%08x", flags);
  745. LPD3DXBUFFER code;
  746. LPD3DXBUFFER errorMsg;
  747. LPD3DXCONSTANTTABLE constantTable;
  748. HRESULT hr;
  749. // Output preprocessed shader so that HLSL can be debugged via GPA
  750. // or PIX. Compiling through memory won't embed preprocessed shader
  751. // file path.
  752. if (debug)
  753. {
  754. std::string hlslfp = _cmdLine.findOption('o');
  755. hlslfp += ".hlsl";
  756. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  757. hr = D3DXCompileShaderFromFileA(hlslfp.c_str()
  758. , NULL
  759. , NULL
  760. , "main"
  761. , profile
  762. , flags
  763. , &code
  764. , &errorMsg
  765. , &constantTable
  766. );
  767. }
  768. else
  769. {
  770. hr = D3DXCompileShader(_code.c_str()
  771. , (uint32_t)_code.size()
  772. , NULL
  773. , NULL
  774. , "main"
  775. , profile
  776. , flags
  777. , &code
  778. , &errorMsg
  779. , &constantTable
  780. );
  781. }
  782. if (FAILED(hr)
  783. || (werror && NULL != errorMsg) )
  784. {
  785. const char* log = (const char*)errorMsg->GetBufferPointer();
  786. char source[1024];
  787. int32_t line = 0;
  788. int32_t column = 0;
  789. int32_t start = 0;
  790. int32_t end = INT32_MAX;
  791. if (3 == sscanf(log, "%[^(](%u,%u):", source, &line, &column)
  792. && 0 != line)
  793. {
  794. start = bx::uint32_imax(1, line-10);
  795. end = start + 20;
  796. }
  797. printCode(_code.c_str(), line, start, end);
  798. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  799. errorMsg->Release();
  800. return false;
  801. }
  802. D3DXCONSTANTTABLE_DESC desc;
  803. hr = constantTable->GetDesc(&desc);
  804. if (FAILED(hr) )
  805. {
  806. fprintf(stderr, "Error 0x%08x\n", (uint32_t)hr);
  807. return false;
  808. }
  809. BX_TRACE("Creator: %s 0x%08x", desc.Creator, (uint32_t /*mingw warning*/)desc.Version);
  810. BX_TRACE("Num constants: %d", desc.Constants);
  811. BX_TRACE("# cl ty RxC S By Name");
  812. UniformArray uniforms;
  813. for (uint32_t ii = 0; ii < desc.Constants; ++ii)
  814. {
  815. D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
  816. D3DXCONSTANT_DESC constDesc;
  817. uint32_t count;
  818. constantTable->GetConstantDesc(handle, &constDesc, &count);
  819. BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
  820. , ii
  821. , constDesc.Class
  822. , constDesc.Type
  823. , constDesc.Rows
  824. , constDesc.Columns
  825. , constDesc.StructMembers
  826. , constDesc.Bytes
  827. , constDesc.Name
  828. , constDesc.Elements
  829. , constDesc.RegisterIndex
  830. , constDesc.RegisterCount
  831. );
  832. UniformType::Enum type = findUniformTypeDx9(constDesc);
  833. if (UniformType::Count != type)
  834. {
  835. Uniform un;
  836. un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
  837. un.type = type;
  838. un.num = constDesc.Elements;
  839. un.regIndex = constDesc.RegisterIndex;
  840. un.regCount = constDesc.RegisterCount;
  841. uniforms.push_back(un);
  842. }
  843. }
  844. uint16_t count = (uint16_t)uniforms.size();
  845. bx::write(_writer, count);
  846. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  847. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  848. {
  849. const Uniform& un = *it;
  850. uint8_t nameSize = (uint8_t)un.name.size();
  851. bx::write(_writer, nameSize);
  852. bx::write(_writer, un.name.c_str(), nameSize);
  853. uint8_t type = un.type|fragmentBit;
  854. bx::write(_writer, type);
  855. bx::write(_writer, un.num);
  856. bx::write(_writer, un.regIndex);
  857. bx::write(_writer, un.regCount);
  858. BX_TRACE("%s, %s, %d, %d, %d"
  859. , un.name.c_str()
  860. , s_uniformTypeName[un.type]
  861. , un.num
  862. , un.regIndex
  863. , un.regCount
  864. );
  865. }
  866. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  867. bx::write(_writer, shaderSize);
  868. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  869. uint8_t nul = 0;
  870. bx::write(_writer, nul);
  871. if (_cmdLine.hasArg('\0', "disasm") )
  872. {
  873. LPD3DXBUFFER disasm;
  874. D3DXDisassembleShader( (const DWORD*)code->GetBufferPointer()
  875. , false
  876. , NULL
  877. , &disasm
  878. );
  879. if (NULL != disasm)
  880. {
  881. std::string disasmfp = _cmdLine.findOption('o');
  882. disasmfp += ".disasm";
  883. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), disasm->GetBufferSize() );
  884. disasm->Release();
  885. }
  886. }
  887. if (NULL != code)
  888. {
  889. code->Release();
  890. }
  891. if (NULL != errorMsg)
  892. {
  893. errorMsg->Release();
  894. }
  895. if (NULL != constantTable)
  896. {
  897. constantTable->Release();
  898. }
  899. return true;
  900. #else
  901. BX_UNUSED(_cmdLine, _code, _writer);
  902. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  903. return false;
  904. #endif // BX_PLATFORM_WINDOWS
  905. }
  906. bool compileHLSLShaderDx11(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  907. {
  908. #if BX_PLATFORM_WINDOWS
  909. BX_TRACE("DX11");
  910. const char* profile = _cmdLine.findOption('p', "profile");
  911. if (NULL == profile)
  912. {
  913. fprintf(stderr, "Shader profile must be specified.\n");
  914. return false;
  915. }
  916. bool debug = _cmdLine.hasArg('\0', "debug");
  917. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  918. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  919. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  920. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
  921. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  922. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  923. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  924. bool werror = _cmdLine.hasArg('\0', "Werror");
  925. if (werror)
  926. {
  927. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  928. }
  929. uint32_t optimization = 3;
  930. if (_cmdLine.hasArg(optimization, 'O') )
  931. {
  932. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx11)-1);
  933. flags |= s_optimizationLevelDx11[optimization];
  934. }
  935. else
  936. {
  937. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  938. }
  939. BX_TRACE("Profile: %s", profile);
  940. BX_TRACE("Flags: 0x%08x", flags);
  941. ID3DBlob* code;
  942. ID3DBlob* errorMsg;
  943. // Output preprocessed shader so that HLSL can be debugged via GPA
  944. // or PIX. Compiling through memory won't embed preprocessed shader
  945. // file path.
  946. std::string hlslfp;
  947. if (debug)
  948. {
  949. hlslfp = _cmdLine.findOption('o');
  950. hlslfp += ".hlsl";
  951. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  952. }
  953. HRESULT hr = D3DCompile(_code.c_str()
  954. , _code.size()
  955. , hlslfp.c_str()
  956. , NULL
  957. , NULL
  958. , "main"
  959. , profile
  960. , flags
  961. , 0
  962. , &code
  963. , &errorMsg
  964. );
  965. if (FAILED(hr)
  966. || (werror && NULL != errorMsg) )
  967. {
  968. const char* log = (char*)errorMsg->GetBufferPointer();
  969. int32_t line = 0;
  970. int32_t column = 0;
  971. int32_t start = 0;
  972. int32_t end = INT32_MAX;
  973. if (2 == sscanf(log, "(%u,%u):", &line, &column)
  974. && 0 != line)
  975. {
  976. start = bx::uint32_imax(1, line-10);
  977. end = start + 20;
  978. }
  979. printCode(_code.c_str(), line, start, end);
  980. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  981. errorMsg->Release();
  982. return false;
  983. }
  984. UniformArray uniforms;
  985. ID3D11ShaderReflection* reflect = NULL;
  986. hr = D3DReflect(code->GetBufferPointer()
  987. , code->GetBufferSize()
  988. , IID_ID3D11ShaderReflection
  989. , (void**)&reflect
  990. );
  991. if (FAILED(hr) )
  992. {
  993. fprintf(stderr, "Error: 0x%08x\n", (uint32_t)hr);
  994. return false;
  995. }
  996. D3D11_SHADER_DESC desc;
  997. hr = reflect->GetDesc(&desc);
  998. if (FAILED(hr) )
  999. {
  1000. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr);
  1001. return false;
  1002. }
  1003. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  1004. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  1005. BX_TRACE("Input:");
  1006. uint8_t attrMask[Attrib::Count];
  1007. memset(attrMask, 0, sizeof(attrMask) );
  1008. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  1009. {
  1010. D3D11_SIGNATURE_PARAMETER_DESC spd;
  1011. reflect->GetInputParameterDesc(ii, &spd);
  1012. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  1013. , ii
  1014. , spd.SemanticName
  1015. , spd.SemanticIndex
  1016. , spd.SystemValueType
  1017. , spd.ComponentType
  1018. , spd.Mask
  1019. , spd.Register
  1020. );
  1021. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
  1022. if (ris.m_attr != Attrib::Count)
  1023. {
  1024. attrMask[ris.m_attr] = 0xff;
  1025. }
  1026. }
  1027. BX_TRACE("Output:");
  1028. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  1029. {
  1030. D3D11_SIGNATURE_PARAMETER_DESC spd;
  1031. reflect->GetOutputParameterDesc(ii, &spd);
  1032. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  1033. }
  1034. uint16_t size = 0;
  1035. for (uint32_t ii = 0; ii < bx::uint32_min(1, desc.ConstantBuffers); ++ii)
  1036. {
  1037. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  1038. D3D11_SHADER_BUFFER_DESC bufferDesc;
  1039. hr = cbuffer->GetDesc(&bufferDesc);
  1040. size = (uint16_t)bufferDesc.Size;
  1041. if (SUCCEEDED(hr) )
  1042. {
  1043. BX_TRACE("%s, %d, vars %d, size %d"
  1044. , bufferDesc.Name
  1045. , bufferDesc.Type
  1046. , bufferDesc.Variables
  1047. , bufferDesc.Size
  1048. );
  1049. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  1050. {
  1051. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  1052. ID3D11ShaderReflectionType* type = var->GetType();
  1053. D3D11_SHADER_VARIABLE_DESC varDesc;
  1054. hr = var->GetDesc(&varDesc);
  1055. if (SUCCEEDED(hr) )
  1056. {
  1057. D3D11_SHADER_TYPE_DESC constDesc;
  1058. hr = type->GetDesc(&constDesc);
  1059. if (SUCCEEDED(hr) )
  1060. {
  1061. UniformType::Enum type = findUniformTypeDx11(constDesc);
  1062. if (UniformType::Count != type
  1063. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  1064. {
  1065. Uniform un;
  1066. un.name = varDesc.Name;
  1067. un.type = type;
  1068. un.num = constDesc.Elements;
  1069. un.regIndex = varDesc.StartOffset;
  1070. un.regCount = BX_ALIGN_16(varDesc.Size)/16;
  1071. uniforms.push_back(un);
  1072. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d"
  1073. , varDesc.Name
  1074. , varDesc.StartOffset
  1075. , varDesc.Size
  1076. , varDesc.uFlags
  1077. , type
  1078. );
  1079. }
  1080. else
  1081. {
  1082. BX_TRACE("\t%s, unknown type", varDesc.Name);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. }
  1088. }
  1089. BX_TRACE("Bound:");
  1090. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  1091. {
  1092. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  1093. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  1094. if (SUCCEEDED(hr) )
  1095. {
  1096. // if (bindDesc.Type == D3D_SIT_SAMPLER)
  1097. {
  1098. BX_TRACE("\t%s, %d, %d, %d"
  1099. , bindDesc.Name
  1100. , bindDesc.Type
  1101. , bindDesc.BindPoint
  1102. , bindDesc.BindCount
  1103. );
  1104. }
  1105. }
  1106. }
  1107. uint16_t count = (uint16_t)uniforms.size();
  1108. bx::write(_writer, count);
  1109. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  1110. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  1111. {
  1112. const Uniform& un = *it;
  1113. uint8_t nameSize = (uint8_t)un.name.size();
  1114. bx::write(_writer, nameSize);
  1115. bx::write(_writer, un.name.c_str(), nameSize);
  1116. uint8_t type = un.type|fragmentBit;
  1117. bx::write(_writer, type);
  1118. bx::write(_writer, un.num);
  1119. bx::write(_writer, un.regIndex);
  1120. bx::write(_writer, un.regCount);
  1121. BX_TRACE("%s, %s, %d, %d, %d"
  1122. , un.name.c_str()
  1123. , s_uniformTypeName[un.type]
  1124. , un.num
  1125. , un.regIndex
  1126. , un.regCount
  1127. );
  1128. }
  1129. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  1130. bx::write(_writer, shaderSize);
  1131. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  1132. uint8_t nul = 0;
  1133. bx::write(_writer, nul);
  1134. bx::write(_writer, attrMask, sizeof(attrMask) );
  1135. bx::write(_writer, size);
  1136. if (_cmdLine.hasArg('\0', "disasm") )
  1137. {
  1138. ID3DBlob* disasm;
  1139. D3DDisassemble(code->GetBufferPointer()
  1140. , code->GetBufferSize()
  1141. , 0
  1142. , NULL
  1143. , &disasm
  1144. );
  1145. if (NULL != disasm)
  1146. {
  1147. std::string disasmfp = _cmdLine.findOption('o');
  1148. disasmfp += ".disasm";
  1149. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  1150. disasm->Release();
  1151. }
  1152. }
  1153. if (NULL != reflect)
  1154. {
  1155. reflect->Release();
  1156. }
  1157. if (NULL != errorMsg)
  1158. {
  1159. errorMsg->Release();
  1160. }
  1161. code->Release();
  1162. return true;
  1163. #else
  1164. BX_UNUSED(_cmdLine, _code, _writer);
  1165. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  1166. return false;
  1167. #endif // BX_PLATFORM_WINDOWS
  1168. }
  1169. struct Preprocessor
  1170. {
  1171. Preprocessor(const char* _filePath, bool _gles, const char* _includeDir = NULL)
  1172. : m_tagptr(m_tags)
  1173. , m_scratchPos(0)
  1174. , m_fgetsPos(0)
  1175. {
  1176. m_tagptr->tag = FPPTAG_USERDATA;
  1177. m_tagptr->data = this;
  1178. m_tagptr++;
  1179. m_tagptr->tag = FPPTAG_DEPENDS;
  1180. m_tagptr->data = (void*)fppDepends;
  1181. m_tagptr++;
  1182. m_tagptr->tag = FPPTAG_INPUT;
  1183. m_tagptr->data = (void*)fppInput;
  1184. m_tagptr++;
  1185. m_tagptr->tag = FPPTAG_OUTPUT;
  1186. m_tagptr->data = (void*)fppOutput;
  1187. m_tagptr++;
  1188. m_tagptr->tag = FPPTAG_ERROR;
  1189. m_tagptr->data = (void*)fppError;
  1190. m_tagptr++;
  1191. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  1192. m_tagptr->data = (void*)0;
  1193. m_tagptr++;
  1194. m_tagptr->tag = FPPTAG_LINE;
  1195. m_tagptr->data = (void*)0;
  1196. m_tagptr++;
  1197. m_tagptr->tag = FPPTAG_INPUT_NAME;
  1198. m_tagptr->data = scratch(_filePath);
  1199. m_tagptr++;
  1200. if (NULL != _includeDir)
  1201. {
  1202. addInclude(_includeDir);
  1203. }
  1204. if (!_gles)
  1205. {
  1206. m_default = "#define lowp\n#define mediump\n#define highp\n";
  1207. }
  1208. }
  1209. void setDefine(const char* _define)
  1210. {
  1211. m_tagptr->tag = FPPTAG_DEFINE;
  1212. m_tagptr->data = scratch(_define);
  1213. m_tagptr++;
  1214. }
  1215. void setDefaultDefine(const char* _name)
  1216. {
  1217. char temp[1024];
  1218. bx::snprintf(temp, BX_COUNTOF(temp)
  1219. , "#ifndef %s\n"
  1220. "# define %s 0\n"
  1221. "#endif // %s\n"
  1222. "\n"
  1223. , _name
  1224. , _name
  1225. , _name
  1226. );
  1227. m_default += temp;
  1228. }
  1229. void writef(const char* _format, ...)
  1230. {
  1231. va_list argList;
  1232. va_start(argList, _format);
  1233. bx::stringPrintfVargs(m_default, _format, argList);
  1234. va_end(argList);
  1235. }
  1236. void addInclude(const char* _includeDir)
  1237. {
  1238. char* start = scratch(_includeDir);
  1239. for (char* split = strchr(start, ';'); NULL != split; split = strchr(start, ';'))
  1240. {
  1241. *split = '\0';
  1242. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1243. m_tagptr->data = start;
  1244. m_tagptr++;
  1245. start = split + 1;
  1246. }
  1247. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1248. m_tagptr->data = start;
  1249. m_tagptr++;
  1250. }
  1251. void addDependency(const char* _fileName)
  1252. {
  1253. m_depends += " \\\n ";
  1254. m_depends += _fileName;
  1255. }
  1256. bool run(const char* _input)
  1257. {
  1258. m_fgetsPos = 0;
  1259. m_preprocessed.clear();
  1260. m_input = m_default;
  1261. m_input += "\n\n";
  1262. size_t len = strlen(_input)+1;
  1263. char* temp = new char[len];
  1264. bx::eolLF(temp, len, _input);
  1265. m_input += temp;
  1266. delete [] temp;
  1267. fppTag* tagptr = m_tagptr;
  1268. tagptr->tag = FPPTAG_END;
  1269. tagptr->data = 0;
  1270. tagptr++;
  1271. int result = fppPreProcess(m_tags);
  1272. return 0 == result;
  1273. }
  1274. char* fgets(char* _buffer, int _size)
  1275. {
  1276. int ii = 0;
  1277. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  1278. {
  1279. _buffer[ii++] = ch;
  1280. if (ch == '\n' || ii == _size)
  1281. {
  1282. _buffer[ii] = '\0';
  1283. m_fgetsPos++;
  1284. return _buffer;
  1285. }
  1286. }
  1287. return NULL;
  1288. }
  1289. static void fppDepends(char* _fileName, void* _userData)
  1290. {
  1291. Preprocessor* thisClass = (Preprocessor*)_userData;
  1292. thisClass->addDependency(_fileName);
  1293. }
  1294. static char* fppInput(char* _buffer, int _size, void* _userData)
  1295. {
  1296. Preprocessor* thisClass = (Preprocessor*)_userData;
  1297. return thisClass->fgets(_buffer, _size);
  1298. }
  1299. static void fppOutput(int _ch, void* _userData)
  1300. {
  1301. Preprocessor* thisClass = (Preprocessor*)_userData;
  1302. thisClass->m_preprocessed += _ch;
  1303. }
  1304. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  1305. {
  1306. vfprintf(stderr, _format, _vargs);
  1307. }
  1308. char* scratch(const char* _str)
  1309. {
  1310. char* result = &m_scratch[m_scratchPos];
  1311. strcpy(result, _str);
  1312. m_scratchPos += (uint32_t)strlen(_str)+1;
  1313. return result;
  1314. }
  1315. fppTag m_tags[MAX_TAGS];
  1316. fppTag* m_tagptr;
  1317. std::string m_depends;
  1318. std::string m_default;
  1319. std::string m_input;
  1320. std::string m_preprocessed;
  1321. char m_scratch[16<<10];
  1322. uint32_t m_scratchPos;
  1323. uint32_t m_fgetsPos;
  1324. };
  1325. const char* baseName(const char* _filePath)
  1326. {
  1327. const char* bs = strrchr(_filePath, '\\');
  1328. const char* fs = strrchr(_filePath, '/');
  1329. const char* column = strrchr(_filePath, ':');
  1330. const char* basename = std::max(std::max(bs, fs), column);
  1331. if (NULL != basename)
  1332. {
  1333. return basename+1;
  1334. }
  1335. return _filePath;
  1336. }
  1337. typedef std::vector<std::string> InOut;
  1338. uint32_t parseInOut(InOut& _inout, const char* _str, const char* _eol)
  1339. {
  1340. uint32_t hash = 0;
  1341. _str = bx::strws(_str);
  1342. if (_str < _eol)
  1343. {
  1344. const char* delim;
  1345. do
  1346. {
  1347. delim = strpbrk(_str, " ,");
  1348. if (NULL != delim)
  1349. {
  1350. delim = delim > _eol ? _eol : delim;
  1351. std::string token;
  1352. token.assign(_str, delim-_str);
  1353. _inout.push_back(token);
  1354. _str = bx::strws(delim + 1);
  1355. }
  1356. }
  1357. while (delim < _eol && _str < _eol && NULL != delim);
  1358. std::sort(_inout.begin(), _inout.end() );
  1359. bx::HashMurmur2A murmur;
  1360. murmur.begin();
  1361. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  1362. {
  1363. murmur.add(it->c_str(), (uint32_t)it->size() );
  1364. }
  1365. hash = murmur.end();
  1366. }
  1367. return hash;
  1368. }
  1369. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  1370. {
  1371. char find[32];
  1372. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  1373. char replace[32];
  1374. bx::snprintf(replace, sizeof(replace), "gl_FragData_%d_", _idx);
  1375. strreplace(_data, find, replace);
  1376. _preprocessor.writef(
  1377. " \\\n\t%sout vec4 gl_FragData_%d_ : SV_TARGET%d"
  1378. , _comma ? ", " : " "
  1379. , _idx
  1380. , _idx
  1381. );
  1382. }
  1383. // c - compute
  1384. // d - domain
  1385. // f - fragment
  1386. // g - geometry
  1387. // h - hull
  1388. // v - vertex
  1389. //
  1390. // OpenGL #version Features Direct3D Features Shader Model
  1391. // 2.1 120 vf 9.0 vf 2.0
  1392. // 3.0 130
  1393. // 3.1 140
  1394. // 3.2 150 vgf
  1395. // 3.3 330 10.0 vgf 4.0
  1396. // 4.0 400 vhdgf
  1397. // 4.1 410
  1398. // 4.2 420 11.0 vhdgf+c 5.0
  1399. // 4.3 430 vhdgf+c
  1400. // 4.4 440
  1401. void help(const char* _error = NULL)
  1402. {
  1403. if (NULL != _error)
  1404. {
  1405. fprintf(stderr, "Error:\n%s\n\n", _error);
  1406. }
  1407. fprintf(stderr
  1408. , "shaderc, bgfx shader compiler tool\n"
  1409. "Copyright 2011-2014 Branimir Karadzic. All rights reserved.\n"
  1410. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  1411. );
  1412. fprintf(stderr
  1413. , "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  1414. "\n"
  1415. "Options:\n"
  1416. " -f <file path> Input file path.\n"
  1417. " -i <include path> Include path (for multiple paths use semicolon).\n"
  1418. " -o <file path> Output file path.\n"
  1419. " --bin2c <file path> Generate C header file.\n"
  1420. " --depends <file path> Generate makefile style depends file.\n"
  1421. " --platform <platform> Target platform.\n"
  1422. " android\n"
  1423. " asm.js\n"
  1424. " ios\n"
  1425. " linux\n"
  1426. " nacl\n"
  1427. " osx\n"
  1428. " windows\n"
  1429. " --preprocess Preprocess only.\n"
  1430. " --raw Do not process shader. No preprocessor, and no glsl-optimizer (GLSL only).\n"
  1431. " --type <type> Shader type (vertex, fragment)\n"
  1432. " --varyingdef <file path> Path to varying.def.sc file.\n"
  1433. " --verbose Verbose.\n"
  1434. "\n"
  1435. "Options (DX9 and DX11 only):\n"
  1436. "\n"
  1437. " --debug Debug information.\n"
  1438. " --disasm Disassemble compiled shader.\n"
  1439. " -p, --profile <profile> Shader model (f.e. ps_3_0).\n"
  1440. " -O <level> Optimization level (0, 1, 2, 3).\n"
  1441. " --Werror Treat warnings as errors.\n"
  1442. "\n"
  1443. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  1444. );
  1445. }
  1446. int main(int _argc, const char* _argv[])
  1447. {
  1448. bx::CommandLine cmdLine(_argc, _argv);
  1449. if (cmdLine.hasArg('h', "help") )
  1450. {
  1451. help();
  1452. return EXIT_FAILURE;
  1453. }
  1454. g_verbose = cmdLine.hasArg("verbose");
  1455. const char* filePath = cmdLine.findOption('f');
  1456. if (NULL == filePath)
  1457. {
  1458. help("Shader file name must be specified.");
  1459. return EXIT_FAILURE;
  1460. }
  1461. const char* outFilePath = cmdLine.findOption('o');
  1462. if (NULL == outFilePath)
  1463. {
  1464. help("Output file name must be specified.");
  1465. return EXIT_FAILURE;
  1466. }
  1467. const char* type = cmdLine.findOption('\0', "type");
  1468. if (NULL == type)
  1469. {
  1470. help("Must specify shader type.");
  1471. return EXIT_FAILURE;
  1472. }
  1473. const char* platform = cmdLine.findOption('\0', "platform");
  1474. if (NULL == platform)
  1475. {
  1476. help("Must specify platform.");
  1477. return EXIT_FAILURE;
  1478. }
  1479. bool raw = cmdLine.hasArg('\0', "raw");
  1480. uint32_t gles = 0;
  1481. uint32_t hlsl = 2;
  1482. const char* profile = cmdLine.findOption('p', "profile");
  1483. if (NULL != profile)
  1484. {
  1485. if (0 == strncmp(&profile[1], "s_3", 3) )
  1486. {
  1487. hlsl = 3;
  1488. }
  1489. else if (0 == strncmp(&profile[1], "s_4", 3) )
  1490. {
  1491. hlsl = 4;
  1492. }
  1493. else if (0 == strncmp(&profile[1], "s_5", 3) )
  1494. {
  1495. hlsl = 5;
  1496. }
  1497. }
  1498. else
  1499. {
  1500. gles = 2;
  1501. }
  1502. const char* bin2c = NULL;
  1503. if (cmdLine.hasArg("bin2c") )
  1504. {
  1505. bin2c = cmdLine.findOption("bin2c");
  1506. if (NULL == bin2c)
  1507. {
  1508. bin2c = baseName(outFilePath);
  1509. uint32_t len = (uint32_t)strlen(bin2c);
  1510. char* temp = (char*)alloca(len+1);
  1511. for (char *out = temp; *bin2c != '\0';)
  1512. {
  1513. char ch = *bin2c++;
  1514. if (isalnum(ch) )
  1515. {
  1516. *out++ = ch;
  1517. }
  1518. else
  1519. {
  1520. *out++ = '_';
  1521. }
  1522. }
  1523. temp[len] = '\0';
  1524. bin2c = temp;
  1525. }
  1526. }
  1527. bool depends = cmdLine.hasArg("depends");
  1528. bool preprocessOnly = cmdLine.hasArg("preprocess");
  1529. const char* includeDir = cmdLine.findOption('i');
  1530. Preprocessor preprocessor(filePath, 0 != gles, includeDir);
  1531. std::string dir;
  1532. {
  1533. const char* base = baseName(filePath);
  1534. if (base != filePath)
  1535. {
  1536. dir.assign(filePath, base-filePath);
  1537. preprocessor.addInclude(dir.c_str() );
  1538. }
  1539. }
  1540. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  1541. preprocessor.setDefaultDefine("BX_PLATFORM_EMSCRIPTEN");
  1542. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  1543. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  1544. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  1545. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  1546. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  1547. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  1548. // preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_ESSL");
  1549. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  1550. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  1551. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_COMPUTE");
  1552. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  1553. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  1554. bool glsl = false;
  1555. if (0 == bx::stricmp(platform, "android") )
  1556. {
  1557. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  1558. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1559. glsl = true;
  1560. }
  1561. else if (0 == bx::stricmp(platform, "asm.js") )
  1562. {
  1563. preprocessor.setDefine("BX_PLATFORM_EMSCRIPTEN=1");
  1564. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1565. glsl = true;
  1566. }
  1567. else if (0 == bx::stricmp(platform, "ios") )
  1568. {
  1569. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1570. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1571. glsl = true;
  1572. }
  1573. else if (0 == bx::stricmp(platform, "linux") )
  1574. {
  1575. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  1576. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1577. glsl = true;
  1578. }
  1579. else if (0 == bx::stricmp(platform, "nacl") )
  1580. {
  1581. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  1582. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1583. glsl = true;
  1584. }
  1585. else if (0 == bx::stricmp(platform, "osx") )
  1586. {
  1587. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  1588. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1589. glsl = true;
  1590. }
  1591. else if (0 == bx::stricmp(platform, "windows") )
  1592. {
  1593. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  1594. char temp[256];
  1595. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  1596. preprocessor.setDefine(temp);
  1597. }
  1598. else if (0 == bx::stricmp(platform, "xbox360") )
  1599. {
  1600. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  1601. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=3");
  1602. }
  1603. else
  1604. {
  1605. fprintf(stderr, "Unknown platform %s?!", platform);
  1606. return EXIT_FAILURE;
  1607. }
  1608. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  1609. char shaderType = tolower(type[0]);
  1610. switch (shaderType)
  1611. {
  1612. case 'c':
  1613. preprocessor.setDefine("BGFX_SHADER_TYPE_COMPUTE=1");
  1614. break;
  1615. case 'f':
  1616. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1617. break;
  1618. case 'v':
  1619. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1620. break;
  1621. default:
  1622. fprintf(stderr, "Unknown type: %s?!", type);
  1623. return EXIT_FAILURE;
  1624. }
  1625. bool compiled = false;
  1626. FILE* file = fopen(filePath, "r");
  1627. if (NULL != file)
  1628. {
  1629. VaryingMap varyingMap;
  1630. std::string defaultVarying = dir + "varying.def.sc";
  1631. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  1632. File attribdef(varyingdef);
  1633. const char* parse = attribdef.getData();
  1634. if (NULL != parse
  1635. && *parse != '\0')
  1636. {
  1637. preprocessor.addDependency(varyingdef);
  1638. }
  1639. while (NULL != parse
  1640. && *parse != '\0')
  1641. {
  1642. parse = bx::strws(parse);
  1643. const char* eol = strchr(parse, ';');
  1644. if (NULL == eol)
  1645. {
  1646. eol = bx::streol(parse);
  1647. }
  1648. if (NULL != eol)
  1649. {
  1650. const char* precision = NULL;
  1651. const char* interpolation = NULL;
  1652. const char* type = parse;
  1653. if (0 == strncmp(type, "lowp", 4)
  1654. || 0 == strncmp(type, "mediump", 7)
  1655. || 0 == strncmp(type, "highp", 5) )
  1656. {
  1657. precision = type;
  1658. type = parse = bx::strws(bx::strword(parse) );
  1659. }
  1660. if (0 == strncmp(type, "flat", 4)
  1661. || 0 == strncmp(type, "smooth", 6)
  1662. || 0 == strncmp(type, "noperspective", 13) )
  1663. {
  1664. interpolation = type;
  1665. type = parse = bx::strws(bx::strword(parse) );
  1666. }
  1667. const char* name = parse = bx::strws(bx::strword(parse) );
  1668. const char* column = parse = bx::strws(bx::strword(parse) );
  1669. const char* semantics = parse = bx::strws(bx::strnws (parse) );
  1670. const char* assign = parse = bx::strws(bx::strword(parse) );
  1671. const char* init = parse = bx::strws(bx::strnws (parse) );
  1672. if (type < eol
  1673. && name < eol
  1674. && column < eol
  1675. && ':' == *column
  1676. && semantics < eol)
  1677. {
  1678. Varying var;
  1679. if (NULL != precision)
  1680. {
  1681. var.m_precision.assign(precision, bx::strword(precision)-precision);
  1682. }
  1683. if (NULL != interpolation)
  1684. {
  1685. var.m_interpolation.assign(interpolation, bx::strword(interpolation)-interpolation);
  1686. }
  1687. var.m_type.assign(type, bx::strword(type)-type);
  1688. var.m_name.assign(name, bx::strword(name)-name);
  1689. var.m_semantics.assign(semantics, bx::strword(semantics)-semantics);
  1690. if (assign < eol
  1691. && '=' == *assign
  1692. && init < eol)
  1693. {
  1694. var.m_init.assign(init, eol-init);
  1695. }
  1696. varyingMap.insert(std::make_pair(var.m_name, var) );
  1697. }
  1698. parse = bx::strnl(eol);
  1699. }
  1700. }
  1701. InOut shaderInputs;
  1702. InOut shaderOutputs;
  1703. uint32_t inputHash = 0;
  1704. uint32_t outputHash = 0;
  1705. char* data;
  1706. char* input;
  1707. {
  1708. const size_t padding = 16;
  1709. uint32_t size = (uint32_t)fsize(file);
  1710. data = new char[size+padding+1];
  1711. size = (uint32_t)fread(data, 1, size, file);
  1712. // Compiler generates "error X3000: syntax error: unexpected end of file"
  1713. // if input doesn't have empty line at EOF.
  1714. data[size] = '\n';
  1715. memset(&data[size+1], 0, padding);
  1716. fclose(file);
  1717. input = data;
  1718. while (input[0] == '$')
  1719. {
  1720. const char* str = input+1;
  1721. const char* eol = bx::streol(str);
  1722. const char* nl = bx::strnl(eol);
  1723. input = const_cast<char*>(nl);
  1724. if (0 == strncmp(str, "input", 5) )
  1725. {
  1726. str += 5;
  1727. const char* comment = strstr(str, "//");
  1728. eol = NULL != comment && comment < eol ? comment : eol;
  1729. inputHash = parseInOut(shaderInputs, str, eol);
  1730. }
  1731. else if (0 == strncmp(str, "output", 6) )
  1732. {
  1733. str += 6;
  1734. const char* comment = strstr(str, "//");
  1735. eol = NULL != comment && comment < eol ? comment : eol;
  1736. outputHash = parseInOut(shaderOutputs, str, eol);
  1737. }
  1738. else if (0 == strncmp(str, "raw", 3) )
  1739. {
  1740. raw = true;
  1741. str += 3;
  1742. }
  1743. }
  1744. if (!raw)
  1745. {
  1746. // To avoid commented code being recognized as used feature,
  1747. // first preprocess pass is used to strip all comments before
  1748. // substituting code.
  1749. preprocessor.run(input);
  1750. delete [] data;
  1751. size = (uint32_t)preprocessor.m_preprocessed.size();
  1752. data = new char[size+padding+1];
  1753. memcpy(data, preprocessor.m_preprocessed.c_str(), size);
  1754. memset(&data[size], 0, padding+1);
  1755. input = data;
  1756. }
  1757. }
  1758. if (raw)
  1759. {
  1760. bx::CrtFileWriter* writer = NULL;
  1761. if (NULL != bin2c)
  1762. {
  1763. writer = new Bin2cWriter(bin2c);
  1764. }
  1765. else
  1766. {
  1767. writer = new bx::CrtFileWriter;
  1768. }
  1769. if (0 != writer->open(outFilePath) )
  1770. {
  1771. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1772. return EXIT_FAILURE;
  1773. }
  1774. uint32_t inputHash = 0;
  1775. uint32_t outputHash = 0;
  1776. if ('f' == shaderType)
  1777. {
  1778. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  1779. bx::write(writer, inputHash);
  1780. }
  1781. else if ('v' == shaderType)
  1782. {
  1783. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  1784. bx::write(writer, outputHash);
  1785. }
  1786. else
  1787. {
  1788. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1789. bx::write(writer, outputHash);
  1790. }
  1791. if (glsl)
  1792. {
  1793. bx::write(writer, uint16_t(0) );
  1794. uint32_t shaderSize = (uint32_t)strlen(input);
  1795. bx::write(writer, shaderSize);
  1796. bx::write(writer, input, shaderSize);
  1797. bx::write(writer, uint8_t(0) );
  1798. compiled = true;
  1799. }
  1800. else
  1801. {
  1802. if (hlsl > 3)
  1803. {
  1804. compiled = compileHLSLShaderDx11(cmdLine, input, writer);
  1805. }
  1806. else
  1807. {
  1808. compiled = compileHLSLShaderDx9(cmdLine, input, writer);
  1809. }
  1810. }
  1811. writer->close();
  1812. delete writer;
  1813. }
  1814. else if ('c' == shaderType) // Compute
  1815. {
  1816. char* entry = strstr(input, "void main()");
  1817. if (NULL == entry)
  1818. {
  1819. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1820. }
  1821. else
  1822. {
  1823. if (glsl)
  1824. {
  1825. }
  1826. else
  1827. {
  1828. preprocessor.writef(
  1829. "#define lowp\n"
  1830. "#define mediump\n"
  1831. "#define highp\n"
  1832. "#define ivec2 int2\n"
  1833. "#define ivec3 int3\n"
  1834. "#define ivec4 int4\n"
  1835. "#define uvec2 uint2\n"
  1836. "#define uvec3 uint3\n"
  1837. "#define uvec4 uint4\n"
  1838. "#define vec2 float2\n"
  1839. "#define vec3 float3\n"
  1840. "#define vec4 float4\n"
  1841. "#define mat2 float2x2\n"
  1842. "#define mat3 float3x3\n"
  1843. "#define mat4 float4x4\n"
  1844. );
  1845. entry[4] = '_';
  1846. preprocessor.writef("#define void_main()");
  1847. preprocessor.writef(" \\\n\tvoid main(");
  1848. uint32_t arg = 0;
  1849. const bool hasLocalInvocationID = NULL != strstr(input, "gl_LocalInvocationID");
  1850. const bool hasLocalInvocationIndex = NULL != strstr(input, "gl_LocalInvocationIndex");
  1851. const bool hasGlobalInvocationID = NULL != strstr(input, "gl_GlobalInvocationID");
  1852. const bool hasWorkGroupID = NULL != strstr(input, "gl_WorkGroupID");
  1853. if (hasLocalInvocationID)
  1854. {
  1855. preprocessor.writef(
  1856. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1857. , arg++ > 0 ? ", " : " "
  1858. );
  1859. }
  1860. if (hasLocalInvocationIndex)
  1861. {
  1862. preprocessor.writef(
  1863. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1864. , arg++ > 0 ? ", " : " "
  1865. );
  1866. }
  1867. if (hasGlobalInvocationID)
  1868. {
  1869. preprocessor.writef(
  1870. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1871. , arg++ > 0 ? ", " : " "
  1872. );
  1873. }
  1874. if (hasWorkGroupID)
  1875. {
  1876. preprocessor.writef(
  1877. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1878. , arg++ > 0 ? ", " : " "
  1879. );
  1880. }
  1881. preprocessor.writef(
  1882. " \\\n\t)\n"
  1883. );
  1884. }
  1885. if (preprocessor.run(input) )
  1886. {
  1887. BX_TRACE("Input file: %s", filePath);
  1888. BX_TRACE("Output file: %s", outFilePath);
  1889. if (preprocessOnly)
  1890. {
  1891. bx::CrtFileWriter writer;
  1892. if (0 != writer.open(outFilePath) )
  1893. {
  1894. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1895. return EXIT_FAILURE;
  1896. }
  1897. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1898. writer.close();
  1899. return EXIT_SUCCESS;
  1900. }
  1901. {
  1902. bx::CrtFileWriter* writer = NULL;
  1903. if (NULL != bin2c)
  1904. {
  1905. writer = new Bin2cWriter(bin2c);
  1906. }
  1907. else
  1908. {
  1909. writer = new bx::CrtFileWriter;
  1910. }
  1911. if (0 != writer->open(outFilePath) )
  1912. {
  1913. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1914. return EXIT_FAILURE;
  1915. }
  1916. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1917. bx::write(writer, outputHash);
  1918. if (glsl)
  1919. {
  1920. std::string code;
  1921. if (gles)
  1922. {
  1923. bx::stringPrintf(code, "#version 310 es\n");
  1924. }
  1925. else
  1926. {
  1927. int32_t version = atoi(profile);
  1928. bx::stringPrintf(code, "#version %d\n", version == 0 ? 430 : version);
  1929. }
  1930. code += preprocessor.m_preprocessed;
  1931. #if 1
  1932. bx::write(writer, uint16_t(0) );
  1933. uint32_t shaderSize = (uint32_t)code.size();
  1934. bx::write(writer, shaderSize);
  1935. bx::write(writer, code.c_str(), shaderSize);
  1936. bx::write(writer, uint8_t(0) );
  1937. compiled = true;
  1938. #else
  1939. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  1940. #endif // 0
  1941. }
  1942. else
  1943. {
  1944. if (hlsl > 3)
  1945. {
  1946. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1947. }
  1948. else
  1949. {
  1950. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1951. }
  1952. }
  1953. writer->close();
  1954. delete writer;
  1955. }
  1956. if (compiled)
  1957. {
  1958. if (depends)
  1959. {
  1960. std::string ofp = outFilePath;
  1961. ofp += ".d";
  1962. bx::CrtFileWriter writer;
  1963. if (0 == writer.open(ofp.c_str() ) )
  1964. {
  1965. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1966. writer.close();
  1967. }
  1968. }
  1969. }
  1970. }
  1971. }
  1972. }
  1973. else // Vertex/Fragment
  1974. {
  1975. char* entry = strstr(input, "void main()");
  1976. if (NULL == entry)
  1977. {
  1978. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1979. }
  1980. else
  1981. {
  1982. if (glsl)
  1983. {
  1984. preprocessor.writef(
  1985. "#define ivec2 vec2\n"
  1986. "#define ivec3 vec3\n"
  1987. "#define ivec4 vec4\n"
  1988. );
  1989. if (0 == gles)
  1990. {
  1991. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1992. // not as GLSL language 1.2 specs shadow2D/Proj.
  1993. preprocessor.writef(
  1994. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1995. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1996. );
  1997. }
  1998. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1999. {
  2000. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2001. if (varyingIt != varyingMap.end() )
  2002. {
  2003. const Varying& var = varyingIt->second;
  2004. const char* name = var.m_name.c_str();
  2005. if (0 == strncmp(name, "a_", 2)
  2006. || 0 == strncmp(name, "i_", 2) )
  2007. {
  2008. preprocessor.writef("attribute %s %s %s %s;\n"
  2009. , var.m_precision.c_str()
  2010. , var.m_interpolation.c_str()
  2011. , var.m_type.c_str()
  2012. , name
  2013. );
  2014. }
  2015. else
  2016. {
  2017. preprocessor.writef("%s varying %s %s %s;\n"
  2018. , var.m_interpolation.c_str()
  2019. , var.m_precision.c_str()
  2020. , var.m_type.c_str()
  2021. , name
  2022. );
  2023. }
  2024. }
  2025. }
  2026. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2027. {
  2028. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2029. if (varyingIt != varyingMap.end() )
  2030. {
  2031. const Varying& var = varyingIt->second;
  2032. preprocessor.writef("%s varying %s %s;\n"
  2033. , var.m_interpolation.c_str()
  2034. , var.m_type.c_str()
  2035. , var.m_name.c_str()
  2036. );
  2037. }
  2038. }
  2039. }
  2040. else
  2041. {
  2042. preprocessor.writef(
  2043. "#define lowp\n"
  2044. "#define mediump\n"
  2045. "#define highp\n"
  2046. "#define ivec2 int2\n"
  2047. "#define ivec3 int3\n"
  2048. "#define ivec4 int4\n"
  2049. "#define uvec2 uint2\n"
  2050. "#define uvec3 uint3\n"
  2051. "#define uvec4 uint4\n"
  2052. "#define vec2 float2\n"
  2053. "#define vec3 float3\n"
  2054. "#define vec4 float4\n"
  2055. "#define mat2 float2x2\n"
  2056. "#define mat3 float3x3\n"
  2057. "#define mat4 float4x4\n"
  2058. );
  2059. if (hlsl < 4)
  2060. {
  2061. preprocessor.writef(
  2062. "#define flat\n"
  2063. "#define smooth\n"
  2064. "#define noperspective\n"
  2065. );
  2066. }
  2067. entry[4] = '_';
  2068. if ('f' == shaderType)
  2069. {
  2070. const bool hasFragCoord = NULL != strstr(input, "gl_FragCoord") || hlsl > 3;
  2071. const bool hasFragDepth = NULL != strstr(input, "gl_FragDepth");
  2072. const bool hasFrontFacing = NULL != strstr(input, "gl_FrontFacing");
  2073. const bool hasFragData0 = NULL != strstr(input, "gl_FragData[0]");
  2074. const bool hasFragData1 = NULL != strstr(input, "gl_FragData[1]");
  2075. const bool hasFragData2 = NULL != strstr(input, "gl_FragData[2]");
  2076. const bool hasFragData3 = NULL != strstr(input, "gl_FragData[3]");
  2077. if (!hasFragData0
  2078. && !hasFragData1
  2079. && !hasFragData2
  2080. && !hasFragData3)
  2081. {
  2082. // GL errors when both gl_FragColor and gl_FragData is used.
  2083. // This will trigger the same error with HLSL compiler too.
  2084. preprocessor.writef("#define gl_FragColor gl_FragData_0_\n");
  2085. }
  2086. preprocessor.writef("#define void_main()");
  2087. preprocessor.writef(" \\\n\tvoid main(");
  2088. uint32_t arg = 0;
  2089. if (hasFragCoord)
  2090. {
  2091. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  2092. ++arg;
  2093. }
  2094. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  2095. {
  2096. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2097. if (varyingIt != varyingMap.end() )
  2098. {
  2099. const Varying& var = varyingIt->second;
  2100. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  2101. , arg++ > 0 ? ", " : " "
  2102. , interpolationDx11(var.m_interpolation.c_str() )
  2103. , var.m_type.c_str()
  2104. , var.m_name.c_str()
  2105. , var.m_semantics.c_str()
  2106. );
  2107. }
  2108. }
  2109. addFragData(preprocessor, input, 0, arg++ > 0);
  2110. if (hasFragData1)
  2111. {
  2112. addFragData(preprocessor, input, 1, arg++ > 0);
  2113. }
  2114. if (hasFragData2)
  2115. {
  2116. addFragData(preprocessor, input, 2, arg++ > 0);
  2117. }
  2118. if (hasFragData3)
  2119. {
  2120. addFragData(preprocessor, input, 3, arg++ > 0);
  2121. }
  2122. if (hasFragDepth)
  2123. {
  2124. preprocessor.writef(
  2125. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  2126. , arg++ > 0 ? ", " : " "
  2127. );
  2128. }
  2129. if (hasFrontFacing)
  2130. {
  2131. preprocessor.writef(
  2132. " \\\n\t%sfloat __vface : VFACE"
  2133. , arg++ > 0 ? ", " : " "
  2134. );
  2135. }
  2136. preprocessor.writef(
  2137. " \\\n\t)\n"
  2138. );
  2139. if (hasFrontFacing)
  2140. {
  2141. preprocessor.writef(
  2142. "#define gl_FrontFacing (__vface <= 0.0)\n"
  2143. );
  2144. }
  2145. }
  2146. else if ('v' == shaderType)
  2147. {
  2148. const char* brace = strstr(entry, "{");
  2149. if (NULL != brace)
  2150. {
  2151. const char* end = bx::strmb(brace, '{', '}');
  2152. if (NULL != end)
  2153. {
  2154. strins(const_cast<char*>(end), "__RETURN__;\n");
  2155. }
  2156. }
  2157. preprocessor.writef(
  2158. "struct Output\n"
  2159. "{\n"
  2160. "\tvec4 gl_Position : SV_POSITION;\n"
  2161. "#define gl_Position _varying_.gl_Position\n"
  2162. );
  2163. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2164. {
  2165. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2166. if (varyingIt != varyingMap.end() )
  2167. {
  2168. const Varying& var = varyingIt->second;
  2169. preprocessor.writef("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  2170. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  2171. }
  2172. }
  2173. preprocessor.writef(
  2174. "};\n"
  2175. );
  2176. preprocessor.writef("#define void_main() \\\n");
  2177. preprocessor.writef("Output main(");
  2178. bool first = true;
  2179. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  2180. {
  2181. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2182. if (varyingIt != varyingMap.end() )
  2183. {
  2184. const Varying& var = varyingIt->second;
  2185. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  2186. first = false;
  2187. }
  2188. }
  2189. preprocessor.writef(
  2190. ") \\\n"
  2191. "{ \\\n"
  2192. "\tOutput _varying_;"
  2193. );
  2194. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2195. {
  2196. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2197. if (varyingIt != varyingMap.end() )
  2198. {
  2199. const Varying& var = varyingIt->second;
  2200. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  2201. }
  2202. }
  2203. preprocessor.writef(
  2204. "\n#define __RETURN__ \\\n"
  2205. "\t} \\\n"
  2206. "\treturn _varying_"
  2207. );
  2208. }
  2209. }
  2210. if (preprocessor.run(input) )
  2211. {
  2212. BX_TRACE("Input file: %s", filePath);
  2213. BX_TRACE("Output file: %s", outFilePath);
  2214. if (preprocessOnly)
  2215. {
  2216. bx::CrtFileWriter writer;
  2217. if (0 != writer.open(outFilePath) )
  2218. {
  2219. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2220. return EXIT_FAILURE;
  2221. }
  2222. if (glsl)
  2223. {
  2224. const char* profile = cmdLine.findOption('p', "profile");
  2225. if (NULL == profile)
  2226. {
  2227. writef(&writer
  2228. , "#ifdef GL_ES\n"
  2229. "precision highp float;\n"
  2230. "#endif // GL_ES\n\n"
  2231. );
  2232. }
  2233. }
  2234. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  2235. writer.close();
  2236. return EXIT_SUCCESS;
  2237. }
  2238. {
  2239. bx::CrtFileWriter* writer = NULL;
  2240. if (NULL != bin2c)
  2241. {
  2242. writer = new Bin2cWriter(bin2c);
  2243. }
  2244. else
  2245. {
  2246. writer = new bx::CrtFileWriter;
  2247. }
  2248. if (0 != writer->open(outFilePath) )
  2249. {
  2250. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2251. return EXIT_FAILURE;
  2252. }
  2253. if ('f' == shaderType)
  2254. {
  2255. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  2256. bx::write(writer, inputHash);
  2257. }
  2258. else if ('v' == shaderType)
  2259. {
  2260. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  2261. bx::write(writer, outputHash);
  2262. }
  2263. else
  2264. {
  2265. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  2266. bx::write(writer, outputHash);
  2267. }
  2268. if (glsl)
  2269. {
  2270. std::string code;
  2271. bool hasTextureLod = NULL != bx::findIdentifierMatch(input, s_ARB_shader_texture_lod /*EXT_shader_texture_lod*/);
  2272. if (0 == gles)
  2273. {
  2274. bx::stringPrintf(code, "#version %s\n", profile);
  2275. int32_t version = atoi(profile);
  2276. bx::stringPrintf(code
  2277. , "#define bgfxShadow2D shadow2D\n"
  2278. "#define bgfxShadow2DProj shadow2DProj\n"
  2279. );
  2280. if (hasTextureLod
  2281. && 130 > version)
  2282. {
  2283. bx::stringPrintf(code
  2284. , "#extension GL_ARB_shader_texture_lod : enable\n"
  2285. );
  2286. }
  2287. }
  2288. else
  2289. {
  2290. // Pretend that all extensions are available.
  2291. // This will be stripped later.
  2292. if (hasTextureLod)
  2293. {
  2294. bx::stringPrintf(code
  2295. , "#extension GL_EXT_shader_texture_lod : enable\n"
  2296. "#define texture2DLod texture2DLodEXT\n"
  2297. "#define texture2DProjLod texture2DProjLodEXT\n"
  2298. "#define textureCubeLod textureCubeLodEXT\n"
  2299. // "#define texture2DGrad texture2DGradEXT\n"
  2300. // "#define texture2DProjGrad texture2DProjGradEXT\n"
  2301. // "#define textureCubeGrad textureCubeGradEXT\n"
  2302. );
  2303. }
  2304. if (NULL != bx::findIdentifierMatch(input, s_OES_standard_derivatives) )
  2305. {
  2306. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  2307. }
  2308. if (NULL != bx::findIdentifierMatch(input, s_OES_texture_3D) )
  2309. {
  2310. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  2311. }
  2312. if (NULL != bx::findIdentifierMatch(input, s_EXT_shadow_samplers) )
  2313. {
  2314. bx::stringPrintf(code
  2315. , "#extension GL_EXT_shadow_samplers : enable\n"
  2316. "#define shadow2D shadow2DEXT\n"
  2317. "#define shadow2DProj shadow2DProjEXT\n"
  2318. );
  2319. }
  2320. if (NULL != bx::findIdentifierMatch(input, "gl_FragDepth") )
  2321. {
  2322. bx::stringPrintf(code
  2323. , "#extension GL_EXT_frag_depth : enable\n"
  2324. "#define gl_FragDepth gl_FragDepthEXT\n"
  2325. );
  2326. }
  2327. }
  2328. code += preprocessor.m_preprocessed;
  2329. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  2330. }
  2331. else
  2332. {
  2333. if (hlsl > 3)
  2334. {
  2335. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  2336. }
  2337. else
  2338. {
  2339. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  2340. }
  2341. }
  2342. writer->close();
  2343. delete writer;
  2344. }
  2345. if (compiled)
  2346. {
  2347. if (depends)
  2348. {
  2349. std::string ofp = outFilePath;
  2350. ofp += ".d";
  2351. bx::CrtFileWriter writer;
  2352. if (0 == writer.open(ofp.c_str() ) )
  2353. {
  2354. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  2355. writer.close();
  2356. }
  2357. }
  2358. }
  2359. }
  2360. }
  2361. }
  2362. delete [] data;
  2363. }
  2364. if (compiled)
  2365. {
  2366. return EXIT_SUCCESS;
  2367. }
  2368. remove(outFilePath);
  2369. fprintf(stderr, "Failed to build shader.\n");
  2370. return EXIT_FAILURE;
  2371. }