Android OpenGL ES (iv)----Adjust the aspect ratio of the screen

Source: Internet
Author: User

1. Aspect ratio problem


We are quite familiar with the fact that in OpenGL, everything we want to render is mapped to the range of [ -1,1] on the x-axis and the y-axis, as well as the z-axis. The coordinates within this range are called normalized device coordinates, which are independent of the actual size or shape of the screen.


Unfortunately, because they are independent of the actual screen size, if they are used directly, we will encounter problems, such as a flattened table in horizontal screen mode.


Assuming that the actual device resolution is 1280*720 in pixels, this is a common resolution on the new Android device. To make the discussion easier, let's also assume for the time being that OpenGL occupies the entire display.


If the device is in portrait mode, the range of [ -1,1] corresponds to 1280 pixels high, but only 720 pixels wide. The image will appear flat on the x-axis, and the same problem will occur on the y-axis if you are in horizontal screen mode.


Normalized device coordinates assume that the coordinate space is a square, as shown in:



However, because the actual viewport may not be a square, the image is stretched in one direction and flattened in the other direction. On a vertical screen device, the image defined on the normalized device coordinates appears to have been flattened in the horizontal direction:




In landscape mode, the same image looks squashed in the other direction.




2. Adapt to aspect ratio

We need to adjust the coordinate space so that it takes the shape of the screen into account, one possible way is to fix the smaller range within [ -1,1], and adjust the larger range by the proportion of the screen size.

For example, in the case of a vertical screen, the width is 720 and the height is 1280, so we can limit the width to [ -1,1] and adjust the height range to [ -1280/720,1280/720] or [ -1.78,1.78]. Similarly, in the case of horizontal screen mode, set the height range to [ -1.78,1.78] and the height range to [ -1,1].


By adjusting the existing coordinate space, we will eventually change the space available to us.


With this method, the object looks the same whether it is in portrait or landscape mode.



3. Using Virtual coordinate space

Adjusting the coordinate space so that we can take the screen orientation into account, we need to stop working directly on the normalized device coordinates, and start working in the virtual coordinate space remotely. Next, we need to find some way to convert the virtual space coordinates back to the device coordinates, so that OpenGL can render them correctly. This conversion should take the screen orientation into account so that the image looks the same in both portrait and landscape mode.


The operation we want to make is called an orthographic projection. With orthogonal projections, all objects look the same size, no matter how far or how close. For a higher understanding of what this projection is for, imagine that there is a train track in our scene that looks straight from the air, and these tracks look something like this:




There is also a special type of orthogonal projection, known as isometric projection, which is an orthogonal projection from the side angle. As seen in some of the city simulation and strategy games, this type of projection can be used to recreate a classic three-dimensional angle.





When we use orthogonal projection to transform the virtual coordinate transformation into the device coordinates, we actually define a region within the three-dimensional world. Everything in this area will be displayed on the screen, and everything outside the area will be trimmed off.


Use the orthogonal projection matrix to change the size of the cube so that we can see more or less scenes on the screen. We can also change the shape of the cube to compensate for the effect of the screen's aspect ratio.



4. Linear Algebra Basics


OpenGL uses a lot of vectors and matrices, and one of the most important uses of matrices is to set up orthogonal and perspective projections. One reason for this is that, in essence, using a matrix for projection only involves performing a number of additions and multiplication sequentially on a set of data, which are performed very quickly on modern GPUs.


4.1 Vector



A vector is a one-dimensional array with multiple elements. In OpenGL, a position is usually a four-element vector, and the color is the same. Most of the vectors we use generally have four elements. In the following example, we can see a position vector, which has an x, a Y, a Z, a W component.




4.2 Matrix



A matrix is a two-dimensional array with multiple elements. In OpenGL, we typically use matrices as vector projections, such as orthogonal or perspective projections, and also use them to rotate objects, translate objects, and scale objects. We can achieve these transformations by multiplying the matrix with each vector to be transformed. Here is a matrix:




4.3 multiplication of matrices and vectors


To multiply a matrix by a vector, we put the matrix on the left and the vector on the right. As follows:




Rules is the first row of the matrix multiplied by the first column of the vector, in the first example: the first row of the matrix is multiplied by the first element of the first column of the vector, the second element of the first row of the matrix multiplied by the second element of the first column of the Matrix, the third element of the first row of the vector multiplied by the third element Add the fourth element of the first row of the matrix multiplied by the fourth element in the first column of the vector. Matrices Two, three, four lines are the same.



4.4 Unit Matrix


The unit matrix is as follows:



of so called the unit matrix, is because this matrix is multiplied by any vector that always gets the same vector as the original. It's like multiplying any number by 1 to get the same number.



4.5 Translation Matrix

