OpenGL, Access violation

2.8k views Asked by At

I am making an OpenGL project in Visual Studio 2010. I am following a tutorial from youtube. I don't know where the error is, and I have this error:

Unhandled exception at 0x00000000 in OpenGL First Game.exe: 0xC0000005: Access violation.

Main.cpp

#include <GL/glew.h>
#include <iostream>
#include <GL/glut.h>
#include "Sprite.h"

Sprite _sprite;

void Init() {
    glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
    _sprite.Init(-1.0f, -1.0f, 1.0f, 1.0f);
}

void Render() {
    glClearDepth(1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    _sprite.Render();

    glutSwapBuffers();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(520, 200);
    glutInitWindowSize(800, 600);
    glutInitDisplayMode(GLUT_DOUBLE);
    glutCreateWindow("OpenGL [ 1 ]");
    glutDisplayFunc(Render);
    Init();
    glutMainLoop();
}

Sprite.cpp

#include <GL/glew.h>
#include "Sprite.h"

Sprite::Sprite(void){
    _vboID = 0;
}


Sprite::~Sprite(void){
    if(_vboID != 0)
        glDeleteBuffers(1, &_vboID);
}

void Sprite::Init(float x, float y, float width, float height){
    _x = x;
    _y = y;
    _width = width;
    _height = height;

    if(_vboID == 0){
        glGenBuffers(1, &_vboID);
    }

    float VertexData[12];
    // Prvi trougao
    VertexData[0] = x + width;
    VertexData[1] = y + height;
    VertexData[2] = x;
    VertexData[3] = y + height;
    VertexData[4] = x;
    VertexData[5] = y;

    // Drugi trougao
    VertexData[6] = x;
    VertexData[7] = y;
    VertexData[8] = x + width;
    VertexData[9] = y;
    VertexData[10] = x + width;
    VertexData[11] = y + height;

    glBindBuffer(GL_ARRAY_BUFFER, _vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void Sprite::Render(){
    glBindBuffer(GL_ARRAY_BUFFER, _vboID);

    glEnableVertexAttribArray(0);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    glDisableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

Sprite.h

#pragma once
#include <GL/glut.h>

class Sprite{
    public:
        Sprite(void);
        ~Sprite(void);
        void Init(float x, float y, float width, float height);
        void Render();
    private:
        float _x;
        float _y;
        float _width;
        float _height;
        GLuint _vboID; // Gluint na garantira da ce int biti 32 bita
};
1

There are 1 answers

1
datenwolf On BEST ANSWER

You did not initialize GLEW. Without doing that all the entry points provided by GLEW (which is everything beyond OpenGL-1.1) are left uninitialized and calling them crashes your program.

Add

if( GLEW_OK != glewInit() ) { return 1; }
while( GL_NO_ERROR != glGetError() ); /* glewInit may cause some OpenGL errors -- flush the error state */

after glutCreateWindow.