What is GLSL?

GLSL is called OpenGL Shading Language, which is used to write shader programs in OpenGL. The shader program written with GLSL is executed on the GPU (Graphic Processor Unit) of the graphics card, replacing part of the fixed rendering pipeline, so that different levels in the rendering pipeline have programmability. For example: view conversion, projection conversion, color blending and so on. GLSL (GL Shading Language) Shader code is divided into two parts: Vertex Shader, Fragment Shader, and sometimes Geometry Shader.

A preliminary study on GLSL grammar

identifier

Identifiers are programmer – defined variable names, function names, and so on. Variable names can consist of underscores, arrays, and letters. We can use underscores, arrays, and letters to define variable names, but there are a few things to note:

  1. You can’t start with a number
  2. Do not start with gl_,gl_ is a reserved prefix for GLSL internal variables, such as gl_Position, etc.
  3. In addition, keywords and some internal GLSL reserved names cannot be used as variable names

The data type

Only the following basic data types are supported in GLSL. Note that there are no characters, strings, and Pointers in GLSL compared to C.

Type

Meaning

void

for functions that do not return a value

bool

a conditional type, taking on values of true or false

int

a signed integer

float

a single floating-point scalar

vec2

a two component floating-point vector

vec3

a three component floating-point vector

vec4

a four component floating-point vector

bvec2

a two component Boolean vector

bvec3

a three component Boolean vector

bvec4

a four component Boolean vector

ivec2

a two component integer vector

ivec3

a three component integer vector

ivec4

a four component integer vector

mat2

A 2 x 2 floating – point matrix

mat3

A 3 x 3 floating – point matrix

mat4

A floating – point 4 * 4 matrix

mat2x2

same as a mat2

mat2x3

a floating-point matrix with 2 columns and 3 rows

mat2x4

a floating-point matrix with 2 columns and 4 rows

mat3x2

a floating-point matrix with 3 columns and 2 rows

mat3x3

same as a mat3

mat3x4

a floating-point matrix with 3 columns and 4 rows

mat4x2

a floating-point matrix with 4 columns and 2 rows

mat4x3

a floating-point matrix with 4 columns and 3 rows

mat4x4

same as a mat4

sampler1D

a handle for accessing a 1D texture

sampler2D

a handle for accessing a 2D texture

sampler3D

a handle for accessing a 3D texture

samplerCube

a handle for accessing a cube mapped texture

sampler1DShadow

a handle for accessing a 1D depth texture with comparison

sampler2DShadow

a handle for accessing a 2D depth texture with comparison

In addition to these basic data types, GLSL also supports structures, arrays and other composite data types composed of these types

You can use the struct keyword to aggregate defined data types together to form structures, for example:

struct light {
 float intensity;
 vec3 position;
} lightVar;Copy the code

Structs are used in the same way as C so there’s not much padding here; Array is the same as C, but GLSL does not support multi-dimensional arrays, that is, the elements of an array cannot be arrays.

Storage qualifier

The definition of a variable in GLSL can specify a storage qualifier in front of the type, for example:

Attribute VEC4 Position Uniform VEC3 color = VEC3 (0.7, 0.7, 0.2)Copy the code

Common storage qualifiers in GLSL are as follows:

qualifiers

You mean

< none: default >

By default, it can be omitted, in which case only one read/write permission is provided to memory on the relevant processor

const

Compile-time constants whose values must be initialized at declaration time, or read-only function arguments.

attribute

Connect vertex shaders to OpenGL for each vertex data. So attribute represents read-only vertex data and is only used in vertex shaders. The data comes from the current vertex state or vertex array. It must be declared globally, not inside a function. A variable modified by an attribute can be a scalar, vector, or matrix of floating-point type. Cannot be an array or structure

uniform

Unify variables. The value of a uniform variable is constant during the execution of the shader. Unlike const constants, this value is unknown at compile time and is initialized from outside the shader. Unity variables are shared between vertex shaders and fragment shaders. It can only be declared globally.

varying

Output from the vertex shader. Such as color or texture coordinates, as read-only input to the fragment shader. Must be a global variable declared by the global scope. It can be scalar, vector, matrix of floating-point type. Can’t be an array or structure.

centroid varying

In the absence of multiple samples, varying is the same as varying. In the case of multiple sampling, centorID VARYING is evaluated inside the rasterized graph rather than at a fixed position in the center of the fragment.

Function parameter qualifier

qualifiers

instructions

< none: default >

