Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ OpenGL Superb Learning Notes - GLSL language foundation     - Four IDS intrusion detection tool under Linux environment (Linux)

- GitLab issued Merge Request return error 500 when the two solutions log (Linux)

- Oracle11g CRS-0184 Problem Solving (Database)

- Depth understanding of the TCP protocol (Database)

- Btrfs file system creation and their characteristics in Linux (Linux)

- Use HttpClient remote interface testing (Programming)

- Sort sql MySQL 5.6 upgrade slow Cause Analysis (Database)

- Python 3.5 will support Async / Await Asynchronous Programming (Programming)

- Oracle table space usage monitoring (Database)

- Ubuntu 14.04 to install Blender 2.71 (Linux)

- How to upgrade to Oracle 11g Oracle 12c (Database)

- Live Wallpaper for Linux release adds dynamic background (Linux)

- Linux system security configuration (Linux)

- Sqoop data export import command (Database)

- Github inventory objects Algorithm (Linux)

- Based on Google Cloud Storage Mirroring open Maven Central Repository (Server)

- The easiest 11g Active DataGuard (ADG) to establish the configuration process (Database)

- CentOS 5.x install Lua 5.2.3 error (LIBS = -lncurses) (Linux)

- Windows 8.1 hard drive to install Ubuntu 14.04 dual system reference tutorials and multi-drive Precautions (Linux)

- PHP generates a random password several ways (Programming)

 
         
  OpenGL Superb Learning Notes - GLSL language foundation
     
  Add Date : 2017-08-31      
         
         
         
  Variable

GLSL's variable naming is similar to C's. Variable names can use letters, numbers, and underscores, but variable names can not start with numbers, and variable names can not be prefixed with gl_, which is reserved by GLSL for internal variables in GLSL. Of course, there are some GLSL reserved name is not the name of the variable.


basic type

In addition to Boolean, Integer, and Floating primitive types, GLSL also introduces some of the basic types that are commonly used in shaders. These primitive types can be used as types within the structure. As follows:

Type description
Void is similar to void in the C language and represents an empty type. As a function of the return type, said the function does not return value.
Bool Boolean type, which can be true and false, and boolean expressions.
Int Integer Represents signed integers that contain at least 16 bits. Can be a decimal, hexadecimal, octal.
Float float
Bvec2 contains two Boolean components of the vector
Bvec3 contains three Boolean components of the vector
Bvec4 contains four Boolean components of the vector
Ivec2 contains two vectors of integer components
Ivec3 contains three integer components of the vector
Ivec4 contains four integer components of the vector
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 the main sequence of the column)
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 is used to reference the handle of the specified 1D texture in a built-in texture function. Can only be used as a consistent variable or function parameters
Sampler2D 2D texture handle
Sampler3D 3D texture handle
SamplerCube cube map texture handle
Sampler1DShadow One-dimensional depth texture handle
Sampler2DShadow A 2D depth texture handle
Structure

Structure

Structures can be combined with primitive types and arrays to form user-defined types. In the definition of a structure at the same time, you can define an instance of the structure. Or later defined.

Struct surface {float indexOfRefraction;

Water flow;

} MySurface;

Surface secondeSurface;
You can either assign a value to a struct, or use ==,! = To determine if the two structures are equal.

MySurface = secondSurface;

MySurface == secondSurface;

Only the structure of each component are equal, then the two structures are equal. Access the internal members of the structure using.

Vec3 color = mySurface.color + secondSurface.color;

A structure contains at least one member. Fixed-size arrays can also be included in the structure. GLSL structures do not support nested definitions. Only pre-declared structures can be nested within them.

Struct myStruct {

  Vec3 points [3]; // Fixed-size arrays are legal

  Surface surf; / / Yes, has been defined before

  Struct velocity {// Illegal float speed;

    Vec3 direction;

  } Velo;

  SubSurface sub; / / illegal, no pre-statement;}; struct subSurface {int id;
};
 

