"Reprint" OpenGL Super Treasure Note--GLSL Language Foundation

Source: Internet
Author: User
Tags bitwise operators scalar

Variable

The GLSL variable is named in the same way as the C language. The names of variables can use letters, numbers, and underscores, but variable names cannot start with numbers, and variable names cannot be prefixed with gl_, which is the GLSL reserved prefix for GLSL internal variables. Of course, there are some GLSL reserved names that cannot be used as variable names.

Basic type

In addition to Boolean, Integer, and floating-point basic types, GLSL also introduces some types that are commonly used in shaders as basic types. These basic types can be used as types within the structure body. As the following table:

Type Describe
void Similar to void in C, which represents an empty type. As the return type of the function, it indicates that the function does not return a value.
bool Boolean type, which can be true and false, and an expression that can produce a Boolean type.
Int An integral type represents a signed integer that contains at least 16 bits. can be decimal, hexadecimal, octal.
Float Floating point Type
Bvec2 Vector with 2 Boolean components
Bvec3 Vector with 3 Boolean components
Bvec4 Vector with 4 Boolean components
Ivec2 Vector with 2 integral components
Ivec3 Vector with 3 integral components
Ivec4 Vector with 4 integral components
Mat2 or mat2x2 2x2 floating-point matrix type
MAT3 or mat3x3 3x3 floating-point matrix type
mat4x4 4x4 floating-point matrix
Mat2x3 2-Column 3-row floating-point matrix (OpenGL matrix is column Master order)
mat2x4 2 column 4-row floating-point matrix
mat3x2 3 column 2-row floating-point matrix
mat3x4 3 column 4-row floating-point matrix
mat4x2 4 column 2-row floating-point matrix
Mat4x3 4 column 3-row floating-point matrix
sampler1d A handle to the specified 1D texture referenced in the built-in texture function. Can only be used as a consistent variable or function parameter
Sampler2d Two-dimensional texture handle
Sampler3d Three-dimensional texture handle
Samplercube Cube map Texture Handle
Sampler1dshadow One-dimensional depth texture handle
Sampler2dshadow Two-dimensional depth texture handle

Structural body

Structural body

Structs can combine basic types and arrays to form user-defined types. While defining a struct, you can define an instance of the struct body. or a later definition.

struct Surface {
float indexofrefraction; VEC3 color; float turbulence;} Mysurface;surface Secondesurface;

  

You can assign a value to a struct by = or use ==,!= to determine whether the two structures are equal.

Mysurface = Secondsurface;

Mysurface = = Secondsurface;

The two structures are equal only if each component in the struct is equal. Access to the internal members of the struct body is used. To access.

VEC3 color = Mysurface.color + Secondsurface.color;

A struct contains at least one member. Fixed-size arrays can also be included in structs. Nested definitions are not supported for GLSL structures. Only pre-declared structures can be nested within them.

