gpt4 book ai didi

c++ - OpenGL:绘制立方体

转载 作者:太空宇宙 更新时间:2023-11-04 16:11:01 24 4
gpt4 key购买 nike

我刚开始学习 OpenGL,这是我第一个绘制立方体的程序。我在这里完全迷路了,因为我能够通过在 2d 中指定矩形的坐标来绘制矩形,但是我不能通过指定 (x, y, z) 格式的坐标来绘制立方体。我在这里缺少什么?

代码如下:

#include <GL/glew.h>
#include <GL/gl.h>
#include <math.h>
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

// Open an OpenGL window
GLFWwindow* window;

/****Step 1: define vertices in (x, y, z) form****/

// Coordinates to draw a cube
const GLdouble coordinates[8][3] = {
{-0.5, -0.5, -0.5},
{0.5, -0.5, -0.5},
{0.5, -0.5, 0.5},
{-0.5, -0.5, 0.5},
{-0.5, 0.5, 0.5},
{-0.5, 0.5, -0.5},
{0.5, 0.5, -0.5},
{0.5, 0.5, 0.5}
};
/************************/


int main( void ) {
if (!glfwInit()){
fprintf(stderr, "Failed to initialize GLFW.\n");
return -1;
}

// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(700, 500, "Hello World", NULL, NULL);
if (window == NULL) {
fprintf(stderr, "glfw failed to create window.\n");
//glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);

glewInit();
if (glewInit() != GLEW_OK){
fprintf(stderr, "Failed to initialize GLEW: %s.\n", glewGetErrorString(glewInit()));
return -1;
}
// 4x anti aliasing
glfwWindowHint(GLFW_SAMPLES, 4);

int cube_size = sizeof(coordinates)/sizeof(coordinates[0]);
/**Step 2: send this cube vertices to OpenGL through a buffer**/
GLuint vertexBuffer; // Declare vertex buffer
glGenBuffers(1, &vertexBuffer); // generating 1 buffer, put resulting identifier in this buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, cube_size*12, coordinates, GL_STATIC_DRAW);
/************************/

std::cout << sizeof(coordinates)/sizeof(coordinates[0]);

/**Step 3: Main loop for OpenGL draw the shape**
/* Main loop */
do{
glClearColor(1.0, 0.1, 0.1, .0);
glClear(GL_COLOR_BUFFER_BIT);

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_LINE_LOOP, 0, cube_size);
glDisableVertexAttribArray(0);

// Swap front and back rendering buffers
glfwSwapBuffers(window);
//Poll for and process events
glfwPollEvents();
} // check if the ESC key was pressed or the window was closed
while(glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);
/***********************************************/


// Close window and terminate GLFW
glfwDestroyWindow(window);
glfwTerminate();
// Exit program
exit( EXIT_SUCCESS );
}

最佳答案

您的程序类型不匹配。在此声明中:

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

您要让 OpenGL 将您的数据解释为 float ,但您的坐标点被声明为 double 。

我建议您在坐标类型声明处将 GLdouble 更改为 GLfloat。

顺便说一下,有了这些点你不会得到一个立方体,而只是它的部分草图

关于c++ - OpenGL:绘制立方体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28721385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com