shader_preprocessor.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. .. _doc_shader_preprocessor:
  2. Shader preprocessor
  3. ===================
  4. Why use a shader preprocessor?
  5. ------------------------------
  6. In programming languages, a *preprocessor* allows changing the code before the
  7. compiler reads it. Unlike the compiler, the preprocessor does not care about
  8. whether the syntax of the preprocessed code is valid. The preprocessor always
  9. performs what the *directives* tell it to do. A directive is a statement
  10. starting with a hash symbol (``#``). It is not a *keyword* of the shader
  11. language (such as ``if`` or ``for``), but a special kind of token within the
  12. language.
  13. From Godot 4.0 onwards, you can use a shader preprocessor within text-based
  14. shaders. The syntax is similar to what most GLSL shader compilers support
  15. (which in turn is similar to the C/C++ preprocessor).
  16. .. note::
  17. The shader preprocessor is not available in :ref:`visual shaders <doc_visual_shaders>`.
  18. If you need to introduce preprocessor statements to a visual shader, you can
  19. convert it to a text-based shader using the **Convert to Shader** option in
  20. the VisualShader inspector resource dropdown. This conversion is a one-way
  21. operation; text shaders cannot be converted back to visual shaders.
  22. Directives
  23. ----------
  24. General syntax
  25. ^^^^^^^^^^^^^^
  26. - Preprocessor directives do not use brackets (``{}``), but can use parentheses.
  27. - Preprocessor directives **never** end with semicolons (with the exception of ``#define``,
  28. where this is allowed but potentially dangerous).
  29. - Preprocessor directives can span several lines by ending each line with a
  30. backslash (``\``). The first line break *not* featuring a backslash will end
  31. the preprocessor statement.
  32. #define
  33. ^^^^^^^
  34. **Syntax:** ``#define <identifier> [replacement_code]``.
  35. Defines the identifier after that directive as a macro, and replaces all
  36. successive occurrences of it with the replacement code given in the shader.
  37. Replacement is performed on a "whole words" basis, which means no replacement is
  38. performed if the string is part of another string (without any spaces separating
  39. it).
  40. Defines with replacements may also have one or more *arguments*, which can then
  41. be passed when referencing the define (similar to a function call).
  42. If the replacement code is not defined, the identifier may only be used with
  43. ``#ifdef`` or ``#ifndef`` directives.
  44. Compared to constants (``const CONSTANT = value;``), ``#define`` can be used
  45. anywhere within the shader (including in uniform hints).
  46. ``#define`` can also be used to insert arbitrary shader code at any location,
  47. while constants can't do that.
  48. .. code-block:: glsl
  49. shader_type spatial;
  50. // Notice the lack of semicolon at the end of the line, as the replacement text
  51. // shouldn't insert a semicolon on its own.
  52. // If the directive ends with a semicolon, the semicolon is inserted in every usage
  53. // of the directive, even when this causes a syntax error.
  54. #define USE_MY_COLOR
  55. #define MY_COLOR vec3(1, 0, 0)
  56. // Replacement with arguments.
  57. // All arguments are required (no default values can be provided).
  58. #define BRIGHTEN_COLOR(r, g, b) vec3(r + 0.5, g + 0.5, b + 0.5)
  59. // Multiline replacement using backslashes for continuation:
  60. #define SAMPLE(param1, param2, param3, param4) long_function_call( \
  61. param1, \
  62. param2, \
  63. param3, \
  64. param4 \
  65. )
  66. void fragment() {
  67. #ifdef USE_MY_COLOR
  68. ALBEDO = MY_COLOR;
  69. #endif
  70. }
  71. Defining a ``#define`` for an identifier that is already defined results in an
  72. error. To prevent this, use ``#undef <identifier>``.
  73. #undef
  74. ^^^^^^
  75. **Syntax:** ``#undef identifier``
  76. The ``#undef`` directive may be used to cancel a previously defined ``#define`` directive:
  77. .. code-block:: glsl
  78. #define MY_COLOR vec3(1, 0, 0)
  79. vec3 get_red_color() {
  80. return MY_COLOR;
  81. }
  82. #undef MY_COLOR
  83. #define MY_COLOR vec3(0, 1, 0)
  84. vec3 get_green_color() {
  85. return MY_COLOR;
  86. }
  87. // Like in most preprocessors, undefining a define that was not previously defined is allowed
  88. // (and won't print any warning or error).
  89. #undef THIS_DOES_NOT_EXIST
  90. Without ``#undef`` in the above example, there would be a macro redefinition error.
  91. #if
  92. ^^^
  93. **Syntax:** ``#if <condition>``
  94. The ``#if`` directive checks whether the ``condition`` passed. If it evaluates
  95. to a non-zero value, the code block is included, otherwise it is skipped.
  96. To evaluate correctly, the condition must be an expression giving a simple
  97. floating-point, integer or boolean result. There may be multiple condition
  98. blocks connected by ``&&`` (AND) or ``||`` (OR) operators. It may be continued
  99. by a ``#else`` block, but **must** be ended with the ``#endif`` directive.
  100. .. code-block:: glsl
  101. #define VAR 3
  102. #define USE_LIGHT 0 // Evaluates to `false`.
  103. #define USE_COLOR 1 // Evaluates to `true`.
  104. #if VAR == 3 && (USE_LIGHT || USE_COLOR)
  105. // Condition is `true`. Include this portion in the final shader.
  106. #endif
  107. Using the ``defined()`` *preprocessor function*, you can check whether the
  108. passed identifier is defined a by ``#define`` placed above that directive. This
  109. is useful for creating multiple shader versions in the same file. It may be
  110. continued by a ``#else`` block, but must be ended with the ``#endif`` directive.
  111. The ``defined()`` function's result can be negated by using the ``!`` (boolean NOT)
  112. symbol in front of it. This can be used to check whether a define is *not* set.
  113. .. code-block:: glsl
  114. #define USE_LIGHT
  115. #define USE_COLOR
  116. // Correct syntax:
  117. #if defined(USE_LIGHT) || defined(USE_COLOR) || !defined(USE_REFRACTION)
  118. // Condition is `true`. Include this portion in the final shader.
  119. #endif
  120. Be careful, as ``defined()`` must only wrap a single identifier within parentheses, never more:
  121. .. code-block:: glsl
  122. // Incorrect syntax (parentheses are not placed where they should be):
  123. #if defined(USE_LIGHT || USE_COLOR || !USE_REFRACTION)
  124. // This will cause an error or not behave as expected.
  125. #endif
  126. .. tip::
  127. In the shader editor, preprocessor branches that evaluate to ``false`` (and
  128. are therefore excluded from the final compiled shader) will appear grayed
  129. out. This does not apply to run-time ``if`` statements.
  130. **#if preprocessor versus if statement: Performance caveats**
  131. The :ref:`shading language <doc_shading_language>` supports run-time ``if`` statements:
  132. .. code-block:: glsl
  133. uniform bool USE_LIGHT = true;
  134. if (USE_LIGHT) {
  135. // This part is included in the compiled shader, and always run.
  136. } else {
  137. // This part is included in the compiled shader, but never run.
  138. }
  139. If the uniform is never changed, this behaves identical to the following usage
  140. of the ``#if`` preprocessor statement:
  141. .. code-block:: glsl
  142. #define USE_LIGHT
  143. #if defined(USE_LIGHT)
  144. // This part is included in the compiled shader, and always run.
  145. #else
  146. // This part is *not* included in the compiled shader (and therefore never run).
  147. #endif
  148. However, the ``#if`` variant can be faster in certain scenarios. This is because
  149. all run-time branches in a shader are still compiled and variables within
  150. those branches may still take up register space, even if they are never run in
  151. practice.
  152. Modern GPUs are `quite effective <https://medium.com/@jasonbooth_86226/branching-on-a-gpu-18bfc83694f2>`__
  153. at performing "static" branching. "Static" branching refers to ``if`` statements where
  154. *all* pixels/vertices evaluate to the same result in a given shader invocation. However,
  155. high amounts of :abbr:`VGPRs (Vector General-Purpose Register)` (which can be caused by
  156. having too many branches) can still slow down shader execution significantly.
  157. #elif
  158. ^^^^^
  159. The ``#elif`` directive stands for "else if" and checks the condition passed if
  160. the above ``#if`` evaluated to ``false``. ``#elif`` can only be used within an
  161. ``#if`` block. It is possible to use several ``#elif`` statements after an ``#if`` statement.
  162. .. code-block:: glsl
  163. #define VAR 2
  164. #if VAR == 0
  165. // Not included.
  166. #elif VAR == 1
  167. // Not included.
  168. #elif VAR == 2
  169. // Condition is `true`. Include this portion in the final shader.
  170. #else
  171. // Not included.
  172. #endif
  173. Like with ``#if``, the ``defined()`` preprocessor function can be used:
  174. .. code-block:: glsl
  175. #define SHADOW_QUALITY_MEDIUM
  176. #if defined(SHADOW_QUALITY_HIGH)
  177. // High shadow quality.
  178. #elif defined(SHADOW_QUALITY_MEDIUM)
  179. // Medium shadow quality.
  180. #else
  181. // Low shadow quality.
  182. #endif
  183. #ifdef
  184. ^^^^^^
  185. **Syntax:** ``#ifdef <identifier>``
  186. This is a shorthand for ``#if defined(...)``. Checks whether the passed
  187. identifier is defined by ``#define`` placed above that directive. This is useful
  188. for creating multiple shader versions in the same file. It may be continued by a
  189. ``#else`` block, but must be ended with the ``#endif`` directive.
  190. .. code-block:: glsl
  191. #define USE_LIGHT
  192. #ifdef USE_LIGHT
  193. // USE_LIGHT is defined. Include this portion in the final shader.
  194. #endif
  195. The processor does *not* support ``#elifdef`` as a shortcut for ``#elif defined(...)``.
  196. Instead, use the following series of ``#ifdef`` and ``#else`` when you need more
  197. than two branches:
  198. .. code-block:: glsl
  199. #define SHADOW_QUALITY_MEDIUM
  200. #ifdef SHADOW_QUALITY_HIGH
  201. // High shadow quality.
  202. #else
  203. #ifdef SHADOW_QUALITY_MEDIUM
  204. // Medium shadow quality.
  205. #else
  206. // Low shadow quality.
  207. #endif // This ends `SHADOW_QUALITY_MEDIUM`'s branch.
  208. #endif // This ends `SHADOW_QUALITY_HIGH`'s branch.
  209. #ifndef
  210. ^^^^^^^
  211. **Syntax:** ``#ifndef <identifier>``
  212. This is a shorthand for ``#if !defined(...)``. Similar to ``#ifdef``, but checks
  213. whether the passed identifier is **not** defined by ``#define`` before that
  214. directive.
  215. This is the exact opposite of ``#ifdef``; it will always match in situations
  216. where ``#ifdef`` would never match, and vice versa.
  217. .. code-block:: glsl
  218. #define USE_LIGHT
  219. #ifndef USE_LIGHT
  220. // Evaluates to `false`. This portion won't be included in the final shader.
  221. #endif
  222. #ifndef USE_COLOR
  223. // Evaluates to `true`. This portion will be included in the final shader.
  224. #endif
  225. #else
  226. ^^^^^
  227. **Syntax:** ``#else``
  228. Defines the optional block which is included when the previously defined ``#if``,
  229. ``#elif``, ``#ifdef`` or ``#ifndef`` directive evaluates to false.
  230. .. code-block:: glsl
  231. shader_type spatial;
  232. #define MY_COLOR vec3(1.0, 0, 0)
  233. void fragment() {
  234. #ifdef MY_COLOR
  235. ALBEDO = MY_COLOR;
  236. #else
  237. ALBEDO = vec3(0, 0, 1.0);
  238. #endif
  239. }
  240. #endif
  241. ^^^^^^
  242. **Syntax:** ``#endif``
  243. Used as terminator for the ``#if``, ``#ifdef``, ``#ifndef`` or subsequent ``#else`` directives.
  244. #include
  245. ^^^^^^^^
  246. **Syntax:** ``#include "path"``
  247. The ``#include`` directive includes the *entire* content of a shader include
  248. file in a shader. ``"path"`` can be an absolute ``res://`` path or relative to
  249. the current shader file. Relative paths are only allowed in shaders that are
  250. saved to ``.gdshader`` or ``.gdshaderinc`` files, while absolute paths can be
  251. used in shaders that are built into a scene/resource file.
  252. You can create new shader includes by using the **File > Create Shader Include**
  253. menu option of the shader editor, or by creating a new :ref:`ShaderInclude<class_ShaderInclude>` resource
  254. in the FileSystem dock.
  255. Shader includes can be included from within any shader, or other shader include, at
  256. any point in the file.
  257. When including shader includes in the global scope of a shader, it is recommended
  258. to do this after the initial ``shader_type`` statement.
  259. You can also include shader includes from within the body a function. Please note that
  260. the shader editor is likely going to report errors for your shader include's code, as it
  261. may not be valid outside of the context that it was written for. You can either choose
  262. to ignore these errors (the shader will still compile fine), or you can wrap the include
  263. in an ``#ifdef`` block that checks for a define from your shader.
  264. ``#include`` is useful for creating libraries of helper functions (or macros)
  265. and reducing code duplication. When using ``#include``, be careful about naming
  266. collisions, as redefining functions or macros is not allowed.
  267. ``#include`` is subject to several restrictions:
  268. - Only shader include resources (ending with ``.gdshaderinc``) can be included.
  269. ``.gdshader`` files cannot be included by another shader, but a
  270. ``.gdshaderinc`` file can include other ``.gdshaderinc`` files.
  271. - Cyclic dependencies are **not** allowed and will result in an error.
  272. - To avoid infinite recursion, include depth is limited to 25 steps.
  273. Example shader include file:
  274. .. code-block:: glsl
  275. // fancy_color.gdshaderinc
  276. // While technically allowed, there is usually no `shader_type` declaration in include files.
  277. vec3 get_fancy_color() {
  278. return vec3(0.3, 0.6, 0.9);
  279. }
  280. Example base shader (using the include file we created above):
  281. .. code-block:: glsl
  282. // material.gdshader
  283. shader_type spatial;
  284. #include "res://fancy_color.gdshaderinc"
  285. void fragment() {
  286. // No error, as we've included a definition for `get_fancy_color()` via the shader include.
  287. COLOR = get_fancy_color();
  288. }
  289. #pragma
  290. ^^^^^^^
  291. **Syntax:** ``#pragma value``
  292. The ``#pragma`` directive provides additional information to the preprocessor or compiler.
  293. Currently, it may have only one value: ``disable_preprocessor``. If you don't need
  294. the preprocessor, use that directive to speed up shader compilation by excluding
  295. the preprocessor step.
  296. .. code-block:: glsl
  297. #pragma disable_preprocessor
  298. #if USE_LIGHT
  299. // This causes a shader compilation error, as the `#if USE_LIGHT` and `#endif`
  300. // are included as-is in the final shader code.
  301. #endif