Tag Archives: OpenGL

Learning from OpenGL

Pit 001

:
:
:
:
:
:
:
:
:
:
:

    std::fstream file(filepath);
    std::string shaderText = "";
    std::string line;
    while (std::getline(file, line))
        shaderText = shaderText + line +"\n" ;
    file.close();

In particular, put a newline character “\n” at the end of each line change after reading it.
Pit 002
And then at the end of the transformation into the camera space, we have to multiply by the three basis vectors for the camera space.

Pit 003

Flag ① : Sometimes the render is too frequent, which causes us to process our input too much, so here we use the code in Flag ① to control the render frequency a bit. Render only if the value of count is an integer multiple of 100,000.
flag ② : The Render Callback needs to constantly refresh the transformation matrix we set, otherwise even if we change the render matrix in the code, it will not work.

Common problems and basic concept knowledge of OpenGL

OpenGL FAQ and basic concept knowledge (continuously updated!!)
1. The concept of matrix in OpenGL, what is Model,View,Project?
We know the World in the OpenGL Matrix (World Matrix)/View Matrix (the View Matrix and Projection Matrix (the Projection matirx)
in the Model: the Matrix determine the World coordinates of a unified, mainly aimed at the Model of translation, rotation, scaling, shear, and other functions, is the Model from local space into World space.

Projection matrix is the part of the scene that we can see, with the camera/observer position and so on (set mouse movement, scroll wheel, etc.), and converts all world coordinates to View coordinates.
2. Scheduling between CPU and GPU in OpenGL

OpenGL program involves two types of processing unit CPU and GPU.
engl main program has CPU call to run, image processing part through GLSL to GPU execution.
Data transfer between CPU and GPU is divided into three steps:
1. First use the built-in OpenGL function to generate an ID number
2. According to the need for the ID number of memory types of binding, binding to be used in the receiving system after the completion of the GPU memory of the data in the “identifier” will be ready,
3. This part of memory is initialized. The initialized content is from the system memory, and this part of function is completed by the glBufferData function. After the data is submitted to the GPU dedicated memory, it is necessary to allocate the data according to the application scenarios, such as some data as vertices, some as colors, some for illumination control and so on
In addition, due to the high parallel structure of GPUs, all GPUs have high computational efficiency in processing graphics and complex algorithms. Most of the CPU area is controllers and registers, while GPUs have more ALUs, logical operational units for data processing, rather than data caching and flow control.
The concept of buffers in OpenGL
[1] Frame Buffer: A frame buffer is a combination of the following buffers. Using frame buffers allows you to render your scene into a different frame buffer, which allows you to create mirrors in the scene, or create cool effects that store data for the display.
[2] Color Buffer: Stores the color of all fragments: that is, the effect of visual output.
[3] Depth Buffer: determines which facets are occluded according to the Z value of the buffer. Automatically generated by GLFW.
[4] stencil buffer: Similar to depth testing, the template value is compared to the default value to determine whether to discard the fragment.
Data is processed in OpenGL in the following order: vertex shader – fragment shader – template test – depth test
The concept of depth testing
1. What is depth?

OpenGL will have a special area for storing Z value (the Z value on each pixel), which is the depth cache.
2. Depth Buffer Function?
In general, when we draw a graph, the later drawing overrides the previous graph, and the general drawing order is drawn from the back to the front. So there is a performance problem with the “covered part”, where the first part is covered, and all you see is the top part of the module and the bottom part of the covered part is not meaningful!
depth test appears to solve the covering problem
nction: when the depth test is turned on, the Z value will be checked. The same area close to the observer will be drawn, and other covered areas will not be drawn, regardless of the order of drawing.
3. How to use the deep cache test?

enable (GL_DEPTH_TEST);
glEnable(GL_DEPTH_TEST);
in the above code open depth test by default, the Z value under the condition of small will be overwritten
If the observer is in the positive direction of the Z axis, the Z value is close to the observer
If the observer is in the negative direction of the z-axis, the smaller z-value is closer to the observer

How to solve the conflict problem caused by the same depth value (same Z value)?
The first method: in the second drawing the same Z value, the tiny offset cover problems
note: must be very careful to ensure that the Z value of the gap, or like a refrigerator on the refrigerator as suspended risk
The second method is to sample the GLPolygonOffset function so that the depth value of the fragment can be adjusted so that the depth value is offset without creating a suspended emphasis

Some problems in OpenGL

[size=large] I recently tried to write some OpenGL programs. I found some small problems, and I’m going to record them. If I understand them in the future, I will look back and see that I have witnessed some growth.

> First, the context. In fact, we know color coloring, can be divided into direct use color glColor4f(); You can also use a vertex array to color glColorPointer(); To color. However, if this property is enabled: gl.glEnable(gl10.gl_texture_2d); Will invalidate the color of. So, if enabled before, disable this property before painting, and then paint in the color. As a result, the problem is that texture and color have no co-existence, meaning that color never affects texture. However, I think this is not the case. Is the understanding of mixing not enough or something?I hope to find the answer to this question in the follow-up study.

and, before the use of an array, must open his first, such as color array, using the former to gl. GlEnableClientState (GL10. GL_COLOR_ARRAY);

Otherwise it’s white. Checking up is also more troublesome.

[/size]

OpenGL learning — problems encountered in compiling OpenGL program for the first time

The first time you compile and run an OpenGL program, you run into a bug that makes you crazy.
It looks like this:

A lot of search on the Internet, found that this is the first time to compile OpenGL program will meet the error. The solution is as simple as the #include< gl/glut.h> Preface it with a code like this:

Also note that the order of the code must be in #include< gl/glut.h> Before, can not error, otherwise still can not pass.

Learning notes of OpenGL — blending

Note: This document is only about the main points and some of my own new ideas. It is not a tutorial. For a tutorial, see the OpenGlLearn article.

Blending can make the object transparent.
Transparency can be achieved in two ways:
‘1’ means discard part of the fragments. In this case, there are no translucent fragments.
Two is really mixing. The current segment and the target segment are weighted according to a certain formula.
【 1 】

#version 330 core
out vec4 FragColor;

in vec2 TexCoords;

uniform sampler2D texture1;

void main()
{             
    vec4 texColor = texture(texture1, TexCoords);
    if(texColor.a < 0.1)
        discard;
    FragColor = texColor;
}

A segment that is always bright, discarded, but this if will branch logically, so that’s the efficiency…

Set the surround texture to GL_CLAMP_TO_EDGE to slightly improve the visual effect.

[2] Mixing
Enable the blend: glEnable(GL_BLEND);

GLBLENDFUNC (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
So source alpha and 1-source alpha
Here glblendFunc is the mixed operation setup function.
GlblendFunction Separate is a bit more subtle and allows you to set the action function for both color and Alpha separately.

Both set the source and target, how to handle RGB and alpha values.

GlblEndequation can be used to set the blending operator. In fact, the most common one is GL_FUNC_ADD


This function sets the formula to use to handle the alpha and RGB values.

The principle of mixing:
If you’ve already drawn something before mixing it (even a skybox is OK), what about wool?
When blending, the object to be drawn is the Source, and the object already drawn is the Target.
When blending, you don’t have to change anything in your Shader. The pieces will blend themselves with the drawn pieces according to the blending formula and numerical rules. Unity uses the syntax of ShaderLab to set up these functions.

An explanation of a previously encountered problem:
A few months ago, I had an issue with WorldCreatorPro where the trees would become translucent slices when I used Slice LOD instead of SpeedTree, which was far away from the map. At this point, the translucent area hides the terrain behind.

Now it’s easy to explain. Borrowing the graph from the Learnopengl author:


Look at the hoop:
If the previous diagram is drawn first, the transparent pixels here will also be written to the ZBuffer, since the Z-Buffer ignores Alpha.
When the object behind is drawn (whether it is transparent or not, as long as it is farther away from the object in front) the z-test fails and the corresponding pixel is discarded.

Conclusion: When Z-buffer and Blending theory are used together, it is necessary to draw distant objects first and then close ones to ensure no mistakes.
The trees we used before, even if we could sort them, it would be a terrible overhead to arrange thousands of trees in order every frame and then render them. So we could just switch to SpeedTree and use model LOD instead of map LOD, although it would be really cheap.

Method: How to use Blending correctly.

    Draw all opaque objects first. Sort all transparent objects. Draw all transparent objects in order (from far forward). In particular, you can sort by distance insertion, drawing far away first, and then drawing near.

OpenGL Usage Summary (including problems encountered and solutions)


glMatrixMode(gl_modelView);
glMatrixMode(gl_modelView);
// Reset the model observation matrix.
glLoadIdentity ();
//
selection model observation matrix gluLookAt (3.0 f to 2.5 f to 5.0 f to 0.0 f to 0.0 f to 0.0 f to 0.0 f to 1.0 f to 0.0 f);
Note: Be sure to call glLoIdentity to reset the currently specified matrix to the identity matrix before calling gluLookAt.

br> <>>

2. When you do texture mapping, you find that the texture and color are mixed.
To mask the effects of GLColor3F, simply add:
GlColor3f (1.0, 1.0, 1.0);
or add: glTexenvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

glgentextures6, &
glgentextures6, & texture[i]);
glBindTexture (GL_TEXTURE_2D, texture [I]);
glutInit(&
glutInit)
glutInit(&
glutInit)
glutInit(&
glutInit)
glutInit(& argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition (0, 0);
glutInitWindowSize(800, 600);
glutCreateWindow(“Wander”);
wander.load_GL_textures1();
=
=
=
=
=
=
=

1.
GlFrontFace (GL_CCW); // Specifies counterclockwise as the front
GlCullFace (GL_BACK); // Make the back side invisible
GlEnable (GL_CULL_FACE);
 
2.
// Pyramid objects are not mapped, so you should not enable texture mapping, otherwise you will not see the object
//glEnable(GL_TEXTURE_2D);
// Enable texture mapping, enable texture mapping before the object to be mapped, disable texture mapping after the object is drawn, if enabled before all the objects to be drawn, the object will not be seen if GLTextCoord2f is not used
 
3.
GlClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
GlMatrixMode (GL_MODELVIEW); // Set the Model View Matrix to determine the position of an object in 3D space
GlLoadIdentity (); //M=I; I is the identity matrix
 
GlColor3f (1.0f, 0.0f, 0.0f);
GlBegin (GL_TRIANGLES);
GlVertex3f (0.0 f, f, 2.0 0.0 f);
GlVertex3f (0.0-1.0 f to 1.0 f, f);
GlVertex3f (0.0 1.0 f to 1.0 f, f);
GlEnd ();
 
GlTranslatef (0.0 1.0 f, 3.0 f, f); // If x is shifted by 1, y is shifted by 3, and z is guaranteed to remain the same, the corresponding matrix is:
// After translation, M=M*K=I*K,K = x shifted by 1, y shifted by 3, z guaranteed invariant translation matrix
// GlRotatef (90.0F, 0.0F, 0.0F, 1.0F); // Rotate 90 degrees counterclockwise
GlRotatef (-90.0F, 0.0F, 0.0F, 1.0F); // Rotate 90 degrees clockwise
// After rotation, M=M*R=K*R,R is the corresponding selection matrix above
/ *
K =
1 0 0 1
0 1 0 3
1 0 0 0
0 0 0 to 1
 
The rotation matrix of @ degrees about the z axis, R is equal to
Cos @ – sin @ 0 0
Sin @ cos @ 0 0
1 0 0 0
0 0 0 to 1
Substitute @=-90 to get:
1 0 0 0
1 0 0 0
1 0 0 0
0 0 0 to 1
Have to M =
1 0 0 1
1 0 0. 3
1 0 0 0
0 0 0 to 1
And then multiply the homogeneous coordinates of the following three coordinates right by M to get the final coordinates,
P ‘= MP, P for the original coordinates of the corresponding homogeneous coordinates, such as the first point (0.0, 2.0, 0.0) of homogeneous coordinates (0.0, 2.0, 0.0, 1.0) for
The final three coordinate positions are:
   
A1 =
3
3
0
1
 
A2 =
0
4
0
1
 
A3 =
0
2
0
1
Finally, draw the triangle corresponding to the three points
* /
 
GlColor3f (0.0 1.0 f, 0.0 f, f);
GlBegin (GL_TRIANGLES);
GlVertex3f (0.0 f, f, 2.0 0.0 f);
GlVertex3f (0.0-1.0 f to 1.0 f, f);
GlVertex3f (0.0 1.0 f to 1.0 f, f);
GlEnd ();
The results are as follows:

Note: OpenGL uses right multiplication
 
 
4. The maximum size of texture map should not exceed 256*256, preferably BMP image
The width and height of the image must be 2 to the power of n; Width and height must be 64 pixels minimum; And for compatibility reasons, the width and height of the image should not exceed 256 pixels. If the width and height of your raw material is not 64,128,256 pixels, use image processing software to resize the image.
I mentioned earlier that there are ways around OpenGL’s restrictions on texture width and height — 64, 128, 256, etc. The solution is gluBuild2DMipmaps. As I’ve found, you can use any bitmap to create a texture. OpenGL will automatically scale it to its normal size.
GluBuild2DMipmaps (GL_TEXTURE_2D, 3, TextureImage [0] – & gt; sizeX, TextureImage[0]-> sizeY, GL_RGB,GL_UNSIGNED_BYTE, TextureImage[0]-> data);
Note: It seems that only BMP images can be loaded, not other types of images
 
5.
/ *
The purpose is to reset the model observation matrix. If we call glTranslate directly without resetting, unexpected results will occur.
Because the axis has rotated, it’s probably not going in the direction you want. So we wanted to move the object left and right,
Depending on how much Angle you’ve rotated the axis, it might move up and down.
* /
   
6. Default viewpoint position:
The default viewpoint position is at the point (0,0,0) and the orientation is vertical into the screen (that is, negative z-axis).
When you draw an object, notice that you move the Z coordinate of the object back a few units and you see it.
Viewpoints are not changed by default, which can be done by setting the gllookAt function
 
7.
glGenTextures(3, & texture[0]); // The glGenTextures function returns n texture indexes based on the texture parameters,& Texture [0] stores the texture index
// Create Nearest filter map
/ *
GlBindTexture actually changes this state of OpenGL by telling OpenGL that any action done to the texture is done to the texture object to which it is bound,
For example, glBindTexture(GL_TEXTURE_2D,1) tells OpenGL that any Settings for 2D textures in the following code are for textures with index 1
* /
8. OpenGL does not set the color, directly draw four vertices, the resulting square, the default will be white;
9.

Two problems in OpenGL Programming

Error C2381: ‘exit’ : redefinition; error C2381: ‘exit’ : redefinition; error C2381: ‘exit’ : redefinition; __declspec (noreturn) differs. The solution to the problem is to include the #include< stdlib.h> On the # include & lt; gl\glut.h> Just before.

Error LNK2001: unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12 Unresolved external symbol __imp____glutInitWithExit@12

#define GLUT_DISABLE_ATEXIT_HACK

It is estimated that the reason for the above problem is the repeated definition problem.

Configuring OpenGL in Visual Studio

This semester to learn the graphics, to use C ++ to write, which is mainly used OpenGL, so first of all, to configure OpenGL in Visual Studio
1. Create a new C ++ console application. File – & gt; New – & gt; project

2. Then click Item ->; Manage the NuGet package

3. Browse here, type NupenGL and search

4. After downloading and installing both of them, import the header file at the beginning of the source program, and you can use it

OpenGL application cannot start normally

About this problem, there are a lot of people on the Internet also encountered, but basically using other people’s solutions can not solve their own problems. The reason for this is that the dependent library fails, and the dependent library that everyone fails on is different. Here’s what happened to you:

First of all, my computer is 64-bit Win7 system, using VS2012, Win32 compiler . Run on your computer is no problem, but transplanted to the friend’s computer, a lack of “msvcp110d. DLL” began to appear, “msvcr110d. DLL” these two libraries, then I am wrong “D: \ visual studio 2012 VC \ \ lib” inside the library for a friend, actually should be to “ C: \ Windows \ SysWOW64 ” the inside of the library.

Also, at first I thought I was going to change the OpenGL dependency library to 64-bit, and then found out that the current OpenGL library is only 32-bit and is compiled and run with VS Win32 regardless of whether the machine is 64 or 32.

If the appeal method does not resolve the problem, please check your program’s dependent libraries, or re-do all the libraries.

     

MSVCP110D.dll MSVCR110D.dll Download link password: yx07

Vs under the execution of OpenGL program can run successfully, but do not show things

There are possible reasons

1, the graphics card does not support the current version of OpenGL, download Everest Ultimate Edition, then click the display device> after installing and running. OpenGL, to see whether support and other relevant information, if not can only replace the graphics card or to support the OpenGL version of the solution

2, The video driver is not supported, update the video driver

How to use high version OpenGL under Windows

Windows only supports OpenGL1.1, but graphics cards may implement the related functions of higher versions of OpenGL directly from the hardware. How do you call a higher version of OpenGL in development?
 
Let’s start with a look at the OpenGL version and related function extensions supported by a graphics card:
To see what version of OpenGL the graphics card supports: glGetString(GL_VERSION);
To see the supported extensions: glGetString(GL_EXTENSIONS);
See more detailed information.
http://www.opengl.org/wiki/GlGetString
Note: call glGetString(GLemun); Be sure to initialize the drawing window before doing so, otherwise only null will be returned.
 
Calling extensions with glew:
After confirm the graphics support high version of the function can be used to glew libraries (http://sourceforge.net/projects/glew/) to invoke, configured information can be used after glew libraries. What I want to point out here is that before using the OpenGL function declared in the advanced version of Glew, you must make the following call:
GLenum err = glewInit ();
if (GLEW_OK! = err)
{
* Problem: glewInit failed, something is seriously wrong. */
f>tf (stderr, “Error: %s/n”, glewgeterrorString (err));
}
 
 
You can also use glee,glext, and mesa.
Glee is similar to Glew,glext is a bit cumbersome to use, and mesa is a platform-independent implementation of OpenGL.

Some problems and solutions in learning opengl in vs2017

1. Under VS2017, the header file you need to include is <<; gl/glut.h> GL/glut.h>
=
=
=
=
=
=
=
pch.h> Header files, to run a successful
and it will be included in the front, in & lt; gl/glut.h> PCH is a file that is automatically generated by the compiler when you create the project, called a precompiled file. Open PCH.H, and PCH.CPP, and find that there is nothing substantial in it.
for some references below:
(copyright statement: this article original articles for bloggers, follow BY CC 4.0 – SA the copyright agreement, please attach the original source links and reprinted in this statement.

the article links: https://blog.csdn.net/qq_37866732/article/details/83894909 is the beginning of your code without # include “PCH. H” the precompiled header.
H This header file can be put into your.h header file, and having #ifndef, #define, and #endif is to prevent you from linking to a certain header file again.
#ifndef PCH_H
#define PCH_H
// TODO: Add the header to precompile here
#endif //PCH_H
#endif //PCH_H
#endif //PCH_H
Attributes – & gt; Configure properties –>; C/C + + – & gt; Precompiled header –>; To the right of the precompiled header, select not to use the precompiled header and press OK. You can add pch.h without any errors.
)