shaderc.cpp 63 KB

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