ShaderProgramParser.cpp 25 KB

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