无法在C#OpenGL中加载纹理

时间:2011-04-27 15:29:56

标签: c# opengl

我正在通过C#游戏编程来创建严肃的游戏,我似乎已经碰壁了。

以下代码似乎不起作用。即openGLId返回0.

texure好像从磁盘上加载了。但没有Id附加到它。

public void LoadTexture(string textureId, string path)
    {
        int devilId = 0;             
        Il.ilGenImages(1, out devilId);              
        Il.ilBindImage(devilId); // set as the active texture.
        if (!Il.ilLoadImage(path))
        {                  
            System.Diagnostics.Debug.Assert(false,"Could not open file, [" + path + "].");
        }               

        Ilu.iluFlipImage();
        int width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
        int height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);
        int openGLId = Ilut.ilutGLBindTexImage();
        System.Diagnostics.Debug.Assert(openGLId != 0);
        Il.ilDeleteImages(1, ref devilId);

        _textureDatabase.Add(textureId, new Texture(openGLId, width, height, path));
    }

是否有更好的方法来加载OpenGL纹理?

提前致谢

1 个答案:

答案 0 :(得分:0)

我可能有你的答案。

这是我用devIL库加载纹理的类。

public class TextureLoader
{
    int texid;
    bool success;

    int image;
    int width;
    int height;

    string path;

    public TextureLoader(string path)
    {
        this.path = path;
    }

    public void display()
    {
        Il.ilInit();
        Il.ilGenImages(1, out texid);
        Il.ilBindImage(texid);

        success = Il.ilLoadImage(path);

        if (success)
        {
            success = Il.ilConvertImage(Il.IL_RGBA, Il.IL_UNSIGNED_BYTE);

            if (!success)
                Console.WriteLine("ERROR");

            width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
            height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);

            Gl.glGenTextures(1, out image);
            Gl.glBindTexture(Gl.GL_TEXTURE_2D, image);
            Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
            Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
            Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0,
                Il.ilGetInteger(Il.IL_IMAGE_BPP),
                Il.ilGetInteger(Il.IL_IMAGE_WIDTH),
                Il.ilGetInteger(Il.IL_IMAGE_HEIGHT), 0,
                Il.ilGetInteger(Il.IL_IMAGE_FORMAT), Gl.GL_UNSIGNED_BYTE,
                Il.ilGetData()
                );
        }

        Il.ilDeleteImage(texid);

        Gl.glBegin(Gl.GL_QUADS);
            Gl.glTexCoord2f(0.0f, 0.0f); Gl.glVertex2f(-width / 2.0f, height / 2.0f);
            Gl.glTexCoord2f(0.0f, 1.0f); Gl.glVertex2f(-width / 2.0f, height / 2.0f);
            Gl.glTexCoord2f(1, 1); Gl.glVertex2f(1, -1);
            Gl.glTexCoord2f(1, 0); Gl.glVertex2f(1, 1);
        Gl.glEnd();
        Gl.glFlush();

        Gl.glDeleteTextures(1, ref image);
    }
}

代码未注释,但并不复杂。有了这个课程,我可以加载png和jpg图像。

我希望这会对你有所帮助。