shaderc.cpp 64 KB

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