为什么我的纹理会旋转 90 度?

Why is my texture getting rotated by 90 degrees?

我正在尝试绘制一个带有纹理的简单四边形。我正在使用 gluOrtho2d 设置正交投影。我无法理解为什么四边形内的纹理会顺时针旋转 90°。纹理是一个简单的 PNG 文件。

这是有问题的代码:-

#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <SFML/Graphics.hpp>
#include <iostream>


using namespace std;


const int WINDOW_WIDTH = 800, WINDOW_HEIGHT = 600;
sf::Texture texture;


void draw() {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    float x = 0;
    float y = 0;

    sf::Texture::bind(&texture);

    glBegin(GL_QUADS);
    glVertex2f(x, y);
    glTexCoord2f(0, 0);
    glVertex2f(x + 400, y);
    glTexCoord2f(1, 0);
    glVertex2f(x + 400, y + 400);
    glTexCoord2f(1, 1);
    glVertex2f(x, y + 400);
    glTexCoord2f(0, 1);
    glEnd();
}


int main() {
    sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "problem");
    window.setActive(true);


    texture.loadFromFile("texture.png");

    glewInit();
    glEnable(GL_TEXTURE_2D);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    gluOrtho2D(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT);
    glMatrixMode(GL_MODELVIEW);

    bool isRunning = true;
    while(isRunning) {
        sf::Event event;
        while(window.pollEvent(event)) {
            if(event.type == sf::Event::Closed) {
                isRunning = false;
            }
        }
        draw();
        window.display();
    }
}

这是输出。这里可以看到贴图旋转了90°

glVertex*() 调用“锁定”顶点的当前 color/texture-coordinates/position 并将这些值传递给 GL 驱动程序:

glVertex commands are used within glBegin/glEnd pairs to specify point, line, and polygon vertices. The current color, normal, texture coordinates, and fog coordinate are associated with the vertex when glVertex is called.

你现在的样子:

glVertex2f(x, y);
glTexCoord2f(0, 0);

...第一个 glVertex() 调用重新使用最近设置的纹理坐标,来自前一帧的坐标:glTexCoord2f(0, 1)

因此需要在位置之前为顶点设置纹理坐标:

glTexCoord2f(0, 0);
glVertex2f(x, y);
glTexCoord2f(1, 0);
glVertex2f(x + 400, y);
glTexCoord2f(1, 1);
glVertex2f(x + 400, y + 400);
glTexCoord2f(0, 1);
glVertex2f(x, y + 400);