Array

Only one-dimensional arrays can be used in GLSL. The type of array can be all basic types or structures. The following array declarations are legal:

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 parameter to the function or as a return value, or as a member of the structure. The array type has a built-in length () function that returns the length of the array.

LightPositions.length () // Returns the size of the array

Finally, you can not define an array of arrays.

Modifier

Variables can be declared using the following modifier.

Modifier Description
Const const value must be initialized in the declaration. It is read-only and can not be modified.
Attribute Represents the read-only vertex data, used only in the vertex shader. The data comes from the current vertex state or vertex array. It must be globally declared and can not be internal to the function. An attribute can be a scalar, vector, or matrix of the floating-point type. Can not be an array or structure
Uniform 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. Consistent variables are shared between vertex shaders and fragment shaders. It can also be declared globally only.
Varying vertex shader output. Such as color or texture coordinates, (interpolated data) as read-only input data for the fragment shader. The global variable must be a global scope declaration. It can be a scalar, vector, or matrix of floating point types. Can not be an array or structure.
Centorid varying In the absence of multisampling, it is the same as varying. In multisampling, centorid varying is evaluated inside rasterized graphics rather than at a fixed location in the center of the fragment.
The invariant is used to represent the output of the vertex shader and the input of any matched fragment shader, which must be consistent in different shaders. All the data flow and control flow, write an invariant variable is consistent. To ensure that the results are exactly the same, the compiler needs to discard potential optimizations that might lead to inconsistent values. Do not use this modifier unless necessary. Avoid using z-fighting in multichannel rendering.
In used in the function parameters, said this parameter is input, change in the function of this value does not affect the function of the call have side effects. (Equivalent to the value of C language), this is the function parameters default modifier
Out used in the function parameters, said the parameters are output parameters, the value is changed.
Inout used in the function parameters, said that this parameter is the input parameter is 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 for the vertex shader are shown in the following table:

Name Type Description
Gl_Color vec4 Input Property - Indicates the primary color of the vertex
Gl_SecondaryColor vec4 Input Property - A secondary color representing the vertex
Gl_Normal vec3 Input Property - Indicates the normal value of the vertex
Gl_Vertex vec4 Input Property - Indicates the vertex position of the object space
Gl_MultiTexCoordn vec4 Input Property - The coordinate of the nth texture representing the vertex
Gl_FogCoord float Input Property - Represents the fog coordinates of the vertex
Gl_Position vec4 Output attribute - the position of the transformed vertex for later clipping. All vertex shaders must write this value.
Gl_ClipVertex vec4 Output coordinates used for clipping the user's cutting planes
Gl_PointSize The size of the float point
Gl_FrontColor vec4 The dominant output of the dominant color
Gl_BackColor vec4 The dominant output on the back of the color
Gl_FrontSecondaryColor vec4 The dominant output of the auxiliary color
Gl_BackSecondaryColor vec4 The output of the auxiliary colors on the back of varying
Gl_TexCoord [] vec4 An array of texture coordinates for the varying output
Gl_FogFragCoord float The varying output of the fog coordinates
The following are the built-in variables for the fragment shader:

Name Type Description
Gl_Color vec4 Contains an interpolated read-only input of the primary color
Gl_SecondaryColor vec4 An interpolated read-only input containing auxiliary colors
Gl_TexCoord [] vec4 Interpolated read-only input that contains an array of texture coordinates
Gl_FogFragCoord float An interpolated, read-only input that contains fog coordinates
Gl_FragCoord vec4 Read-only input, x, y, z and 1 / w of the window
Gl_FrontFacing bool Read-only input, if the window is part of the front of the element, the value is true
Gl_PointCoord The vec2 point sprite has two-dimensional spatial coordinates in the range of (0.0, 0.0) to (1.0, 1.0) only for point primitives and point sprites on.
Gl_FragData [] vec4 An array of data output using glDrawBuffers. Can not be used in conjunction with gl_FragColor.
Gl_FragColor The color of the vec4 output for subsequent pixel operations
Gl_FragDepth The depth of the float output is used for subsequent pixel operations. If this value is not written, the depth value of the fixed function pipeline is used instead
 