The in qualifier is used by default

in

The default qualifier for the parameter to the in function, which is passed in as a copy of the argument. In a function, modifying the in modifier does not affect the argument itself

out

Out is used to pass new values outside of the function. The argument passed in by out is write-only, like a “pit” that the function assigns to it. In a function, modifying the form of the out modifier affects the argument itself.

inout

Inout can be understood as a “pit” with a value, and can be read or written. In a function, modifying the shape of the inout modifier affects the argument itself.

Built-in variables

GLSL internally defines a number of variables with special meanings for developers to use, these variables are built-in variables, in the vertex shader has the following built-in variables:

The name of the

type

describe

gl_Color

vec4

Input property – Represents the dominant color of the vertex

gl_SecondaryColor

vec4

Input property – Represents the auxiliary color of the vertex

gl_Normal

vec3

Input property – represents the normal value of the vertex

gl_Vertex

vec4

Input property – Represents vertex positions in object space

gl_MultiTexCoordn

vec4

Input property – Represents the coordinates of the NTH texture of the vertex

gl_FogCoord

float

Input property – Represents the fog coordinates of the vertices

gl_Position

vec4

Output property – position of transformed vertices for subsequent fixed clipping operations. All vertex shaders must write this value.

gl_ClipVertex

vec4

Output coordinates for user clipping plane clipping

gl_PointSize

float

The size of the point

gl_FrontColor

vec4

Specifies the output of the main color of the front

gl_BackColor

vec4

Varying is output of the main color on the rear

gl_FrontSecondaryColor

vec4

Specifies the output of the auxiliary color of the front

gl_BackSecondaryColor

vec4

Specifies the output of the auxiliary color varying on the rear

gl_TexCoord[]

vec4

An array of texture coordinates varying output

gl_FogFragCoord

float

Specifies the output of the fog coordinate

Built-in variables in the slice shader:

The name of the

type

describe

gl_Color

vec4

Contains interpolation of primary colors, read only input

gl_SecondaryColor

vec4

Contains interpolation of auxiliary colors, read only input

gl_TexCoord[]

vec4

Contains an array of texture coordinates for interpolation, read only input

gl_FogFragCoord

float

Interpolation containing fog coordinates, read – only input

gl_FragCoord

vec4

Window x,y,z and 1/w, read only input

gl_FrontFacing

bool

Read-only input, true if it is part of a window icon

gl_PointCoord

vec2

The two-dimensional space coordinates of the Sprite range from (0.0, 0.0) to (1.0, 1.0) and are only used when the Sprite and the dot elements are on.

gl_FragData[]

vec4

An array of data output using glDrawBuffers. Cannot be used in combination with gl_FragColor.

gl_FragColor

vec4

The output color is used for subsequent pixel manipulation

gl_FragDepth

float

The depth of the output is used for subsequent pixel operations, and if this value is not written, the depth value of the fixed function pipeline is used instead

The operator

The operator

describe

(a)

Used for expression composition, function calls, construction

[]

Array subscript, vector or matrix selector

.

Member selection of structures and vectors

+ + –

The increment and decrement operator for a prefix or suffix

+ -!

Unary operator representing positive and negative logical non

* /

Multiplication and division operators

+ –

Binary operators represent addition and subtraction operations

<> <= >= =! =

Less than, greater than, less than or equal to, greater than or equal to, equal to, not equal to the identifier

&& | | ^ ^

Logic and, or, xOR

? :

Conditional judge

= += – = *= /=

The assignment operator

.

Said sequence

Note that the address fetch & dereference * operation does not exist in GLSL because GLSL cannot manipulate addresses directly. Type conversion operations are also not allowed. Operator (&, |, ^ ~, < <, > >, and & =, | =, ^ =, <, < =, > > =) are reserved GLSL operators, may be used in the future. The modulo operations (%, %=) are also reserved.

Struct and array operations

Struct fields and array lengths are passed through dots (.). Syntax, similar to C, the corresponding structure and array only the following operations are legal:

field or method selector

Equal to the judge

= =! =

The assignment

=

Index access [array only]

[]

It should be noted that both the equality judgment and the assignment operation must be of the same type and the size can only be carried out.

Vector and matrix operations

With very few exceptions, operations on vectors and matrices are usually equivalent to operations on their respective components. Such as:

vec3 u,v;
float f;
v = u + f;Copy the code

This code is equivalent to:

vec3 u,v;
float f;
v.x = u.x + f;
v.y = u.y + f;
v.z = u.z + f;Copy the code

