ShaderProgramParser.cpp 26 KB

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