expression


Operator

GLSL language operators and C language similar. As the following table (operator priority from high to low arrangement)

Operator description
() Used in combination of expressions, function calls, constructs
[] Arrays of subscripts, vectors, or matrices
Selection of structures and vectors
++ - The increment or decrement operator for prefixes or suffixes
+ -! Unary operator, positive and negative logic
* / Multiply and Divide Operators
+ - The binary operator indicates addition and subtraction
< > < = < ==! = = Less than, greater than, less than or equal to, greater than or equal to, equal to, not equal to the judge
&& || ^^ Logical AND, OR, XOR
?: Conditional Judge
= + = - = * = / = Assignment operator
, Indicating the sequence
The & quot; * & quot; operator of the & quot; address & quot; does not appear in the GLSL because the GLSL can not directly address the address. Type conversion operations are also not allowed. The bitwise operators (&, |, ^, < < , >> >>, & =, | =, ^ =, < < =, >> =) are reserved by GLSL and may be used in the future. Also the modulo operation (%,% =) is reserved.

Array access

The index of the array starts at zero. A reasonable range is [0, size - 1]. Like the C language. If the array access is out of range, the behavior is undefined. If the shader compiler knows at compile time that the array access is out of bounds, it will prompt the compilation to fail.

Vec4 myColor, ambient, diffuse [6], specular [6];

MyColor = ambient + diffuse [4] + specular [4];

Constructor

The constructor can be used to initialize variables that contain multiple members, including arrays and structures. Constructors can also be used in expressions. 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);

You can also use a mixture of scalar and vector to construct, 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 an x value of 2.5, the y value is discarded

For matrices, the matrix in OpenGL is the column master order. If only one value is passed, it is constructed as a diagonal matrix, with the remaining elements being 0.

Mat3 m3 = mat3 (1.0);

Structure of the matrix:

1.0 0.0 0.0

0.0 1.0 0.0

0.0 0.0 1.0

Mat2 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)); // will take the 2x2 matrix in the upper-left corner of the 4x4 matrix.

Constructors can be used to convert scalar data types. GLSL does not support implicit or display conversions, only through constructors. Which int to float value is the same. Float to int then the fractional part is discarded. Int or float to bool, 0 and 0.0 to false, and the rest to true. Bool to int or float, false to 0 and 0.0, true to 1 and 1.0.

Float f = 1.7;

Int I = int (f); // I = 1

Array initialization, you can pass in the constructor function to initialize the value of the corresponding array of each value.

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 structure. One order and type to be one to one correspondence.

Struct surface {int index;
  Vec3 color;
};

Surface mySurface = surface (3, vec3 (red, green, blue), 0.5);
 

Component selection

The individual components in the vector can be represented by the notation of {x, y, z, w}, {r, g, b, a} or {s, t, p, q}. These different notations are used for vertex, color, texture coordinates. In composition selection, you can not mix these notations. Where p in {s, t, p, q} replaces the r-coordinate of the texture because it is repeated with the color r. Here is an example:

Float myY = myVec.yz; float myQ = myVec.q; // error, the array cross-border access, q represents the fourth element float myRY = myVec = {myVec.q; // Illegal, mixed use notation
For more specific uses, you can repeat the elements in the vector, or reverse the order. Such as:

Vec3 yxz = myVec.yxz; / / swap order vec4 mySSTT = myVec.sstt; / / repeat the value
In the assignment is, you can choose the order you want, but can not repeat the composition.

Vec4 myColor = {0.0, 1.0, 2.0, 1.0};
MyColor.x = -1.0;
MyColor.yz = vec2 (3.0, 5.0);
MyColor.wx = vec2 (1.0, 3.0);
MyColor.zz = vec2 (2.0, 3.0); // Illegal
We can also use subscripts to access elements in vectors or matrices. If the cross-border behavior will be undefined.

