OpenGL正确附加纹理

时间:2016-07-20 17:58:19

标签: java c++ opengl graphics jogl

问题:

尝试了几个小时来设置一个简单的交叉头发作为纹理(所以我以后可以像正常的十字线一样粘在视图的中间),没有运气。

我用JOGL编写Java代码。

P.S还需要使纹理的背景透明。但这是另一个问题。

代码:

public void display(GLAutoDrawable gLDrawable) {
    final GL2 gl = gLDrawable.getGL().getGL2();
    gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();  // Reset The View
    gl.glTranslatef(0.0f, 0.0f, -5.0f);

    gl.glTexParameteri ( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT );
    gl.glTexParameteri( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT );
    texture.bind(gl);

    gl.glBegin(GL2.GL_QUADS);
    // Front Face
    gl.glTexCoord2f(0.0f, 0.0f);
    gl.glVertex3f(-1.0f, -1.0f, 1.0f);
    gl.glTexCoord2f(2f, 0.0f);
    gl.glVertex3f(1.0f, -1.0f, 1.0f);
    gl.glTexCoord2f(2f, 1.0f);
    gl.glVertex3f(1.0f, 1.0f, 1.0f);
    gl.glTexCoord2f(0.0f, 1.0f);
    gl.glVertex3f(-1.0f, 1.0f, 1.0f);
    gl.glEnd();
}

public void init(GLAutoDrawable drawable) {
    final GL2 gl = drawable.getGL().getGL2();
    gl.glShadeModel(GL2.GL_SMOOTH);              // Enable Smooth Shading
    gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);    // Black Background
    gl.glClearDepth(1.0f);                      // Depth Buffer Setup
    gl.glEnable(GL2.GL_DEPTH_TEST);              // Enables Depth Testing
    gl.glDepthFunc(GL2.GL_LEQUAL);               // The Type Of Depth Testing To Do
    // Really Nice Perspective Calculations
    gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);
    gl.glEnable(GL2.GL_TEXTURE_2D);
    try {
        String filename = "resources/misc/crosshair.png";
        texture=TextureIO.newTexture(new File( filename ),true);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
}

结果:

demonstration

原始png:

demonstration

1 个答案:

答案 0 :(得分:0)

也许还有更多问题,但至少看起来不对:

gl.glTexCoord2f(2f, 1.0f);

您的纹理水平重复2次,因为其包裹模式为重复,您设置的坐标超过1(在本例中为2f)。要解决此问题,请将2f替换为1f

gl.glTexCoord2f(1f, 1.0f);