opengl中的depth_test不起作用

linux上用python写了个简单的程序,
画了红绿蓝三个方块,但是发现启用了深度测试之后还是按绘制顺序遮挡的,不知道哪错了
初学者,请大佬们指教,谢谢了

def drawImage():
    glEnable(GL_DEPTH_TEST)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glColor3f(1, 0, 0)
    glBegin(GL_POLYGON)
    glVertex3f(0.1,0.1,0.5)
    glVertex3f(0.1,0.7,0.5)
    glVertex3f(0.7, 0.7, 0.5)
    glVertex3f(0.7, 0.1, 0.5)
    glEnd()

    glColor3f(0, 1, 0)
    glBegin(GL_POLYGON)
    glVertex3f(0.3,0.3,0.8)
    glVertex3f(0.3,0.9,0.8)
    glVertex3f(0.9, 0.9, 0.8)
    glVertex3f(0.9, 0.3, 0.8)
    glEnd()

    glColor3f(0, 0, 1)
    glBegin(GL_POLYGON)
    glVertex3f(0.5,0.5,0.3)
    glVertex3f(0.5,1.0,0.3)
    glVertex3f(1.0, 1.0, 0.3)
    glVertex3f(1.0, 0.5, 0.3)
    glEnd()

    glFlush()


glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowPosition(0, 0)
glutInitWindowSize(400, 400)
glutCreateWindow(b"show model")
glutDisplayFunc(drawImage)
glutIdleFunc(drawImage)
glutMainLoop()
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
为什么我开了gl_depth_test先绘制的图形还是会被后绘制的图形覆盖?
#import "ViewController.h" #import "sphere.h" typedef struct { GLKVector3 position; GLKVector3 normal; GLKVector4 color; }SceneVertex; SceneVertex vertex[3888]; @interface ViewController () @property(nonatomic,assign)GLuint program; @property(nonatomic,assign)GLint modelMat; @property(nonatomic,assign)GLint viewMat; @property(nonatomic,assign)GLint projectionMat; @property(nonatomic,assign)GLint tex; @property(nonatomic,assign)GLint color; @end @implementation ViewController { GLKMatrix4 modelMatrix; GLKMatrix4 viewMatrix; GLKMatrix4 projectionMatrix; GLuint earth; GLuint moon; GLuint tx[2]; GLKMatrix4 moonMatrix; GLfloat moonDepth; } - (void)viewDidLoad { [super viewDidLoad]; //初始化绘图上下文 moonDepth = 0.0f; GLKView *view = (GLKView *)self.view; view.context = [[EAGLContext alloc]initWithAPI:kEAGLRenderingAPIOpenGLES2]; [EAGLContext setCurrentContext:view.context]; view.drawableDepthFormat = GLKViewDrawableDepthFormat16; //初始化绘图上下文 for (int i=0; i<1944; i++) { vertex[i].position.x = sphereVerts[3*i]; vertex[i].position.y = sphereVerts[3*i+1]; vertex[i].position.z = sphereVerts[3*i+2]; vertex[i].color = GLKVector4Make(1, 1, 1, 1); vertex[i].normal.x = sphereNormals[3*i]; vertex[i].normal.y = sphereNormals[3*i+1]; vertex[i].normal.z = sphereNormals[3*i+2]; } for (int i=0; i<1944; i++) { vertex[i+1944].position.x = sphereVerts[3*i]+0.3; vertex[i+1944].position.y = sphereVerts[3*i+1]; vertex[i+1944].position.z = sphereVerts[3*i+2]; vertex[i+1944].normal.x = sphereNormals[3*i]; vertex[i+1944].normal.y = sphereNormals[3*i+1]; vertex[i+1944].normal.z = sphereNormals[3*i+2]; vertex[i+1944].color = GLKVector4Make(1, 0.5, 1, 1); } glEnable(GL_CULL_FACE|GL_DEPTH_TEST); glClearColor(0, 0, 0, 1); glGenBuffers(1, &earth); glBindBuffer(GL_ARRAY_BUFFER, earth); ssize_t number = sizeof(vertex) / sizeof(SceneVertex); NSLog(@"%li",number); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), vertex, GL_STATIC_DRAW); glEnableVertexAttribArray(GLKVertexAttribPosition); glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(SceneVertex), NULL); glEnableVertexAttribArray(GLKVertexAttribColor); glVertexAttribPointer(GLKVertexAttribColor, 4, GL_FLOAT, 0, sizeof(SceneVertex), NULL+offsetof(SceneVertex, color)); glEnableVertexAttribArray(GLKVertexAttribNormal); glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, sizeof(SceneVertex), NULL+offsetof(SceneVertex, normal)); glBindBuffer(GL_ARRAY_BUFFER, 0); [self loadShaders]; modelMatrix = GLKMatrix4Identity; viewMatrix = GLKMatrix4Identity; projectionMatrix = GLKMatrix4Identity; moonMatrix = GLKMatrix4Identity; viewMatrix = GLKMatrix4MakeLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0); projectionMatrix = GLKMatrix4MakeFrustum(-1, 1, -1, 1, 8, 1000); } -(void)glkView:(GLKView *)view drawInRect:(CGRect)rect{ float aspect = (GLfloat)view.drawableWidth / (GLfloat)view.drawableHeight; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindBuffer(GL_ARRAY_BUFFER, earth); glUseProgram(_program); modelMatrix = GLKMatrix4MakeScale(1, aspect, 1); glUniformMatrix4fv(_modelMat, 1, 0, modelMatrix.m); glUniformMatrix4fv(_viewMat, 1, 0, viewMatrix.m); glUniformMatrix4fv(_projectionMat, 1, 0, projectionMatrix.m); moonMatrix = GLKMatrix4MakeScale(1, aspect, 1); moonMatrix = GLKMatrix4Translate(moonMatrix, 0.5, 0, moonDepth); glUniformMatrix4fv(_modelMat, 1, 0, moonMatrix.m); glDrawArrays(GL_TRIANGLES, 1944, 1944); glDrawArrays(GL_TRIANGLES, 0, 1944); glBindBuffer(GL_ARRAY_BUFFER, 0); } - (IBAction)changeEyePosition:(id)sender { static float i = 0.1; viewMatrix = GLKMatrix4MakeLookAt(0, 0, 10-i, 0, 0, 0, 0, 1, 0); i+=0.1; } - (IBAction)changeDistance:(id)sender { moonDepth += 0.1; // NSLog(@"%f",moonDepth); for (int i=0; i<1944; i++) { vertex[i+1944].position.x = sphereVerts[3*i]+0.1; vertex[i+1944].position.y = sphereVerts[3*i+1]; vertex[i+1944].position.z = sphereVerts[3*i+2]+moonDepth; vertex[i+1944].normal.x = sphereNormals[3*i]; vertex[i+1944].normal.y = sphereNormals[3*i+1]; vertex[i+1944].normal.z = sphereNormals[3*i+2]; vertex[i+1944].color = GLKVector4Make(1, 0.5, 1, 1); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (BOOL)loadShaders { GLuint vertShader, fragShader; NSString *vertShaderPathname, *fragShaderPathname; // Create shader program. _program = glCreateProgram(); // Create and compile vertex shader. vertShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"vsh"]; if (![self compileShader:&vertShader type:GL_VERTEX_SHADER file:vertShaderPathname]) { NSLog(@"Failed to compile vertex shader"); return NO; } // Create and compile fragment shader. fragShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"fsh"]; if (![self compileShader:&fragShader type:GL_FRAGMENT_SHADER file:fragShaderPathname]) { NSLog(@"Failed to compile fragment shader"); return NO; } // Attach vertex shader to program. glAttachShader(_program, vertShader); // Attach fragment shader to program. glAttachShader(_program, fragShader); // Bind attribute locations. // This needs to be done prior to linking. glBindAttribLocation(_program, GLKVertexAttribPosition, "position"); glBindAttribLocation(_program, GLKVertexAttribNormal, "normal"); glBindAttribLocation(_program, GLKVertexAttribColor, "color"); if (![self linkProgram:_program]) { NSLog(@"Failed to link program: %d", _program); if (vertShader) { glDeleteShader(vertShader); vertShader = 0; } if (fragShader) { glDeleteShader(fragShader); fragShader = 0; } if (_program) { glDeleteProgram(_program); _program = 0; } return NO; } //modelMatrix = glGetUniformLocation(_program, "modelMatrix"); _modelMat = glGetUniformLocation(_program, "modelMatrix"); _viewMat = glGetUniformLocation(_program, "viewMatrix"); _projectionMat = glGetUniformLocation(_program, "projectionMatrix"); // _color = glGetUniformLocation(_program, "color"); // Release vertex and fragment shaders. if (vertShader) { glDetachShader(_program, vertShader); glDeleteShader(vertShader); } if (fragShader) { glDetachShader(_program, fragShader); glDeleteShader(fragShader); } return YES; } - (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file { GLint status; const GLchar *source; source = (GLchar *)[[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] UTF8String]; if (!source) { NSLog(@"Failed to load vertex shader"); return NO; } *shader = glCreateShader(type); glShaderSource(*shader, 1, &source, NULL); glCompileShader(*shader); #if defined(DEBUG) GLint logLength; glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { GLchar *log = (GLchar *)malloc(logLength); glGetShaderInfoLog(*shader, logLength, &logLength, log); NSLog(@"Shader compile log:\n%s", log); free(log); } #endif glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); if (status == 0) { glDeleteShader(*shader); return NO; } return YES; } - (BOOL)linkProgram:(GLuint)prog { GLint status; glLinkProgram(prog); #if defined(DEBUG) GLint logLength; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { GLchar *log = (GLchar *)malloc(logLength); glGetProgramInfoLog(prog, logLength, &logLength, log); NSLog(@"Program link log:\n%s", log); free(log); } #endif glGetProgramiv(prog, GL_LINK_STATUS, &status); if (status == 0) { return NO; } return YES; } - (BOOL)validateProgram:(GLuint)prog { GLint logLength, status; glValidateProgram(prog); glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { GLchar *log = (GLchar *)malloc(logLength); glGetProgramInfoLog(prog, logLength, &logLength, log); NSLog(@"Program validate log:\n%s", log); free(log); } glGetProgramiv(prog, GL_VALIDATE_STATUS, &status); if (status == 0) { return NO; } return YES; } @end ``` shader ``` attribute vec3 position; attribute vec3 normal; attribute vec4 color; attribute vec2 TextureCoords; uniform lowp mat4 modelMatrix; uniform lowp mat4 viewMatrix; uniform lowp mat4 projectionMatrix; varying lowp vec4 colorVarying; varying vec2 TextureCoordsOut; void main() { vec4 pointNormal = normalize(projectionMatrix * viewMatrix * modelMatrix * vec4(normal,1)); vec3 pNormal = normalize(vec3(pointNormal.x,pointNormal.y,pointNormal.z)); vec4 lightColor = vec4(1,0,1,1); vec3 lightDirection = normalize(vec3(1,0,1)); float lightStrength = dot(lightDirection,pNormal); colorVarying = color + lightStrength * lightColor; gl_Position = vec4(position,1);//projectionMatrix * viewMatrix * modelMatrix * vec4(position,1); }
OpenGL 输入多个渲染缓存数据不一致的问题
我在示例代码中申请了一个帧缓存对象: ``` int FrameBuf; glGenFramebuffers(1, &FrameBuf); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FrameBuf); ``` 三个渲染缓存对象,第1个和第3个分别绑定为帧缓存对象的COLOR_ATTACHMENT0和COLOR_ATTACHMENT1,第2个绑定到帧缓存对象的DEPTH_ATTACHMENT: ``` glGenRenderbuffers(3, RendBuf); glBindRenderbuffer(GL_RENDERBUFFER, RendBuf[0]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, 200, 200); glBindRenderbuffer(GL_RENDERBUFFER, RendBuf[1]); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 200, 200); glBindRenderbuffer(GL_RENDERBUFFER, RendBuf[2]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, 200, 200); ``` 设置绑定点: ``` glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, RendBuf[0]); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, RendBuf[1]); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, RendBuf[2]); ``` 然后在绘制到帧缓存对象中: ``` glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FrameBuf); glViewport(0, 0, 200, 200); GLenum bufs[2] = { GL_COLOR_ATTACHMENT0 , GL_COLOR_ATTACHMENT1}; glDrawBuffers(2, bufs); glBindVertexArray(vert); glEnable(GL_DEPTH_TEST); glDrawArrays(GL_TRIANGLES, 0, 6); ``` 再将缓存中的数据写入显示窗口的缓存: ``` glBindFramebuffer(GL_READ_FRAMEBUFFER, FrameBuf); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glViewport(0, 0, 400, 400); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glReadBuffer(GL_COLOR_ATTACHMENT0); glBlitFramebuffer(0, 0, 200, 200, 0, 0, 200, 200, GL_COLOR_BUFFER_BIT, GL_NEAREST); glReadBuffer(GL_COLOR_ATTACHMENT1); glBlitFramebuffer(0, 0, 200, 200, 200, 0, 400, 200, GL_COLOR_BUFFER_BIT, GL_NEAREST); ``` 这是三角形的数据: ``` Vertex Verts[9] = { //第一个大三角形,三个顶点颜色分别为RGB,前四个float为颜色,后三个float为位置 { { 255,0,0,255 },{ 0.0f, 0.9f, 0.0f } }, { { 0,255,0,255 },{ -0.9f, -0.9f, 0.0f } }, { { 0,0,255,255 },{ 0.9f, -0.9f, 0.0f } } , //第二个小三角形,三个顶点颜色为白色 { { 255,255,255,255 },{ 0.0f, 0.8f, -0.2f } } , { { 255,255,255,255 },{ -0.4f, 0.0f, -0.2f } } , { { 255,255,255,255 },{ 0.4f, 0.0f, -0.2f } } }; ``` 以上就是画了两个小三角形,attachment0的在左下角,attachment1的在右下角。按理来说只调用了一次glDrawArrays(),两个三角形应该是一样的,但是真实的图片显示并不一样。这是为什么呢? ![图片说明](https://img-ask.csdn.net/upload/201911/28/1574911083_510881.png)
Opengl中ProcessMouseScroll(GLfloat yOffset)函数不起作用
鼠标滚轮不起作用,不会报错,不知道是怎么回事 主函数如下: ``` #include <iostream> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Shader.h" #include "Camera.h" #include "Light.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mode); void MouseCallback(GLFWwindow *window, double xPos, double yPos); void ScrollCallback(GLFWwindow *window, double xOffset, double yOffset); void DoMovement(); bool keys[1024]; const GLint WIDTH = 800, HEIGHT = 600; Camera camera(glm::vec3(0.0f, 0.0f, 2.0f)); GLfloat deltaTime = 0.0f; GLfloat lastTime = 0.0f; GLfloat lastX = WIDTH / 2; GLfloat lastY = HEIGHT / 2; bool firstMouse = true; glm::vec3 lightPos = glm::vec3(0.0f, 0.0f, 0.0f); int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow * window = glfwCreateWindow(WIDTH, HEIGHT, "w11", nullptr, nullptr); if (nullptr == window) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, KeyCallback); glfwSetCursorPosCallback(window, MouseCallback); glfwSetScrollCallback(window, ScrollCallback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); int screenWidth, screenHeight; glfwGetFramebufferSize(window, &screenWidth, &screenHeight); glewExperimental = GL_TRUE; if (GLEW_OK != glewInit()) { std::cout << "Failed to initialise GLEW" << std::endl; glfwTerminate(); return -1; } Shader lightShader = Shader("res/shaders/light.vs", "res/shaders/light.frag"); Light lightModel = Light(); Shader shader = Shader("res/shaders/core.vs", "res/shaders/core.frag"); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); GLfloat vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; GLuint VAO, VBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); // transfer the data glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // set the attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid *)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid *)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glm::mat4 view = glm::mat4(1.0f); //glm::mat4 projection = glm::perspective(glm::radians(camera.GetZoom()), static_cast<GLfloat>(screenWidth) / static_cast<GLfloat>(screenHeight), 0.1f, 1000.0f); glm::mat4 projection = glm::perspective(camera.GetZoom(), (float)screenWidth / (float)screenHeight, 0.1f, 100.0f); while (!glfwWindowShouldClose(window)) { GLfloat currentTime = glfwGetTime(); deltaTime = currentTime - lastTime; lastTime = currentTime; glfwPollEvents(); DoMovement(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, screenWidth, screenHeight); view = camera.GetViewMatrix(); glm::mat4 transform = glm::mat4(1.0f); lightShader.Use(); lightPos = glm::vec3(20.0f, 0.0f, 0.0f); lightPos = glm::rotate(lightPos, glm::radians(20.0f)*static_cast<GLfloat>(glfwGetTime()), glm::vec3(1.0f, 1.0f, 1.0f)); transform = glm::scale(transform, glm::vec3(0.1f, 0.1f, 0.1f)); transform = glm::translate(transform, lightPos); glUniformMatrix4fv(glGetUniformLocation(lightShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(transform)); glUniformMatrix4fv(glGetUniformLocation(lightShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(lightShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); lightModel.Draw(lightShader); shader.Use(); transform = glm::mat4(1.0f); transform = glm::scale(transform, glm::vec3(0.4f, 0.4f, 0.4f)); GLuint transLoc = glGetUniformLocation(shader.Program, "model"); glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(transform)); GLuint viewLoc = glGetUniformLocation(shader.Program, "view"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); GLuint projLoc = glGetUniformLocation(shader.Program, "projection"); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); glUniform3f(glGetUniformLocation(shader.Program, "LightPos"), lightPos.x, lightPos.y, lightPos.z); glUniform3f(glGetUniformLocation(shader.Program, "ViewPos"), camera.GetPosition().x, camera.GetPosition().y, camera.GetPosition().z); glUniform1f(glGetUniformLocation(shader.Program, "p"), 64.0f); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glfwSwapBuffers(window); } glfwTerminate(); return 0; } void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } if (key >= 0 & key < 1024) { if (action == GLFW_PRESS) { keys[key] = true; } else if (action == GLFW_RELEASE) { keys[key] = false; } } } void DoMovement() { if (keys[GLFW_KEY_W] || keys[GLFW_KEY_UP]) { camera.ProcessKeyboard(FORWARD, deltaTime); } if (keys[GLFW_KEY_S] || keys[GLFW_KEY_DOWN]) { camera.ProcessKeyboard(BACKWARD, deltaTime); } if (keys[GLFW_KEY_A] || keys[GLFW_KEY_LEFT]) { camera.ProcessKeyboard(LEFT, deltaTime); } if (keys[GLFW_KEY_D] || keys[GLFW_KEY_RIGHT]) { camera.ProcessKeyboard(RIGHT, deltaTime); } } void MouseCallback(GLFWwindow *window, double xPos, double yPos) { if (firstMouse) { lastX = xPos; lastY = yPos; firstMouse = false; } GLfloat xOffset = xPos - lastX; GLfloat yOffset = yPos - lastY; lastX = xPos; lastY = yPos; camera.ProcessMouseMovement(xOffset, yOffset); } void ScrollCallback(GLFWwindow* window, double xOffset, double yOffset) { camera.ProcessMouseScroll(yOffset); } ``` Camera.h如下: ``` #pragma once #define GLEW_STATIC #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <vector> enum Camera_Movement { FORWARD, BACKWARD, LEFT, RIGHT }; const GLfloat YAW = -90.0f; const GLfloat PITCH = 0.0f; const GLfloat SPEED = 6.0f; const GLfloat SENSITIVITY = 0.25f; const GLfloat ZOOM = 45.0f; class Camera { public: Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = YAW, GLfloat pitch = PITCH) :front(glm::vec3(0.0f, 0.0f, -1.0f)), movementSpeed(SPEED), mouseSensitivity(SENSITIVITY), zoom(ZOOM) { this->position = position; this->worldUp = up; this->yaw = yaw; this->pitch = pitch; this->updateCameraVectors(); } Camera(GLfloat posX, GLfloat posY, GLfloat posZ, GLfloat upX, GLfloat upY, GLfloat upZ, GLfloat yaw = YAW, GLfloat pitch = PITCH) :front(glm::vec3(0.0f, 0.0f, -1.0f)), movementSpeed(SPEED), mouseSensitivity(SENSITIVITY), zoom(ZOOM) { this->position = glm::vec3(posX, posY, posZ); this->worldUp = glm::vec3(upX, upY, upZ); this->yaw = yaw; this->pitch = pitch; this->updateCameraVectors(); } void ProcessKeyboard(Camera_Movement direction, GLfloat deltaTime) { GLfloat velocity = this->movementSpeed * deltaTime; if (direction == FORWARD) { this->position += this->front * velocity; } if (direction == BACKWARD) { this->position -= this->front * velocity; } if (direction == LEFT) { this->position -= this->right * velocity; } if (direction == RIGHT) { this->position += this->right * velocity; } } void ProcessMouseMovement(GLfloat xOffset, GLfloat yOffset, GLboolean constrainPitch = true) { xOffset *= this->mouseSensitivity; yOffset *= this->mouseSensitivity; this->yaw += xOffset; this->pitch -= yOffset; if (constrainPitch) { if (this->pitch > 89.0f) { this->pitch = 89.0f; } if (this->pitch < -89.0f) { this->pitch = -89.0f; } } updateCameraVectors(); } glm::mat4 GetViewMatrix() { return glm::lookAt(this->position, this->position + this->front, this->up); } void ProcessMouseScroll(GLfloat yOffset) { if (this->zoom >= 1.0f && this->zoom <= 45.0f) { this->zoom -= yOffset ; } if (this->zoom <= 1.0f) { this->zoom = 1.0f; } if (this->zoom >= 45.0f) { this->zoom = 45.0f; } } GLfloat GetZoom() { return this->zoom; } glm::vec3 GetPosition() { return this->position; } private: glm::vec3 position; glm::vec3 front; glm::vec3 up; glm::vec3 right; glm::vec3 worldUp; GLfloat yaw; GLfloat pitch; GLfloat movementSpeed; GLfloat mouseSensitivity; GLfloat zoom; void updateCameraVectors() { glm::vec3 front; front.x = cos(glm::radians(this->pitch))*cos(glm::radians(this->yaw)); front.y = sin(glm::radians(this->pitch)); front.z = cos(glm::radians(this->pitch))*sin(glm::radians(this->yaw)); this->front = glm::normalize(front); this->right = glm::normalize(glm::cross(this->front, this->worldUp)); this->up = glm::normalize(glm::cross(this->right, this->front)); } }; ``` 求大佬讲解
opengl +qt 显示图像 和 文本 纹理贴图 显示文本
1.利用opengl对图片进行显示,点击图片画出一个角度,角度的线可以显示,但是角度的数字没有显示。我把文本的代码单独放到控制台显示,显示是正常的,所以推断可能是图片的纹理 对文本的显示造成了干扰,哪些代码影响到了。 ![图片说明](https://img-ask.csdn.net/upload/201906/20/1561032261_180148.jpg) 具体代码如下: 1> 图像关键代码: QImage GlImage = mpCurQImg->convertToFormat(QImage::Format_RGBA8888); glGenTextures(TEXTURE_SIZE,&m_TextureIndex); glBindTexture(GL_TEXTURE_2D,m_TextureIndex); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, GlImage.width(), GlImage.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, GlImage.bits() ); glPushMatrix(); glBindTexture(GL_TEXTURE_2D,m_TextureIndex); glBegin( GL_QUADS ); glTexCoord2f( 0.0, 0.0 ); glVertex3f( pTextRect[0], pTextRect[2],0); glTexCoord2f( 1.0, 0.0 ); glVertex3f( pTextRect[1], pTextRect[2],0); glTexCoord2f( 1.0, 1.0 ); glVertex3f( pTextRect[1], pTextRect[3],0); glTexCoord2f( 0.0, 1.0 ); glVertex3f( pTextRect[0], pTextRect[3],0); glEnd(); glDisable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glPopMatrix(); ``` ``` 2>角度的数值显示代码: DrawStringInfo(QString * str,QPointF pt) glColor3f(1.0f, 0.0f, 0.0f); glDisable(GL_DEPTH_TEST); QByteArray ba = str->toLatin1(); const char*ch = "test"; glRasterPos2f(0.0f,0.0f);//测试放在中央 static int isFirstCall = 1; static GLuint lists; if (isFirstCall) { isFirstCall = 0; lists = glGenLists(MAX_CHAR); wglUseFontBitmaps(wglGetCurrentDC(), 0, MAX_CHAR, lists); } for (; *ch != '\0'; ++ch) { glCallList(lists + *ch); } glEnable(GL_DEPTH_TEST);
OpenGL glut为什么显示不出来正方形?
#define GLUT_DISABLE_ATEXIT_HACK #include<gl/glut.h> void init() { // glClear(GL_COLOR_BUFFER_BIT); glClearColor(1.0f,.0.0f,0.0f,1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void Display() { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glutWireCube(5.0); glFlush(); } int main(int argc,char*argv[]) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowPosition(0,0); glutInitWindowSize(400,400); glutCreateWindow("global"); init(); glutDisplayFunc(Display); glutMainLoop(); }
OpenGL 默认的Z轴方向问题
OpenGL默认的Z坐标轴的方向是垂直窗口向外的,以前用C语言开发OpenGL程序时一直没有出现问题。现在我用C#开发OpenGL程序,却发现默认的Z轴方向是垂直窗口向内,真的搞不懂怎么回事。我没有使用模型变换和投影变换,仅仅是是在窗口绘制两个简单的图形,发现Z坐标为负的图形可以看得见,而Z坐标为正的图形却被覆盖。已经开启了深度测试。代码如下: ``` void Draw() { GL.glEnable(GLCONST.GL_DEPTH_TEST); GL.glClear(GLCONST.GL_COLOR_BUFFER_BIT); GL.glClear(GLCONST.GL_DEPTH_BUFFER_BIT); //红色的三角形,Z=0; GL.glBegin(GLCONST.GL_TRIANGLES); GL.glColor3(1f, 0f, 0f); GL.glVertex3(-0.5f, -0.5f,0f); GL.glVertex3(0.5f, -0.5f,0f); GL.glVertex3(0f, 0.5f,0f); GL.glEnd(); //绿色的直线,Z=-0.5 GL.glColor3(0f, 1f, 0f); GL.glBegin(GLCONST.GL_LINES); GL.glVertex3(-0.8f, 0f, -0.5f); GL.glVertex3(0.8f, 0f, -0.5f); GL.glEnd(); //蓝色的直线,Z=0.5 GL.glColor3(0f, 0f, 1f); GL.glBegin(GLCONST.GL_LINES); GL.glVertex3(0f, 0.8f, 0.5f); GL.glVertex3(0f, -0.8f, 0.5f); GL.glEnd(); GL.glFlush(); } ``` 绘制时,发现红色的三角形(Z=0)会把蓝色的直线(Z=0.5)掩盖,而绿色的直线(Z=-0.5)浮在三角形之上。效果如下图: ![图片说明](https://img-ask.csdn.net/upload/201712/28/1514439525_203737.jpg) 这种问题,似乎有不少人遇到,但都没有的到很好的解决。特此悬赏160金币,希望有人能解决。只要提供解决的方法,或者给予启示,或者提供线索都可以获得悬赏。
opengl抗锯齿没有效果怎么回事?
我测试了一下opengl的抗锯齿功能, 但是发现开启抗锯齿功能前后锯齿还是很重,没有变化,请高手指点. (开发平台win8 64bit, 开发工具vs2012) 下面是代码, 只是画了一条线. #include "stdafx.h" #include <GL/glut.h> void myDisplay(void) { glEnable(GL_DEPTH_TEST); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT,GL_NICEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLineWidth(2); glColor3d(0,1,0); glBegin(GL_LINES); glVertex2d(0.0,0.0); glVertex2d(0.4,0.05); glEnd(); glFlush(); glutSwapBuffers(); } void myReshape(int w, int h){ glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w>h) glOrtho(-0.5*(float)w/h,0.5*(float)w/h,-0.5,0.5,100,-100); else glOrtho(-0.5,0.5,-0.5*(float)h/w,0.5*(float)h/w,100,-100); glMatrixMode(GL_MODELVIEW); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowPosition(100, 100); glutInitWindowSize(500, 500); glutCreateWindow("锯齿测试"); glutDisplayFunc(&myDisplay); glutReshapeFunc(&myReshape); glutMainLoop(); return 0; }
OpenGL中的图片打不开
我在学习NeHe教程,用的是vs2010,纹理时加载不进去,调试时这段代码直接就跳过了,文件加载不进去 if (File) // Does The File Exist? { fclose(File); // Close The Handle return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer } 各位大神求解答 /* * This Code Was Created By Jeff Molofee 2000 * A HUGE Thanks To Fredric Echols For Cleaning Up * And Optimizing The Base Code, Making It More Flexible! * If You've Found This Code Useful, Please Let Me Know. * Visit My Site At nehe.gamedev.net */ #define _CRT_SECURE_NO_WARNINGS #include <windows.h> // Header File For Windows #include <stdio.h> // Header File For Standard Input/Output #include <gl\gl.h> // Header File For The OpenGL32 Library #include <gl\glu.h> // Header File For The GLu32 Library #include <gl\glaux.h> // Header File For The Glaux Library HDC hDC=NULL; // Private GDI Device Context HGLRC hRC=NULL; // Permanent Rendering Context HWND hWnd=NULL; // Holds Our Window Handle HINSTANCE hInstance; // Holds The Instance Of The Application bool keys[256]; // Array Used For The Keyboard Routine bool active=TRUE; // Window Active Flag Set To TRUE By Default bool fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default bool texLoaded = false; GLfloat xrot; // X Rotation ( NEW ) GLfloat yrot; // Y Rotation ( NEW ) GLfloat zrot; // Z Rotation ( NEW ) GLuint texture[1]; // Storage For One Texture ( NEW ) LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc AUX_RGBImageRec *LoadBMP(char *Filename) // Loads A Bitmap Image { FILE *File=NULL; // File Handle if (!Filename) // Make Sure A Filename Was Given { return NULL; // If Not Return NULL } File=fopen(Filename,"r"); // Check To See If The File Exists if (File) // Does The File Exist? { fclose(File); // Close The Handle return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer } return NULL; // If Load Failed Return NULL } int LoadGLTextures() // Load Bitmaps And Convert To Textures { int Status=FALSE; // Status Indicator AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture memset(TextureImage,0,sizeof(void *)*1); // Set The Pointer To NULL // Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit if (TextureImage[0]=LoadBMP("Data\NeHe.bmp")) { Status=TRUE; // Set The Status To TRUE glGenTextures(1, &texture[0]); // Create The Texture // Typical Texture Generation Using Data From The Bitmap glBindTexture(GL_TEXTURE_2D, texture[0]); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); } if (TextureImage[0]) // If Texture Exists { if (TextureImage[0]->data) // If Texture Image Exists { free(TextureImage[0]->data); // Free The Texture Image Memory } free(TextureImage[0]); // Free The Image Structure } return Status; // Return The Status } GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window { if (height==0) // Prevent A Divide By Zero By { height=1; // Making Height Equal One } glViewport(0,0,width,height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } int InitGL(GLvoid) // All Setup For OpenGL Goes Here { if (!LoadGLTextures()) // Jump To Texture Loading Routine ( NEW ) { return FALSE; // If Texture Didn't Load Return FALSE } glEnable(GL_TEXTURE_2D); // Enable Texture Mapping ( NEW ) glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations return TRUE; // Initialization Went OK } int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer glLoadIdentity(); // Reset The View glTranslatef(0.0f,0.0f,-5.0f); glRotatef(xrot,1.0f,0.0f,0.0f); glRotatef(yrot,0.0f,1.0f,0.0f); glRotatef(zrot,0.0f,0.0f,1.0f); glBegin(GL_QUADS); // Front Face glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Top Face glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Bottom Face glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Right face glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Left Face glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); xrot+=0.3f; yrot+=0.2f; zrot+=0.4f; return TRUE; // Keep Going } GLvoid KillGLWindow(GLvoid) // Properly Kill The Window { if (fullscreen) // Are We In Fullscreen Mode? { ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop ShowCursor(TRUE); // Show Mouse Pointer } if (hRC) // Do We Have A Rendering Context? { if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts? { MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC? { MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } hRC=NULL; // Set RC To NULL } if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC { MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hDC=NULL; // Set DC To NULL } if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window? { MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hWnd=NULL; // Set hWnd To NULL } if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class { MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hInstance=NULL; // Set hInstance To NULL } } /* This Code Creates Our OpenGL Window. Parameters Are: * * title - Title To Appear At The Top Of The Window * * width - Width Of The GL Window Or Fullscreen Mode * * height - Height Of The GL Window Or Fullscreen Mode * * bits - Number Of Bits To Use For Color (8/16/24/32) * * fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */ BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Set Left Value To 0 WindowRect.right=(long)width; // Set Right Value To Requested Width WindowRect.top=(long)0; // Set Top Value To 0 WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height fullscreen=fullscreenflag; // Set The Global Fullscreen Flag hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName ="OpenGL"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; // Return FALSE } } } if (fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style ShowCursor(FALSE); // Hide Mouse Pointer } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "OpenGL", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { KillGLWindow(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format bits, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(hWnd,SW_SHOW); // Show The Window SetForegroundWindow(hWnd); // Slightly Higher Priority SetFocus(hWnd); // Sets Keyboard Focus To The Window ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success } LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_ACTIVATE: // Watch For Window Activate Message { if (!HIWORD(wParam)) // Check Minimization State { active=TRUE; // Program Is Active } else { active=FALSE; // Program Is No Longer Active } return 0; // Return To The Message Loop } case WM_SYSCOMMAND: // Intercept System Commands { switch (wParam) // Check System Calls { case SC_SCREENSAVE: // Screensaver Trying To Start? case SC_MONITORPOWER: // Monitor Trying To Enter Powersave? return 0; // Prevent From Happening } break; // Exit } case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = TRUE; // If So, Mark It As TRUE return 0; // Jump Back } case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = FALSE; // If So, Mark It As FALSE return 0; // Jump Back } case WM_SIZE: // Resize The OpenGL Window { ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); } int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("NeHe's Texture Mapping Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("NeHe's Texture Mapping Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
关于opengl帧缓存对象FBO深度缓存的问题
各位老师好,在下opengl菜鸟一枚,最近学习opengl和glsl的过程中,使用FBO的深度缓存做延时渲染的时候遇到了一些问题。 我想实现个shadowmap,在光源视角下将深度缓存渲染进fbo,但是渲染第一次结束后,附加到fbo中的深度纹理里面的值却全部都为0。后来为了测试问题,我删除掉了第二个shader,只保留了第一个用来产生shadowmap的shader,发现fbo深度缓存依然都是0。如能指教迷津,不胜感激。一下是我的代码: main函数 ``` #include <stdio.h> #include "Declaration.h" #include "LoadShaders.h" #include <gl/glew.h> #include <gl/freeglut.h> #include "cv.h" #include "highgui.h" #include "cxcore.h" #include "StructDef.h" GLuint *FBOUsedVAOs; GLuint *FBOUsedBuffers; GLuint *programs; GLuint *FBOs; GLuint *DepthTextureIDs; void init() { DepthTextureIDs = (GLuint*)malloc(sizeof(GLuint));//申请深度纹理对象ID的内存 glGenTextures(1, DepthTextureIDs);//产生深度纹理ID glBindTexture(GL_TEXTURE_2D, DepthTextureIDs[0]);//绑定深度纹理ID //设置纹理参数 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 512, 512, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glBindTexture(GL_TEXTURE_2D, 0);//解绑纹理ID FBOs = (GLuint*)malloc(sizeof(GLuint));//申请帧缓存对象的内存 glGenFramebuffers(1,FBOs);//产生帧缓存对象 glBindFramebuffer(GL_FRAMEBUFFER, FBOs[0]);//绑定帧缓存对象 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, DepthTextureIDs[0], 0); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0);//解绑帧缓存对象 programs = (GLuint*)malloc(sizeof(GLuint));//申请着色程序内存 ShaderInfo FBOShader[3] = { //用于渲染shadowmap的着色器 { GL_VERTEX_SHADER, "FBOShader.vert" }, { GL_FRAGMENT_SHADER, "FBOShader.frag" }, { GL_NONE, NULL } }; programs[0] = LoadShaders(FBOShader); //加载着色器 //计算各种坐标转换矩阵 float ModelMat[16]; float ViewMat[16]; float PerspectiveProjectMat[16]; float MAngle321[3] = {0, 0, 0.0}; float MOffset[3] = {0.0, 0.0, 0.0}; float VAngle321[3] = {0, 1.57, 0.0}; float VOffset[3] = {0, 0, 5.0}; float FOV = 1.57; float Aspect = 1; float NearDist = 1.0; float FarDist = 6; ModelMatCal(ModelMat, MAngle321, MOffset); ViewMatCal(ViewMat, VAngle321, VOffset); PerspectiveProjectMatCal(PerspectiveProjectMat, FOV, Aspect, NearDist, FarDist); float MVMat[16]; float MVPMat[16]; MatMultiplyMat4(MVMat, ViewMat, ModelMat); MatMultiplyMat4(MVPMat, PerspectiveProjectMat, MVMat); //将矩阵传递进FBOShader glUseProgram(programs[0]);//必须放在向shader中传Uniform数据的前面 GLint MVPMatLoc; MVPMatLoc = glGetUniformLocation(programs[0],"MVPMat"); glUniformMatrix4fv(MVPMatLoc, 1, GL_FALSE, MVPMat); //设置顶点数组 #define BUFFER_OFFSET(offset) ((void *)(NULL+offset)) FBOUsedVAOs = (GLuint*)malloc(sizeof(GLuint)); FBOUsedBuffers = (GLuint*)malloc(sizeof(GLuint)); glGenVertexArrays(1, FBOUsedVAOs); glGenBuffers(1, FBOUsedBuffers); float FBOUsedVertices[24]= { 1.0f, 1.0f, 3.0f, 1.0f, -1.0f, 1.0f, 3.0f, 1.0f, -1.0f, -1.0f, 3.0f, 1.0f, 1.0f, 1.0f, 3.0f, 1.0f, -1.0f, -1.0f, 3.0f, 1.0f, 1.0f, -1.0f, 3.0f, 1.0f }; glBindVertexArray(FBOUsedVAOs[0]); glBindBuffer(GL_ARRAY_BUFFER, FBOUsedBuffers[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(FBOUsedVertices), FBOUsedVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); glEnableVertexAttribArray(0); } void display() { //向帧缓存对象中渲染数据 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindFramebuffer(GL_FRAMEBUFFER, FBOs[0]);//绑定帧缓存对象 glUseProgram(programs[0]);//选定shader glBindVertexArray(FBOUsedVAOs[0]); glDrawArrays(GL_TRIANGLES, 0, 6); float *DepthPixel = (float *)malloc(sizeof(float)); glReadPixels(256,256,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,DepthPixel); glBindFramebuffer(GL_FRAMEBUFFER, 0); glFlush(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA); glutInitWindowSize(512, 512); glutInitContextVersion(4, 3); glutInitContextProfile(GLUT_CORE_PROFILE); glutCreateWindow(argv[0]); glewExperimental = GL_TRUE; if (glewInit()) { cerr << "Unable to initialize GLEW ... exiting" << endl; exit(1); } glEnable(GL_TEXTURE_CUBE_MAP); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); init(); glutDisplayFunc(display); glutMainLoop(); } ``` 顶点着色器 ``` #version 430 layout(location = 0)in vec4 VertPosition; uniform mat4 MVPMat; void main() { gl_Position = MVPMat * VertPosition; } ``` 片元着色器 ``` #version 430 out vec4 FragColor; void main() { FragColor = vec4(vec3(gl_FragCoord.z), 1.0f); } ``` 将display函数中的glBindFramebuffer(GL_FRAMEBUFFER, FBOs[0])注释掉,就能够在DepthPixel中看到正确的深度结果,但是只要绑定了fbo,其深度结果就全都是0.也就是说,在屏渲染的时候,我能够获取到正确的深度值,但是离屏渲染的时候,深度值总是0.
请问如何将OpenGL中的纹理单元传递给片段着色器???
小白我最近在学习GLSL,绝对的菜鸟级别啊~ 今天遇到了一个问题,我用 *texture[1]* 在程序中存储了一个纹理,然后使用了下面两行代码将纹理传递给片段着色器,程序是可以运行的 *texUnitLoc = glGetUniformLocation(p, "tex"); glUniform1i(texUnitLoc, 0);* 但是当我在程序中存储两个纹理以后,想要将两个纹理都传递到着色器时,应该怎么办啊??将上面代码中的‘0’换做‘texture[0]’也不管用啊,什么都不管用啊,glUniform究竟是怎么一回事啊?求大神指点~~T_T 附代码如下: #include <stdio.h> #include <stdlib.h> #include <GL/glew.h> #include <GL/glut.h> #include <glaux.h> #include "textfile.h" #include "printInfoLog.h" GLfloat LightAmbient0[]= {1, 1, 1, 1.0f }; GLfloat LightDiffuse0[]= {1.0f, 1.0f, 1.0f, 1.0f }; GLfloat LightSpecular0[]={1.0f, 1.0f, 1.0f, 1.0f}; GLfloat LightPosition0[]= {3.0f, 3.0f, 3.0f, 0.0f }; GLfloat MaterialAmbient[] = {0.3, 0.3, 0.3, 1.0f}; GLfloat MaterialDiffuse[] = {0.7, 0.7, 0.7, 1.0f}; GLfloat MaterialSpecular[] ={0.3, 0.3, 0.3, 1.0f}; GLfloat MaterialSe = 64.0f; GLUquadricObj *quadratic; GLuint texture[2]; // 存储一个纹理 GLint texUnitLoc,l3dUnitLoc; float a = 0.0f; GLuint v,f,p; float t = 0; GLint loc; AUX_RGBImageRec *LoadBMP(char *Filename) // 载入位图图象 { FILE *File=NULL; // 文件句柄 if (!Filename) // 确保文件名已提供 { return NULL; // 如果没提供,返回 NULL } File=fopen(Filename,"r"); // 尝试打开文件 if (File) // 文件存在么? { fclose(File); // 关闭句柄 return auxDIBImageLoad(Filename);// 载入位图并返回指针 } return NULL; // 如果载入失败,返回 NULL } int LoadGLTextures() // 载入位图(调用上面的代码)并转换成纹理 { int Status=FALSE; // 状态指示器 AUX_RGBImageRec *TextureImage[2]; // 创建纹理的存储空间 memset(TextureImage,0,sizeof(void *)*1); // 将指针设为 NULL // 载入位图,检查有无错误,如果位图没找到则退出 if (TextureImage[0]=LoadBMP("Data/Crate.bmp")) { Status=TRUE; // 将 Status 设为 TRUE glGenTextures(1, &texture[0]); // 创建纹理 // 创建 MipMapped 纹理 glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); } if (TextureImage[0]) // 纹理是否存在 { if (TextureImage[0]->data) // 纹理图像是否存在 { free(TextureImage[0]->data); // 释放纹理图像占用的内存 } free(TextureImage[0]); // 释放图像结构 } if (TextureImage[1]=LoadBMP("Data/1.bmp")) { Status=TRUE; // 将 Status 设为 TRUE glGenTextures(1, &texture[1]); // 创建纹理 // 创建 MipMapped 纹理 glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[1]->sizeX, TextureImage[1]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[1]->data); } if (TextureImage[1]) // 纹理是否存在 { if (TextureImage[1]->data) // 纹理图像是否存在 { free(TextureImage[1]->data); // 释放纹理图像占用的内存 } free(TextureImage[1]); // 释放图像结构 } return Status; // 返回 Status } void changeSize(int w, int h) { float ratio = 1.0* w / h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); gluPerspective(45,ratio,1,100); glMatrixMode(GL_MODELVIEW); } void init() { glEnable(GL_DEPTH_TEST); glClearColor(0.0,0.0,0.0,0.0); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbient0); glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse0); glLightfv(GL_LIGHT0,GL_SPECULAR, LightSpecular0); glLightfv(GL_LIGHT0, GL_POSITION, LightPosition0); glEnable(GL_LIGHT0); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, MaterialAmbient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialDiffuse); glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR, MaterialSpecular); glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS, MaterialSe); quadratic=gluNewQuadric(); gluQuadricNormals(quadratic, GLU_SMOOTH); gluQuadricTexture(quadratic, GL_TRUE); LoadGLTextures(); // 调用纹理载入子例程 glEnable(GL_TEXTURE_2D); // 启用纹理映射 } void renderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(0.0,0.0,5.0, 0.0,0.0,-1.0, 0.0f,1.0f,0.0f); a += 0.35f; if(a > 360) a -= 360.0f; glRotatef(a, 0, 1, 0); glRotatef(0, 1, 0, 0); //glBindTexture(GL_TEXTURE_2D, texture[0]); gluSphere(quadratic, 1, 32, 16); t+=0.01; glutPostRedisplay(); glutSwapBuffers(); } int main(int argc, char **argv) { void setShaders(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutCreateWindow("GLSL DEMO"); init(); glutDisplayFunc(renderScene); glutReshapeFunc(changeSize); glewInit(); if (glewIsSupported("GL_VERSION_2_0")) printf("Ready for OpenGL 2.0\n"); else { printf("OpenGL 2.0 not supported\n"); exit(1); } setShaders(); texUnitLoc = glGetUniformLocation(p, "tex"); glUniform1i(texUnitLoc, 0); //l3dUnitLoc = glGetUniformLocation(p, "l3d"); //glUniform1i(l3dUnitLoc, texture[1]); glutMainLoop(); return 0; } void setShaders() { char *vs = NULL,*fs = NULL,*fs2 = NULL; v = glCreateShader(GL_VERTEX_SHADER); f = glCreateShader(GL_FRAGMENT_SHADER); vs = textFileRead("vs.txt"); fs = textFileRead("fs.txt"); const char * vv = vs; const char * ff = fs; glShaderSource(v, 1, &vv,NULL); glShaderSource(f, 1, &ff,NULL); free(vs);free(fs); glCompileShader(v); glCompileShader(f); printShaderInfoLog(v); printShaderInfoLog(f); p = glCreateProgram(); glAttachShader(p,v); glAttachShader(p,f); glLinkProgram(p); printProgramInfoLog(p); glUseProgram(p); //将p改为0表示使用固定的管线 }
opengl字符纹理的问题
为甚么使用下面的函数制作的字符纹理显示不了 #define FONT_SIZE 64 #define TEXTURE_SIZE FONT_SIZE GLuint drawChar_To_Texture(const char* s) { wchar_t w; HDC hDC = wglGetCurrentDC(); // 选择字体字号、颜色 // 不指定字体名字,操作系统提供默认字体 // 设置颜色为白色 selectFont(FONT_SIZE, DEFAULT_CHARSET, ""); glColor3f(1.0f, 1.0f, 1.0f); // 转化为宽字符 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, s, 2, &w, 1); // 计算绘制的位置 { int width, x, y; GetCharWidth32W(hDC, w, w, &width); // 取得字符的宽度 x = (TEXTURE_SIZE - width) / 2; y = FONT_SIZE / 8; glWindowPos2iARB(x, y); // 一个扩展函数 } // 绘制字符 // 绘制前应该将各种可能影响字符颜色的效果关闭 // 以保证能够绘制出白色的字符 { GLuint list = glGenLists(1); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glDisable(GL_FOG); glDisable(GL_TEXTURE_2D); wglUseFontBitmaps(hDC, w, 1, list); glCallList(list); glDeleteLists(list, 1); } // 复制字符像素到纹理 // 注意纹理的格式 // 不使用通常的GL_RGBA,而使用GL_LUMINANCE4 // 因为字符本来只有一种颜色,使用GL_RGBA浪费了存储空间 // GL_RGBA可能占16位或者32位,而GL_LUMINANCE4只占4位 { GLuint texID; glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_2D, texID); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE4, 0, 0, TEXTURE_SIZE, TEXTURE_SIZE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); return texID; } }
绘制有限元中的六面体单元,使用opengl,遮挡关系出现问题
void polygon(GLfloat *a, GLfloat *b, GLfloat *c, GLfloat *d) { glBegin(GL_POLYGON); glVertex3fv(a); glVertex3fv(b); glVertex3fv(c); glVertex3fv(d); glEnd(); } void cube(struct Data_Link d_p) { double *pNodxy = d_p.pNodxy; int *pEle=d_p.pEle; int Ne = d_p.Ne;int Nn = d_p.Nn; int i,j,k=0; GLfloat (*pN)[3] = (GLfloat(*)[3])malloc(3 * Nn * sizeof(GLfloat));//将节点坐标导入二维数组 GLint(*pE)[8] = (GLint(*)[8])malloc( 8 * Ne * sizeof(GLint)); for (i = 0;i < Nn;i++) { for (j = 0;j < 3;j++) { pN[i][j] =pNodxy[k]; k++; } } k = 0; for (i = 0;i < Ne;i++) { for (j = 0;j < 8;j++) { if (k % 9 != 0) { pE[i][j] = pEle[k];printf("%d\t", pEle[k]); k++; } else { k++; j--; } } } for(i=0;i<Ne;i++) { polygon(pN[pE[i][0]], pN[pE[i][3]], pN[pE[i][2]], pN[pE[i][1]]); polygon(pN[pE[i][2]], pN[pE[i][3]], pN[pE[i][7]], pN[pE[i][6]]); polygon(pN[pE[i][3]], pN[pE[i][0]], pN[pE[i][4]], pN[pE[i][7]]); polygon(pN[pE[i][1]], pN[pE[i][2]], pN[pE[i][6]], pN[pE[i][5]]); polygon(pN[pE[i][4]], pN[pE[i][5]], pN[pE[i][6]], pN[pE[i][7]]); polygon(pN[pE[i][5]], pN[pE[i][4]], pN[pE[i][0]], pN[pE[i][1]]); } } void display() { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(1, 1, 1, 0, 0, 0, 0, 1, 0); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); cube(m_data_link); glutSwapBuffers(); } void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-4, 4, -4, 4, -4, 4); } void init() { glClearColor(1, 1, 1, 1); glClearDepth(1); glColor3f(1, 0, 0); glEnable(GL_DEPTH_TEST); } int main(int argc, char**argv) { struct Data_Link_KgFg m_KF; FEM_Link_Read("FEM_TEST.txt", &m_data_link); FEM_Link_Print(m_data_link); getchar(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(800, 600); glutInitWindowPosition(0, 0); glutCreateWindow("FEM_TEST"); glutReshapeFunc(reshape); glutDisplayFunc(display); init(); glutMainLoop(); } 这段代码时为了绘制有限元中的六面体单元,已经省略了数据读取的代码。各端点的坐标存储在pN[]数组中,经过一个六面体接一个六面体的循环绘制,已经实现了所有六面体的绘制,并且设置了背面不显示。且已开启深度缓存和深度测试,但是并没有起到作用,不知道是什么状况,求大神指点迷津!!!![图片说明](https://img-ask.csdn.net/upload/201703/06/1488814743_463373.png) 运行后如上图所示
opengl VBO(vertex buffer object), 在线等
初学opengl,代码如下,不知哪里出了问题,没有办法显示正方体,一片空白。 // myFirstOpengl.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <GLTools.h> #define FREEGLUT_STATIC #include <GL/glut.h> #include <GLFrustum.h> #include <GLShaderManager.h> extern GLfloat vertexData[8][3]; //顶点数据指针 extern GLubyte colorData[8][4]; //颜色指针 extern GLuint indexData[12][3]; //索引指针 GLuint BufferName[3]; //顶点缓存和索引缓存的数组id GLFrustum viewFrustum; GLShaderManager shaderManager; void SetupRC() { //glClearColor(0.0f, 0.0f, 0.75f, 1.0f); //设置背景颜色 glEnable(GL_DEPTH_TEST); printf("setupRc"); shaderManager.InitializeStockShaders(); } void ShutdownRC() { glGenBuffers(3, BufferName); glBindBuffer(GL_ARRAY_BUFFER, BufferName[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, BufferName[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(colorData), colorData, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[2]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData, GL_STATIC_DRAW); } void ChangeSize(int w, int h) { printf("changesize"); if(h == 0) h = 1; glViewport(0, 0, w, h); // set viewport to window dimensions viewFrustum.SetPerspective(35.0f, float(w)/float(h), 1.0f, 1000.0f); //angle, w/h, near, far } void SpecialKeys(int key, int x, int y) { } void RenderScene() { printf("render"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glBindBuffer(GL_ARRAY_BUFFER, BufferName[0]); //glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glVertexPointer(3, GL_FLOAT, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, BufferName[1]); //glBufferData(GL_ARRAY_BUFFER, sizeof(colorData), colorData, GL_STATIC_DRAW); glColorPointer(4, GL_FLOAT, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[2]); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData, GL_STATIC_DRAW); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, 0); //glDisableClientState(GL_VERTEX_ARRAY); } int main(int argc, char* argv[]) { gltSetWorkingDirectory(argv[0]); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA |GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(800, 600); glutCreateWindow("My first Opengl Example"); glutReshapeFunc(ChangeSize);//原型函数 glutSpecialFunc(SpecialKeys);//原型函数 glutDisplayFunc(RenderScene); GLenum err = glewInit(); if(GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return 1; } SetupRC(); glutMainLoop(); ShutdownRC(); return 0; }
QT中加入gl开头的函数,没效果??? ??
代码如下: pro文件中已加QT += opengl 并且我是将glut32.lib与glut.lib放在了QT的lib目录下 #ifndef OPENGL_H #define OPENGL_H #include class OpenGL : public QDialog { Q_OBJECT public: OpenGL(QDialog *parent = 0); ~OpenGL(); protected: void paintGL(); void initializeGL( void ); }; #endif // OPENGL_H #include "opengl.h" #include OpenGL::OpenGL(QDialog *parent) : QDialog(parent) { setGeometry(100, 100, 500, 500); setWindowTitle(tr("wo men")); initializeGL(); paintGL(); } OpenGL::~OpenGL() { } void OpenGL::paintGL() { glClear(GL_COLOR_BUFFER_BIT); glClearColor(0, 1, 0, 0); glColor3f(1, 0, 0); glPointSize(50); glBegin(GL_POINTS); glVertex3f(0.5, 0.5, 0); glEnd(); glFlush(); } void OpenGL::initializeGL() { glShadeModel( GL_SMOOTH ); glClearColor( 0.0, 0.0, 0.0, 0.0 ); glClearDepth( 1.0 ); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); } 可以运行,但是现实空白
QT中加入gl开头的函数,没效果???
代码如下: pro文件中已加QT += opengl 并且我是将glut32.lib与glut.lib放在了QT的lib目录下 #ifndef OPENGL_H #define OPENGL_H #include <QDialog> class OpenGL : public QDialog { Q_OBJECT public: OpenGL(QDialog *parent = 0); ~OpenGL(); protected: void paintGL(); void initializeGL( void ); }; #endif // OPENGL_H #include "opengl.h" #include <gl/glut.h> OpenGL::OpenGL(QDialog *parent) : QDialog(parent) { setGeometry(100, 100, 500, 500); setWindowTitle(tr("wo men")); initializeGL(); paintGL(); } OpenGL::~OpenGL() { } void OpenGL::paintGL() { glClear(GL_COLOR_BUFFER_BIT); glClearColor(0, 1, 0, 0); glColor3f(1, 0, 0); glPointSize(50); glBegin(GL_POINTS); glVertex3f(0.5, 0.5, 0); glEnd(); glFlush(); } void OpenGL::initializeGL() { glShadeModel( GL_SMOOTH ); glClearColor( 0.0, 0.0, 0.0, 0.0 ); glClearDepth( 1.0 ); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); }
以mfc为框架的opengl,为什么连背景都没有显示啊。
自己按照网上的尝试了下mfc框架的opengl,但是根本就没有绘图,连背景都没有显示。求帮助。以下是代码,我自己创建了一个继承CWnd的类,如下: C/C++ code IMPLEMENT_DYNAMIC(COpenGL, CWnd) COpenGL::COpenGL() { } COpenGL::~COpenGL() { wglMakeCurrent(NULL,NULL); wglDeleteContext(hglrc); ::ReleaseDC(m_hWnd,hdc); } BEGIN_MESSAGE_MAP(COpenGL, CWnd) ON_WM_CREATE() ON_WM_PAINT() END_MESSAGE_MAP() // COpenGL 消息处理程序 int COpenGL::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; // TODO: 在此添加您专用的创建代码 MySetPixelFormat(::GetDC(m_hWnd)); hdc = ::GetDC(m_hWnd); hglrc = wglCreateContext(hdc); CRect rect; this->GetWindowRect(&rect); wglMakeCurrent(hdc,hglrc); glShadeModel(GL_SMOOTH); glClearColor(1.0f,1.0f,1.0f,1.5f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glViewport (0, 0, rect.Width(),rect.Height()); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective(65.0, (GLfloat)rect.Width()/(GLfloat)rect.Height(), 1, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); return 0; } void COpenGL::OnPaint() { //CPaintDC dc(this); // device context for painting // TODO: 在此处添加消息处理程序代码 // 不为绘图消息调用 CWnd::OnPaint() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //清除颜色缓存和深度缓存 glLoadIdentity(); gluLookAt(0,5,2, 0,0,0, 0,0,1); glColor3f(0.5f,0.5f,1.0f); // 一次性将当前色设置为蓝色 glBegin(GL_QUADS); // 绘制正方形 glVertex3f(300.0f, 300.0f, 0.0f); glVertex3f(300.0f, -300.0f, 0.0f); glVertex3f(-300.0f, -300.0f, 0.0f); glVertex3f(-300.0f, 300.0f, 0.0f); glEnd(); SwapBuffers(hdc); } int COpenGL::MySetPixelFormat(HDC hdc) { PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW| PFD_SUPPORT_OPENGL| PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 24, 0 ,0 ,0 ,0 ,0 ,0 , 0 , 0 , 0 , 0 ,0 ,0 ,0 , 32 , 0 , 0 , PFD_MAIN_PLANE, 0 , 0 ,0 ,0 }; int iPixelFormat; if(iPixelFormat = ChoosePixelFormat(hdc,&pfd) == 0) { ::MessageBox(NULL,"ChoosePixelFormat Failed","error",MB_OK); return 0; } if(SetPixelFormat(hdc,iPixelFormat,&pfd)) { ::MessageBox(NULL,"SetPixelFormat Failed","error",MB_OK); return 0; } return 1; } 另外 在主对话框中有如下代码: C/C++ code BOOL CMyProjectDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 CRect rect; GetDlgItem(IDC_STATIC)->GetWindowRect(rect); ScreenToClient(rect); m_pDisplay->Create(NULL, NULL, WS_CHILD|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_VISIBLE, rect, this, 0); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE }
OpenGL中glutMouseFunc函数问题
我想在MouseFunc中给一个结构体中成员赋值,但是一直报错Segmentation fault (core dumped),用gdb查了一下是这个赋值语句的问题,以下是代码 ``` #include<GL/glut.h> #include<stdio.h> #include<math.h> #include<malloc.h> #include<stdlib.h> struct PointD { int x; int y; PointD* next; }; struct PointU { int x; int y; PointU* next; }; struct PointD* D=NULL; struct PointU* U=NULL; void MouseClick(int btn,int state ,int x,int y) { x=ReCoordinate(x); y=ReCoordinate(y); x=x-half; y=half-y; if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN) { D->x=x; //报错语句 D->y=y;//报错语句 PointD* p=NULL; p=(PointD*)malloc(sizeof(PointD)); D->next=p;//报错语句 D=D->next; pressed=1; } else if(btn==GLUT_LEFT_BUTTON && state==GLUT_UP && pressed==1) { U->x=x; U->y=y; PointU* q=NULL; q=(PointU*)malloc(sizeof(PointU)); U->next=q; U=U->next; pressed=0; glutPostRedisplay; } } int main(int argc,char** argv) { D=(struct PointD*)malloc(sizeof(PointD)); U=(struct PointU*)malloc(sizeof(PointU)); glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE|GLUT_DEPTH); glutInitWindowPosition(100,100); glutInitWindowSize(800,800); int half=400; glutCreateWindow("TEST"); glMatrixMode(GL_PROJECTION); glOrtho(-half,half,-half,half,-half,half); glutDisplayFunc(&display); glutMouseFunc(MouseClick); glutMainLoop(); return 0; } ```
vs2015环境下OpenGL中怎样实现鼠标右键控制物体旋转
#include "StdAfx.h" #include "CloudPoint.h" #define GLUT_DISABLE_ATEXIT_HACK #include <GL/glut.h> #include <math.h> #include <stdio.h> CCloudPoint::CCloudPoint(void) { } CCloudPoint::~CCloudPoint(void) { } CCloudPoint *CCloudPoint::s_pCurrent = NULL; char *m_cFilename = NULL; //int CCloudPoint::s_argc = 0;//char** CCloudPoint::s_argv = 0; bool mouseLeftDown; bool mouseRightDown; float CCloudPoint::c=3.1415926535/180.0f; //弧度和角度转换参数 int CCloudPoint::du=90,CCloudPoint::oldmy=-1,CCloudPoint::oldmx=-1; //du是视点绕y轴的角度,opengl里默认y轴是上方向 float CCloudPoint::r=0.3f,CCloudPoint::h=0.0f; //r是视点绕y轴的半径,h是视点高度即在y轴上的坐标 int CCloudPoint::scale = 10; int CCloudPoint::iWindowsWidth = 800, CCloudPoint::iWindowHeight = 800; float CCloudPoint::x[1000000], CCloudPoint::y[1000000], CCloudPoint::z[1000000]; int CCloudPoint::iPointNumber = 0; int mButton = -1; void CCloudPoint::setFilename(char * m_cFilename) { this->m_cFilename = m_cFilename; } char* CCloudPoint::getFilename() { return m_cFilename; } void CCloudPoint::MouseCallback(int button, int state, int x, int y) { CCloudPoint::s_pCurrent->Mouse(button, state, x, y); } void CCloudPoint::onMouseMoveCallback( int x,int y) { CCloudPoint::s_pCurrent->onMouseMove( x,y); } void CCloudPoint::reshapeCallback(int w,int h) { CCloudPoint::s_pCurrent->reshape(w,h); } void CCloudPoint::myDisplayCallback(void) { CCloudPoint::s_pCurrent->myDisplay(); } void CCloudPoint::Mouse(int button, int state, int x, int y) //处理鼠标点击 { if (state == GLUT_DOWN) { oldmx = x, oldmy = y; } else { if (state == GLUT_UP && button == GLUT_WHEEL_UP) { if (scale>1) scale -= 1; else scale = 1; //glutPostRedisplay(); } else if (state == GLUT_UP && button == GLUT_WHEEL_DOWN) { scale += 1; //glutPostRedisplay(); } else if (state == GLUT_DOWN && button == GLUT_RIGHT_BUTTON) { mouseRightDown = true; } else if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) { mouseLeftDown = true; } } } void CCloudPoint::onMouseMove(int x,int y) //处理鼠标拖动 { //printf("%d\n",du); if (mouseRightDown) { du += x - oldmx; //鼠标在窗口x轴方向上的增量加到视点绕y轴的角度上,这样就左右转了 h += 0.03f*(y - oldmy); //鼠标在窗口y轴方向上的改变加到视点的y坐标上,就上下转了 if (h > 1.0f) h = 1.0f; //视点y坐标作一些限制,不会使视点太奇怪 else if (h < -1.0f) h = -1.0f; oldmx = x, oldmy = y; //把此时的鼠标坐标作为旧值,为下一次计算增量做准备 } } void CCloudPoint::init() { glEnable(GL_DEPTH_TEST); } void CCloudPoint::reshape(int w,int h) { glViewport( 0, 0, (GLsizei)w, (GLsizei)h ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective(90.0f, (GLfloat)w / (GLfloat)h, 1.0f, 1.0f); glMatrixMode( GL_MODELVIEW ); } void CCloudPoint::loadFile(char *cFileName) { FILE* file = fopen(cFileName,"r"); if (!file) { printf("load file %s failed\n",cFileName); } else { /*fseek(file,0,SEEK_END); long fileSize = ftell(file);*/ char buffer[1000]; while(fgets(buffer,300,file) != NULL) { sscanf(buffer,"%f, %f, %f", &x[iPointNumber], &y[iPointNumber], &z[iPointNumber]); iPointNumber++; //printf("x=%f, y=%f, z=%f\n", x, y, z); } } } void CCloudPoint::myDisplay(void) { int i; /*glClear(GL_COLOR_BUFFER_BIT);*/ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); //printf("At:%.2f %.2f %.2f\n",r*cos(c*du),h,r*sin(c*du)); //这就是视点的坐标 gluLookAt(r*cos(c*du), h, r*sin(c*du), 0, 0, 0, 0, 1.0f, 0); //从视点看远点,y轴方向(0,1,0)是上方向 glBegin(GL_POINTS); /*glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.5f, 0.5f, 0.5f);*/ for (i = 0; i < iPointNumber; i++) { glVertex3f(x[i]/scale, y[i]/scale, z[i]/scale); } glEnd(); glFlush(); glutSwapBuffers(); } void CCloudPoint::LoadAndShow() { int argc=1; char* argv[]={"good"}; //loadFile(CCloudPoint::getFilename()); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowPosition(100, 0); glutInitWindowSize(iWindowsWidth, iWindowHeight); glutCreateWindow("OpenGL程序"); init(); glutReshapeFunc(CCloudPoint::reshapeCallback); glutDisplayFunc(myDisplayCallback); /*glutDisplayFunc(display);*/ glutIdleFunc(CCloudPoint::myDisplayCallback); //设置不断调用显示函数 glutMouseFunc(CCloudPoint::MouseCallback); glutMotionFunc(CCloudPoint::onMouseMoveCallback); glutMainLoop(); return; } 上面是我的代码,但是没有用,如果将void CCloudPoint::onMouseMove(int x,int y) 中的if语句去掉,就是任意鼠标键移动控制旋转,想问问大神
opengl在mfc中载入一副BMP文件作为纹理,编译链接都通过了但运行时就提示停止工作
HBITMAP hBMP;//定义BMP头 BITMAP BMP;//BMP结构体 //byte Texture[]={IDB_BITMAP3}; byte Texture[]={IDB_BITMAP4}; glGenTextures(sizeof(Texture), &texture[0]);// Generate 6 Textures (sizeof(Texture)=6 ID's) for(int loop=0;loop<sizeof(Texture); loop++)// Loop Through All The ID's (Bitmap Images) { hBMP=(HBITMAP)LoadImage(GetModuleHandle(NULL),MAKEINTRESOURCE(Texture[loop]),IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION); if (hBMP) // Does The Bitmap Exist? { // If So... GetObject(hBMP,sizeof(BMP), &BMP);// // Get The Object // hBMP: Handle To Graphics Object // sizeof(BMP): Size Of Buffer For Object Information // Buffer For Object Information glPixelStorei(GL_UNPACK_ALIGNMENT,4);// Pixel Storage Mode (Word Alignment / 4 Bytes) glBindTexture(GL_TEXTURE_2D, texture[loop]);// Bind Our Texture glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR); // Mipmap Linear Filtering // Generate Mipmapped Texture (3 Bytes, Width, Height And Data From The BMP) gluBuild2DMipmaps(GL_TEXTURE_2D,3,BMP.bmWidth,BMP.bmHeight,GL_BGR_EXT,GL_UNSIGNED_BYTE,BMP.bmBits); DeleteObject(hBMP);// Delete The Bitmap Object } } glClearColor(0.0f,0.0f,0.0f,1.0f);//清除背景颜色 glEnable(GL_TEXTURE_2D);//启用纹理模式 glEnable(GL_DEPTH_TEST);//启动深度测试 glMatrixMode(GL_PROJECTION);//投影 glLoadIdentity();
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
相关热词 c# clr dll c# 如何orm c# 固定大小的字符数组 c#框架设计 c# 删除数据库 c# 中文文字 图片转 c# 成员属性 接口 c#如何将程序封装 16进制负数转换 c# c#练手项目
立即提问