Float myY = myVec [1];

In a matrix, the column vector can be obtained by a one-dimensional index (the OpenGL matrix is the column master). Two-dimensional small scalar to get the elements in the vector.

Mat3 myMat = mat3 (1.0);
Vec3 myVec = myMat [0]; // get the first column vector 1.0, 0.0, 0.0 float f = myMat [0] [0]; // first vector in the first column.
 

Control flow


cycle

Similar to C and C ++, the GLSL language also provides a loop for for, while, do / while. Use continue to jump to the next iteration, break to end the loop.

For (l = 0; l < numLights; l ++)
{If (! LightExists [l]) continue;
    Color + = light [l];
} While (i < num)
{
    Sum + = color [i];
    I ++;
} Do {
    Color + = light [lightNum];
    LightNum--;
} While (lightNum> 0)
 

If / else

Color = unlitColor; if (numLights> 0)
{
    Color = litColor;
} Else {
    Color = unlitColor;
}}
 

Discard

There is a special kind of control flow in the fragment shader. Use discard to exit the fragment shader and not perform subsequent fragment shading operations. Fragments are 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 argument in the main function is optional, but is required when the return value is void.

Void main (void)
{
 ...
}}
Functions in GLSL must be defined and declared globally. You can not declare or define functions in a function definition. The function must have a return type and the parameter is optional. The parameter modifier (in, out, inout, const, etc.) is optional.

// function declaration bool isAnyNegative (const vec4 v); // function call void main (void)
{Bool isNegative = isAnyNegative (gl_Color);
    ...
} // Define bool isAnyNegative (const vec4 v)
{If (v.x < 0.0 || v.y < 0.0 || v .z < 0.0 || v.w < 0.0) return true; elsereturn false;
}}
Structures and arrays can also be used as arguments to functions. If an array is an argument to a function, it must be sized. In the call Senate, only the array name on it.

Vec4 sumVectors (int sumSize, vec4 v [10]); void main ()
{
    Vec4 myColors [10];
    ...
    Vec4 sumColor = sumVectors (5, myColors);
}}

Vec4 sumVectors (int sumSize, vec4 v [10])
{Int i = 0;
    Vec4 sum = vec4 (0.0); for (; i < sumSize; ++ i)
    {
        Sum + = v [i];
    } Return sum;
}}
The GLSL functions support overloading. Function can be the same name, but its parameter type or number of parameters can be different.

Float sum (float a, float b)
{Return a + b;
}}

Vec3 sum (vec3 v1, vec3 v2)
{Return v1 + v2;
}}
Function recursion in GLSL is not allowed. Its behavior is undefined.
     
         
         
         
  More:      
 
- About Git (Linux)
- Netapp storage routine inspections and information gathering (Linux)
- C language print various graphic (Programming)
- Chrome plug-in management, online-offline installation, part of the plug presentations (Linux)
- Ten correct use Redis skills (Database)
- Android studio multi-channel ultra-compact version of the package (Programming)
- Use ldap implement Windows Remote Desktop Ubuntu Linux (Linux)
- Oracle table compression Technology Introduction (Database)
- The development environment to build Nodejs under Ubuntu 14.04 (Linux)
- Android application simulates the phone keypad (Programming)
- Story timestamp and time zones: daily programmer (Programming)
- Create a custom pixel format based on an existing image data BufferedImage (Programming)
- 64-bit Windows Server 2012 R2 install Oracle 10g Second Edition (Database)
- Programmers Do not neglect debugging techniques (Programming)
- Cacti monitoring service Nginx (Linux)
- Installed in the desktop version of Ubuntu Unity Tweak Tool (Linux)
- About AWR More Description (Database)
- Create Your Own Docker base image in two ways (Linux)
- Linux user directory (Linux)
- Large computer network security policy Experience (Linux)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.