ShaderProgramParser.cpp 26 KB

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