Now that we understand the unit matrix, let's look at a very simple matrix type---translation matrix. It is very common in OpenGL. Using this type of matrix, we can move an object along a specified distance. This matrix is similar to the unit matrix, but three additional elements are specified on the right:



Let us shield a position (2,2) example, this position z default is 0,w default is 1. We translate this vector along the x-axis by 3, and also translate 3 along the y-axis, so the xtranslation assignment is 3,ytranslation assignment of 3. The results are as follows:



It location is exactly what we expect and (5,5).



5. Orthogonal projection


To define an orthographic projection, we will use the Android matrix class, which is in the Android.opengl package. This class has a method called Orthom (), which can generate an orthographic projection for us.

Let's take a look at the Orthom () parameter:


Orthom (float[] m,int moffset,float left,float rigth,float bottom,float top,float near,float FAR)


Float[] M: The target array, which has at least 16 elements in length, so that it can store an orthogonal projection matrix.

int Moffset: The offset value at which the result matrix starts.

The minimum range of the float left:x axis.

The maximum range of the float right:x axis.

The minimum range of the float bottom:y axis.

The maximum range of the float top:y axis.

The minimum range of the float near:z axis.

The maximum range of the float far:z axis.


When we call this method, it should produce the following orthogonal projection matrix:



It an orthogonal projection matrix will map all the things between the left and right, between the top and the bottom and the near and far into the range of normalized device coordinates from 1 to 1, where everything is visible on the screen.


The main difference is that the z-axis has a negative sign, and its effect is to invert the z-coordinate. This means that the farther away the object is, the less negative the z-coordinate will be. The reason why this is completely historical and traditional.




6. Left and right hand coordinate system


To better understand the z-axis problem, we need to understand the difference between the left-handed coordinate system and the right-hand coordinate system. To know if a coordinate system is left-handed or right-handed, you take out a hand, point the thumb to the x-axis positive direction, and then point the index finger to the y-axis positive direction.


Now, point your middle finger to the z axis. If you need to do this with your left hand, what you see is a left-handed coordinate system; If you need to use your right hand, you see a right-handed coordinate system. Point your middle finger at the z-axis, and remember to point the thumb to the x-axis and the index finger to the y-axis positive direction. Such as:



actually left or right hand choice is OK, just a simple conversion. Normalized device coordinates use a left-handed coordinate system, whereas in earlier versions of OpenGL, the default use of the true right-hand coordinate system, which uses a negative value of z increases the distance increase. This is why the matrix of Android is generated by default to invert Z matrices.



7. Update program

7.1 Updating shaders

The code in the vertex shader of the previous chapter is modified as follows:


Uniform mat4 U_matrix;

Attribute Vec4 a_position;
Attribute Vec4 A_color;
Varying VEC4 v_color;
void Main ()
{
V_color=a_color;
Gl_position =
u_matrix*a_position;
Gl_pointsize = 10.0;
}



We have added a new uniform definition of "u_matrix" and defined it as a mat4 type, meaning that this uniform represents a 4*4 matrix. Update position negative line:



gl_position =u_matrix*a_position;


Instead of passing the position defined in the array, we pass the product of that position to a matrix. It means that the vertex array is no longer translated into the coordinates of the normalized device, which is understood to exist in the virtual coordinate space defined by the matrix. This matrix returns the coordinates from the virtual coordinate space to the coordinate of the device.



7.2 Adding an array of matrices and a new uniform

Open the Lyjrenderer of the previous section to add member variables:


private static final String u_matrix= "U_matrix";


We also need a top-point group storage matrix:


Private final float[] projectionmatrix=new float[16];


We also need an integer value to hold the position of the matrix uniform:


private int umatrixlocation;


Then we just need to add the following code to the onsurfacecreated ():


Umatrixlocation=gles20.glgetuniformlocation (Program,u_matrix);



7.3 Creating an Orthographic projection matrix


Update onsurfacechanged () and add the following code after the Gles20.glviewport () Call:


Final float aspectratio=width>height? (float) width/(float) heigth: (float) height/(float) width;

if (width>height) {

Orthom (projectionmatrix,0,-aspectratio,aspectratio,-1f,1f,-1f,1f);

}else{

Orthom (projectionmatrix,0,-1f,1f,-aspectratio,aspectratio,-1f,1f);

}


This code creates an orthogonal projection matrix that calculates the current orientation of the screen. Note there is not only one Matrix class in Android, so make sure you import Android.opengl.Matrix.


We first calculate the aspect ratio, which uses the larger values of wide and high schools divided by the smaller values of width and height. This is the same value, whether it is a vertical screen or a horizontal screen.



7.4 Passing matrices to shaders

In Ondrawframe () in Lyjrenderer, we add the following code after the Glclear () Call:


GLES20.GLUNIFORMMATRIX4FV (umatrixlocation,1,false,projectionmatrix,0);

Android OpenGL ES (iv)----Adjust the aspect ratio of the screen

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.