ShaderProgramParser.cpp 26 KB

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