ShaderProgramParser.cpp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  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. #define ANKI_RP mediump
  211. #define ANKI_FP highp
  212. )";
  213. static const U64 SHADER_HEADER_HASH = computeHash(SHADER_HEADER, sizeof(SHADER_HEADER));
  214. ShaderProgramParser::ShaderProgramParser(CString fname, ShaderProgramFilesystemInterface* fsystem,
  215. GenericMemoryPoolAllocator<U8> alloc,
  216. const ShaderCompilerOptions& compilerOptions)
  217. : m_alloc(alloc)
  218. , m_fname(alloc, fname)
  219. , m_fsystem(fsystem)
  220. , m_compilerOptions(compilerOptions)
  221. {
  222. }
  223. ShaderProgramParser::~ShaderProgramParser()
  224. {
  225. }
  226. void ShaderProgramParser::tokenizeLine(CString line, DynamicArrayAuto<StringAuto>& tokens) const
  227. {
  228. ANKI_ASSERT(line.getLength() > 0);
  229. StringAuto l(m_alloc, line);
  230. // Replace all tabs with spaces
  231. for(char& c : l)
  232. {
  233. if(c == '\t')
  234. {
  235. c = ' ';
  236. }
  237. }
  238. // Split
  239. StringListAuto spaceTokens(m_alloc);
  240. spaceTokens.splitString(l, ' ', false);
  241. // Create the array
  242. for(const String& s : spaceTokens)
  243. {
  244. tokens.emplaceBack(m_alloc, s);
  245. }
  246. }
  247. Error ShaderProgramParser::parsePragmaStart(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  248. {
  249. ANKI_ASSERT(begin && end);
  250. if(begin >= end)
  251. {
  252. ANKI_PP_ERROR_MALFORMED();
  253. }
  254. ShaderType shaderType = ShaderType::COUNT;
  255. if(*begin == "vert")
  256. {
  257. shaderType = ShaderType::VERTEX;
  258. }
  259. else if(*begin == "tessc")
  260. {
  261. shaderType = ShaderType::TESSELLATION_CONTROL;
  262. }
  263. else if(*begin == "tesse")
  264. {
  265. }
  266. else if(*begin == "geom")
  267. {
  268. shaderType = ShaderType::GEOMETRY;
  269. }
  270. else if(*begin == "frag")
  271. {
  272. shaderType = ShaderType::FRAGMENT;
  273. }
  274. else if(*begin == "comp")
  275. {
  276. shaderType = ShaderType::COMPUTE;
  277. }
  278. else if(*begin == "rgen")
  279. {
  280. shaderType = ShaderType::RAY_GEN;
  281. }
  282. else if(*begin == "ahit")
  283. {
  284. shaderType = ShaderType::ANY_HIT;
  285. }
  286. else if(*begin == "chit")
  287. {
  288. shaderType = ShaderType::CLOSEST_HIT;
  289. }
  290. else if(*begin == "miss")
  291. {
  292. shaderType = ShaderType::MISS;
  293. }
  294. else if(*begin == "int")
  295. {
  296. shaderType = ShaderType::INTERSECTION;
  297. }
  298. else if(*begin == "call")
  299. {
  300. shaderType = ShaderType::CALLABLE;
  301. }
  302. else
  303. {
  304. ANKI_PP_ERROR_MALFORMED();
  305. }
  306. m_codeLines.pushBackSprintf("#ifdef ANKI_%s_SHADER", SHADER_STAGE_NAMES[shaderType].cstr());
  307. ++begin;
  308. if(begin != end)
  309. {
  310. // Should be the last token
  311. ANKI_PP_ERROR_MALFORMED();
  312. }
  313. // Set the mask
  314. const ShaderTypeBit mask = ShaderTypeBit(1 << shaderType);
  315. if(!!(mask & m_shaderTypes))
  316. {
  317. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start <shader> appearing more than once");
  318. }
  319. m_shaderTypes |= mask;
  320. // Check bounds
  321. if(m_insideShader)
  322. {
  323. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start before you close the previous pragma start");
  324. }
  325. m_insideShader = true;
  326. return Error::NONE;
  327. }
  328. Error ShaderProgramParser::parsePragmaEnd(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  329. {
  330. ANKI_ASSERT(begin && end);
  331. // Check tokens
  332. if(begin != end)
  333. {
  334. ANKI_PP_ERROR_MALFORMED();
  335. }
  336. // Check bounds
  337. if(!m_insideShader)
  338. {
  339. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma end before you open with a pragma start");
  340. }
  341. m_insideShader = false;
  342. // Write code
  343. m_codeLines.pushBack("#endif // Shader guard");
  344. return Error::NONE;
  345. }
  346. Error ShaderProgramParser::parsePragmaMutator(const StringAuto* begin, const StringAuto* end, CString line,
  347. CString fname)
  348. {
  349. ANKI_ASSERT(begin && end);
  350. if(begin >= end)
  351. {
  352. ANKI_PP_ERROR_MALFORMED();
  353. }
  354. m_mutators.emplaceBack(m_alloc);
  355. Mutator& mutator = m_mutators.getBack();
  356. // Name
  357. {
  358. if(begin >= end)
  359. {
  360. // Need to have a name
  361. ANKI_PP_ERROR_MALFORMED();
  362. }
  363. // Check for duplicate mutators
  364. for(U32 i = 0; i < m_mutators.getSize() - 1; ++i)
  365. {
  366. if(m_mutators[i].m_name == *begin)
  367. {
  368. ANKI_PP_ERROR_MALFORMED_MSG("Duplicate mutator");
  369. }
  370. }
  371. if(begin->getLength() > MAX_SHADER_BINARY_NAME_LENGTH)
  372. {
  373. ANKI_PP_ERROR_MALFORMED_MSG("Too big name");
  374. }
  375. mutator.m_name.create(begin->toCString());
  376. ++begin;
  377. }
  378. // Values
  379. {
  380. // Gather them
  381. for(; begin < end; ++begin)
  382. {
  383. MutatorValue value = 0;
  384. if(tokenIsComment(begin->toCString()))
  385. {
  386. break;
  387. }
  388. if(begin->toNumber(value))
  389. {
  390. ANKI_PP_ERROR_MALFORMED();
  391. }
  392. mutator.m_values.emplaceBack(value);
  393. }
  394. // Check for correct count
  395. if(mutator.m_values.getSize() < 2)
  396. {
  397. ANKI_PP_ERROR_MALFORMED_MSG("Mutator with less that 2 values doesn't make sense");
  398. }
  399. std::sort(mutator.m_values.getBegin(), mutator.m_values.getEnd());
  400. // Check for duplicates
  401. for(U32 i = 1; i < mutator.m_values.getSize(); ++i)
  402. {
  403. if(mutator.m_values[i - 1] == mutator.m_values[i])
  404. {
  405. ANKI_PP_ERROR_MALFORMED_MSG("Same value appeared more than once");
  406. }
  407. }
  408. }
  409. return Error::NONE;
  410. }
  411. Error ShaderProgramParser::parsePragmaLibraryName(const StringAuto* begin, const StringAuto* end, CString line,
  412. CString fname)
  413. {
  414. ANKI_ASSERT(begin && end);
  415. if(begin >= end)
  416. {
  417. ANKI_PP_ERROR_MALFORMED();
  418. }
  419. if(m_libName.getLength() > 0)
  420. {
  421. ANKI_PP_ERROR_MALFORMED_MSG("Library name already set");
  422. }
  423. m_libName = *begin;
  424. return Error::NONE;
  425. }
  426. Error ShaderProgramParser::parsePragmaRayType(const StringAuto* begin, const StringAuto* end, CString line,
  427. CString fname)
  428. {
  429. ANKI_ASSERT(begin && end);
  430. if(begin >= end)
  431. {
  432. ANKI_PP_ERROR_MALFORMED();
  433. }
  434. if(m_rayType != MAX_U32)
  435. {
  436. ANKI_PP_ERROR_MALFORMED_MSG("Ray type already set");
  437. }
  438. ANKI_CHECK(begin->toNumber(m_rayType));
  439. if(m_rayType > 128)
  440. {
  441. ANKI_PP_ERROR_MALFORMED_MSG("Ray type has a very large value");
  442. }
  443. return Error::NONE;
  444. }
  445. Error ShaderProgramParser::parsePragmaReflect(const StringAuto* begin, const StringAuto* end, CString line,
  446. CString fname)
  447. {
  448. ANKI_ASSERT(begin && end);
  449. if(begin >= end)
  450. {
  451. ANKI_PP_ERROR_MALFORMED();
  452. }
  453. m_symbolsToReflect.pushBack(*begin);
  454. return Error::NONE;
  455. }
  456. Error ShaderProgramParser::parsePragmaRewriteMutation(const StringAuto* begin, const StringAuto* end, CString line,
  457. CString fname)
  458. {
  459. ANKI_ASSERT(begin && end);
  460. // Some basic sanity checks
  461. const U tokenCount = end - begin;
  462. constexpr U minTokenCount = 2 + 1 + 2; // Mutator + value + "to" + mutator + value
  463. if(tokenCount < minTokenCount)
  464. {
  465. ANKI_PP_ERROR_MALFORMED();
  466. }
  467. MutationRewrite& rewrite = *m_mutationRewrites.emplaceBack(m_alloc);
  468. Bool servingFrom = true;
  469. do
  470. {
  471. if(*begin == "to")
  472. {
  473. if(servingFrom == false)
  474. {
  475. ANKI_PP_ERROR_MALFORMED();
  476. }
  477. servingFrom = false;
  478. }
  479. else
  480. {
  481. // Mutator & value
  482. // Get mutator and value
  483. const CString mutatorName = *begin;
  484. ++begin;
  485. if(begin == end)
  486. {
  487. ANKI_PP_ERROR_MALFORMED();
  488. }
  489. const CString valueStr = *begin;
  490. MutatorValue value;
  491. if(valueStr.toNumber(value))
  492. {
  493. ANKI_PP_ERROR_MALFORMED_MSG("Malformed value");
  494. }
  495. // Get or create new record
  496. if(servingFrom)
  497. {
  498. MutationRewrite::Record& rec = *rewrite.m_records.emplaceBack();
  499. for(U32 i = 0; i < m_mutators.getSize(); ++i)
  500. {
  501. if(m_mutators[i].getName() == mutatorName)
  502. {
  503. rec.m_mutatorIndex = i;
  504. break;
  505. }
  506. }
  507. if(rec.m_mutatorIndex == MAX_U32)
  508. {
  509. ANKI_PP_ERROR_MALFORMED_MSG("Mutator not found");
  510. }
  511. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  512. {
  513. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  514. }
  515. rec.m_valueFrom = value;
  516. }
  517. else
  518. {
  519. Bool found = false;
  520. for(MutationRewrite::Record& rec : rewrite.m_records)
  521. {
  522. if(m_mutators[rec.m_mutatorIndex].m_name == mutatorName)
  523. {
  524. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  525. {
  526. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  527. }
  528. rec.m_valueTo = value;
  529. found = true;
  530. break;
  531. }
  532. }
  533. if(!found)
  534. {
  535. ANKI_PP_ERROR_MALFORMED();
  536. }
  537. }
  538. }
  539. ++begin;
  540. } while(begin < end && !tokenIsComment(*begin));
  541. // Sort for some later cross checking
  542. std::sort(rewrite.m_records.getBegin(), rewrite.m_records.getEnd(),
  543. [](const MutationRewrite::Record& a, const MutationRewrite::Record& b) {
  544. return a.m_mutatorIndex < b.m_mutatorIndex;
  545. });
  546. // More cross checking
  547. for(U32 i = 1; i < rewrite.m_records.getSize(); ++i)
  548. {
  549. if(rewrite.m_records[i - 1].m_mutatorIndex == rewrite.m_records[i].m_mutatorIndex)
  550. {
  551. ANKI_PP_ERROR_MALFORMED_MSG("Mutator appeared more than once");
  552. }
  553. }
  554. for(U32 i = 0; i < m_mutationRewrites.getSize() - 1; ++i)
  555. {
  556. const MutationRewrite& other = m_mutationRewrites[i];
  557. if(other.m_records.getSize() != rewrite.m_records.getSize())
  558. {
  559. continue;
  560. }
  561. Bool same = true;
  562. for(U32 j = 0; j < rewrite.m_records.getSize(); ++j)
  563. {
  564. if(rewrite.m_records[j] != other.m_records[j])
  565. {
  566. same = false;
  567. break;
  568. }
  569. }
  570. if(same)
  571. {
  572. ANKI_PP_ERROR_MALFORMED_MSG("Mutation already exists");
  573. }
  574. }
  575. return Error::NONE;
  576. }
  577. Error ShaderProgramParser::parseInclude(const StringAuto* begin, const StringAuto* end, CString line, CString fname,
  578. U32 depth)
  579. {
  580. // Gather the path
  581. StringAuto path(m_alloc);
  582. for(; begin < end; ++begin)
  583. {
  584. path.append(*begin);
  585. }
  586. if(path.isEmpty())
  587. {
  588. ANKI_PP_ERROR_MALFORMED();
  589. }
  590. // Check
  591. const char firstChar = path[0];
  592. const char lastChar = path[path.getLength() - 1];
  593. if((firstChar == '\"' && lastChar == '\"') || (firstChar == '<' && lastChar == '>'))
  594. {
  595. StringAuto fname2(m_alloc);
  596. fname2.create(path.begin() + 1, path.begin() + path.getLength() - 1);
  597. const Bool dontIgnore =
  598. fname2.find("AnKi/Shaders/") != String::NPOS || fname2.find("ThirdParty/") != String::NPOS;
  599. if(!dontIgnore)
  600. {
  601. // The shaders can't include C++ files. Ignore the include
  602. return Error::NONE;
  603. }
  604. if(parseFile(fname2, depth + 1))
  605. {
  606. ANKI_PP_ERROR_MALFORMED_MSG("Error parsing include. See previous errors");
  607. }
  608. }
  609. else
  610. {
  611. ANKI_PP_ERROR_MALFORMED();
  612. }
  613. return Error::NONE;
  614. }
  615. Error ShaderProgramParser::parseLine(CString line, CString fname, Bool& foundPragmaOnce, U32 depth)
  616. {
  617. // Tokenize
  618. DynamicArrayAuto<StringAuto> tokens(m_alloc);
  619. tokenizeLine(line, tokens);
  620. ANKI_ASSERT(tokens.getSize() > 0);
  621. const StringAuto* token = tokens.getBegin();
  622. const StringAuto* end = tokens.getEnd();
  623. // Skip the hash
  624. Bool foundAloneHash = false;
  625. if(*token == "#")
  626. {
  627. ++token;
  628. foundAloneHash = true;
  629. }
  630. if((token < end) && ((foundAloneHash && *token == "include") || *token == "#include"))
  631. {
  632. // We _must_ have an #include
  633. ANKI_CHECK(parseInclude(token + 1, end, line, fname, depth));
  634. }
  635. else if((token < end) && ((foundAloneHash && *token == "pragma") || *token == "#pragma"))
  636. {
  637. // We may have a #pragma once or a #pragma anki or something else
  638. ++token;
  639. if(*token == "once")
  640. {
  641. // Pragma once
  642. if(foundPragmaOnce)
  643. {
  644. ANKI_PP_ERROR_MALFORMED_MSG("Can't have more than one #pragma once per file");
  645. }
  646. if(token + 1 != end)
  647. {
  648. ANKI_PP_ERROR_MALFORMED();
  649. }
  650. // Add the guard unique for this file
  651. foundPragmaOnce = true;
  652. const U64 hash = fname.computeHash();
  653. m_codeLines.pushBackSprintf("#ifndef _ANKI_INCL_GUARD_%llu\n"
  654. "#define _ANKI_INCL_GUARD_%llu",
  655. hash, hash);
  656. }
  657. else if(*token == "anki")
  658. {
  659. // Must be a #pragma anki
  660. ++token;
  661. if(*token == "mutator")
  662. {
  663. ANKI_CHECK(parsePragmaMutator(token + 1, end, line, fname));
  664. }
  665. else if(*token == "start")
  666. {
  667. ANKI_CHECK(parsePragmaStart(token + 1, end, line, fname));
  668. }
  669. else if(*token == "end")
  670. {
  671. ANKI_CHECK(parsePragmaEnd(token + 1, end, line, fname));
  672. }
  673. else if(*token == "rewrite_mutation")
  674. {
  675. ANKI_CHECK(parsePragmaRewriteMutation(token + 1, end, line, fname));
  676. }
  677. else if(*token == "library")
  678. {
  679. ANKI_CHECK(parsePragmaLibraryName(token + 1, end, line, fname));
  680. }
  681. else if(*token == "ray_type")
  682. {
  683. ANKI_CHECK(parsePragmaRayType(token + 1, end, line, fname));
  684. }
  685. else if(*token == "reflect")
  686. {
  687. ANKI_CHECK(parsePragmaReflect(token + 1, end, line, fname));
  688. }
  689. else
  690. {
  691. ANKI_PP_ERROR_MALFORMED();
  692. }
  693. // Add the line as a comment because of hashing of the source
  694. m_codeLines.pushBackSprintf("//%s", line.cstr());
  695. }
  696. else
  697. {
  698. // Some other pragma
  699. ANKI_SHADER_COMPILER_LOGW("Ignoring: %s", line.cstr());
  700. m_codeLines.pushBack(line);
  701. }
  702. }
  703. else
  704. {
  705. // Ignore
  706. m_codeLines.pushBack(line);
  707. }
  708. return Error::NONE;
  709. }
  710. Error ShaderProgramParser::parseFile(CString fname, U32 depth)
  711. {
  712. // First check the depth
  713. if(depth > MAX_INCLUDE_DEPTH)
  714. {
  715. ANKI_SHADER_COMPILER_LOGE("The include depth is too high. Probably circular includance");
  716. }
  717. Bool foundPragmaOnce = false;
  718. // Load file in lines
  719. StringAuto txt(m_alloc);
  720. ANKI_CHECK(m_fsystem->readAllText(fname, txt));
  721. StringListAuto lines(m_alloc);
  722. lines.splitString(txt.toCString(), '\n');
  723. if(lines.getSize() < 1)
  724. {
  725. ANKI_SHADER_COMPILER_LOGE("Source is empty");
  726. }
  727. // Parse lines
  728. for(const String& line : lines)
  729. {
  730. if(line.find("pragma") != CString::NPOS || line.find("include") != CString::NPOS)
  731. {
  732. // Possibly a preprocessor directive we care
  733. ANKI_CHECK(parseLine(line.toCString(), fname, foundPragmaOnce, depth));
  734. }
  735. else
  736. {
  737. // Just append the line
  738. m_codeLines.pushBack(line.toCString());
  739. }
  740. }
  741. if(foundPragmaOnce)
  742. {
  743. // Append the guard
  744. m_codeLines.pushBack("#endif // Include guard");
  745. }
  746. return Error::NONE;
  747. }
  748. Error ShaderProgramParser::parse()
  749. {
  750. ANKI_ASSERT(!m_fname.isEmpty());
  751. ANKI_ASSERT(m_codeLines.isEmpty());
  752. const CString fname = m_fname;
  753. // Parse recursively
  754. ANKI_CHECK(parseFile(fname, 0));
  755. // Checks
  756. {
  757. if(!!(m_shaderTypes & ShaderTypeBit::COMPUTE))
  758. {
  759. if(m_shaderTypes != ShaderTypeBit::COMPUTE)
  760. {
  761. ANKI_SHADER_COMPILER_LOGE("Can't combine compute shader with other types of shaders");
  762. return Error::USER_DATA;
  763. }
  764. }
  765. else if(!!(m_shaderTypes & ShaderTypeBit::ALL_GRAPHICS))
  766. {
  767. if(!(m_shaderTypes & ShaderTypeBit::VERTEX))
  768. {
  769. ANKI_SHADER_COMPILER_LOGE("Missing vertex shader");
  770. return Error::USER_DATA;
  771. }
  772. if(!(m_shaderTypes & ShaderTypeBit::FRAGMENT))
  773. {
  774. ANKI_SHADER_COMPILER_LOGE("Missing fragment shader");
  775. return Error::USER_DATA;
  776. }
  777. }
  778. if(m_insideShader)
  779. {
  780. ANKI_SHADER_COMPILER_LOGE("Forgot a \"pragma anki end\"");
  781. return Error::USER_DATA;
  782. }
  783. }
  784. // Create the code lines
  785. if(m_codeLines.getSize())
  786. {
  787. m_codeLines.join("\n", m_codeSource);
  788. m_codeLines.destroy();
  789. }
  790. // Create the hash
  791. {
  792. if(m_codeSource.getLength())
  793. {
  794. m_codeSourceHash = appendHash(m_codeSource.getBegin(), m_codeSource.getLength(), SHADER_HEADER_HASH);
  795. }
  796. if(m_libName.getLength() > 0)
  797. {
  798. m_codeSourceHash = appendHash(m_libName.getBegin(), m_libName.getLength(), m_codeSourceHash);
  799. }
  800. m_codeSourceHash = appendHash(&m_rayType, sizeof(m_rayType), m_codeSourceHash);
  801. }
  802. return Error::NONE;
  803. }
  804. void ShaderProgramParser::generateAnkiShaderHeader(ShaderType shaderType, const ShaderCompilerOptions& compilerOptions,
  805. StringAuto& header)
  806. {
  807. header.sprintf(SHADER_HEADER, SHADER_STAGE_NAMES[shaderType].cstr(), ANKI_OS_ANDROID, ANKI_OS_WINDOWS,
  808. ANKI_OS_LINUX, compilerOptions.m_bindlessLimits.m_bindlessTextureCount,
  809. compilerOptions.m_bindlessLimits.m_bindlessImageCount);
  810. }
  811. Error ShaderProgramParser::generateVariant(ConstWeakArray<MutatorValue> mutation,
  812. ShaderProgramParserVariant& variant) const
  813. {
  814. // Sanity checks
  815. ANKI_ASSERT(m_codeSource.getLength() > 0);
  816. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  817. for(U32 i = 0; i < mutation.getSize(); ++i)
  818. {
  819. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]) && "Value not found");
  820. }
  821. // Init variant
  822. ::new(&variant) ShaderProgramParserVariant();
  823. variant.m_alloc = m_alloc;
  824. // Create the mutator defines
  825. StringAuto mutatorDefines(m_alloc);
  826. for(U32 i = 0; i < mutation.getSize(); ++i)
  827. {
  828. mutatorDefines.append(StringAuto(m_alloc).sprintf("#define %s %d\n", m_mutators[i].m_name.cstr(), mutation[i]));
  829. }
  830. // Generate souce per stage
  831. for(ShaderType shaderType : EnumIterable<ShaderType>())
  832. {
  833. if(!(ShaderTypeBit(1u << shaderType) & m_shaderTypes))
  834. {
  835. continue;
  836. }
  837. // Create the header
  838. StringAuto header(m_alloc);
  839. generateAnkiShaderHeader(shaderType, m_compilerOptions, header);
  840. // Create the final source without the bindings
  841. StringAuto finalSource(m_alloc);
  842. finalSource.append(header);
  843. finalSource.append(mutatorDefines);
  844. finalSource.append(m_codeSource);
  845. // Move the source
  846. variant.m_sources[shaderType] = std::move(finalSource);
  847. }
  848. return Error::NONE;
  849. }
  850. Bool ShaderProgramParser::rewriteMutation(WeakArray<MutatorValue> mutation) const
  851. {
  852. // Checks
  853. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  854. for(U32 i = 0; i < mutation.getSize(); ++i)
  855. {
  856. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]));
  857. }
  858. // Early exit
  859. if(mutation.getSize() == 0)
  860. {
  861. return false;
  862. }
  863. // Find if mutation exists
  864. for(const MutationRewrite& rewrite : m_mutationRewrites)
  865. {
  866. Bool found = true;
  867. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  868. {
  869. if(rewrite.m_records[i].m_valueFrom != mutation[rewrite.m_records[i].m_mutatorIndex])
  870. {
  871. found = false;
  872. break;
  873. }
  874. }
  875. if(found)
  876. {
  877. // Rewrite it
  878. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  879. {
  880. mutation[rewrite.m_records[i].m_mutatorIndex] = rewrite.m_records[i].m_valueTo;
  881. }
  882. return true;
  883. }
  884. }
  885. return false;
  886. }
  887. Bool ShaderProgramParser::mutatorHasValue(const ShaderProgramParserMutator& mutator, MutatorValue value)
  888. {
  889. for(MutatorValue v : mutator.m_values)
  890. {
  891. if(value == v)
  892. {
  893. return true;
  894. }
  895. }
  896. return false;
  897. }
  898. } // end namespace anki