本文共 2244 字,大约阅读时间需要 7 分钟。
OpenGL
(vertex_shader.glsl)
glsl
#version 330 corelayout (location = 0) in vec3 aPos;layout (location = 1) in vec2 aTexCoord;out vec2 TexCoord;void main(){gl_Position = vec4(aPos, 1.0);TexCoord = aTexCoord;
(fragment_shader.glsl)
glsl
#version 330 core out vec4 FragColor; in vec2 TexCoord; uniform sampler2D texture1; void main(){ FragColor = texture(texture1, TexCoord);
SOIL
cpp
#includeGLuint loadTexture(const char *path){ GLuint textureID; glGenTextures(1, &textureID); int width, height;unsigned char* image = SOIL_load_image(path, &width, &height, 0, SOIL_LOAD_RGB);if (image == nullptr){std::cout << "Texture failed to load at path: " << path << std::endl; return 0;}glBindTexture(GL_TEXTURE_2D, textureID);glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);glGenerateMipmap(GL_TEXTURE_2D);SOIL_free_image_data(image);glBindTexture(GL_TEXTURE_2D, 0);return textureID;cpp
#include#include #include #include //
GLfloat vertices[] = {
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f,0.5f, -0.5f, 0.0f, 1.0f, 0.0f,0.5f, 0.5f, 0.0f, 1.0f, 1.0f,-0.5f, 0.5f, 0.0f, 0.0f, 1.0f
GLuint indices[] = {
0, 1, 2,2, 3, 0
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);glCompileShader(vertexShader);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);glCompileShader(fragmentShader);
GLuint shaderProgram = glCreateProgram();glAttachShader(shaderProgram, vertexShader);glAttachShader(shaderProgram, fragmentShader);glLinkProgram(shaderProgram);
glDeleteShader(vertexShader);glDeleteShader(fragmentShader);
GLuint texture1 = loadTexture("path_to_texture.jpg");
while (!glfwWindowShouldClose(window)){
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);glClear(GL_COLOR_BUFFER_BIT);glBindTexture(GL_TEXTURE_2D, texture1);glUseProgram(shaderProgram);glBindVertexArray(VAO);glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);glBindVertexArray(0);glfwSwapBuffers(window);glfwPollEvents();
转载地址:http://qzpfk.baihongyu.com/