Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用三角形条对球体进行纹理处理的java问题

我正在学习opengl,但在绘制球体时遇到了问题。我可以正常地绘制和绑定多边形的纹理,但当我尝试用同样的方法绘制三角形条绘制的球体时,效果并不理想。部分纹理被破坏。(下图)

我能知道我做错了什么吗?如果这是一个明显的问题,很抱歉

以下是sphere的代码: (在添加纹理部分之前,可以正常显示球体)

private void drawSphere(GL gl) {
        Position spherePosition = state.getSpherePosition();
        final float PI = 3.141592f;
        gl.glPushMatrix();
        if(spheretexture == null){
           setSphereTexture();
        }

        gl.glTranslated(spherePosition.getX(), spherePosition.getY(), spherePosition.getZ());
        float[] ambientDiffuse = new float[] {255.0f, 255.0f, 255.0f, 1.0f};
        gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, ambientDiffuse, 0);

        gl.glEnable(GL_BLEND);
        gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        float x, y, z, alpha, beta; // Storage for coordinates and angles
        float radius = 25f;
        int gradation = 10;
        for (alpha = 0.0f; alpha < PI; alpha += PI / gradation) {
        spheretexture.enable();
        spheretexture.bind();
        gl.glBegin(GL_TRIANGLE_STRIP);
        for (beta = 0.0f; beta < 2.01 * PI; beta += PI / gradation) {
            x = (float) (radius * Math.cos(beta) * Math.sin(alpha));
            y = (float) (radius * Math.sin(beta) * Math.sin(alpha));
            z = (float) (radius * Math.cos(alpha));
            gl.glTexCoord2f(beta / (2.0f * PI), alpha / PI);
            gl.glVertex3f(x, y, z);
            x = (float) (radius * Math.cos(beta) * Math.sin(alpha + PI / gradation));
            y = (float) (radius * Math.sin(beta) * Math.sin(alpha + PI / gradation));
            z = (float) (radius * Math.cos(alpha + PI / gradation));
            gl.glTexCoord2f(beta / (2.0f * PI), alpha / PI + 1.0f / gradation);
            gl.glVertex3f(x, y, z);
        }

        gl.glEnd();

        spheretexture.disable();
        gl.glDisable(GL_BLEND);
        gl.glPopMatrix();
    }

    }

输出图片:img


共 (1) 个答案

  1. # 1 楼答案

    主要问题是球体的顶帽被画了两次。这导致Z-fighting。注意,首先在PI-PI/gradationPI之间绘制,然后在PIPI+PI/gradation之间绘制。这是因为外环做了一个额外的传递。将其更改为:

    for (alpha = 0.0f; alpha < PI-PI/gradation; alpha += PI / gradation) {
        // [...]
    }
    

    甚至更好

    for (int i = 0; i < gradation; ++ i ) {
        float alpha =  PI * (float)i / (float)(gradation);
        // [...]
    }