shading_language.rst 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. .. _doc_shading_language:
  2. Shading language
  3. ================
  4. Introduction
  5. ------------
  6. Godot uses a shading language similar to GLSL ES 3.0. Most datatypes and
  7. functions are supported, and the few remaining ones will likely be added over
  8. time.
  9. If you are already familiar with GLSL, the :ref:`Godot Shader Migration
  10. Guide<doc_converting_glsl_to_godot_shaders>` is a resource that will help you
  11. transition from regular GLSL to Godot's shading language.
  12. Data types
  13. ----------
  14. Most GLSL ES 3.0 datatypes are supported:
  15. +---------------------+---------------------------------------------------------------------------------+
  16. | Type | Description |
  17. +=====================+=================================================================================+
  18. | **void** | Void datatype, useful only for functions that return nothing. |
  19. +---------------------+---------------------------------------------------------------------------------+
  20. | **bool** | Boolean datatype, can only contain ``true`` or ``false``. |
  21. +---------------------+---------------------------------------------------------------------------------+
  22. | **bvec2** | Two-component vector of booleans. |
  23. +---------------------+---------------------------------------------------------------------------------+
  24. | **bvec3** | Three-component vector of booleans. |
  25. +---------------------+---------------------------------------------------------------------------------+
  26. | **bvec4** | Four-component vector of booleans. |
  27. +---------------------+---------------------------------------------------------------------------------+
  28. | **int** | Signed scalar integer. |
  29. +---------------------+---------------------------------------------------------------------------------+
  30. | **ivec2** | Two-component vector of signed integers. |
  31. +---------------------+---------------------------------------------------------------------------------+
  32. | **ivec3** | Three-component vector of signed integers. |
  33. +---------------------+---------------------------------------------------------------------------------+
  34. | **ivec4** | Four-component vector of signed integers. |
  35. +---------------------+---------------------------------------------------------------------------------+
  36. | **uint** | Unsigned scalar integer; can't contain negative numbers. |
  37. +---------------------+---------------------------------------------------------------------------------+
  38. | **uvec2** | Two-component vector of unsigned integers. |
  39. +---------------------+---------------------------------------------------------------------------------+
  40. | **uvec3** | Three-component vector of unsigned integers. |
  41. +---------------------+---------------------------------------------------------------------------------+
  42. | **uvec4** | Four-component vector of unsigned integers. |
  43. +---------------------+---------------------------------------------------------------------------------+
  44. | **float** | Floating-point scalar. |
  45. +---------------------+---------------------------------------------------------------------------------+
  46. | **vec2** | Two-component vector of floating-point values. |
  47. +---------------------+---------------------------------------------------------------------------------+
  48. | **vec3** | Three-component vector of floating-point values. |
  49. +---------------------+---------------------------------------------------------------------------------+
  50. | **vec4** | Four-component vector of floating-point values. |
  51. +---------------------+---------------------------------------------------------------------------------+
  52. | **mat2** | 2x2 matrix, in column major order. |
  53. +---------------------+---------------------------------------------------------------------------------+
  54. | **mat3** | 3x3 matrix, in column major order. |
  55. +---------------------+---------------------------------------------------------------------------------+
  56. | **mat4** | 4x4 matrix, in column major order. |
  57. +---------------------+---------------------------------------------------------------------------------+
  58. | **sampler2D** | Sampler type for binding 2D textures, which are read as float. |
  59. +---------------------+---------------------------------------------------------------------------------+
  60. | **isampler2D** | Sampler type for binding 2D textures, which are read as signed integer. |
  61. +---------------------+---------------------------------------------------------------------------------+
  62. | **usampler2D** | Sampler type for binding 2D textures, which are read as unsigned integer. |
  63. +---------------------+---------------------------------------------------------------------------------+
  64. | **sampler2DArray** | Sampler type for binding 2D texture arrays, which are read as float. |
  65. +---------------------+---------------------------------------------------------------------------------+
  66. | **isampler2DArray** | Sampler type for binding 2D texture arrays, which are read as signed integer. |
  67. +---------------------+---------------------------------------------------------------------------------+
  68. | **usampler2DArray** | Sampler type for binding 2D texture arrays, which are read as unsigned integer. |
  69. +---------------------+---------------------------------------------------------------------------------+
  70. | **sampler3D** | Sampler type for binding 3D textures, which are read as float. |
  71. +---------------------+---------------------------------------------------------------------------------+
  72. | **isampler3D** | Sampler type for binding 3D textures, which are read as signed integer. |
  73. +---------------------+---------------------------------------------------------------------------------+
  74. | **usampler3D** | Sampler type for binding 3D textures, which are read as unsigned integer. |
  75. +---------------------+---------------------------------------------------------------------------------+
  76. | **samplerCube** | Sampler type for binding Cubemaps, which are read as floats. |
  77. +---------------------+---------------------------------------------------------------------------------+
  78. Casting
  79. ~~~~~~~
  80. Just like GLSL ES 3.0, implicit casting between scalars and vectors of the same
  81. size but different type is not allowed. Casting of types of different size is
  82. also not allowed. Conversion must be done explicitly via constructors.
  83. Example:
  84. .. code-block:: glsl
  85. float a = 2; // invalid
  86. float a = 2.0; // valid
  87. float a = float(2); // valid
  88. Default integer constants are signed, so casting is always needed to convert to
  89. unsigned:
  90. .. code-block:: glsl
  91. int a = 2; // valid
  92. uint a = 2; // invalid
  93. uint a = uint(2); // valid
  94. Members
  95. ~~~~~~~
  96. Individual scalar members of vector types are accessed via the "x", "y", "z" and
  97. "w" members. Alternatively, using "r", "g", "b" and "a" also works and is
  98. equivalent. Use whatever fits best for your needs.
  99. For matrices, use the ``m[row][column]`` indexing syntax to access each scalar,
  100. or ``m[idx]`` to access a vector by row index. For example, for accessing the y
  101. position of an object in a mat4 you use ``m[3][1]``.
  102. Constructing
  103. ~~~~~~~~~~~~
  104. Construction of vector types must always pass:
  105. .. code-block:: glsl
  106. // The required amount of scalars
  107. vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
  108. // Complementary vectors and/or scalars
  109. vec4 a = vec4(vec2(0.0, 1.0), vec2(2.0, 3.0));
  110. vec4 a = vec4(vec3(0.0, 1.0, 2.0), 3.0);
  111. // A single scalar for the whole vector
  112. vec4 a = vec4(0.0);
  113. Construction of matrix types requires vectors of the same dimension as the
  114. matrix. You can also build a diagonal matrix using ``matx(float)`` syntax.
  115. Accordingly, ``mat4(1.0)`` is an identity matrix.
  116. .. code-block:: glsl
  117. mat2 m2 = mat2(vec2(1.0, 0.0), vec2(0.0, 1.0));
  118. mat3 m3 = mat3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0));
  119. mat4 identity = mat4(1.0);
  120. Matrices can also be built from a matrix of another dimension. There are two
  121. rules:
  122. 1. If a larger matrix is constructed from a smaller matrix, the additional rows
  123. and columns are set to the values they would have in an identity matrix.
  124. 2. If a smaller matrix is constructed from a larger matrix, the top, left
  125. submatrix of the larger matrix is used.
  126. .. code-block:: glsl
  127. mat3 basis = mat3(WORLD_MATRIX);
  128. mat4 m4 = mat4(basis);
  129. mat2 m2 = mat2(m4);
  130. Swizzling
  131. ~~~~~~~~~
  132. It is possible to obtain any combination of components in any order, as long as
  133. the result is another vector type (or scalar). This is easier shown than
  134. explained:
  135. .. code-block:: glsl
  136. vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
  137. vec3 b = a.rgb; // Creates a vec3 with vec4 components.
  138. vec3 b = a.ggg; // Also valid; creates a vec3 and fills it with a single vec4 component.
  139. vec3 b = a.bgr; // "b" will be vec3(2.0, 1.0, 0.0).
  140. vec3 b = a.xyz; // Also rgba, xyzw are equivalent.
  141. vec3 b = a.stp; // And stpq (for texture coordinates).
  142. float c = b.w; // Invalid, because "w" is not present in vec3 b.
  143. vec3 c = b.xrt; // Invalid, mixing different styles is forbidden.
  144. b.rrr = a.rgb; // Invalid, assignment with duplication.
  145. b.bgr = a.rgb; // Valid assignment. "b"'s "blue" component will be "a"'s "red" and vice versa.
  146. Precision
  147. ~~~~~~~~~
  148. It is possible to add precision modifiers to datatypes; use them for uniforms,
  149. variables, arguments and varyings:
  150. .. code-block:: glsl
  151. lowp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // low precision, usually 8 bits per component mapped to 0-1
  152. mediump vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // medium precision, usually 16 bits or half float
  153. highp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // high precision, uses full float or integer range (default)
  154. Using lower precision for some operations can speed up the math involved (at the
  155. cost of less precision). This is rarely needed in the vertex processor function
  156. (where full precision is needed most of the time), but is often useful in the
  157. fragment processor.
  158. Some architectures (mainly mobile) can benefit significantly from this, but
  159. there are downsides such as the additional overhead of conversion between
  160. precisions. Refer to the documentation of the target architecture for further
  161. information. In many cases, mobile drivers cause inconsistent or unexpected
  162. behavior and it is best to avoid specifying precision unless necessary.
  163. Arrays
  164. ------
  165. Arrays are containers for multiple variables of a similar type.
  166. Local arrays
  167. ~~~~~~~~~~~~
  168. Local arrays are declared in functions. They can use all of the allowed
  169. datatypes, except samplers. The array declaration follows a C-style syntax:
  170. ``[const] + [precision] + typename + identifier + [array size]``.
  171. .. code-block:: glsl
  172. void fragment() {
  173. float arr[3];
  174. }
  175. They can be initialized at the beginning like:
  176. .. code-block:: glsl
  177. float float_arr[3] = float[3] (1.0, 0.5, 0.0); // first constructor
  178. int int_arr[3] = int[] (2, 1, 0); // second constructor
  179. vec2 vec2_arr[3] = { vec2(1.0, 1.0), vec2(0.5, 0.5), vec2(0.0, 0.0) }; // third constructor
  180. bool bool_arr[] = { true, true, false }; // fourth constructor - size is defined automatically from the element count
  181. You can declare multiple arrays (even with different sizes) in one expression:
  182. .. code-block:: glsl
  183. float a[3] = float[3] (1.0, 0.5, 0.0),
  184. b[2] = { 1.0, 0.5 },
  185. c[] = { 0.7 },
  186. d = 0.0,
  187. e[5];
  188. To access an array element, use the indexing syntax:
  189. .. code-block:: glsl
  190. float arr[3];
  191. arr[0] = 1.0; // setter
  192. COLOR.r = arr[0]; // getter
  193. Arrays also have a built-in function ``.length()`` (not to be confused with the
  194. built-in ``length()`` function). It doesn't accept any parameters and will
  195. return the array's size.
  196. .. code-block:: glsl
  197. float arr[] = { 0.0, 1.0, 0.5, -1.0 };
  198. for (int i = 0; i < arr.length(); i++) {
  199. // ...
  200. }
  201. .. note::
  202. If you use an index either below 0 or greater than array size - the shader will
  203. crash and break rendering. To prevent this, use ``length()``, ``if``, or
  204. ``clamp()`` functions to ensure the index is between 0 and the array's
  205. length. Always carefully test and check your code. If you pass a constant
  206. expression or a number, the editor will check its bounds to prevent
  207. this crash.
  208. Global arrays
  209. ~~~~~~~~~~~~~
  210. You can declare arrays at global space like:
  211. .. code-block:: glsl
  212. shader_type spatial;
  213. const lowp vec3 v[1] = lowp vec3[1] ( vec3(0, 0, 1) );
  214. void fragment() {
  215. ALBEDO = v[0];
  216. }
  217. .. note::
  218. Global arrays have to be declared as global constants, otherwise they can be
  219. declared the same as local arrays.
  220. Constants
  221. ---------
  222. Use the ``const`` keyword before the variable declaration to make that variable
  223. immutable, which means that it cannot be modified. All basic types, except
  224. samplers can be declared as constants. Accessing and using a constant value is
  225. slightly faster than using a uniform. Constants must be initialized at their
  226. declaration.
  227. .. code-block:: glsl
  228. const vec2 a = vec2(0.0, 1.0);
  229. vec2 b;
  230. a = b; // invalid
  231. b = a; // valid
  232. Constants cannot be modified and additionally cannot have hints, but multiple of
  233. them (if they have the same type) can be declared in a single expression e.g
  234. .. code-block:: glsl
  235. const vec2 V1 = vec2(1, 1), V2 = vec2(2, 2);
  236. Similar to variables, arrays can also be declared with ``const``.
  237. .. code-block:: glsl
  238. const float arr[] = { 1.0, 0.5, 0.0 };
  239. arr[0] = 1.0; // invalid
  240. COLOR.r = arr[0]; // valid
  241. Constants can be declared both globally (outside of any function) or locally
  242. (inside a function). Global constants are useful when you want to have access to
  243. a value throughout your shader that does not need to be modified. Like uniforms,
  244. global constants are shared between all shader stages, but they are not
  245. accessible outside of the shader.
  246. .. code-block:: glsl
  247. shader_type spatial;
  248. const float PI = 3.14159265358979323846;
  249. Structs
  250. -------
  251. Structs are compound types which can be used for better abstraction of shader
  252. code. You can declare them at the global scope like:
  253. .. code-block:: glsl
  254. struct PointLight {
  255. vec3 position;
  256. vec3 color;
  257. float intensity;
  258. };
  259. After declaration, you can instantiate and initialize them like:
  260. .. code-block:: glsl
  261. void fragment()
  262. {
  263. PointLight light;
  264. light.position = vec3(0.0);
  265. light.color = vec3(1.0, 0.0, 0.0);
  266. light.intensity = 0.5;
  267. }
  268. Or use struct constructor for same purpose:
  269. .. code-block:: glsl
  270. PointLight light = PointLight(vec3(0.0), vec3(1.0, 0.0, 0.0), 0.5);
  271. Structs may contain other struct or array, you can also instance them as global
  272. constant:
  273. .. code-block:: glsl
  274. shader_type spatial;
  275. ...
  276. struct Scene {
  277. PointLight lights[2];
  278. };
  279. const Scene scene = Scene(PointLight[2](PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0)));
  280. void fragment()
  281. {
  282. ALBEDO = scene.lights[0].color;
  283. }
  284. You can also pass them to functions:
  285. .. code-block:: glsl
  286. shader_type canvas_item;
  287. ...
  288. Scene construct_scene(PointLight light1, PointLight light2) {
  289. return Scene({light1, light2});
  290. }
  291. void fragment()
  292. {
  293. COLOR.rgb = construct_scene(PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 1.0), 1.0)).lights[0].color;
  294. }
  295. Operators
  296. ---------
  297. Godot shading language supports the same set of operators as GLSL ES 3.0. Below
  298. is the list of them in precedence order:
  299. +-------------+------------------------+------------------+
  300. | Precedence | Class | Operator |
  301. +-------------+------------------------+------------------+
  302. | 1 (highest) | parenthetical grouping | **()** |
  303. +-------------+------------------------+------------------+
  304. | 2 | unary | **+, -, !, ~** |
  305. +-------------+------------------------+------------------+
  306. | 3 | multiplicative | **/, \*, %** |
  307. +-------------+------------------------+------------------+
  308. | 4 | additive | **+, -** |
  309. +-------------+------------------------+------------------+
  310. | 5 | bit-wise shift | **<<, >>** |
  311. +-------------+------------------------+------------------+
  312. | 6 | relational | **<, >, <=, >=** |
  313. +-------------+------------------------+------------------+
  314. | 7 | equality | **==, !=** |
  315. +-------------+------------------------+------------------+
  316. | 8 | bit-wise AND | **&** |
  317. +-------------+------------------------+------------------+
  318. | 9 | bit-wise exclusive OR | **^** |
  319. +-------------+------------------------+------------------+
  320. | 10 | bit-wise inclusive OR | **|** |
  321. +-------------+------------------------+------------------+
  322. | 11 | logical AND | **&&** |
  323. +-------------+------------------------+------------------+
  324. | 12 (lowest) | logical inclusive OR | **||** |
  325. +-------------+------------------------+------------------+
  326. Flow control
  327. ------------
  328. Godot Shading language supports the most common types of flow control:
  329. .. code-block:: glsl
  330. // `if` and `else`.
  331. if (cond) {
  332. } else {
  333. }
  334. // Ternary operator.
  335. // This is an expression that behaves like `if`/`else` and returns the value.
  336. // If `cond` evaluates to `true`, `result` will be `9`.
  337. // Otherwise, `result` will be `5`.
  338. int result = cond ? 9 : 5;
  339. // `switch`.
  340. switch (i) { // `i` should be a signed integer expression.
  341. case -1:
  342. break;
  343. case 0:
  344. return; // `break` or `return` to avoid running the next `case`.
  345. case 1: // Fallthrough (no `break` or `return`): will run the next `case`.
  346. case 2:
  347. break;
  348. //...
  349. default: // Only run if no `case` above matches. Optional.
  350. break;
  351. }
  352. // `for` loop. Best used when the number of elements to iterate on
  353. // is known in advance.
  354. for (int i = 0; i < 10; i++) {
  355. }
  356. // `while` loop. Best used when the number of elements to iterate on
  357. // is not known in advance.
  358. while (cond) {
  359. }
  360. // `do while`. Like `while`, but always runs at least once even if `cond`
  361. // never evaluates to `true`.
  362. do {
  363. } while (cond);
  364. Keep in mind that, in modern GPUs, an infinite loop can exist and can freeze
  365. your application (including editor). Godot can't protect you from this, so be
  366. careful not to make this mistake!
  367. Also, when comparing floating-point values against a number, make sure to
  368. compare them against a *range* instead of an exact number.
  369. A comparison like ``if (value == 0.3)`` may not evaluate to ``true``.
  370. Floating-point math is often approximate and can defy expectations. It can also
  371. behave differently depending on the hardware.
  372. **Don't** do this.
  373. .. code-block:: glsl
  374. float value = 0.1 + 0.2;
  375. // May not evaluate to `true`!
  376. if (value == 0.3) {
  377. // ...
  378. }
  379. Instead, always perform a range comparison with an epsilon value. The larger the
  380. floating-point number (and the less precise the floating-point number, the
  381. larger the epsilon value should be.
  382. .. code-block:: glsl
  383. const float EPSILON = 0.0001;
  384. if (value >= 0.3 - EPSILON && value <= 0.3 + EPSILON) {
  385. // ...
  386. }
  387. See `floating-point-gui.de <https://floating-point-gui.de/>`__ for more
  388. information.
  389. .. warning::
  390. When exporting a GLES2 project to HTML5, WebGL 1.0 will be used. WebGL 1.0
  391. doesn't support dynamic loops, so shaders using those won't work there.
  392. Discarding
  393. ----------
  394. Fragment and light functions can use the **discard** keyword. If used, the
  395. fragment is discarded and nothing is written.
  396. Functions
  397. ---------
  398. It is possible to define functions in a Godot shader. They use the following
  399. syntax:
  400. .. code-block:: glsl
  401. ret_type func_name(args) {
  402. return ret_type; // if returning a value
  403. }
  404. // a more specific example:
  405. int sum2(int a, int b) {
  406. return a + b;
  407. }
  408. You can only use functions that have been defined above (higher in the editor)
  409. the function from which you are calling them.
  410. Function arguments can have special qualifiers:
  411. * **in**: Means the argument is only for reading (default).
  412. * **out**: Means the argument is only for writing.
  413. * **inout**: Means the argument is fully passed via reference.
  414. * **const**: Means the argument is a constant and cannot be changed, may be
  415. combined with **in** qualifier.
  416. Example below:
  417. .. code-block:: glsl
  418. void sum2(int a, int b, inout int result) {
  419. result = a + b;
  420. }
  421. Varyings
  422. ~~~~~~~~
  423. To send data from the vertex to the fragment (or light) processor function, *varyings* are
  424. used. They are set for every primitive vertex in the *vertex processor*, and the
  425. value is interpolated for every pixel in the *fragment processor*.
  426. .. code-block:: glsl
  427. shader_type spatial;
  428. varying vec3 some_color;
  429. void vertex() {
  430. some_color = NORMAL; // Make the normal the color.
  431. }
  432. void fragment() {
  433. ALBEDO = some_color;
  434. }
  435. void light() {
  436. DIFFUSE_LIGHT = some_color * 100; // optionally
  437. }
  438. Varying can also be an array:
  439. .. code-block:: glsl
  440. shader_type spatial;
  441. varying float var_arr[3];
  442. void vertex() {
  443. var_arr[0] = 1.0;
  444. var_arr[1] = 0.0;
  445. }
  446. void fragment() {
  447. ALBEDO = vec3(var_arr[0], var_arr[1], var_arr[2]); // red color
  448. }
  449. It's also possible to send data from *fragment* to *light* processors using *varying* keyword. To do so you can assign it in the *fragment* and later use it in the *light* function.
  450. .. code-block:: glsl
  451. shader_type spatial;
  452. varying vec3 some_light;
  453. void fragment() {
  454. some_light = ALBEDO * 100.0; // Make a shinning light.
  455. }
  456. void light() {
  457. DIFFUSE_LIGHT = some_light;
  458. }
  459. Note that varying may not be assigned in custom functions or a *light processor* function like:
  460. .. code-block:: glsl
  461. shader_type spatial;
  462. varying float test;
  463. void foo() {
  464. test = 0.0; // Error.
  465. }
  466. void vertex() {
  467. test = 0.0;
  468. }
  469. void light() {
  470. test = 0.0; // Error too.
  471. }
  472. This limitation was introduced to prevent incorrect usage before initialization.
  473. Interpolation qualifiers
  474. ~~~~~~~~~~~~~~~~~~~~~~~~
  475. Certain values are interpolated during the shading pipeline. You can modify how
  476. these interpolations are done by using *interpolation qualifiers*.
  477. .. code-block:: glsl
  478. shader_type spatial;
  479. varying flat vec3 our_color;
  480. void vertex() {
  481. our_color = COLOR.rgb;
  482. }
  483. void fragment() {
  484. ALBEDO = our_color;
  485. }
  486. There are two possible interpolation qualifiers:
  487. +-------------------+---------------------------------------------------------------------------------+
  488. | Qualifier | Description |
  489. +===================+=================================================================================+
  490. | **flat** | The value is not interpolated. |
  491. +-------------------+---------------------------------------------------------------------------------+
  492. | **smooth** | The value is interpolated in a perspective-correct fashion. This is the default.|
  493. +-------------------+---------------------------------------------------------------------------------+
  494. Uniforms
  495. ~~~~~~~~
  496. Passing values to shaders is possible. These are global to the whole shader and
  497. are called *uniforms*. When a shader is later assigned to a material, the
  498. uniforms will appear as editable parameters in it. Uniforms can't be written
  499. from within the shader.
  500. .. note::
  501. Uniform arrays are not implemented yet.
  502. .. code-block:: glsl
  503. shader_type spatial;
  504. uniform float some_value;
  505. You can set uniforms in the editor in the material. Or you can set them through
  506. GDScript:
  507. ::
  508. material.set_shader_param("some_value", some_value)
  509. .. note:: The first argument to ``set_shader_param`` is the name of the uniform
  510. in the shader. It must match *exactly* to the name of the uniform in
  511. the shader or else it will not be recognized.
  512. Any GLSL type except for *void* can be a uniform. Additionally, Godot provides
  513. optional shader hints to make the compiler understand for what the uniform is
  514. used.
  515. .. code-block:: glsl
  516. shader_type spatial;
  517. uniform vec4 color : hint_color;
  518. uniform float amount : hint_range(0, 1);
  519. uniform vec4 other_color : hint_color = vec4(1.0);
  520. It's important to understand that textures that are supplied as color require
  521. hints for proper sRGB->linear conversion (i.e. ``hint_albedo``), as Godot's 3D
  522. engine renders in linear color space.
  523. Full list of hints below:
  524. +----------------+------------------------------+-------------------------------------+
  525. | Type | Hint | Description |
  526. +================+==============================+=====================================+
  527. | **vec4** | hint_color | Used as color |
  528. +----------------+------------------------------+-------------------------------------+
  529. | **int, float** | hint_range(min, max[, step]) | Used as range (with min/max/step) |
  530. +----------------+------------------------------+-------------------------------------+
  531. | **sampler2D** | hint_albedo | Used as albedo color, default white |
  532. +----------------+------------------------------+-------------------------------------+
  533. | **sampler2D** | hint_black_albedo | Used as albedo color, default black |
  534. +----------------+------------------------------+-------------------------------------+
  535. | **sampler2D** | hint_normal | Used as normalmap |
  536. +----------------+------------------------------+-------------------------------------+
  537. | **sampler2D** | hint_white | As value, default to white. |
  538. +----------------+------------------------------+-------------------------------------+
  539. | **sampler2D** | hint_black | As value, default to black |
  540. +----------------+------------------------------+-------------------------------------+
  541. | **sampler2D** | hint_aniso | As flowmap, default to right. |
  542. +----------------+------------------------------+-------------------------------------+
  543. GDScript uses different variable types than GLSL does, so when passing variables
  544. from GDScript to shaders, Godot converts the type automatically. Below is a
  545. table of the corresponding types:
  546. +-----------------+-----------+
  547. | GDScript type | GLSL type |
  548. +=================+===========+
  549. | **bool** | **bool** |
  550. +-----------------+-----------+
  551. | **int** | **int** |
  552. +-----------------+-----------+
  553. | **float** | **float** |
  554. +-----------------+-----------+
  555. | **Vector2** | **vec2** |
  556. +-----------------+-----------+
  557. | **Vector3** | **vec3** |
  558. +-----------------+-----------+
  559. | **Color** | **vec4** |
  560. +-----------------+-----------+
  561. | **Transform** | **mat4** |
  562. +-----------------+-----------+
  563. | **Transform2D** | **mat4** |
  564. +-----------------+-----------+
  565. .. note:: Be careful when setting shader uniforms from GDScript, no error will
  566. be thrown if the type does not match. Your shader will just exhibit
  567. undefined behavior.
  568. Uniforms can also be assigned default values:
  569. .. code-block:: glsl
  570. shader_type spatial;
  571. uniform vec4 some_vector = vec4(0.0);
  572. uniform vec4 some_color : hint_color = vec4(1.0);
  573. Built-in variables
  574. ------------------
  575. A large number of built-in variables are available, like ``UV``, ``COLOR`` and ``VERTEX``. What variables are available depends on the type of shader (``spatial``, ``canvas_item`` or ``particle``) and the function used (``vertex``, ``fragment`` or ``light``).
  576. For a list of the build-in variables that are available, please see the corresponding pages:
  577. - :ref:`Spatial shaders <doc_spatial_shader>`
  578. - :ref:`Canvas item shaders <doc_canvas_item_shader>`
  579. - :ref:`Particle shaders <doc_particle_shader>`
  580. Built-in functions
  581. ------------------
  582. A large number of built-in functions are supported, conforming to GLSL ES 3.0.
  583. When vec_type (float), vec_int_type, vec_uint_type, vec_bool_type nomenclature
  584. is used, it can be scalar or vector.
  585. .. note:: For a list of the functions that are not available in the GLES2
  586. backend, please see the :ref:`Differences between GLES2 and GLES3 doc
  587. <doc_gles2_gles3_differences>`.
  588. +------------------------------------------------------------------------+---------------------------------------------------------------+
  589. | Function | Description / Return value |
  590. +========================================================================+===============================================================+
  591. | vec_type **radians** (vec_type degrees) | Convert degrees to radians |
  592. +------------------------------------------------------------------------+---------------------------------------------------------------+
  593. | vec_type **degrees** (vec_type radians) | Convert radians to degrees |
  594. +------------------------------------------------------------------------+---------------------------------------------------------------+
  595. | vec_type **sin** (vec_type x) | Sine |
  596. +------------------------------------------------------------------------+---------------------------------------------------------------+
  597. | vec_type **cos** (vec_type x) | Cosine |
  598. +------------------------------------------------------------------------+---------------------------------------------------------------+
  599. | vec_type **tan** (vec_type x) | Tangent |
  600. +------------------------------------------------------------------------+---------------------------------------------------------------+
  601. | vec_type **asin** (vec_type x) | Arcsine |
  602. +------------------------------------------------------------------------+---------------------------------------------------------------+
  603. | vec_type **acos** (vec_type x) | Arccosine |
  604. +------------------------------------------------------------------------+---------------------------------------------------------------+
  605. | vec_type **atan** (vec_type y_over_x) | Arctangent |
  606. +------------------------------------------------------------------------+---------------------------------------------------------------+
  607. | vec_type **atan** (vec_type y, vec_type x) | Arctangent to convert vector to angle |
  608. +------------------------------------------------------------------------+---------------------------------------------------------------+
  609. | vec_type **sinh** (vec_type x) | Hyperbolic sine |
  610. +------------------------------------------------------------------------+---------------------------------------------------------------+
  611. | vec_type **cosh** (vec_type x) | Hyperbolic cosine |
  612. +------------------------------------------------------------------------+---------------------------------------------------------------+
  613. | vec_type **tanh** (vec_type x) | Hyperbolic tangent |
  614. +------------------------------------------------------------------------+---------------------------------------------------------------+
  615. | vec_type **asinh** (vec_type x) | Inverse hyperbolic sine |
  616. +------------------------------------------------------------------------+---------------------------------------------------------------+
  617. | vec_type **acosh** (vec_type x) | Inverse hyperbolic cosine |
  618. +------------------------------------------------------------------------+---------------------------------------------------------------+
  619. | vec_type **atanh** (vec_type x) | Inverse hyperbolic tangent |
  620. +------------------------------------------------------------------------+---------------------------------------------------------------+
  621. | vec_type **pow** (vec_type x, vec_type y) | Power (undefined if ``x`` < 0 or if ``x`` = 0 and ``y`` <= 0) |
  622. +------------------------------------------------------------------------+---------------------------------------------------------------+
  623. | vec_type **exp** (vec_type x) | Base-e exponential |
  624. +------------------------------------------------------------------------+---------------------------------------------------------------+
  625. | vec_type **exp2** (vec_type x) | Base-2 exponential |
  626. +------------------------------------------------------------------------+---------------------------------------------------------------+
  627. | vec_type **log** (vec_type x) | Natural logarithm |
  628. +------------------------------------------------------------------------+---------------------------------------------------------------+
  629. | vec_type **log2** (vec_type x) | Base-2 logarithm |
  630. +------------------------------------------------------------------------+---------------------------------------------------------------+
  631. | vec_type **sqrt** (vec_type x) | Square root |
  632. +------------------------------------------------------------------------+---------------------------------------------------------------+
  633. | vec_type **inversesqrt** (vec_type x) | Inverse square root |
  634. +------------------------------------------------------------------------+---------------------------------------------------------------+
  635. | vec_type **abs** (vec_type x) | Absolute value (returns positive value if negative) |
  636. +------------------------------------------------------------------------+---------------------------------------------------------------+
  637. | ivec_type **abs** (ivec_type x) | Absolute value (returns positive value if negative) |
  638. +------------------------------------------------------------------------+---------------------------------------------------------------+
  639. | vec_type **sign** (vec_type x) | Sign (returns ``1.0`` if positive, ``-1.0`` if negative, |
  640. | | ``0.0`` if zero) |
  641. +------------------------------------------------------------------------+---------------------------------------------------------------+
  642. | ivec_type **sign** (ivec_type x) | Sign (returns ``1`` if positive, ``-1`` if negative, |
  643. | | ``0`` if zero) |
  644. +------------------------------------------------------------------------+---------------------------------------------------------------+
  645. | vec_type **floor** (vec_type x) | Round to the integer below |
  646. +------------------------------------------------------------------------+---------------------------------------------------------------+
  647. | vec_type **round** (vec_type x) | Round to the nearest integer |
  648. +------------------------------------------------------------------------+---------------------------------------------------------------+
  649. | vec_type **roundEven** (vec_type x) | Round to the nearest even integer |
  650. +------------------------------------------------------------------------+---------------------------------------------------------------+
  651. | vec_type **trunc** (vec_type x) | Truncation |
  652. +------------------------------------------------------------------------+---------------------------------------------------------------+
  653. | vec_type **ceil** (vec_type x) | Round to the integer above |
  654. +------------------------------------------------------------------------+---------------------------------------------------------------+
  655. | vec_type **fract** (vec_type x) | Fractional (returns ``x - floor(x)``) |
  656. +------------------------------------------------------------------------+---------------------------------------------------------------+
  657. | vec_type **mod** (vec_type x, vec_type y) | Modulo (division remainder) |
  658. +------------------------------------------------------------------------+---------------------------------------------------------------+
  659. | vec_type **mod** (vec_type x, float y) | Modulo (division remainder) |
  660. +------------------------------------------------------------------------+---------------------------------------------------------------+
  661. | vec_type **modf** (vec_type x, out vec_type i) | Fractional of ``x``, with ``i`` as integer part |
  662. +------------------------------------------------------------------------+---------------------------------------------------------------+
  663. | vec_type **min** (vec_type a, vec_type b) | Lowest value between ``a`` and ``b`` |
  664. +------------------------------------------------------------------------+---------------------------------------------------------------+
  665. | vec_type **max** (vec_type a, vec_type b) | Highest value between ``a`` and ``b`` |
  666. +------------------------------------------------------------------------+---------------------------------------------------------------+
  667. | vec_type **clamp** (vec_type x, vec_type min, vec_type max) | Clamp ``x`` between ``min`` and ``max`` (inclusive) |
  668. +------------------------------------------------------------------------+---------------------------------------------------------------+
  669. | float **mix** (float a, float b, float c) | Linear interpolate between ``a`` and ``b`` by ``c`` |
  670. +------------------------------------------------------------------------+---------------------------------------------------------------+
  671. | vec_type **mix** (vec_type a, vec_type b, float c) | Linear interpolate between ``a`` and ``b`` by ``c`` |
  672. | | (scalar coefficient) |
  673. +------------------------------------------------------------------------+---------------------------------------------------------------+
  674. | vec_type **mix** (vec_type a, vec_type b, vec_type c) | Linear interpolate between ``a`` and ``b`` by ``c`` |
  675. | | (vector coefficient) |
  676. +------------------------------------------------------------------------+---------------------------------------------------------------+
  677. | vec_type **mix** (vec_type a, vec_type b, bvec_type c) | Linear interpolate between ``a`` and ``b`` by ``c`` |
  678. | | (boolean-vector selection) |
  679. +------------------------------------------------------------------------+---------------------------------------------------------------+
  680. | vec_type **fma** (vec_type a, vec_type b, vec_type c) | Performs a fused multiply-add operation: ``(a * b + c)`` |
  681. | | (faster than doing it manually) |
  682. +------------------------------------------------------------------------+---------------------------------------------------------------+
  683. | vec_type **step** (vec_type a, vec_type b) | ``b[i] < a[i] ? 0.0 : 1.0`` |
  684. +------------------------------------------------------------------------+---------------------------------------------------------------+
  685. | vec_type **step** (float a, vec_type b) | ``b[i] < a ? 0.0 : 1.0`` |
  686. +------------------------------------------------------------------------+---------------------------------------------------------------+
  687. | vec_type **smoothstep** (vec_type a, vec_type b, vec_type c) | Hermite interpolate between ``a`` and ``b`` by ``c`` |
  688. +------------------------------------------------------------------------+---------------------------------------------------------------+
  689. | vec_type **smoothstep** (float a, float b, vec_type c) | Hermite interpolate between ``a`` and ``b`` by ``c`` |
  690. +------------------------------------------------------------------------+---------------------------------------------------------------+
  691. | bvec_type **isnan** (vec_type x) | Returns ``true`` if scalar or vector component is ``NaN`` |
  692. +------------------------------------------------------------------------+---------------------------------------------------------------+
  693. | bvec_type **isinf** (vec_type x) | Returns ``true`` if scalar or vector component is ``INF`` |
  694. +------------------------------------------------------------------------+---------------------------------------------------------------+
  695. | ivec_type **floatBitsToInt** (vec_type x) | Float->Int bit copying, no conversion |
  696. +------------------------------------------------------------------------+---------------------------------------------------------------+
  697. | uvec_type **floatBitsToUint** (vec_type x) | Float->UInt bit copying, no conversion |
  698. +------------------------------------------------------------------------+---------------------------------------------------------------+
  699. | vec_type **intBitsToFloat** (ivec_type x) | Int->Float bit copying, no conversion |
  700. +------------------------------------------------------------------------+---------------------------------------------------------------+
  701. | vec_type **uintBitsToFloat** (uvec_type x) | UInt->Float bit copying, no conversion |
  702. +------------------------------------------------------------------------+---------------------------------------------------------------+
  703. | float **length** (vec_type x) | Vector length |
  704. +------------------------------------------------------------------------+---------------------------------------------------------------+
  705. | float **distance** (vec_type a, vec_type b) | Distance between vectors i.e ``length(a - b)`` |
  706. +------------------------------------------------------------------------+---------------------------------------------------------------+
  707. | float **dot** (vec_type a, vec_type b) | Dot product |
  708. +------------------------------------------------------------------------+---------------------------------------------------------------+
  709. | vec3 **cross** (vec3 a, vec3 b) | Cross product |
  710. +------------------------------------------------------------------------+---------------------------------------------------------------+
  711. | vec_type **normalize** (vec_type x) | Normalize to unit length |
  712. +------------------------------------------------------------------------+---------------------------------------------------------------+
  713. | vec3 **reflect** (vec3 I, vec3 N) | Reflect |
  714. +------------------------------------------------------------------------+---------------------------------------------------------------+
  715. | vec3 **refract** (vec3 I, vec3 N, float eta) | Refract |
  716. +------------------------------------------------------------------------+---------------------------------------------------------------+
  717. | vec_type **faceforward** (vec_type N, vec_type I, vec_type Nref) | If ``dot(Nref, I)`` < 0, return N, otherwise –N |
  718. +------------------------------------------------------------------------+---------------------------------------------------------------+
  719. | mat_type **matrixCompMult** (mat_type x, mat_type y) | Matrix component multiplication |
  720. +------------------------------------------------------------------------+---------------------------------------------------------------+
  721. | mat_type **outerProduct** (vec_type column, vec_type row) | Matrix outer product |
  722. +------------------------------------------------------------------------+---------------------------------------------------------------+
  723. | mat_type **transpose** (mat_type m) | Transpose matrix |
  724. +------------------------------------------------------------------------+---------------------------------------------------------------+
  725. | float **determinant** (mat_type m) | Matrix determinant |
  726. +------------------------------------------------------------------------+---------------------------------------------------------------+
  727. | mat_type **inverse** (mat_type m) | Inverse matrix |
  728. +------------------------------------------------------------------------+---------------------------------------------------------------+
  729. | bvec_type **lessThan** (vec_type x, vec_type y) | Bool vector comparison on < int/uint/float vectors |
  730. +------------------------------------------------------------------------+---------------------------------------------------------------+
  731. | bvec_type **greaterThan** (vec_type x, vec_type y) | Bool vector comparison on > int/uint/float vectors |
  732. +------------------------------------------------------------------------+---------------------------------------------------------------+
  733. | bvec_type **lessThanEqual** (vec_type x, vec_type y) | Bool vector comparison on <= int/uint/float vectors |
  734. +------------------------------------------------------------------------+---------------------------------------------------------------+
  735. | bvec_type **greaterThanEqual** (vec_type x, vec_type y) | Bool vector comparison on >= int/uint/float vectors |
  736. +------------------------------------------------------------------------+---------------------------------------------------------------+
  737. | bvec_type **equal** (vec_type x, vec_type y) | Bool vector comparison on == int/uint/float vectors |
  738. +------------------------------------------------------------------------+---------------------------------------------------------------+
  739. | bvec_type **notEqual** (vec_type x, vec_type y) | Bool vector comparison on != int/uint/float vectors |
  740. +------------------------------------------------------------------------+---------------------------------------------------------------+
  741. | bool **any** (bvec_type x) | ``true`` if any component is ``true``, ``false`` otherwise |
  742. +------------------------------------------------------------------------+---------------------------------------------------------------+
  743. | bool **all** (bvec_type x) | ``true`` if all components are ``true``, ``false`` otherwise |
  744. +------------------------------------------------------------------------+---------------------------------------------------------------+
  745. | bvec_type **not** (bvec_type x) | Invert boolean vector |
  746. +------------------------------------------------------------------------+---------------------------------------------------------------+
  747. | ivec2 **textureSize** (sampler2D_type s, int lod) | Get the size of a 2D texture |
  748. +------------------------------------------------------------------------+---------------------------------------------------------------+
  749. | ivec3 **textureSize** (sampler2DArray_type s, int lod) | Get the size of a 2D texture array |
  750. +------------------------------------------------------------------------+---------------------------------------------------------------+
  751. | ivec3 **textureSize** (sampler3D s, int lod) | Get the size of a 3D texture |
  752. +------------------------------------------------------------------------+---------------------------------------------------------------+
  753. | ivec2 **textureSize** (samplerCube s, int lod) | Get the size of a cubemap texture |
  754. +------------------------------------------------------------------------+---------------------------------------------------------------+
  755. | vec4_type **texture** (sampler2D_type s, vec2 uv [, float bias]) | Perform a 2D texture read |
  756. +------------------------------------------------------------------------+---------------------------------------------------------------+
  757. | vec4_type **texture** (sampler2DArray_type s, vec3 uv [, float bias]) | Perform a 2D texture array read |
  758. +------------------------------------------------------------------------+---------------------------------------------------------------+
  759. | vec4_type **texture** (sampler3D_type s, vec3 uv [, float bias]) | Perform a 3D texture read |
  760. +------------------------------------------------------------------------+---------------------------------------------------------------+
  761. | vec4 **texture** (samplerCube s, vec3 uv [, float bias]) | Perform a cubemap texture read |
  762. +------------------------------------------------------------------------+---------------------------------------------------------------+
  763. | vec4_type **textureProj** (sampler2D_type s, vec3 uv [, float bias]) | Perform a 2D texture read with projection |
  764. +------------------------------------------------------------------------+---------------------------------------------------------------+
  765. | vec4_type **textureProj** (sampler2D_type s, vec4 uv [, float bias]) | Perform a 2D texture read with projection |
  766. +------------------------------------------------------------------------+---------------------------------------------------------------+
  767. | vec4_type **textureProj** (sampler3D_type s, vec4 uv [, float bias]) | Perform a 3D texture read with projection |
  768. +------------------------------------------------------------------------+---------------------------------------------------------------+
  769. | vec4_type **textureLod** (sampler2D_type s, vec2 uv, float lod) | Perform a 2D texture read at custom mipmap |
  770. +------------------------------------------------------------------------+---------------------------------------------------------------+
  771. | vec4_type **textureLod** (sampler2DArray_type s, vec3 uv, float lod) | Perform a 2D texture array read at custom mipmap |
  772. +------------------------------------------------------------------------+---------------------------------------------------------------+
  773. | vec4_type **textureLod** (sampler3D_type s, vec3 uv, float lod) | Perform a 3D texture read at custom mipmap |
  774. +------------------------------------------------------------------------+---------------------------------------------------------------+
  775. | vec4 **textureLod** (samplerCube s, vec3 uv, float lod) | Perform a 3D texture read at custom mipmap |
  776. +------------------------------------------------------------------------+---------------------------------------------------------------+
  777. | vec4_type **textureProjLod** (sampler2D_type s, vec3 uv, float lod) | Perform a 2D texture read with projection/LOD |
  778. +------------------------------------------------------------------------+---------------------------------------------------------------+
  779. | vec4_type **textureProjLod** (sampler2D_type s, vec4 uv, float lod) | Perform a 2D texture read with projection/LOD |
  780. +------------------------------------------------------------------------+---------------------------------------------------------------+
  781. | vec4_type **textureProjLod** (sampler3D_type s, vec4 uv, float lod) | Perform a 3D texture read with projection/LOD |
  782. +------------------------------------------------------------------------+---------------------------------------------------------------+
  783. | vec4_type **texelFetch** (sampler2D_type s, ivec2 uv, int lod) | Fetch a single texel using integer coordinates |
  784. +------------------------------------------------------------------------+---------------------------------------------------------------+
  785. | vec4_type **texelFetch** (sampler2DArray_type s, ivec3 uv, int lod) | Fetch a single texel using integer coordinates |
  786. +------------------------------------------------------------------------+---------------------------------------------------------------+
  787. | vec4_type **texelFetch** (sampler3D_type s, ivec3 uv, int lod) | Fetch a single texel using integer coordinates |
  788. +------------------------------------------------------------------------+---------------------------------------------------------------+
  789. | vec_type **dFdx** (vec_type p) | Derivative in ``x`` using local differencing |
  790. +------------------------------------------------------------------------+---------------------------------------------------------------+
  791. | vec_type **dFdy** (vec_type p) | Derivative in ``y`` using local differencing |
  792. +------------------------------------------------------------------------+---------------------------------------------------------------+
  793. | vec_type **fwidth** (vec_type p) | Sum of absolute derivative in ``x`` and ``y`` |
  794. +------------------------------------------------------------------------+---------------------------------------------------------------+