shader_preprocessor.rst 12 KB

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