ShaderProgramParser.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/ShaderCompiler/ShaderProgramParser.h>
  6. namespace anki
  7. {
  8. #define ANKI_PP_ERROR_MALFORMED() \
  9. ANKI_SHADER_COMPILER_LOGE("%s: Malformed expression: %s", fname.cstr(), line.cstr()); \
  10. return Error::USER_DATA
  11. #define ANKI_PP_ERROR_MALFORMED_MSG(msg_) \
  12. ANKI_SHADER_COMPILER_LOGE("%s: " msg_ ": %s", fname.cstr(), line.cstr()); \
  13. return Error::USER_DATA
  14. static const Array<CString, U32(ShaderType::COUNT)> SHADER_STAGE_NAMES = {
  15. {"VERTEX", "TESSELLATION_CONTROL", "TESSELLATION_EVALUATION", "GEOMETRY", "FRAGMENT", "COMPUTE", "RAY_GEN",
  16. "ANY_HIT", "CLOSEST_HIT", "MISS", "INTERSECTION", "CALLABLE"}};
  17. static const char* SHADER_HEADER = R"(#version 460 core
  18. #define ANKI_BACKEND_MINOR %u
  19. #define ANKI_BACKEND_MAJOR %u
  20. #define ANKI_VENDOR_%s 1
  21. #define ANKI_%s_SHADER 1
  22. #define gl_VertexID gl_VertexIndex
  23. #extension GL_EXT_control_flow_attributes : require
  24. #define ANKI_UNROLL [[unroll]]
  25. #define ANKI_LOOP [[dont_unroll]]
  26. #define ANKI_BRANCH [[branch]]
  27. #define ANKI_FLATTEN [[flatten]]
  28. #extension GL_KHR_shader_subgroup_vote : require
  29. #extension GL_KHR_shader_subgroup_ballot : require
  30. #extension GL_KHR_shader_subgroup_shuffle : require
  31. #extension GL_KHR_shader_subgroup_arithmetic : require
  32. #extension GL_EXT_samplerless_texture_functions : require
  33. #extension GL_EXT_shader_image_load_formatted : require
  34. #extension GL_EXT_nonuniform_qualifier : enable
  35. #extension GL_EXT_buffer_reference : enable
  36. #extension GL_EXT_buffer_reference2 : enable
  37. #extension GL_EXT_shader_explicit_arithmetic_types : enable
  38. #extension GL_EXT_shader_explicit_arithmetic_types_int8 : enable
  39. #extension GL_EXT_shader_explicit_arithmetic_types_int16 : enable
  40. #extension GL_EXT_shader_explicit_arithmetic_types_int32 : enable
  41. #extension GL_EXT_shader_explicit_arithmetic_types_int64 : enable
  42. #extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable
  43. #extension GL_EXT_shader_explicit_arithmetic_types_float32 : enable
  44. #extension GL_EXT_shader_explicit_arithmetic_types_float64 : enable
  45. #extension GL_EXT_shader_atomic_int64 : enable
  46. #extension GL_EXT_shader_subgroup_extended_types_int64 : enable
  47. #extension GL_EXT_nonuniform_qualifier : enable
  48. #extension GL_EXT_scalar_block_layout : enable
  49. #define ANKI_MAX_BINDLESS_TEXTURES %u
  50. #define ANKI_MAX_BINDLESS_IMAGES %u
  51. #if %u || defined(ANKI_RAY_GEN_SHADER) || defined(ANKI_ANY_HIT_SHADER) || defined(ANKI_CLOSEST_HIT_SHADER) || defined(ANKI_MISS_SHADER) || defined(ANKI_INTERSECTION_SHADER) || defined(ANKI_CALLABLE_SHADER)
  52. # extension GL_EXT_ray_tracing : enable
  53. #endif
  54. #define ANKI_BINDLESS_SET(set_) \
  55. layout(set = set_, binding = 0) uniform utexture2D u_bindlessTextures2dU32[ANKI_MAX_BINDLESS_TEXTURES]; \
  56. layout(set = set_, binding = 0) uniform itexture2D u_bindlessTextures2dI32[ANKI_MAX_BINDLESS_TEXTURES]; \
  57. layout(set = set_, binding = 0) uniform texture2D u_bindlessTextures2dF32[ANKI_MAX_BINDLESS_TEXTURES]; \
  58. layout(set = set_, binding = 1) uniform readonly uimage2D u_bindlessImages2dU32[ANKI_MAX_BINDLESS_IMAGES]; \
  59. layout(set = set_, binding = 1) uniform readonly iimage2D u_bindlessImages2dI32[ANKI_MAX_BINDLESS_IMAGES]; \
  60. layout(set = set_, binding = 1) uniform readonly image2D u_bindlessImages2dF32[ANKI_MAX_BINDLESS_IMAGES]
  61. #define F32 float
  62. #define _ANKI_SIZEOF_float 4
  63. #define Vec2 vec2
  64. #define _ANKI_SIZEOF_vec2 8
  65. #define Vec3 vec3
  66. #define _ANKI_SIZEOF_vec3 12
  67. #define Vec4 vec4
  68. #define _ANKI_SIZEOF_vec4 16
  69. #define F16 float16_t
  70. #define _ANKI_SIZEOF_float16_t 2
  71. #define HVec2 f16vec2
  72. #define _ANKI_SIZEOF_f16vec2 4
  73. #define HVec3 f16vec3
  74. #define _ANKI_SIZEOF_f16vec3 6
  75. #define HVec4 f16vec4
  76. #define _ANKI_SIZEOF_f16vec4 8
  77. #define U8 uint8_t
  78. #define _ANKI_SIZEOF_uint8_t 1
  79. #define U8Vec2 u8vec2
  80. #define _ANKI_SIZEOF_u8vec2 2
  81. #define U8Vec3 u8vec3
  82. #define _ANKI_SIZEOF_u8vec3 3
  83. #define U8Vec4 u8vec4
  84. #define _ANKI_SIZEOF_u8vec4 4
  85. #define I8 int8_t
  86. #define _ANKI_SIZEOF_int8_t 1
  87. #define I8Vec2 i8vec2
  88. #define _ANKI_SIZEOF_i8vec2 2
  89. #define I8Vec3 i8vec3
  90. #define _ANKI_SIZEOF_i8vec3 3
  91. #define I8Vec4 i8vec4
  92. #define _ANKI_SIZEOF_i8vec4 4
  93. #define U16 uint16_t
  94. #define _ANKI_SIZEOF_uint16_t 2
  95. #define U16Vec2 u16vec2
  96. #define _ANKI_SIZEOF_u16vec2 4
  97. #define U16Vec3 u16vec3
  98. #define _ANKI_SIZEOF_u16vec3 6
  99. #define U16Vec4 u16vec4
  100. #define _ANKI_SIZEOF_u16vec4 8
  101. #define I16 int16_t
  102. #define _ANKI_SIZEOF_int16_t 2
  103. #define I16Vec2 i16vec2
  104. #define _ANKI_SIZEOF_i16vec2 4
  105. #define I16Vec3 i16vec3
  106. #define _ANKI_SIZEOF_i16vec3 6
  107. #define i16Vec4 i16vec4
  108. #define _ANKI_SIZEOF_i16vec4 8
  109. #define U32 uint
  110. #define _ANKI_SIZEOF_uint 4
  111. #define UVec2 uvec2
  112. #define _ANKI_SIZEOF_uvec2 8
  113. #define UVec3 uvec3
  114. #define _ANKI_SIZEOF_uvec3 12
  115. #define UVec4 uvec4
  116. #define _ANKI_SIZEOF_uvec4 16
  117. #define I32 int
  118. #define _ANKI_SIZEOF_int 4
  119. #define IVec2 ivec2
  120. #define _ANKI_SIZEOF_ivec2 8
  121. #define IVec3 ivec3
  122. #define _ANKI_SIZEOF_ivec3 12
  123. #define IVec4 ivec4
  124. #define _ANKI_SIZEOF_ivec4 16
  125. #define U64 uint64_t
  126. #define _ANKI_SIZEOF_uint64_t 8
  127. #define U64Vec2 u64vec2
  128. #define _ANKI_SIZEOF_u64vec2 16
  129. #define U64Vec3 u64vec3
  130. #define _ANKI_SIZEOF_u64vec3 24
  131. #define U64Vec4 u64vec4
  132. #define _ANKI_SIZEOF_u64vec4 32
  133. #define I64 int64_t
  134. #define _ANKI_SIZEOF_int64_t 8
  135. #define I64Vec2 i64vec2
  136. #define _ANKI_SIZEOF_i64vec2 16
  137. #define I64Vec3 i64vec3
  138. #define _ANKI_SIZEOF_i64vec3 24
  139. #define I64Vec4 i64vec4
  140. #define _ANKI_SIZEOF_i64vec4 32
  141. #define Mat3 mat3
  142. #define Mat4 mat4
  143. #define _ANKI_SIZEOF_mat4 64
  144. #define Mat3x4 mat3x4
  145. #define _ANKI_SIZEOF_mat3x4 48
  146. #define Bool bool
  147. #define _ANKI_CONCATENATE(a, b) a##b
  148. #define ANKI_CONCATENATE(a, b) _ANKI_CONCATENATE(a, b)
  149. #define ANKI_SIZEOF(type) _ANKI_CONCATENATE(_ANKI_SIZEOF_, type)
  150. #define ANKI_ALIGNOF(type) _ANKI_CONCATENATE(_ANKI_ALIGNOF_, type)
  151. #define _ANKI_SCONST_X(type, n, id, defltVal) \
  152. layout(constant_id = id) const type n = defltVal; \
  153. const U32 ANKI_CONCATENATE(n, _CONST_ID) = id
  154. #define _ANKI_SCONST_X2(type, componentType, n, id, defltVal, constWorkaround) \
  155. layout(constant_id = id + 0) const componentType ANKI_CONCATENATE(_anki_const_0_2_, n) = defltVal[0]; \
  156. layout(constant_id = id + 1) const componentType ANKI_CONCATENATE(_anki_const_1_2_, n) = defltVal[1]; \
  157. constWorkaround componentType ANKI_CONCATENATE(n, _X) = ANKI_CONCATENATE(_anki_const_0_2_, n) + componentType(0); \
  158. constWorkaround componentType ANKI_CONCATENATE(n, _Y) = ANKI_CONCATENATE(_anki_const_1_2_, n) + componentType(0); \
  159. constWorkaround type n = type(ANKI_CONCATENATE(n, _X), ANKI_CONCATENATE(n, _Y)); \
  160. const UVec2 ANKI_CONCATENATE(n, _CONST_ID) = UVec2(id, id + 1)
  161. #define _ANKI_SCONST_X3(type, componentType, n, id, defltVal, constWorkaround) \
  162. layout(constant_id = id + 0) const componentType ANKI_CONCATENATE(_anki_const_0_3_, n) = defltVal[0]; \
  163. layout(constant_id = id + 1) const componentType ANKI_CONCATENATE(_anki_const_1_3_, n) = defltVal[1]; \
  164. layout(constant_id = id + 2) const componentType ANKI_CONCATENATE(_anki_const_2_3_, n) = defltVal[2]; \
  165. constWorkaround componentType ANKI_CONCATENATE(n, _X) = ANKI_CONCATENATE(_anki_const_0_3_, n) + componentType(0); \
  166. constWorkaround componentType ANKI_CONCATENATE(n, _Y) = ANKI_CONCATENATE(_anki_const_1_3_, n) + componentType(0); \
  167. constWorkaround componentType ANKI_CONCATENATE(n, _Z) = ANKI_CONCATENATE(_anki_const_2_3_, n) + componentType(0); \
  168. constWorkaround type n = type(ANKI_CONCATENATE(n, _X), ANKI_CONCATENATE(n, _Y), ANKI_CONCATENATE(n, _Z)); \
  169. const UVec3 ANKI_CONCATENATE(n, _CONST_ID) = UVec3(id, id + 1, id + 2)
  170. #define _ANKI_SCONST_X4(type, componentType, n, id, defltVal, constWorkaround) \
  171. layout(constant_id = id + 0) const componentType ANKI_CONCATENATE(_anki_const_0_4_, n) = defltVal[0]; \
  172. layout(constant_id = id + 1) const componentType ANKI_CONCATENATE(_anki_const_1_4_, n) = defltVal[1]; \
  173. layout(constant_id = id + 2) const componentType ANKI_CONCATENATE(_anki_const_2_4_, n) = defltVal[2]; \
  174. layout(constant_id = id + 3) const componentType ANKI_CONCATENATE(_anki_const_3_4_, n) = defltVal[3]; \
  175. constWorkaround componentType ANKI_CONCATENATE(n, _X) = ANKI_CONCATENATE(_anki_const_0_4_, n) + componentType(0); \
  176. constWorkaround componentType ANKI_CONCATENATE(n, _Y) = ANKI_CONCATENATE(_anki_const_1_4_, n) + componentType(0); \
  177. constWorkaround componentType ANKI_CONCATENATE(n, _Z) = ANKI_CONCATENATE(_anki_const_2_4_, n) + componentType(0); \
  178. constWorkaround componentType ANKI_CONCATENATE(n, _W) = ANKI_CONCATENATE(_anki_const_3_4_, n) + componentType(0); \
  179. constWorkaround type n = type(ANKI_CONCATENATE(n, _X), ANKI_CONCATENATE(n, _Y), ANKI_CONCATENATE(n, _Z), \
  180. ANKI_CONCATENATE(n, _W)); \
  181. const UVec4 ANKI_CONCATENATE(n, _CONST_ID) = UVec4(id, id + 1, id + 2, id + 3)
  182. #define ANKI_SPECIALIZATION_CONSTANT_I32(n, id, defltVal) _ANKI_SCONST_X(I32, n, id, defltVal)
  183. #define ANKI_SPECIALIZATION_CONSTANT_IVEC2(n, id, defltVal) _ANKI_SCONST_X2(IVec2, I32, n, id, defltVal, const)
  184. #define ANKI_SPECIALIZATION_CONSTANT_IVEC3(n, id, defltVal) _ANKI_SCONST_X3(IVec3, I32, n, id, defltVal, const)
  185. #define ANKI_SPECIALIZATION_CONSTANT_IVEC4(n, id, defltVal) _ANKI_SCONST_X4(IVec4, I32, n, id, defltVal, const)
  186. #define ANKI_SPECIALIZATION_CONSTANT_U32(n, id, defltVal) _ANKI_SCONST_X(U32, n, id, defltVal)
  187. #define ANKI_SPECIALIZATION_CONSTANT_UVEC2(n, id, defltVal) _ANKI_SCONST_X2(UVec2, U32, n, id, defltVal, const)
  188. #define ANKI_SPECIALIZATION_CONSTANT_UVEC3(n, id, defltVal) _ANKI_SCONST_X3(UVec3, U32, n, id, defltVal, const)
  189. #define ANKI_SPECIALIZATION_CONSTANT_UVEC4(n, id, defltVal) _ANKI_SCONST_X4(UVec4, U32, n, id, defltVal, const)
  190. #define ANKI_SPECIALIZATION_CONSTANT_F32(n, id, defltVal) _ANKI_SCONST_X(F32, n, id, defltVal)
  191. #define ANKI_SPECIALIZATION_CONSTANT_VEC2(n, id, defltVal) _ANKI_SCONST_X2(Vec2, F32, n, id, defltVal,)
  192. #define ANKI_SPECIALIZATION_CONSTANT_VEC3(n, id, defltVal) _ANKI_SCONST_X3(Vec3, F32, n, id, defltVal,)
  193. #define ANKI_SPECIALIZATION_CONSTANT_VEC4(n, id, defltVal) _ANKI_SCONST_X4(Vec4, F32, n, id, defltVal,)
  194. #define ANKI_REF(type, alignment) \
  195. layout(buffer_reference, scalar, buffer_reference_align = (alignment)) buffer type##Ref \
  196. { \
  197. type m_value; \
  198. }
  199. #define ANKI_PADDING(bytes) U8 _padding_ ## __LINE__[bytes]
  200. layout(std140, row_major) uniform;
  201. layout(std140, row_major) buffer;
  202. )";
  203. static const U64 SHADER_HEADER_HASH = computeHash(SHADER_HEADER, sizeof(SHADER_HEADER));
  204. ShaderProgramParser::ShaderProgramParser(CString fname, ShaderProgramFilesystemInterface* fsystem,
  205. GenericMemoryPoolAllocator<U8> alloc,
  206. const GpuDeviceCapabilities& gpuCapabilities,
  207. const BindlessLimits& bindlessLimits)
  208. : m_alloc(alloc)
  209. , m_fname(alloc, fname)
  210. , m_fsystem(fsystem)
  211. , m_gpuCapabilities(gpuCapabilities)
  212. , m_bindlessLimits(bindlessLimits)
  213. {
  214. }
  215. ShaderProgramParser::~ShaderProgramParser()
  216. {
  217. }
  218. void ShaderProgramParser::tokenizeLine(CString line, DynamicArrayAuto<StringAuto>& tokens) const
  219. {
  220. ANKI_ASSERT(line.getLength() > 0);
  221. StringAuto l(m_alloc, line);
  222. // Replace all tabs with spaces
  223. for(char& c : l)
  224. {
  225. if(c == '\t')
  226. {
  227. c = ' ';
  228. }
  229. }
  230. // Split
  231. StringListAuto spaceTokens(m_alloc);
  232. spaceTokens.splitString(l, ' ', false);
  233. // Create the array
  234. for(const String& s : spaceTokens)
  235. {
  236. tokens.emplaceBack(m_alloc, s);
  237. }
  238. }
  239. Error ShaderProgramParser::parsePragmaStart(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  240. {
  241. ANKI_ASSERT(begin && end);
  242. if(begin >= end)
  243. {
  244. ANKI_PP_ERROR_MALFORMED();
  245. }
  246. ShaderType shaderType = ShaderType::COUNT;
  247. if(*begin == "vert")
  248. {
  249. shaderType = ShaderType::VERTEX;
  250. }
  251. else if(*begin == "tessc")
  252. {
  253. shaderType = ShaderType::TESSELLATION_CONTROL;
  254. }
  255. else if(*begin == "tesse")
  256. {
  257. }
  258. else if(*begin == "geom")
  259. {
  260. shaderType = ShaderType::GEOMETRY;
  261. }
  262. else if(*begin == "frag")
  263. {
  264. shaderType = ShaderType::FRAGMENT;
  265. }
  266. else if(*begin == "comp")
  267. {
  268. shaderType = ShaderType::COMPUTE;
  269. }
  270. else if(*begin == "rgen")
  271. {
  272. shaderType = ShaderType::RAY_GEN;
  273. }
  274. else if(*begin == "ahit")
  275. {
  276. shaderType = ShaderType::ANY_HIT;
  277. }
  278. else if(*begin == "chit")
  279. {
  280. shaderType = ShaderType::CLOSEST_HIT;
  281. }
  282. else if(*begin == "miss")
  283. {
  284. shaderType = ShaderType::MISS;
  285. }
  286. else if(*begin == "int")
  287. {
  288. shaderType = ShaderType::INTERSECTION;
  289. }
  290. else if(*begin == "call")
  291. {
  292. shaderType = ShaderType::CALLABLE;
  293. }
  294. else
  295. {
  296. ANKI_PP_ERROR_MALFORMED();
  297. }
  298. m_codeLines.pushBackSprintf("#ifdef ANKI_%s_SHADER", SHADER_STAGE_NAMES[shaderType].cstr());
  299. ++begin;
  300. if(begin != end)
  301. {
  302. // Should be the last token
  303. ANKI_PP_ERROR_MALFORMED();
  304. }
  305. // Set the mask
  306. const ShaderTypeBit mask = ShaderTypeBit(1 << shaderType);
  307. if(!!(mask & m_shaderTypes))
  308. {
  309. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start <shader> appearing more than once");
  310. }
  311. m_shaderTypes |= mask;
  312. // Check bounds
  313. if(m_insideShader)
  314. {
  315. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start before you close the previous pragma start");
  316. }
  317. m_insideShader = true;
  318. return Error::NONE;
  319. }
  320. Error ShaderProgramParser::parsePragmaEnd(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  321. {
  322. ANKI_ASSERT(begin && end);
  323. // Check tokens
  324. if(begin != end)
  325. {
  326. ANKI_PP_ERROR_MALFORMED();
  327. }
  328. // Check bounds
  329. if(!m_insideShader)
  330. {
  331. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma end before you open with a pragma start");
  332. }
  333. m_insideShader = false;
  334. // Write code
  335. m_codeLines.pushBack("#endif // Shader guard");
  336. return Error::NONE;
  337. }
  338. Error ShaderProgramParser::parsePragmaMutator(const StringAuto* begin, const StringAuto* end, CString line,
  339. CString fname)
  340. {
  341. ANKI_ASSERT(begin && end);
  342. if(begin >= end)
  343. {
  344. ANKI_PP_ERROR_MALFORMED();
  345. }
  346. m_mutators.emplaceBack(m_alloc);
  347. Mutator& mutator = m_mutators.getBack();
  348. // Name
  349. {
  350. if(begin >= end)
  351. {
  352. // Need to have a name
  353. ANKI_PP_ERROR_MALFORMED();
  354. }
  355. // Check for duplicate mutators
  356. for(U32 i = 0; i < m_mutators.getSize() - 1; ++i)
  357. {
  358. if(m_mutators[i].m_name == *begin)
  359. {
  360. ANKI_PP_ERROR_MALFORMED_MSG("Duplicate mutator");
  361. }
  362. }
  363. if(begin->getLength() > MAX_SHADER_BINARY_NAME_LENGTH)
  364. {
  365. ANKI_PP_ERROR_MALFORMED_MSG("Too big name");
  366. }
  367. mutator.m_name.create(begin->toCString());
  368. ++begin;
  369. }
  370. // Values
  371. {
  372. // Gather them
  373. for(; begin < end; ++begin)
  374. {
  375. MutatorValue value = 0;
  376. if(tokenIsComment(begin->toCString()))
  377. {
  378. break;
  379. }
  380. if(begin->toNumber(value))
  381. {
  382. ANKI_PP_ERROR_MALFORMED();
  383. }
  384. mutator.m_values.emplaceBack(value);
  385. }
  386. // Check for correct count
  387. if(mutator.m_values.getSize() < 2)
  388. {
  389. ANKI_PP_ERROR_MALFORMED_MSG("Mutator with less that 2 values doesn't make sense");
  390. }
  391. std::sort(mutator.m_values.getBegin(), mutator.m_values.getEnd());
  392. // Check for duplicates
  393. for(U32 i = 1; i < mutator.m_values.getSize(); ++i)
  394. {
  395. if(mutator.m_values[i - 1] == mutator.m_values[i])
  396. {
  397. ANKI_PP_ERROR_MALFORMED_MSG("Same value appeared more than once");
  398. }
  399. }
  400. }
  401. return Error::NONE;
  402. }
  403. Error ShaderProgramParser::parsePragmaLibraryName(const StringAuto* begin, const StringAuto* end, CString line,
  404. CString fname)
  405. {
  406. ANKI_ASSERT(begin && end);
  407. if(begin >= end)
  408. {
  409. ANKI_PP_ERROR_MALFORMED();
  410. }
  411. if(m_libName.getLength() > 0)
  412. {
  413. ANKI_PP_ERROR_MALFORMED_MSG("Library name already set");
  414. }
  415. m_libName = *begin;
  416. return Error::NONE;
  417. }
  418. Error ShaderProgramParser::parsePragmaRayType(const StringAuto* begin, const StringAuto* end, CString line,
  419. CString fname)
  420. {
  421. ANKI_ASSERT(begin && end);
  422. if(begin >= end)
  423. {
  424. ANKI_PP_ERROR_MALFORMED();
  425. }
  426. if(m_rayType != MAX_U32)
  427. {
  428. ANKI_PP_ERROR_MALFORMED_MSG("Ray type already set");
  429. }
  430. ANKI_CHECK(begin->toNumber(m_rayType));
  431. if(m_rayType > 128)
  432. {
  433. ANKI_PP_ERROR_MALFORMED_MSG("Ray type has a very large value");
  434. }
  435. return Error::NONE;
  436. }
  437. Error ShaderProgramParser::parsePragmaRewriteMutation(const StringAuto* begin, const StringAuto* end, CString line,
  438. CString fname)
  439. {
  440. ANKI_ASSERT(begin && end);
  441. // Some basic sanity checks
  442. const U tokenCount = end - begin;
  443. constexpr U minTokenCount = 2 + 1 + 2; // Mutator + value + "to" + mutator + value
  444. if(tokenCount < minTokenCount)
  445. {
  446. ANKI_PP_ERROR_MALFORMED();
  447. }
  448. MutationRewrite& rewrite = *m_mutationRewrites.emplaceBack(m_alloc);
  449. Bool servingFrom = true;
  450. do
  451. {
  452. if(*begin == "to")
  453. {
  454. if(servingFrom == false)
  455. {
  456. ANKI_PP_ERROR_MALFORMED();
  457. }
  458. servingFrom = false;
  459. }
  460. else
  461. {
  462. // Mutator & value
  463. // Get mutator and value
  464. const CString mutatorName = *begin;
  465. ++begin;
  466. if(begin == end)
  467. {
  468. ANKI_PP_ERROR_MALFORMED();
  469. }
  470. const CString valueStr = *begin;
  471. MutatorValue value;
  472. if(valueStr.toNumber(value))
  473. {
  474. ANKI_PP_ERROR_MALFORMED_MSG("Malformed value");
  475. }
  476. // Get or create new record
  477. if(servingFrom)
  478. {
  479. MutationRewrite::Record& rec = *rewrite.m_records.emplaceBack();
  480. for(U32 i = 0; i < m_mutators.getSize(); ++i)
  481. {
  482. if(m_mutators[i].getName() == mutatorName)
  483. {
  484. rec.m_mutatorIndex = i;
  485. break;
  486. }
  487. }
  488. if(rec.m_mutatorIndex == MAX_U32)
  489. {
  490. ANKI_PP_ERROR_MALFORMED_MSG("Mutator not found");
  491. }
  492. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  493. {
  494. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  495. }
  496. rec.m_valueFrom = value;
  497. }
  498. else
  499. {
  500. Bool found = false;
  501. for(MutationRewrite::Record& rec : rewrite.m_records)
  502. {
  503. if(m_mutators[rec.m_mutatorIndex].m_name == mutatorName)
  504. {
  505. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  506. {
  507. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  508. }
  509. rec.m_valueTo = value;
  510. found = true;
  511. break;
  512. }
  513. }
  514. if(!found)
  515. {
  516. ANKI_PP_ERROR_MALFORMED();
  517. }
  518. }
  519. }
  520. ++begin;
  521. } while(begin < end && !tokenIsComment(*begin));
  522. // Sort for some later cross checking
  523. std::sort(rewrite.m_records.getBegin(), rewrite.m_records.getEnd(),
  524. [](const MutationRewrite::Record& a, const MutationRewrite::Record& b) {
  525. return a.m_mutatorIndex < b.m_mutatorIndex;
  526. });
  527. // More cross checking
  528. for(U32 i = 1; i < rewrite.m_records.getSize(); ++i)
  529. {
  530. if(rewrite.m_records[i - 1].m_mutatorIndex == rewrite.m_records[i].m_mutatorIndex)
  531. {
  532. ANKI_PP_ERROR_MALFORMED_MSG("Mutator appeared more than once");
  533. }
  534. }
  535. for(U32 i = 0; i < m_mutationRewrites.getSize() - 1; ++i)
  536. {
  537. const MutationRewrite& other = m_mutationRewrites[i];
  538. if(other.m_records.getSize() != rewrite.m_records.getSize())
  539. {
  540. continue;
  541. }
  542. Bool same = true;
  543. for(U32 j = 0; j < rewrite.m_records.getSize(); ++j)
  544. {
  545. if(rewrite.m_records[j] != other.m_records[j])
  546. {
  547. same = false;
  548. break;
  549. }
  550. }
  551. if(same)
  552. {
  553. ANKI_PP_ERROR_MALFORMED_MSG("Mutation already exists");
  554. }
  555. }
  556. return Error::NONE;
  557. }
  558. Error ShaderProgramParser::parseInclude(const StringAuto* begin, const StringAuto* end, CString line, CString fname,
  559. U32 depth)
  560. {
  561. // Gather the path
  562. StringAuto path(m_alloc);
  563. for(; begin < end; ++begin)
  564. {
  565. path.append(*begin);
  566. }
  567. if(path.isEmpty())
  568. {
  569. ANKI_PP_ERROR_MALFORMED();
  570. }
  571. // Check
  572. const char firstChar = path[0];
  573. const char lastChar = path[path.getLength() - 1];
  574. if((firstChar == '\"' && lastChar == '\"') || (firstChar == '<' && lastChar == '>'))
  575. {
  576. StringAuto fname2(m_alloc);
  577. fname2.create(path.begin() + 1, path.begin() + path.getLength() - 1);
  578. if(parseFile(fname2, depth + 1))
  579. {
  580. ANKI_PP_ERROR_MALFORMED_MSG("Error parsing include. See previous errors");
  581. }
  582. }
  583. else
  584. {
  585. ANKI_PP_ERROR_MALFORMED();
  586. }
  587. return Error::NONE;
  588. }
  589. Error ShaderProgramParser::parseLine(CString line, CString fname, Bool& foundPragmaOnce, U32 depth)
  590. {
  591. // Tokenize
  592. DynamicArrayAuto<StringAuto> tokens(m_alloc);
  593. tokenizeLine(line, tokens);
  594. ANKI_ASSERT(tokens.getSize() > 0);
  595. const StringAuto* token = tokens.getBegin();
  596. const StringAuto* end = tokens.getEnd();
  597. // Skip the hash
  598. Bool foundAloneHash = false;
  599. if(*token == "#")
  600. {
  601. ++token;
  602. foundAloneHash = true;
  603. }
  604. if((token < end) && ((foundAloneHash && *token == "include") || *token == "#include"))
  605. {
  606. // We _must_ have an #include
  607. ANKI_CHECK(parseInclude(token + 1, end, line, fname, depth));
  608. }
  609. else if((token < end) && ((foundAloneHash && *token == "pragma") || *token == "#pragma"))
  610. {
  611. // We may have a #pragma once or a #pragma anki or something else
  612. ++token;
  613. if(*token == "once")
  614. {
  615. // Pragma once
  616. if(foundPragmaOnce)
  617. {
  618. ANKI_PP_ERROR_MALFORMED_MSG("Can't have more than one #pragma once per file");
  619. }
  620. if(token + 1 != end)
  621. {
  622. ANKI_PP_ERROR_MALFORMED();
  623. }
  624. // Add the guard unique for this file
  625. foundPragmaOnce = true;
  626. const U64 hash = fname.computeHash();
  627. m_codeLines.pushBackSprintf("#ifndef _ANKI_INCL_GUARD_%llu\n"
  628. "#define _ANKI_INCL_GUARD_%llu",
  629. hash, hash);
  630. }
  631. else if(*token == "anki")
  632. {
  633. // Must be a #pragma anki
  634. ++token;
  635. if(*token == "mutator")
  636. {
  637. ANKI_CHECK(parsePragmaMutator(token + 1, end, line, fname));
  638. }
  639. else if(*token == "start")
  640. {
  641. ANKI_CHECK(parsePragmaStart(token + 1, end, line, fname));
  642. }
  643. else if(*token == "end")
  644. {
  645. ANKI_CHECK(parsePragmaEnd(token + 1, end, line, fname));
  646. }
  647. else if(*token == "rewrite_mutation")
  648. {
  649. ANKI_CHECK(parsePragmaRewriteMutation(token + 1, end, line, fname));
  650. }
  651. else if(*token == "library")
  652. {
  653. ANKI_CHECK(parsePragmaLibraryName(token + 1, end, line, fname));
  654. }
  655. else if(*token == "ray_type")
  656. {
  657. ANKI_CHECK(parsePragmaRayType(token + 1, end, line, fname));
  658. }
  659. else
  660. {
  661. ANKI_PP_ERROR_MALFORMED();
  662. }
  663. // Add the line as a comment because of hashing of the source
  664. m_codeLines.pushBackSprintf("//%s", line.cstr());
  665. }
  666. else
  667. {
  668. // Some other pragma
  669. ANKI_SHADER_COMPILER_LOGW("Ignoring: %s", line.cstr());
  670. m_codeLines.pushBack(line);
  671. }
  672. }
  673. else
  674. {
  675. // Ignore
  676. m_codeLines.pushBack(line);
  677. }
  678. return Error::NONE;
  679. }
  680. Error ShaderProgramParser::parseFile(CString fname, U32 depth)
  681. {
  682. // First check the depth
  683. if(depth > MAX_INCLUDE_DEPTH)
  684. {
  685. ANKI_SHADER_COMPILER_LOGE("The include depth is too high. Probably circular includance");
  686. }
  687. Bool foundPragmaOnce = false;
  688. // Load file in lines
  689. StringAuto txt(m_alloc);
  690. ANKI_CHECK(m_fsystem->readAllText(fname, txt));
  691. StringListAuto lines(m_alloc);
  692. lines.splitString(txt.toCString(), '\n');
  693. if(lines.getSize() < 1)
  694. {
  695. ANKI_SHADER_COMPILER_LOGE("Source is empty");
  696. }
  697. // Parse lines
  698. for(const String& line : lines)
  699. {
  700. if(line.find("pragma") != CString::NPOS || line.find("include") != CString::NPOS)
  701. {
  702. // Possibly a preprocessor directive we care
  703. ANKI_CHECK(parseLine(line.toCString(), fname, foundPragmaOnce, depth));
  704. }
  705. else
  706. {
  707. // Just append the line
  708. m_codeLines.pushBack(line.toCString());
  709. }
  710. }
  711. if(foundPragmaOnce)
  712. {
  713. // Append the guard
  714. m_codeLines.pushBack("#endif // Include guard");
  715. }
  716. return Error::NONE;
  717. }
  718. Error ShaderProgramParser::parse()
  719. {
  720. ANKI_ASSERT(!m_fname.isEmpty());
  721. ANKI_ASSERT(m_codeLines.isEmpty());
  722. const CString fname = m_fname;
  723. // Parse recursively
  724. ANKI_CHECK(parseFile(fname, 0));
  725. // Checks
  726. {
  727. if(!!(m_shaderTypes & ShaderTypeBit::COMPUTE))
  728. {
  729. if(m_shaderTypes != ShaderTypeBit::COMPUTE)
  730. {
  731. ANKI_SHADER_COMPILER_LOGE("Can't combine compute shader with other types of shaders");
  732. return Error::USER_DATA;
  733. }
  734. }
  735. else if(!!(m_shaderTypes & ShaderTypeBit::ALL_GRAPHICS))
  736. {
  737. if(!(m_shaderTypes & ShaderTypeBit::VERTEX))
  738. {
  739. ANKI_SHADER_COMPILER_LOGE("Missing vertex shader");
  740. return Error::USER_DATA;
  741. }
  742. if(!(m_shaderTypes & ShaderTypeBit::FRAGMENT))
  743. {
  744. ANKI_SHADER_COMPILER_LOGE("Missing fragment shader");
  745. return Error::USER_DATA;
  746. }
  747. }
  748. if(m_insideShader)
  749. {
  750. ANKI_SHADER_COMPILER_LOGE("Forgot a \"pragma anki end\"");
  751. return Error::USER_DATA;
  752. }
  753. }
  754. // Create the code lines
  755. if(m_codeLines.getSize())
  756. {
  757. m_codeLines.join("\n", m_codeSource);
  758. m_codeLines.destroy();
  759. }
  760. // Create the hash
  761. {
  762. if(m_codeSource.getLength())
  763. {
  764. m_codeSourceHash = appendHash(m_codeSource.getBegin(), m_codeSource.getLength(), SHADER_HEADER_HASH);
  765. }
  766. if(m_libName.getLength() > 0)
  767. {
  768. m_codeSourceHash = appendHash(m_libName.getBegin(), m_libName.getLength(), m_codeSourceHash);
  769. }
  770. m_codeSourceHash = appendHash(&m_rayType, sizeof(m_rayType), m_codeSourceHash);
  771. }
  772. return Error::NONE;
  773. }
  774. void ShaderProgramParser::generateAnkiShaderHeader(ShaderType shaderType, const GpuDeviceCapabilities& caps,
  775. const BindlessLimits& limits, StringAuto& header)
  776. {
  777. header.sprintf(SHADER_HEADER, caps.m_minorApiVersion, caps.m_majorApiVersion,
  778. GPU_VENDOR_STR[caps.m_gpuVendor].cstr(), SHADER_STAGE_NAMES[shaderType].cstr(),
  779. limits.m_bindlessTextureCount, limits.m_bindlessImageCount, U(caps.m_rayTracingEnabled));
  780. }
  781. Error ShaderProgramParser::generateVariant(ConstWeakArray<MutatorValue> mutation,
  782. ShaderProgramParserVariant& variant) const
  783. {
  784. // Sanity checks
  785. ANKI_ASSERT(m_codeSource.getLength() > 0);
  786. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  787. for(U32 i = 0; i < mutation.getSize(); ++i)
  788. {
  789. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]) && "Value not found");
  790. }
  791. // Init variant
  792. ::new(&variant) ShaderProgramParserVariant();
  793. variant.m_alloc = m_alloc;
  794. // Create the mutator defines
  795. StringAuto mutatorDefines(m_alloc);
  796. for(U32 i = 0; i < mutation.getSize(); ++i)
  797. {
  798. mutatorDefines.append(StringAuto(m_alloc).sprintf("#define %s %d\n", m_mutators[i].m_name.cstr(), mutation[i]));
  799. }
  800. // Generate souce per stage
  801. for(ShaderType shaderType : EnumIterable<ShaderType>())
  802. {
  803. if(!(ShaderTypeBit(1u << shaderType) & m_shaderTypes))
  804. {
  805. continue;
  806. }
  807. // Create the header
  808. StringAuto header(m_alloc);
  809. generateAnkiShaderHeader(shaderType, m_gpuCapabilities, m_bindlessLimits, header);
  810. // Create the final source without the bindings
  811. StringAuto finalSource(m_alloc);
  812. finalSource.append(header);
  813. finalSource.append(mutatorDefines);
  814. finalSource.append(m_codeSource);
  815. // Move the source
  816. variant.m_sources[shaderType] = std::move(finalSource);
  817. }
  818. return Error::NONE;
  819. }
  820. Bool ShaderProgramParser::rewriteMutation(WeakArray<MutatorValue> mutation) const
  821. {
  822. // Checks
  823. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  824. for(U32 i = 0; i < mutation.getSize(); ++i)
  825. {
  826. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]));
  827. }
  828. // Early exit
  829. if(mutation.getSize() == 0)
  830. {
  831. return false;
  832. }
  833. // Find if mutation exists
  834. for(const MutationRewrite& rewrite : m_mutationRewrites)
  835. {
  836. Bool found = true;
  837. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  838. {
  839. if(rewrite.m_records[i].m_valueFrom != mutation[rewrite.m_records[i].m_mutatorIndex])
  840. {
  841. found = false;
  842. break;
  843. }
  844. }
  845. if(found)
  846. {
  847. // Rewrite it
  848. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  849. {
  850. mutation[rewrite.m_records[i].m_mutatorIndex] = rewrite.m_records[i].m_valueTo;
  851. }
  852. return true;
  853. }
  854. }
  855. return false;
  856. }
  857. Bool ShaderProgramParser::mutatorHasValue(const ShaderProgramParserMutator& mutator, MutatorValue value)
  858. {
  859. for(MutatorValue v : mutator.m_values)
  860. {
  861. if(value == v)
  862. {
  863. return true;
  864. }
  865. }
  866. return false;
  867. }
  868. } // end namespace anki