struct MyStruct {    vec3 points[3];//fixed-size arrays are legitimate    surface surf;  Yes, the    struct velocity {  //illegal float speed has been defined before;    VEC3 direction;  } Velo;  Subsurface sub; unlawful, without prior notice;};struct subsurface {  int id;};
Array

Only one-dimensional arrays can be used in GLSL. The type of an array can be any basic type or struct. The following types of array declarations are valid:

Surface mysurfaces[];vec4 lightpositions[8];vec4 lightpos[] = lightpositions;const int numsurfaces = 5;surface MYFIVESURFACES[NUMSURFACES];FLOAT[5] values;

An array that specifies the size of the display can be used as a function parameter or as a return value, or as a member of a struct. The array type has a length () function built in, which returns the lengths of the arrays.

Lightpositions.length ()//Returns the size of the array 8

Finally, you cannot define an array of arrays.

Modifier

The declaration of a variable can use the following modifier.

Modifier Describe
Const The constant value must be initialized in the declaration. It is read-only and cannot be modified.
Attribute Represents read-only vertex data and is used only in the vertex shader. The data is from the current vertex state or array of vertices. It must be declared in the global scope and cannot be inside the function. A attribute can be a scalar, vector, or matrix of a floating-point type. Can not be an array or struct body
Uniform A consistent variable. The value of the consistent variable is constant during shader execution. Unlike const constants, this value is unknown at compile time and is initialized externally by the shader. A consistent variable is shared between the vertex shader and the fragment shader. It can also be declared only at the global scope.
Varying The output of the vertex shader. For example, color or texture coordinates, (interpolated data) as read-only input data for the fragment shader. Must be a global variable declared by the global scope. Can be a scalar, vector, or matrix of floating-point number types. cannot be an array or struct.
Centorid varying In the absence of multiple sampling, the same is true with varying. In multi-sampling, the centorid varying is evaluated inside the rasterized graph rather than at a fixed position in the center of the fragment.
Invariant (invariants) is used to represent the output of a vertex shader and any input that matches a fragment shader, and the resulting values must be consistent in different shaders. All data flows and control flows are written to a invariant variable that is consistent. To ensure that the results are consistent, the compiler needs to discard potential optimizations that could lead to inconsistent values. Do not use this modifier unless necessary. Avoid z-fighting that may be used in multichannel rendering.
Inch It is used in the parameters of the function to indicate that the parameter is input, and changing the value in the function does not affect the side effect of the called function. (equivalent to the value of the C language), which is the default modifier for the function parameter
Out Used in the parameters of the function, indicating that the parameter is an output parameter, the value is changed.
InOut The parameter that is used in the function indicates that the input parameter is also the output parameter.
Built-in variables

Built-in variables can interact with fixed function functions. No declaration is required before use. The built-in variables available to the vertex shader are the following table:

Name Type Describe
Gl_color Vec4 Input attribute-represents the main color of the vertex
Gl_secondarycolor Vec4 Input Properties-Represents the secondary color of a vertex
Gl_normal Vec3 Input attribute-represents the normal value of a vertex
Gl_vertex Vec4 Input attribute-represents the vertex position of the object space
Gl_multitexcoordn Vec4 Input attribute-The coordinates of the nth texture representing the vertex
Gl_fogcoord Float Input Properties-Represents the fog coordinates of a vertex
Gl_position Vec4 Output properties-The position of the transformed vertex, used for subsequent fixed cropping operations. All vertex shaders must write this value.
Gl_clipvertex Vec4 Output coordinates for clipping of the user clipping plane
Gl_pointsize Float The size of the point
Gl_frontcolor Vec4 Varying output of the main color of the front
Gl_backcolor Vec4 Varying output of the main color on the back
Gl_frontsecondarycolor Vec4 Varying output of the positive auxiliary color
Gl_backsecondarycolor Vec4 Varying output of auxiliary colors on the back
Gl_texcoord[] Vec4 Array of texture coordinates varying output
Gl_fogfragcoord Float Varying output of fog coordinates

The built-in variables for the fragment shader are in the following table:

Name Type Describe
Gl_color Vec4 Interpolated read-only input with primary color
Gl_secondarycolor Vec4 Interpolated read-only input with secondary colors
Gl_texcoord[] Vec4 Interpolated read-only input containing an array of texture coordinates
Gl_fogfragcoord Float Interpolated read-only input with fog coordinates
Gl_fragcoord Vec4 Read-only input, x, Y, Z, and 1/w of Windows
Gl_frontfacing bool Read-only input, which is true if it is part of a window's front-side entity
Gl_pointcoord Vec2 The point Elf's two-dimensional space coordinates range from (0.0, 0.0) to (1.0, 1.0), only for point entities and point sprites.
Gl_fragdata[] Vec4 An array of data that is output using gldrawbuffers. cannot be used in conjunction with Gl_fragcolor.
Gl_fragcolor Vec4 The color of the output is used for subsequent pixel operations
Gl_fragdepth Float The depth of the output is used for subsequent pixel operations, and if the value is not written, the depth value of the fixed-function pipeline is used instead
An expression operator

The GLSL language operator is similar to the C language. The following table (the precedence of the operators is ranked from highest to lowest)

Operator Describe
() Used for expression combinations, function calls, construction
[] Array subscript, vector, or matrix selector
. Member selection for structs and vectors
++ -- Self-increment decrement operator for prefix or suffix
+–! unary operators, which represent positive and negative logic non-
* / Multiplication operator
+ - Binary operators represent add and subtract operations
<> <= >= = = =! Less than, greater than, equal to, greater than or equal to, not equal to the judge
&& | | ^^ Logical AND, OR, XOR
?: Conditional-Judging character
= +=–= *=/= Assignment operator
, Represents a sequence

The * operator, like the & and GLSL of the address, is no longer present in the GLSL because the address cannot be manipulated directly. Type conversion operations are also not allowed. Bitwise operators (&,|,^,~, <<, >>, &=, |=, ^=, <<=, >>=) are GLSL reserved operators that may be used in the future. Also, the modulo operation (%,%=) is also reserved.

Array access

The subscript of the array starts with 0. The reasonable range is [0, size-1]. Same as C language. If the array access is out of bounds, the behavior is undefined. If the shader compiler knows that the array access is out of bounds at compile time, the compiler will be prompted to fail.

Vec4 MyColor, Ambient, diffuse[6], Specular[6];mycolor = ambient + diffuse[4] + specular[4];
constructor function

Constructors can be used to initialize variables that contain multiple members, including arrays and struct bodies. Constructors can also be used in an expression. The method is called as follows:

VEC3 Mynormal = VEC3 (1.0, 1.0, 1.0); greentint = MyColor + vec3 (0.0, 1.0, 0.0); IVEC4 MyColor = IVEC4 (255);

It can also be constructed using a mixture of scalar and vector, as long as your element is sufficient to fill the vector.

VEC4 color = VEC4 (1.0, VEC2 (0.0, 1.0), 1.0), vec3 v = VEC3 (1.0, 10.0, 1.0); VEC3 v1 = VEC3 (v); VEC2 FV = VEC2 (5.0, 6.0); float f = float (FV); Constructed with x value 2.5, the Y value is discarded

For matrices, the matrix in OpenGL is the column master order. If only one value is passed, the diagonal matrix is created, and the remaining elements are 0.

MAT3 m3 = MAT3 (1.0);

Constructed matrix:

1.0 0.0 0.00.0 1.0 0.00.0 0.0 1.0MAT2 matrix1= MAT2 (1.0,0.0,0.0,1.0); Mat2 matrix2= Mat2 (VEC2 (1.0,0.0), VEC2 (0.0,1.0)); Mat2 matrix3= MAT2 (1.0); MAT2 matrix4= Mat2 (MAT4 (2.0));//the 2x2 matrix in the upper-left corner of the 4x4 matrix is taken. 

Constructors can be used for conversion of scalar data types. GLSL does not support implicit or explicit conversions, only through constructors. where int to float value is the same. float to int the fractional part is discarded. int or float to bool,0 and 0.0 to false, and the remaining values to true. BOOL converted to int or float,false values to 0 and 0.0,true to 1 and 1.0.

floatf =1.7;intI =int(f);//I = 1///array initialization, you can pass in the constructor the value to initialize each of the corresponding values in the array. IVEC2 position[3] = ivec2[3]((0,0), (1,1), (2,2)); IVEC2 pos2[3] = ivec2[] ((3,3), (2,1), (3,1) );//The constructor can also initialize the struct body. Where the order and type should correspond. structSurface {intindex;  VEC3 color; floatrotate;}; Surface Mysurface= Surface (3, VEC3 (red, green, blue),0.5);

Ingredient selection

The individual components of a vector can be represented by notation of {X,y,z,w},{r,g,b,a} or {s,t,p,q}. These different notation is used for vertex, color, and texture coordinates. In the composition selection, you can not mix these notation. where P in {S,T,P,Q} replaces the R coordinate of the texture, because it repeats with color R. Here are some examples of usage:

Vec3 Myvec = {0.50.350.7}; float r = MYVEC.R; float myyz = Myvec.yz; float MyQ = myvec.q; // error, array out-of-bounds access, q represents the fourth element float // illegal, mixed use notation

In a more specific way, you can repeat the elements in the vector, or reverse their order. Such as:

// Order of Exchange // repeat the values

In the assignment, you can also choose the order you want, but you can't repeat the ingredients.

Vec4 MyColor = {0.01.02.01.0=-1.0= VEC2 (3.0  5.0 = VEC2 (1.0 3.0 = VEC2 (2.0 3.0   Not legal

We can also access the elements in a vector or matrix by using subscripts. If the bounds of that behavior will be undefined.

float MyY = myvec[1];

In the matrix, the vector of the column can be obtained by a one-dimensional subscript (The matrix of OpenGL is the column Master order). Two-dimensional small mark to get the elements in the vector.

MAT3 Mymat = MAT3 (1.0= mymat[0// get first column Vector 1.0, 0.0, 0.0float f = mymat[0] [0// first vector of column one. 
Control Flow Loops

Similar to C and C + +, the GLSL language also provides a looping way for, while, Do/while. Use continue to jump into the next loop and break to end the loop.

 for 0; L < numlights; l++) {   if (!  LIGHTEXISTS[L])            continue;     + = light[l];}  while (I < num) {    + = Color[i];    I+ +;}  Do {    + = Light[lightnum];    Lightnum--;}  while 0)

If/else
color = Unlitcolor; if 0 ) {    = litcolor;} Else {    = unlitcolor;}
Discard

There is a special control flow in the fragment shader that becomes discard. Using discard exits the fragment shader and does not perform subsequent fragment shading operations. The fragment is also not written to the frame buffer.

if (Color.a < 0.9)

Discard

Function

There must be a main function in each shader. The void parameter in the main function is optional, but the return value is required when void.

void Main (void) {...}

The functions in GLSL must be defined and declared at the global scope. Functions cannot be declared or defined in a function definition. The function must have a return type, and the parameter is optional. The modifiers (in, out, inout, const, and so on) of the parameters are optional.

//function DeclarationBOOLIsanynegative (ConstVec4 v);//function CallvoidMainvoid){      BOOLIsnegative =isanynegative (Gl_color); ...}//definitionBOOLIsanynegative (ConstVEC4 v) {      if(V.x <0.0|| V.y <0.0|| V.z <0.0|| V.W <0.0)         return true; Else        return false;}

Structs and arrays can also be used as arguments to functions. If an array is an argument to a function, its size must be set. When you call a parameter, only the array name is passed.

VEC4 Sumvectors (intSumsize, Vec4 v[Ten]);voidMain () {VEC4 mycolors[Ten]; ... vec4 Sumcolor= Sumvectors (5, mycolors);} VEC4 Sumvectors (intSumsize, Vec4 v[Ten]){    inti =0; VEC4 sum= VEC4 (0.0);  for(; i < sumsize; + +)i) {sum+=V[i]; }    returnsum;}

The function of GLSL is to support overloading. A function can have the same name but has a different parameter type or number of arguments.

float sum (floatfloat  b) {    return a + b;} VEC3 sum (VEC3 v1, VEC3 v2) {    return v1 + v2;}

The recursive function in GLSL is not allowed. Its behavior is undefined.

GLSL provides a number of built-in functions to facilitate our use. The relevant functions can be found in the official manual http://www.opengl.org/sdk/docs/man/

GLSL Guide Http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf

"Reprint" OpenGL Super Treasure Note--GLSL Language Foundation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.