Real-rime rendering (2)-transformation and matrix (translation and Matrics)

Source: Internet
Author: User
Tags in degrees
Document directory
  • Translation Transformation
  • Rotating matrix rotating
  • Scaling and Scaling
  • Shear transformation shearing
  • Cascade transformation concatenation of transforms
  • Euler Transform
  • Model matrix, view matrix and projection matrix the model, view and projection Matrices
Abstract

In Graphics computing, such as rotation, scaling, translation, and projection operations, matrices play an extremely important role and are the basic tools for operating elements. Although many graphic APIs have encapsulated these matrix operations, it is very helpful to understand the principles of these matrix operations. For example, we can use some rapid matrix computing to accelerate your code.

If you have some basis for linear algebra, it will not be easy to read the following content, because it is a little difficult and boring. If you have not taken this course, we 'd better take a look at this book on linear algebra, because these things are the foundation and very important.

Homogeneous notation)

A point in a space corresponds to a space position, and a vector corresponds to a direction. Both of them can be expressed by a three-dimensional vector v = (VX, Vy, VZ.

If the two are used for transformation (such as rotation and scaling), a 3*3 matrix can be used, but it is not applicable to translation transformation because location transformation is meaningless to vectors, it makes sense for vertices.

The Qi record method is used to solve this problem.

In the record method, the space point is recordedP= (PX, Py, PZ, PW), PW = 1.

The space vector is recordedV= (VX, Vy, VZ, VW), where vw = 0.

When PW appears! = 0 and PW! When the value is 1, the coordinates must be homogeneous. The method is divided by PW and recorded as (PX/PW, Py/PW, PZ/PW, 1 ).

The transformation matrix of the homogeneous record method is as follows:

Given a moving Transformation Matrix

For a vectorV= (VX, Vy, VZ, VW) andTAfter multiplication, the values remain unchanged.

For a vertexP= (PX, Py, PZ, PW) andTAfter multiplication, the result is (PX + Tx, Py + ty, PZ + tz, 1 ).

Basic Transformation

Basic transformations include translation, rotation, scaling, shear, reflection, projection, etc.

Translation Transformation

As mentioned above, the translation matrix is represented by T:

TX, Ty, and TZ indicate the distance to move to X, Y, and Z respectively,

Note that offine Tranform Matrics does not work for spatial vectors.

Its Inverse Moment indicates moving in the opposite direction.

Rotating matrix rotating

Rotation change refers to the rotation angle around an axis. The rotation matrix around X, Y, and Z can be recorded:

Inverse array, which indicates the rotation of the same angle around the same axis in the opposite direction.

The determine factor of the rotation matrix is 1 because it is an orthogonal matrix.

When a graph (or object) rotates around a certain point of its own, the actual process is to first move the object to the position where the rotation point and the coordinate origin coincide, and then rotate the graph around the origin, then, perform the translation transformation to the original position.

The entire matrix calculation process is

Scaling and Scaling

Zoom is to zoom in and out, and its matrix is represented

If SX = Sy = SZ, it is called the proportional Transformation (Uniform), otherwise it is not (nonuniform ).

Its Inverse array indicates scaling in the opposite way.

If one of SX, Sy, and Sz is a negative number, the matrix is the reflection matrix. If two factors are-1, the image is rotated. Reflection matrices usually need special treatment. For example, for a triangle, after reflection transformation, the order of vertices may change, which will affect the face's normal, algorithms such as illumination and backend hiding will be affected. It can be determined by calculating the value of the 3*3 matrix in the upper left corner. If the value of the determinant is negative, it is the reflection matrix.

Shear transformation shearing

Shear transformation can be used in games to produce the effect of image jitter during an explosion. There are six types:

The first subscript represents the coordinate axis to be changed, and the second subscript represents the transformation along that coordinate axis. The related matrix can also be obtained from this: The first subscript determines the row, and the second determines the column, there are:

The effect is as follows:

Its Inverse array:

Cascade transformation concatenation of transforms

Since matrix multiplication has no exchange rate, the order of matrix multiplication is very important, such as S (2, 0.5, 1) and, depending on the order in which they are executed, the results are also different.

Another advantage of integrating multiple matrices is to improve efficiency. In general order, TRS is used.

Euler Transform

Euler's transformation can rotate an object to any direction. An Euler's transformation can be divided into three parts: H (EAD), P (ICH), R (oll), and recorded as E (H, p, R ).

In fact, it is the cascade matrix of three rotating matrices: because they are symmetric arrays, their inverse arrays =.

Gimbal lock is a tough problem when you use Euler's transform. You can watch this video-YouTube
Video explaining gimbal lock

Another problem that may occur is the interpolation problem between two orah angles.

To avoid Halloween locks, you can set the rotation sequence of the rotation axis.

Another method is to use tuples.

Model matrix, view matrix and projection matrix the model, view and projection Matrices

A model consists of a series of vertices. The coordinates of a vertex are defined relative to the center of the model. If the coordinate value of a vertex is (, 0 ), this means that the vertex is in the middle of the model.

Now, if the world coordinates are on the left side of the model, the left side of the model corresponds to the world coordinates multiplied by a translation matrix, which is the model matrix ).

When people operate this model, they need to perform some transformations, and they need to move each of their fixed points to the origin.

Move the model to the origin using the Black Arrow.

