Opengl 带有着色器的LWJGL纹理生成倾斜图像

Opengl 带有着色器的LWJGL纹理生成倾斜图像,opengl,lwjgl,Opengl,Lwjgl,我正在尝试以正交模式绘制二维图形。代码加载一个cat图片和两个简单着色器,它们只通过它们的输入,未经修改。我希望程序能在屏幕中部显示猫(或至少部分)的图片,没有任何旋转或歪斜。 程序执行成功,但我不明白为什么结果是这样: OpenGL专家可能会很快发现问题,但我找不到。我觉得问题可能出在“为顶点和纹理坐标创建缓冲区”部分,但看起来一切正常 cat图像: 顶点着色器: #version 150 core in vec4 in_Position; in vec2 in_TextureCoord

我正在尝试以正交模式绘制二维图形。代码加载一个cat图片和两个简单着色器,它们只通过它们的输入,未经修改。我希望程序能在屏幕中部显示猫(或至少部分)的图片,没有任何旋转或歪斜。

程序执行成功,但我不明白为什么结果是这样:

OpenGL专家可能会很快发现问题,但我找不到。我觉得问题可能出在“为顶点和纹理坐标创建缓冲区”部分,但看起来一切正常

cat图像:

顶点着色器:

#version 150 core

in vec4 in_Position;
in vec2 in_TextureCoord;

out vec2 pass_TextureCoord;

void main(void) {
    gl_Position = in_Position;

    pass_TextureCoord = in_TextureCoord;
}
像素着色器:

#version 150 core

uniform sampler2D texture_diffuse;
in vec2 pass_TextureCoord;
out vec4 out_Color;

void main(void) {
    out_Color = texture(texture_diffuse, pass_TextureCoord);
}
Java(LWJGL)代码:

