shaderc.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774
  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. fprintf(stderr, "Unable to open file '%s'.\n", filePath);
  1621. }
  1622. else
  1623. {
  1624. VaryingMap varyingMap;
  1625. std::string defaultVarying = dir + "varying.def.sc";
  1626. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  1627. File attribdef(varyingdef);
  1628. const char* parse = attribdef.getData();
  1629. if (NULL != parse
  1630. && *parse != '\0')
  1631. {
  1632. preprocessor.addDependency(varyingdef);
  1633. }
  1634. while (NULL != parse
  1635. && *parse != '\0')
  1636. {
  1637. parse = bx::strws(parse);
  1638. const char* eol = strchr(parse, ';');
  1639. if (NULL == eol)
  1640. {
  1641. eol = bx::streol(parse);
  1642. }
  1643. if (NULL != eol)
  1644. {
  1645. const char* precision = NULL;
  1646. const char* interpolation = NULL;
  1647. const char* type = parse;
  1648. if (0 == strncmp(type, "lowp", 4)
  1649. || 0 == strncmp(type, "mediump", 7)
  1650. || 0 == strncmp(type, "highp", 5) )
  1651. {
  1652. precision = type;
  1653. type = parse = bx::strws(bx::strword(parse) );
  1654. }
  1655. if (0 == strncmp(type, "flat", 4)
  1656. || 0 == strncmp(type, "smooth", 6)
  1657. || 0 == strncmp(type, "noperspective", 13) )
  1658. {
  1659. interpolation = type;
  1660. type = parse = bx::strws(bx::strword(parse) );
  1661. }
  1662. const char* name = parse = bx::strws(bx::strword(parse) );
  1663. const char* column = parse = bx::strws(bx::strword(parse) );
  1664. const char* semantics = parse = bx::strws(bx::strnws (parse) );
  1665. const char* assign = parse = bx::strws(bx::strword(parse) );
  1666. const char* init = parse = bx::strws(bx::strnws (parse) );
  1667. if (type < eol
  1668. && name < eol
  1669. && column < eol
  1670. && ':' == *column
  1671. && semantics < eol)
  1672. {
  1673. Varying var;
  1674. if (NULL != precision)
  1675. {
  1676. var.m_precision.assign(precision, bx::strword(precision)-precision);
  1677. }
  1678. if (NULL != interpolation)
  1679. {
  1680. var.m_interpolation.assign(interpolation, bx::strword(interpolation)-interpolation);
  1681. }
  1682. var.m_type.assign(type, bx::strword(type)-type);
  1683. var.m_name.assign(name, bx::strword(name)-name);
  1684. var.m_semantics.assign(semantics, bx::strword(semantics)-semantics);
  1685. if (assign < eol
  1686. && '=' == *assign
  1687. && init < eol)
  1688. {
  1689. var.m_init.assign(init, eol-init);
  1690. }
  1691. varyingMap.insert(std::make_pair(var.m_name, var) );
  1692. }
  1693. parse = bx::strnl(eol);
  1694. }
  1695. }
  1696. InOut shaderInputs;
  1697. InOut shaderOutputs;
  1698. uint32_t inputHash = 0;
  1699. uint32_t outputHash = 0;
  1700. char* data;
  1701. char* input;
  1702. {
  1703. const size_t padding = 1024;
  1704. uint32_t size = (uint32_t)fsize(file);
  1705. data = new char[size+padding+1];
  1706. size = (uint32_t)fread(data, 1, size, file);
  1707. // Compiler generates "error X3000: syntax error: unexpected end of file"
  1708. // if input doesn't have empty line at EOF.
  1709. data[size] = '\n';
  1710. memset(&data[size+1], 0, padding);
  1711. fclose(file);
  1712. input = const_cast<char*>(bx::strws(data) );
  1713. while (input[0] == '$')
  1714. {
  1715. const char* str = bx::strws(input+1);
  1716. const char* eol = bx::streol(str);
  1717. const char* nl = bx::strnl(eol);
  1718. input = const_cast<char*>(nl);
  1719. if (0 == strncmp(str, "input", 5) )
  1720. {
  1721. str += 5;
  1722. const char* comment = strstr(str, "//");
  1723. eol = NULL != comment && comment < eol ? comment : eol;
  1724. inputHash = parseInOut(shaderInputs, str, eol);
  1725. }
  1726. else if (0 == strncmp(str, "output", 6) )
  1727. {
  1728. str += 6;
  1729. const char* comment = strstr(str, "//");
  1730. eol = NULL != comment && comment < eol ? comment : eol;
  1731. outputHash = parseInOut(shaderOutputs, str, eol);
  1732. }
  1733. else if (0 == strncmp(str, "raw", 3) )
  1734. {
  1735. raw = true;
  1736. str += 3;
  1737. }
  1738. input = const_cast<char*>(bx::strws(input) );
  1739. }
  1740. if (!raw)
  1741. {
  1742. // To avoid commented code being recognized as used feature,
  1743. // first preprocess pass is used to strip all comments before
  1744. // substituting code.
  1745. preprocessor.run(input);
  1746. delete [] data;
  1747. size = (uint32_t)preprocessor.m_preprocessed.size();
  1748. data = new char[size+padding+1];
  1749. memcpy(data, preprocessor.m_preprocessed.c_str(), size);
  1750. memset(&data[size], 0, padding+1);
  1751. input = data;
  1752. }
  1753. }
  1754. if (raw)
  1755. {
  1756. bx::CrtFileWriter* writer = NULL;
  1757. if (NULL != bin2c)
  1758. {
  1759. writer = new Bin2cWriter(bin2c);
  1760. }
  1761. else
  1762. {
  1763. writer = new bx::CrtFileWriter;
  1764. }
  1765. if (0 != writer->open(outFilePath) )
  1766. {
  1767. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1768. return EXIT_FAILURE;
  1769. }
  1770. uint32_t inputHash = 0;
  1771. uint32_t outputHash = 0;
  1772. if ('f' == shaderType)
  1773. {
  1774. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  1775. bx::write(writer, inputHash);
  1776. }
  1777. else if ('v' == shaderType)
  1778. {
  1779. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  1780. bx::write(writer, outputHash);
  1781. }
  1782. else
  1783. {
  1784. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1785. bx::write(writer, outputHash);
  1786. }
  1787. if (glsl)
  1788. {
  1789. bx::write(writer, uint16_t(0) );
  1790. uint32_t shaderSize = (uint32_t)strlen(input);
  1791. bx::write(writer, shaderSize);
  1792. bx::write(writer, input, shaderSize);
  1793. bx::write(writer, uint8_t(0) );
  1794. compiled = true;
  1795. }
  1796. else
  1797. {
  1798. if (d3d > 9)
  1799. {
  1800. compiled = compileHLSLShaderDx11(cmdLine, input, writer);
  1801. }
  1802. else
  1803. {
  1804. compiled = compileHLSLShaderDx9(cmdLine, input, writer);
  1805. }
  1806. }
  1807. writer->close();
  1808. delete writer;
  1809. }
  1810. else if ('c' == shaderType) // Compute
  1811. {
  1812. char* entry = strstr(input, "void main()");
  1813. if (NULL == entry)
  1814. {
  1815. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1816. }
  1817. else
  1818. {
  1819. if (glsl)
  1820. {
  1821. }
  1822. else
  1823. {
  1824. preprocessor.writef(
  1825. "#define lowp\n"
  1826. "#define mediump\n"
  1827. "#define highp\n"
  1828. "#define ivec2 int2\n"
  1829. "#define ivec3 int3\n"
  1830. "#define ivec4 int4\n"
  1831. "#define uvec2 uint2\n"
  1832. "#define uvec3 uint3\n"
  1833. "#define uvec4 uint4\n"
  1834. "#define vec2 float2\n"
  1835. "#define vec3 float3\n"
  1836. "#define vec4 float4\n"
  1837. "#define mat2 float2x2\n"
  1838. "#define mat3 float3x3\n"
  1839. "#define mat4 float4x4\n"
  1840. );
  1841. entry[4] = '_';
  1842. preprocessor.writef("#define void_main()");
  1843. preprocessor.writef(" \\\n\tvoid main(");
  1844. uint32_t arg = 0;
  1845. const bool hasLocalInvocationID = NULL != strstr(input, "gl_LocalInvocationID");
  1846. const bool hasLocalInvocationIndex = NULL != strstr(input, "gl_LocalInvocationIndex");
  1847. const bool hasGlobalInvocationID = NULL != strstr(input, "gl_GlobalInvocationID");
  1848. const bool hasWorkGroupID = NULL != strstr(input, "gl_WorkGroupID");
  1849. if (hasLocalInvocationID)
  1850. {
  1851. preprocessor.writef(
  1852. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1853. , arg++ > 0 ? ", " : " "
  1854. );
  1855. }
  1856. if (hasLocalInvocationIndex)
  1857. {
  1858. preprocessor.writef(
  1859. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1860. , arg++ > 0 ? ", " : " "
  1861. );
  1862. }
  1863. if (hasGlobalInvocationID)
  1864. {
  1865. preprocessor.writef(
  1866. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1867. , arg++ > 0 ? ", " : " "
  1868. );
  1869. }
  1870. if (hasWorkGroupID)
  1871. {
  1872. preprocessor.writef(
  1873. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1874. , arg++ > 0 ? ", " : " "
  1875. );
  1876. }
  1877. preprocessor.writef(
  1878. " \\\n\t)\n"
  1879. );
  1880. }
  1881. if (preprocessor.run(input) )
  1882. {
  1883. BX_TRACE("Input file: %s", filePath);
  1884. BX_TRACE("Output file: %s", outFilePath);
  1885. if (preprocessOnly)
  1886. {
  1887. bx::CrtFileWriter writer;
  1888. if (0 != writer.open(outFilePath) )
  1889. {
  1890. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1891. return EXIT_FAILURE;
  1892. }
  1893. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1894. writer.close();
  1895. return EXIT_SUCCESS;
  1896. }
  1897. {
  1898. bx::CrtFileWriter* writer = NULL;
  1899. if (NULL != bin2c)
  1900. {
  1901. writer = new Bin2cWriter(bin2c);
  1902. }
  1903. else
  1904. {
  1905. writer = new bx::CrtFileWriter;
  1906. }
  1907. if (0 != writer->open(outFilePath) )
  1908. {
  1909. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1910. return EXIT_FAILURE;
  1911. }
  1912. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1913. bx::write(writer, outputHash);
  1914. if (glsl)
  1915. {
  1916. std::string code;
  1917. if (gles)
  1918. {
  1919. bx::stringPrintf(code, "#version 310 es\n");
  1920. }
  1921. else
  1922. {
  1923. int32_t version = atoi(profile);
  1924. bx::stringPrintf(code, "#version %d\n", version == 0 ? 430 : version);
  1925. }
  1926. code += preprocessor.m_preprocessed;
  1927. #if 1
  1928. bx::write(writer, uint16_t(0) );
  1929. uint32_t shaderSize = (uint32_t)code.size();
  1930. bx::write(writer, shaderSize);
  1931. bx::write(writer, code.c_str(), shaderSize);
  1932. bx::write(writer, uint8_t(0) );
  1933. compiled = true;
  1934. #else
  1935. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  1936. #endif // 0
  1937. }
  1938. else
  1939. {
  1940. if (d3d > 9)
  1941. {
  1942. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1943. }
  1944. else
  1945. {
  1946. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1947. }
  1948. }
  1949. writer->close();
  1950. delete writer;
  1951. }
  1952. if (compiled)
  1953. {
  1954. if (depends)
  1955. {
  1956. std::string ofp = outFilePath;
  1957. ofp += ".d";
  1958. bx::CrtFileWriter writer;
  1959. if (0 == writer.open(ofp.c_str() ) )
  1960. {
  1961. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1962. writer.close();
  1963. }
  1964. }
  1965. }
  1966. }
  1967. }
  1968. }
  1969. else // Vertex/Fragment
  1970. {
  1971. char* entry = strstr(input, "void main()");
  1972. if (NULL == entry)
  1973. {
  1974. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1975. }
  1976. else
  1977. {
  1978. if (glsl)
  1979. {
  1980. preprocessor.writef(
  1981. "#define ivec2 vec2\n"
  1982. "#define ivec3 vec3\n"
  1983. "#define ivec4 vec4\n"
  1984. );
  1985. if (0 == gles)
  1986. {
  1987. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1988. // not as GLSL language 1.2 specs shadow2D/Proj.
  1989. preprocessor.writef(
  1990. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1991. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1992. );
  1993. }
  1994. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1995. {
  1996. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1997. if (varyingIt != varyingMap.end() )
  1998. {
  1999. const Varying& var = varyingIt->second;
  2000. const char* name = var.m_name.c_str();
  2001. if (0 == strncmp(name, "a_", 2)
  2002. || 0 == strncmp(name, "i_", 2) )
  2003. {
  2004. preprocessor.writef("attribute %s %s %s %s;\n"
  2005. , var.m_precision.c_str()
  2006. , var.m_interpolation.c_str()
  2007. , var.m_type.c_str()
  2008. , name
  2009. );
  2010. }
  2011. else
  2012. {
  2013. preprocessor.writef("%s varying %s %s %s;\n"
  2014. , var.m_interpolation.c_str()
  2015. , var.m_precision.c_str()
  2016. , var.m_type.c_str()
  2017. , name
  2018. );
  2019. }
  2020. }
  2021. }
  2022. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2023. {
  2024. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2025. if (varyingIt != varyingMap.end() )
  2026. {
  2027. const Varying& var = varyingIt->second;
  2028. preprocessor.writef("%s varying %s %s;\n"
  2029. , var.m_interpolation.c_str()
  2030. , var.m_type.c_str()
  2031. , var.m_name.c_str()
  2032. );
  2033. }
  2034. }
  2035. }
  2036. else
  2037. {
  2038. preprocessor.writef(
  2039. "#define lowp\n"
  2040. "#define mediump\n"
  2041. "#define highp\n"
  2042. "#define ivec2 int2\n"
  2043. "#define ivec3 int3\n"
  2044. "#define ivec4 int4\n"
  2045. "#define uvec2 uint2\n"
  2046. "#define uvec3 uint3\n"
  2047. "#define uvec4 uint4\n"
  2048. "#define vec2 float2\n"
  2049. "#define vec3 float3\n"
  2050. "#define vec4 float4\n"
  2051. "#define mat2 float2x2\n"
  2052. "#define mat3 float3x3\n"
  2053. "#define mat4 float4x4\n"
  2054. );
  2055. if (hlsl < 4)
  2056. {
  2057. preprocessor.writef(
  2058. "#define flat\n"
  2059. "#define smooth\n"
  2060. "#define noperspective\n"
  2061. );
  2062. }
  2063. entry[4] = '_';
  2064. if ('f' == shaderType)
  2065. {
  2066. const char* brace = strstr(entry, "{");
  2067. if (NULL != brace)
  2068. {
  2069. strins(const_cast<char*>(brace+1), "\nvec4 bgfx_VoidFrag;\n");
  2070. }
  2071. const bool hasFragCoord = NULL != strstr(input, "gl_FragCoord") || hlsl > 3;
  2072. const bool hasFragDepth = NULL != strstr(input, "gl_FragDepth");
  2073. const bool hasFrontFacing = NULL != strstr(input, "gl_FrontFacing");
  2074. bool hasFragData[8] = {};
  2075. uint32_t numFragData = 0;
  2076. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  2077. {
  2078. char temp[32];
  2079. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  2080. hasFragData[ii] = NULL != strstr(input, temp);
  2081. numFragData += hasFragData[ii];
  2082. }
  2083. if (0 == numFragData)
  2084. {
  2085. // GL errors when both gl_FragColor and gl_FragData is used.
  2086. // This will trigger the same error with HLSL compiler too.
  2087. preprocessor.writef("#define gl_FragColor gl_FragData_0_\n");
  2088. }
  2089. preprocessor.writef("#define void_main()");
  2090. preprocessor.writef(" \\\n\tvoid main(");
  2091. uint32_t arg = 0;
  2092. if (hasFragCoord)
  2093. {
  2094. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  2095. ++arg;
  2096. }
  2097. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  2098. {
  2099. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2100. if (varyingIt != varyingMap.end() )
  2101. {
  2102. const Varying& var = varyingIt->second;
  2103. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  2104. , arg++ > 0 ? ", " : " "
  2105. , interpolationDx11(var.m_interpolation.c_str() )
  2106. , var.m_type.c_str()
  2107. , var.m_name.c_str()
  2108. , var.m_semantics.c_str()
  2109. );
  2110. }
  2111. }
  2112. addFragData(preprocessor, input, 0, arg++ > 0);
  2113. const uint32_t maxRT = d3d > 9 ? BX_COUNTOF(hasFragData) : 4;
  2114. for (uint32_t ii = 1; ii < BX_COUNTOF(hasFragData); ++ii)
  2115. {
  2116. if (ii < maxRT)
  2117. {
  2118. if (hasFragData[ii])
  2119. {
  2120. addFragData(preprocessor, input, ii, arg++ > 0);
  2121. }
  2122. }
  2123. else
  2124. {
  2125. voidFragData(input, ii);
  2126. }
  2127. }
  2128. if (hasFragDepth)
  2129. {
  2130. preprocessor.writef(
  2131. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  2132. , arg++ > 0 ? ", " : " "
  2133. );
  2134. }
  2135. if (hasFrontFacing
  2136. && hlsl >= 3)
  2137. {
  2138. preprocessor.writef(
  2139. " \\\n\t%sfloat __vface : VFACE"
  2140. , arg++ > 0 ? ", " : " "
  2141. );
  2142. }
  2143. preprocessor.writef(
  2144. " \\\n\t)\n"
  2145. );
  2146. if (hasFrontFacing)
  2147. {
  2148. if (hlsl >= 3)
  2149. {
  2150. preprocessor.writef(
  2151. "#define gl_FrontFacing (__vface <= 0.0)\n"
  2152. );
  2153. }
  2154. else
  2155. {
  2156. preprocessor.writef(
  2157. "#define gl_FrontFacing false\n"
  2158. );
  2159. }
  2160. }
  2161. }
  2162. else if ('v' == shaderType)
  2163. {
  2164. const char* brace = strstr(entry, "{");
  2165. if (NULL != brace)
  2166. {
  2167. const char* end = bx::strmb(brace, '{', '}');
  2168. if (NULL != end)
  2169. {
  2170. strins(const_cast<char*>(end), "__RETURN__;\n");
  2171. }
  2172. }
  2173. preprocessor.writef(
  2174. "struct Output\n"
  2175. "{\n"
  2176. "\tvec4 gl_Position : SV_POSITION;\n"
  2177. "#define gl_Position _varying_.gl_Position\n"
  2178. );
  2179. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.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("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  2186. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  2187. }
  2188. }
  2189. preprocessor.writef(
  2190. "};\n"
  2191. );
  2192. preprocessor.writef("#define void_main() \\\n");
  2193. preprocessor.writef("Output main(");
  2194. bool first = true;
  2195. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  2196. {
  2197. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2198. if (varyingIt != varyingMap.end() )
  2199. {
  2200. const Varying& var = varyingIt->second;
  2201. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  2202. first = false;
  2203. }
  2204. }
  2205. preprocessor.writef(
  2206. ") \\\n"
  2207. "{ \\\n"
  2208. "\tOutput _varying_;"
  2209. );
  2210. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2211. {
  2212. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2213. if (varyingIt != varyingMap.end() )
  2214. {
  2215. const Varying& var = varyingIt->second;
  2216. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  2217. }
  2218. }
  2219. preprocessor.writef(
  2220. "\n#define __RETURN__ \\\n"
  2221. "\t} \\\n"
  2222. "\treturn _varying_"
  2223. );
  2224. }
  2225. }
  2226. if (preprocessor.run(input) )
  2227. {
  2228. BX_TRACE("Input file: %s", filePath);
  2229. BX_TRACE("Output file: %s", outFilePath);
  2230. if (preprocessOnly)
  2231. {
  2232. bx::CrtFileWriter writer;
  2233. if (0 != writer.open(outFilePath) )
  2234. {
  2235. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2236. return EXIT_FAILURE;
  2237. }
  2238. if (glsl)
  2239. {
  2240. const char* profile = cmdLine.findOption('p', "profile");
  2241. if (NULL == profile)
  2242. {
  2243. writef(&writer
  2244. , "#ifdef GL_ES\n"
  2245. "precision highp float;\n"
  2246. "#endif // GL_ES\n\n"
  2247. );
  2248. }
  2249. }
  2250. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  2251. writer.close();
  2252. return EXIT_SUCCESS;
  2253. }
  2254. {
  2255. bx::CrtFileWriter* writer = NULL;
  2256. if (NULL != bin2c)
  2257. {
  2258. writer = new Bin2cWriter(bin2c);
  2259. }
  2260. else
  2261. {
  2262. writer = new bx::CrtFileWriter;
  2263. }
  2264. if (0 != writer->open(outFilePath) )
  2265. {
  2266. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2267. return EXIT_FAILURE;
  2268. }
  2269. if ('f' == shaderType)
  2270. {
  2271. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  2272. bx::write(writer, inputHash);
  2273. }
  2274. else if ('v' == shaderType)
  2275. {
  2276. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  2277. bx::write(writer, outputHash);
  2278. }
  2279. else
  2280. {
  2281. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  2282. bx::write(writer, outputHash);
  2283. }
  2284. if (glsl)
  2285. {
  2286. std::string code;
  2287. bool hasTextureLod = NULL != bx::findIdentifierMatch(input, s_ARB_shader_texture_lod /*EXT_shader_texture_lod*/);
  2288. if (0 == gles)
  2289. {
  2290. bx::stringPrintf(code, "#version %s\n", profile);
  2291. int32_t version = atoi(profile);
  2292. bx::stringPrintf(code
  2293. , "#define bgfxShadow2D shadow2D\n"
  2294. "#define bgfxShadow2DProj shadow2DProj\n"
  2295. );
  2296. if (hasTextureLod
  2297. && 130 > version)
  2298. {
  2299. bx::stringPrintf(code
  2300. , "#extension GL_ARB_shader_texture_lod : enable\n"
  2301. );
  2302. }
  2303. }
  2304. else
  2305. {
  2306. // Pretend that all extensions are available.
  2307. // This will be stripped later.
  2308. if (hasTextureLod)
  2309. {
  2310. bx::stringPrintf(code
  2311. , "#extension GL_EXT_shader_texture_lod : enable\n"
  2312. "#define texture2DLod texture2DLodEXT\n"
  2313. "#define texture2DProjLod texture2DProjLodEXT\n"
  2314. "#define textureCubeLod textureCubeLodEXT\n"
  2315. // "#define texture2DGrad texture2DGradEXT\n"
  2316. // "#define texture2DProjGrad texture2DProjGradEXT\n"
  2317. // "#define textureCubeGrad textureCubeGradEXT\n"
  2318. );
  2319. }
  2320. if (NULL != bx::findIdentifierMatch(input, s_OES_standard_derivatives) )
  2321. {
  2322. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  2323. }
  2324. if (NULL != bx::findIdentifierMatch(input, s_OES_texture_3D) )
  2325. {
  2326. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  2327. }
  2328. if (NULL != bx::findIdentifierMatch(input, s_EXT_shadow_samplers) )
  2329. {
  2330. bx::stringPrintf(code
  2331. , "#extension GL_EXT_shadow_samplers : enable\n"
  2332. "#define shadow2D shadow2DEXT\n"
  2333. "#define shadow2DProj shadow2DProjEXT\n"
  2334. );
  2335. }
  2336. if (NULL != bx::findIdentifierMatch(input, "gl_FragDepth") )
  2337. {
  2338. bx::stringPrintf(code
  2339. , "#extension GL_EXT_frag_depth : enable\n"
  2340. "#define gl_FragDepth gl_FragDepthEXT\n"
  2341. );
  2342. }
  2343. }
  2344. code += preprocessor.m_preprocessed;
  2345. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  2346. }
  2347. else
  2348. {
  2349. if (d3d > 9)
  2350. {
  2351. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  2352. }
  2353. else
  2354. {
  2355. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  2356. }
  2357. }
  2358. writer->close();
  2359. delete writer;
  2360. }
  2361. if (compiled)
  2362. {
  2363. if (depends)
  2364. {
  2365. std::string ofp = outFilePath;
  2366. ofp += ".d";
  2367. bx::CrtFileWriter writer;
  2368. if (0 == writer.open(ofp.c_str() ) )
  2369. {
  2370. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  2371. writer.close();
  2372. }
  2373. }
  2374. }
  2375. }
  2376. }
  2377. }
  2378. delete [] data;
  2379. }
  2380. if (compiled)
  2381. {
  2382. return EXIT_SUCCESS;
  2383. }
  2384. remove(outFilePath);
  2385. fprintf(stderr, "Failed to build shader.\n");
  2386. return EXIT_FAILURE;
  2387. }