This transformation matrix isModel Matrix).

This process can be described as follows:

Next is view matrix ).

When you stand in front of a mountain and want to observe it from various angles, you can choose to go to different positions or move the whole mountain. This does not seem to work in real life, but it is feasible in graphics.

Now there is only one model in the world. When we need to observe this object, we need a camera to observe it. Assuming that the camera is initialized at the origin and moved through a translation matrix,

glm::mat4 ViewMatrix = glm::translate(Tx, Ty ,Tz);

This matrix is the view matrix, which corresponds to the conversion matrix of the world's moving far points to the camera. The process can be described.

Here is a magic lookat function in GLM ~ Super powerful view Matrics generation

glm::mat4 CameraMatrix = glm::LookAt(    cameraPosition, // the position of your camera, in world space    cameraTarget,   // where you want to look at, in world space    upVector        // probably glm::vec3(0,1,0), but (0,-1,0) would make you looking upside-down, which can be great too);

The entire stage is described as follows:

Next, projection matrices (projection matrix)

After the previous transformation of model matriix and view matrix, the current camera space is located, which means that the points on () will appear at the center of the screen, however, it is not two coordinates that determine whether the vertex is displayed. We cannot ignore the Z coordinate, that is, the distance between the vertex and the camera.

In Perspective Projection, based on the coordinate value of the vertex, when the VX and Vy values are the same, the larger the value of VZ, the more the vertex is in the middle. For details, see.

A 4*4 matrix can be used to describe projection:

glm::mat4 projectionMatrix = glm::perspective(    FoV,         // The horizontal Field of View, in degrees : the amount of "zoom". Think "camera lens". Usually between 90° (extra wide) and 30° (quite zoomed in)    4.0f / 3.0f, // Aspect Ratio. Depends on the size of your window. Notice that 4/3 == 800/600 == 1280/960, sounds familiar ?    0.1f,        // Near clipping plane. Keep as big as possible, or you'll get precision issues.    100.0f       // Far clipping plane. Keep as little as possible.);

Through projection matrix transformation, the model is changed from camera coordinate to homogeneous coordinate. The process is described as follows:

Glsl MVP

We know that OpenGL comes with some interface functions that can easily define the view and projection matrix. However, if glsl is used, the positions of all vertices are from *. vert code to determine, next we will practice the model, view, projection just learned.

First, there are two simple shader:

Basic. Vert

#version 400layout(location = 0) in vec3 vertexPosition_modelspace;// Values that stay constant for the whole mesh.uniform mat4 MVP;void main(){// Output position of the vertex, in clip space : MVP * positiongl_Position =   MVP * vec4(vertexPosition_modelspace,1);}

The model coordinate is multiplied by the MVP matrix.

Basic. Frag

#version 400// Ouput dataout vec3 color;void main(){// Output color = red color = vec3(1,0,0);}

Then initialize shader, VAO

void CGL::compileShader(){static const GLfloat g_vertex_buffer_data[] = {-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f,  1.0f, 0.0f,};static const GLushort g_element_buffer_data[] = { 0, 1, 2 };GLuint vertexbuffer;glGenBuffers(1, &vertexbuffer);glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);    glEnableVertexAttribArray(0);    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);    glVertexAttribPointer(0,                  // attribute. No particular reason for 0, but must match the layout in the shader.3,                  // sizeGL_FLOAT,           // typeGL_FALSE,           // normalized?0,                  // stride(void*)0            // array buffer offset    );    if( ! prog.compileShaderFromFile("shader/basic.vert",GLSLShader::VERTEX) )    {        printf("Vertex shader failed to compile!\n%s",               prog.log().c_str());        exit(1);    }    if( ! prog.compileShaderFromFile("shader/basic.frag",GLSLShader::FRAGMENT))    {        printf("Fragment shader failed to compile!\n%s",               prog.log().c_str());        exit(1);    }    if( ! prog.link() )    {        printf("Shader program failed to link!\n%s",               prog.log().c_str());        exit(1);    }    if( ! prog.validate() )    {        printf("Program failed to validate!\n%s",               prog.log().c_str());        exit(1);    }    prog.use();}

Then initialize the uniform variable:

void CGL::setUniform(){// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units    glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);    // Camera matrixglm::mat4 View       = glm::lookAt(glm::vec3(3,3,3), // Camera is at (4,3,3), in World Spaceglm::vec3(0,0,0), // and looks at the originglm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)   );// Model matrix : an identity matrix (model will be at the origin)glm::mat4 Model      = glm::mat4(1.0f);// Our ModelViewProjection : multiplication of our 3 matricesglm::mat4 MVP        = Projection * View * Model; // Remember, matrix multiplication is the other way around    prog.setUniform("MVP",MVP);    prog.setUniform("modelMatrics",Model);}

Rendering:

Reference

Wiki. Transformation Matrix-http://zh.wikipedia.org/wiki/%E5%8F%98%E6%8D%A2%E7%9F%A9%E9%98%B5#.E4.BB.BF.E5.B0.84.E5.8F.98.E6.8D.A2

The matrix and quaternions FAQ-http://www.cs.princeton.edu /~ Gewang/projects/Darth/stuff/quat_faq.html

Matrices http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/

Real-time rendering 3rd

Fundamentals of computer graphics 2rd

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.