包装lwjgl_测试1;
导入java.awt.image.buffereImage;
导入java.io.*;
导入java.nio.*;
导入javax.imageio.imageio;
导入org.lwjgl.*;
导入org.lwjgl.opengl.*;
导入静态org.lwjgl.glfw.glfw.*;
导入java.util.concurrent.TimeUnit;
导入静态org.lwjgl.opengl.GL11.*;
公共班机{
公共静态void main(字符串[]args){
试一试{
如果(!glfwInit()){
抛出(新异常(“不能初始化glfw”);
}
/*
*创建窗口
*/
glfwWindowHint(GLFW_可调整大小,0);
长窗口glid=glfwCreateWindow(1024768,“示例OpenGL应用程序”,0,0);
glfwSetWindowPos(windowGlID,50,50);
glfwMakeContextCurrent(windowGlID);
glfwShowWindow(windowGlID);
/*
*初始化OpenGL
*/
GL.createCapabilities();
glMatrixMode(GL_投影);
glLoadIdentity();
格洛托(0,1024,768,0,0,1);
glMatrixMode(GLU模型视图);
/*
*加载纹理
*/
int cat=loadTexture(“cat.png”);
/*
*加载着色器
*/
int vertexShader=loadShader(“vertex\u shader.txt”,GL20.GL\u vertex\u shader);
int pixelShader=loadShader(“pixel\u shader.txt”,GL20.GL\u FRAGMENT\u shader);
int pId=GL20.glCreateProgram();
GL20.glAttachShader(pId,vertexShader);
GL20.glAttachShader(pId,pixelShader);
//位置信息将为属性0
GL20.GLBindAttriblLocation(pId,0,“处于位置”);
//Textute信息将是属性1
GL20.glBindAttribLocation(pId,1,“in_TextureCoord”);
GL20.glLinkProgram(pId);
GL20.glValidateProgram(pId);
exitOnGLError(“编译着色器失败”);
/*
*为顶点和纹理坐标创建缓冲区
*/
浮子尺寸=120.0f;
FloatBuffer vertex_data=BufferUtils.createFloatBuffer(20);
顶点数据放置(新浮点[]{-size,-size,0f,0f,0f});/(Vx,Vy,Vz,Tx,Ty)
vertex_data.put(新浮点[]{size,-size,0f,0f,1f});
vertex_data.put(新浮点[]{size,size,0f,1f,1f});
vertex_data.put(新浮点[]{-size,size,0f,1f,0f});
vertex_data.flip();
int vbo_vertex_handle=GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_数组_BUFFER,vbo_顶点_句柄);
GL15.glBufferData(GL15.GLU数组缓冲区、顶点数据、GL15.GLU静态绘制);
GL20.glvertexattributepointer(0,3,GL11.GL_FLOAT,false,2*4,0);//标记顶点坐标
GL20.glVertexAttribute指针(1,2,GL11.GL_FLOAT,false,3*4,3*4);//标记纹理坐标
GL15.glBindBuffer(GL15.GL_数组_BUFFER,0);
GL30.glBindVertexArray(0);
exitOnGLError(“创建缓冲区失败”);
/*
*主渲染循环
*/
while(true){
/*
*清屏
*/
glClearColor(0.0f、1.0f、1.0f、0.0f);
glClear(GL_颜色_缓冲_位| GL_深度_缓冲_位);
/*
*应用着色器程序
*/
GL20.glUseProgram(pId);
//绑定纹理
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D,cat);
/*
*绘制(使用缓冲区)
*/
GL20.GlenableVertexAttributeArray(0);
GL20.GlenableVertexAttributeArray(1);
GL15.glBindBuffer(GL15.GL_数组_BUFFER,vbo_顶点_句柄);
GL11.gldrawArray(GL11.GL_QUADS,0,4);//绘制具有4个顶点的实体
GL15.glBindBuffer(GL15.GL_数组_BUFFER,0);
exitOnGLError(“绘制失败”);
GL11.glBindTexture(GL11.GL_TEXTURE_2D,0);
GL20.glUseProgram(0);//取消选择
/*
*交换缓冲区
*/
glfwSwapBuffers(windowGlID);
/*
*事件
*/
glfwPollEvents();
如果(glfwWindowShouldClose(windowGlID)){
打破
}
时间单位。毫秒。睡眠(10);
}
}捕获(例外e){
e、 printStackTrace();
}
}
私有静态int loadTexture(字符串路径)引发异常{
int[]像素=空;
BuffereImage图像=空;
image=ImageIO.read(新文件输入流(路径));
int width=image.getWidth();
int height=image.getHeight();
像素=新整数[宽度*高度];
getRGB(0,0,宽度,高度,像素,0,宽度);
int[]数据=新int[宽度*高度];
对于(int i=0;i>24;
int r=(像素[i]&0xff0000)>>16;
int g=(像素[i]&0xff00)
package lwjgl_test1;

import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.*;

import javax.imageio.ImageIO;

import org.lwjgl.*;
import org.lwjgl.opengl.*;

import static org.lwjgl.glfw.GLFW.*;
import java.util.concurrent.TimeUnit;
import static org.lwjgl.opengl.GL11.*;


public class Main {
    public static void main(String[] args) {
        try {
            if (!glfwInit()) {
                throw(new Exception("Can't init glfw."));
            }

            /*
             * Create Window
             */
            glfwWindowHint(GLFW_RESIZABLE, 0);
            long windowGlID = glfwCreateWindow(1024, 768, "Example OpenGL App", 0, 0);

            glfwSetWindowPos(windowGlID, 50, 50);
            glfwMakeContextCurrent(windowGlID);
            glfwShowWindow(windowGlID);

            /*
             * Initialize OpenGL
             */
            GL.createCapabilities();

            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glOrtho(0, 1024, 768, 0, 0, 1);
            glMatrixMode(GL_MODELVIEW);

            /*
             * Load texture
             */
            int cat = loadTexture("cat.png");

            /*
             * Load shaders
             */
            int vertexShader = loadShader("vertex_shader.txt", GL20.GL_VERTEX_SHADER);
            int pixelShader = loadShader("pixel_shader.txt", GL20.GL_FRAGMENT_SHADER);

            int pId = GL20.glCreateProgram();
            GL20.glAttachShader(pId, vertexShader);
            GL20.glAttachShader(pId, pixelShader);

            // Position information will be attribute 0
            GL20.glBindAttribLocation(pId, 0, "in_Position");
            // Textute information will be attribute 1
            GL20.glBindAttribLocation(pId, 1, "in_TextureCoord");

            GL20.glLinkProgram(pId);
            GL20.glValidateProgram(pId);

            exitOnGLError("Compiling shaders failed.");

            /*
             * Create buffer for vertex and texture coordinates
             */
            float size = 120.0f;

            FloatBuffer vertex_data = BufferUtils.createFloatBuffer(20);
            vertex_data.put(new float[] { -size, -size, 0f, 0f, 0f });  // (Vx, Vy, Vz, Tx, Ty)
            vertex_data.put(new float[] { size, -size, 0f, 0f, 1f });
            vertex_data.put(new float[] { size, size, 0f, 1f, 1f });
            vertex_data.put(new float[] { -size, size, 0f, 1f, 0f });
            vertex_data.flip();

            int vbo_vertex_handle = GL15.glGenBuffers();
            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo_vertex_handle);
            GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertex_data, GL15.GL_STATIC_DRAW);

            GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 2 * 4, 0);   // mark vertex coordinates
            GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, 3 * 4, 3 * 4);   // mark texture coordinates

            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
            GL30.glBindVertexArray(0);

            exitOnGLError("Creating buffers failed.");

            /*
             * Main rendering loop
             */
            while(true) {
                /*
                 * Clear screen
                 */
                glClearColor(0.0f, 1.0f, 1.0f, 0.0f);
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

                /*
                 * Apply shader program
                 */
                GL20.glUseProgram(pId);

                // Bind the texture
                GL13.glActiveTexture(GL13.GL_TEXTURE0);
                GL11.glBindTexture(GL11.GL_TEXTURE_2D, cat);

                /*
                 * Draw (use buffers)
                 */
                GL20.glEnableVertexAttribArray(0);
                GL20.glEnableVertexAttribArray(1);

                GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo_vertex_handle);
                GL11.glDrawArrays(GL11.GL_QUADS, 0, 4); // Draw an entity with 4 vertices
                GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);

                exitOnGLError("Draw failed.");

                GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
                GL20.glUseProgram(0); // deselect

                /*
                 * Swap buffers
                 */
                glfwSwapBuffers(windowGlID);

                /*
                 * Events
                 */
                glfwPollEvents();
                if (glfwWindowShouldClose(windowGlID)) {
                    break;
                }

                TimeUnit.MILLISECONDS.sleep(10);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static int loadTexture(String path) throws Exception {
        int[] pixels = null;
        BufferedImage image = null;

        image = ImageIO.read(new FileInputStream(path));
        int width = image.getWidth();
        int height = image.getHeight();
        pixels = new int[width * height];
        image.getRGB(0, 0, width, height, pixels, 0, width);

        int[] data = new int[width * height];
        for (int i = 0; i < width * height; i++) {
            int a = (pixels[i] & 0xff000000) >> 24;
            int r = (pixels[i] & 0xff0000) >> 16;
            int g = (pixels[i] & 0xff00) >> 8;
            int b = (pixels[i] & 0xff);

            data[i] = a << 24 | b << 16 | g << 8 | r;
        }

        IntBuffer intBuffer1 = ByteBuffer.allocateDirect(data.length << 2).order(ByteOrder.nativeOrder()).asIntBuffer();
        intBuffer1.put(data).flip();

        int result = glGenTextures();
        glBindTexture(GL_TEXTURE_2D, result);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, intBuffer1);
        glBindTexture(GL_TEXTURE_2D, 0);

        exitOnGLError("Loading texture '"+ path +"' failed.");

        return result;
    }

    private static int loadShader(String filename, int type) {
        StringBuilder shaderSource = new StringBuilder();
        int shaderID = 0;

        try {
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = reader.readLine()) != null) {
                shaderSource.append(line).append("\n");
            }
            reader.close();
        } catch (IOException e) {
            System.err.println("Could not read file.");
            e.printStackTrace();
            System.exit(-1);
        }

        shaderID = GL20.glCreateShader(type);
        GL20.glShaderSource(shaderID, shaderSource);
        GL20.glCompileShader(shaderID);

        if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
            System.err.println("Could not compile shader.");
            System.exit(-1);
        }

        return shaderID;
    }

    private static void exitOnGLError(String errorMessage) throws Exception {
        int errorValue = GL11.glGetError();

        if (errorValue != GL11.GL_NO_ERROR) {
            throw new Exception(errorMessage);
        }
    }
}
GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 2 * 4, 0);
GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, 3 * 4, 3 * 4);
GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 5 * 4, 0);
GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, 5 * 4, 3 * 4);