OpenGL红宝书例3.1 -- glBufferSubData使用

  1. 代码实现
    1.1 C++部分
GLFWwindow *window;

GLuint shader_program;
GLuint VAO;

void init()
{
	static const GLfloat positions[] = 
	{
		-1.0f, -1.0f, 0.0f, 1.0f,
		 1.0f, -1.0f, 0.0f, 1.0f,
		 1.0f,  1.0f, 0.0f, 1.0f,
		-1.0f,  1.0f, 0.0f, 1.0f,
	};
	
	static const GLfloat colors[] =
	{
		1.0f, 0.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
		0.0f, 0.0f, 1.0f,
		1.0f, 1.0f, 1.0f,
	};

	
	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);

	GLuint buffer;
	glGenBuffers(1, &buffer);
	glBindBuffer(GL_ARRAY_BUFFER, buffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(positions)+sizeof(colors), nullptr, GL_STATIC_DRAW); 

	glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(positions), positions);
	glBufferSubData(GL_ARRAY_BUFFER, sizeof(positions), sizeof(colors), colors);


	shader_program = CreateShaderProgram();
	GLuint vec_shader = LoadShader("triangles.vert", GL_VERTEX_SHADER);
	GLuint fs_shader = LoadShader("triangles.frag", GL_FRAGMENT_SHADER);
	LinkShader(shader_program, vec_shader, fs_shader, 0);
	glUseProgram(shader_program);

	glBindVertexArray(0);

	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
}

void display()
{
	while (!glfwWindowShouldClose(window))
	{
		/* Render here */
		glClear(GL_COLOR_BUFFER_BIT);

		glBindVertexArray(VAO);
		glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, (void *)0);
		glEnableVertexAttribArray(0);
		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
		glEnableVertexAttribArray(1);
		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
		glBindVertexArray(0);

		glfwSwapBuffers(window);

		/* Poll for and process events */
		glfwPollEvents();
	}

	glfwTerminate();
	glDeleteProgram(shader_program);
}

int CALLBACK WinMain( HINSTANCE hInstance,
					 HINSTANCE hPrevInstance, 
					 LPSTR lpCmdLine, int nShowCmd )
{
	if(!glfwInit())
		return -1;

	glfwWindowHint(GLFW_SAMPLES, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	window = glfwCreateWindow(512, 512, "Hello World", NULL, NULL);
	if(!window)
	{
		glfwTerminate();
		return -1;
	}
	
	glfwMakeContextCurrent(window);

	// Initialize GLEW
	glewExperimental = true; // Needed for core profile
	if( GLEW_OK != glewInit())
		return -1;

	init();

	display();

	return 0;
}

1.2 代码实现 -- shader 部分

// vexter
#version 430 core
layout (location = 0) in vec4 poistion;
layout (location = 1) in vec3 color;

out vec3 out_color;
 
void main()
{
    gl_Position = poistion;
    out_color = color;
}


// fragment
#version 430 core

// Ouput data
out vec4 color;

in vec3 out_color;


void main()
{
	color = vec4(out_color, 1.0);
}

posted @ 2015-10-26 20:47  zyh_think  阅读(2719)  评论(0编辑  收藏  举报