Similarly, the code:

vec3 v, u, w;
w = v + u;Copy the code

Is equivalent to:

w.x = v.x + u.x;
w.y = v.y + u.y;
w.z = v.z + u.z;Copy the code

I’m not going to do much of anything else here, but you can refer to linear algebra or 3D math. Here is a brief description of access to vector components:

The individual components of a vector can be denoted by {x,y,z,w},{r,g,b,a} or {s,t,p,q}. These different notations are used for vertex coordinates, color components, texture coordinates. You cannot mix these notations in component access. Where the p in {s,t,p,q} replaces the r-coordinate of the texture because it is duplicated with the color R. Such as:

vec4 v4;
v4.rgba; // is a vec4 and the same as just using v4,
v4.rgb; // is a vec3,
v4.b; // is a float,
v4.xy; // is a vec2,
v4.xgba; // is illegal Copy the code

The order of components can be swapped or repeated: for example:

Vec4 pos = VEC4 (1.0, 2.0, 3.0, 4.0); vec4 swiz= pos.wzyx; // swiz = (4.0, 3.0, 2.0, 1.0) vec4 dUP = pos.xxyy; // dup = (1.0, 1.0, 2.0, 2.0)Copy the code

This expression can also be used on the left side of the expression, but it is not allowed to repeat:

Vec4 pos = VEC4 (1.0, 2.0, 3.0, 4.0); Pos. Xw = vec2 (5.0, 6.0); / / pos = (5.0, 2.0, 3.0, 6.0) pos. Wx = vec2 (7.0, 8.0); / / pos = (8.0, 2.0, 3.0, 7.0) pos. Xx = vec2 (3.0, 4.0); // illegal -'x'Used twice pos.xy = vec3(1.0, 2.0, 3.0); // illegal - mismatch between vec2 and vec3Copy the code

For arrays whose matrices can be treated as vectors, the components of the matrix can be accessed using array subscript syntax. Apply a single subscript to a matrix Treat the matrix as an array of column vectors and select a single column whose type is a vector of the same size as the matrix. The leftmost column is column 0. The second index then operates on the column vectors as defined previously for vectors. Thus, the two subscripts select a column and then a row of that column. Such as:

mat4 m; M [1] = vec4 (2.0); // set the second column to all 2.0m [0][0] = 1.0; // set the upper left element to 1.0 m[2][3] = 2.0; // set the 4th element of the third column to 2.0Copy the code

Process control

If (condition) : bool (bool); bool (bool); bool (bool); bool (bool);

vec4 color = unlitColor;
if (numLights > 0)
{
    color = litColor;
}else{
    color = unlitColor;
}Copy the code

Loop control: C language similar to support for, while, do-while three writing, you can use contine to jump out of the loop, break out of all loops.

Discard control: A special control flow in the slice shader is called discard. Using discard exits the slice shader, does not perform subsequent slice coloring operations, and does not write to the frame buffer.

function

There must be only one main function per shader. Functions in GLSL must be defined and declared globally. A function cannot be declared or defined in a function definition. The function must have a return type and the argument is optional. Parameter modifiers (in, out, inout, const, etc.) are optional.

Structs and arrays can also be used as arguments to functions. If an array is used as an argument to a function, its size must be specified. When calling a parameter, just pass the array name.

A few other points to note:

  • Function names can be overloaded by parameter types, but not by return type values;
  • All parameters must match exactly. Parameters are not automatic.
  • Functions cannot be called recursively;
  • The return value of a function cannot be an array

At the end of the article, we’ve just covered the basic syntax of GLSL, but that’s enough for iOS developers. If you want to learn more about GLSL, you can refer to the official documentation

Related articles:
  1. OpenGL first lesson — Name explanation
  2. OpenGL is introduced in lesson 2 – The common fixed storage shader

  3. OpenGL introduction third lesson — matrix transformation and coordinate system

  4. OpenGL entry lesson 4 — Depth

  5. OpenGL entry lesson 5 — front and back elimination

  6. OpenGL entry lesson 6 — Clipping and Blending

  7. OpenGL entry lesson 7 — Texture

  8. OpenGL is in class 8 — a supplementary case

  9. OpenGL ES que

  10. The application of GLKit

  11. GLSL met

  12. How to use custom shaders written in GLSL in iOS

  13. Precision qualifier in GLSL

  14. Use OpenGL to write a rotating stereo album for your girlfriend