/**
 * Copy buffers to memory, set shader attributes, bind to VAO.
 * Return bound VAO ID.
 */
GLuint initBuffers(GLuint shaderProgram) {
    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), 0);

    GLint colorAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colorAttrib);
    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,
                          5*sizeof(float), (void*)(2*sizeof(float)));

    GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor");
    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);
    printGlErrors();
    return vao;
}
void initGlew() {
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if(err != GLEW_OK)
        fail("glewInit failed: %s\n", glewGetErrorString(err));
    printGlErrors();
}
SDL_GLContext initContext(SDL_Window *window) {
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                        SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GLContext context = SDL_GL_CreateContext(window);
    printGlErrors();
    return context;
}
/**
 * Return ID of the linked and activated shader.
 */
GLuint initShaders() {
    auto vshader = compileShader("vshader.glsl", ShaderType::vertex);
    auto fshader = compileShader("fshader.glsl", ShaderType::fragment);
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vshader);
    glAttachShader(shaderProgram, fshader);
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);
    printGlErrors();
    return shaderProgram;
}
// Listens to events during the whole time of the application
// and distributes corresponding tasks
void Application::loop() {
    initTimers();
    m_LastStartTime = getTime();
    SDL_Event event;
    
    // While the application is running (done==false),
    while (m_bRunning) {
        // SDL_PollEvent return 1 when there is still events on the stack of events
        // It takes the first event in the queue and writes it in the "event" parameter
        // Then it removes it from the stack.
        while (SDL_PollEvent(&event))
            handleEvent(event); // Checks each event for types and loach corresponding actions

        // Reports any possible glError
        printGlErrors();
    }
}
// Distributes task for the "user" kind of events 
// For example : rendrFrame action occurs if a timer event is passed
void Application::handleUserEvent(const SDL_Event& event) {
    // In case an animate event occured      
    if (event.user.code == timerId) {
        animate();
        renderFrame();

        // Reports any possible glError
        printGlErrors();

        // Gets the average frame duration over 20 frames
        ++m_FrameCount;
        if (m_FrameCount % 20 == 0) {
            uint64_t time = getTime();
            m_FrameDuration = (time - m_LastStartTime) / 20LL;
            m_LastStartTime = time;
        }
    }
}
void paint() {
    glClear(GL_COLOR_BUFFER_BIT);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    printGlErrors();
}
int main(int argc, char* argv[]) {
    Display *display = XOpenDisplay(NULL);
    if (!display)
        fail("Failed to open X display\n");
    checkGlxVersion(display);
    auto bestFbc = chooseFBConfig(display);

    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig(display, bestFbc);
    printf("Chosen visual ID = 0x%lx\n", vi->visualid);

    printf("Creating colormap\n");
    XSetWindowAttributes swa;
    Colormap cmap;
    swa.colormap = cmap = XCreateColormap(display,
            RootWindow(display, vi->screen),
            vi->visual, AllocNone);
    swa.background_pixmap = None ;
    swa.border_pixel      = 0;
    swa.event_mask        = StructureNotifyMask;

    printf("Creating window\n");
    Window win = XCreateWindow(display, RootWindow(display, vi->screen),
            0, 0, 100, 100, 0, vi->depth, InputOutput,
            vi->visual,
            CWBorderPixel|CWColormap|CWEventMask, &swa);
    if (!win)
        fail("Failed to create window.\n");

    // Done with the visual info data
    XFree(vi);
    XStoreName(display, win, "GL 3.0 Window");
    printf("Mapping window\n");
    XMapWindow(display, win);

    auto context = createContext(display, bestFbc);
    printf("Making context current\n");
    glXMakeCurrent(display, win, context);
    initGlew();

    GLuint tex_;
    GLuint fbo_;
    glGenTextures(1, &tex_);
    glBindTexture(GL_TEXTURE_2D, tex_);

    glGenFramebuffers(1, &fbo_);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
    glFramebufferTexture2D(GL_FRAMEBUFFER,
                           GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D,
                           tex_,
                           0);
    printGlErrors();

    glBindTexture(GL_TEXTURE_2D, tex_);
    glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGBA8, 2, 2);
    char source_pixels[16] = {
        1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4
    };
    printGlErrors();
    printf("Crash here\n");
    glTexSubImage2D(GL_TEXTURE_2D,
                    0,
                    0, 0,
                    2, 2,
                    GL_RGBA, GL_UNSIGNED_BYTE,
                    source_pixels);
    printf("Crashed :( \n");
    printGlErrors();

    glCheckFramebufferStatus(GL_FRAMEBUFFER);

    char pixels[16] = {0};
    glReadPixels(0, 0, 2, 2, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    glCheckFramebufferStatus(GL_FRAMEBUFFER);
    printGlErrors();

    glXMakeCurrent(display, 0, 0);
    glXDestroyContext(display, context);
    XDestroyWindow(display, win);
    XFreeColormap(display, cmap);
    XCloseDisplay(display);
    printf("Test success\n");
    return 0;
}
Esempio n. 9
0
// Entry point in the program
int main(int argc, char **argv)
{
    std::cout<<std::endl<<std::endl<<"________Template OpenGL3________"<<std::endl<<std::endl;
    //__________________________________________________________________________

    // Application creation
    std::cout<<"  Application creation"<<std::endl;
    Application * application=new Application(800, 600);
    //__________________________________________________________________________

    // Scene creation
    std::cout<<"    Scene creation"<<std::endl;
    Scene * scene=new Scene(800, 600);
    application->setScene(scene);
    GLfloat red[]= {1.0, 0.0, 0.0, 1.0};
    scene->setDefaultColor(red); // Color for the objects drawn in the scene

    //__________________________________________________________________________

    // Camera position and orientation
    std::cout<<"    Camera settings"<<std::endl;
    scene->camera->c[2]=6.0; // Position of the camera
    scene->camera->c[1]=0.0; // Position of the camera
    scene->camera->c[0]=0.0; // Position of the camera
    scene->camera->updateView();


    GLfloat c[]= {-0.2, 0.3, 0.1}; // Camera position
    GLfloat aim[]= {0.0, 0.0, 0.0}; // Where we look
    GLfloat up[]= {0.0, 1.0, 0.0}; // Vector pointing over the camera
    //scene->camera->lookAt(c, aim, up);

    //__________________________________________________________________________

    // Creation of the shaders
    std::cout<<"    Shaders reading, compiling and linking"<<std::endl;

    // Compilation and storage of the program
    std::vector<std::string> files;

    // The special shaders used for mac os are only necesary until Snow Leopard
    // From Leon on, mac os drivers version for Opengl is 3.2
    // Therefore the shaders in folder oldGLSL become out-of-date

    // One very simple shader (one color everywhere on the object)
    files.push_back("../shaders/simpleShader.glsl");
    GLuint simpleShaderID=loadProgram(files);
    files.pop_back();
    scene->setDefaultShaderID(simpleShaderID);

    // One coloring shader (colors per vertex)
    files.push_back("../shaders/colorShader.glsl");
    GLuint colorShaderID=loadProgram(files);
    files.pop_back();

    // One lighting shader
#ifdef APPLE
    files.push_back("../shaders/oldGLSL/shaderTools.glsl");
    files.push_back("../shaders/oldGLSL/lightingShader.glsl");
#else
    files.push_back("../shaders/shaderTools.glsl");
    files.push_back("../shaders/lightingShader.glsl");
#endif
    GLuint lightingShaderID=loadProgram(files);
    files.pop_back();
    scene->setDefaultShaderID(lightingShaderID);


    // Uniforms filling
    glUseProgram(lightingShaderID);
    // Material creation and to shader
    GLfloat ambient[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat ka=0.01;
    GLfloat diffuse[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat kd=1.0;
    GLfloat specular[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat ks=2.0;
    GLfloat shininess=5.0;
    setMaterialInShader(lightingShaderID, ambient, diffuse, specular, ka, kd, ks, shininess);

    files.push_back("../shaders/persoShader.glsl");
    GLuint persoShaderID=loadProgram(files);
    files.pop_back();

    // Light creation
    GLfloat lightPosition[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat lightPower=2.0;
    scene->setLight(lightPosition, lightPower);

    // One texture and Phong shader
#ifdef __APPLE__
    files.push_back("../shaders/oldGLSL/lightingTexturingShader.glsl");
#else
    files.push_back("../shaders/lightingTexturingShader.glsl");
#endif
    GLuint lightingTextureShaderID=loadProgram(files);
    files.pop_back();
    glUseProgram(lightingTextureShaderID);
    setMaterialInShader(lightingTextureShaderID, ambient, diffuse, specular, ka, kd, ks, shininess);
    setTextureUnitsInShader(lightingTextureShaderID);


    //__________________________________________________________________________


    // Creation of the objects to store
    std::cout<<"    Generic objects creation and storage :"<<std::endl;

    // Définition du repère
    Object * objectAxis=new Object(GL_LINES);
    GLuint storedObjectAxisID=scene->storeObject(objectAxis);


    // Définition boundingBox
    Object * objectBB=new Object(GL_TRIANGLES);
    GLuint storedObjectBBID=scene->storeObject(objectBB);

    // Définition de la cible
    Object * objectCible=new Object(GL_LINES);
    GLuint storedObjectCibleID=scene->storeObject(objectCible);

    // Environnement
    Object * objectLaby=new Object(GL_TRIANGLES);
    GLuint storedObjectLaby=scene->storeObject(objectLaby);
    bool smoothObjectFlag=true;
    GLuint houseTextureDiffuseID=loadTexture("../textures/mur_contour.ppm");
    GLuint houseTextureSpecularID=loadTexture("../textures/mur_contour.ppm");

    //portal
    Object * objectPortal = new Object(GL_TRIANGLES);
    GLuint storedObjectPortal=scene->storeObject(objectPortal);
    //std::cout<<"IIIIIDDDDDD"<<storedObjectPortal<<std::endl;

    GLuint portalTextureDiffuseID=loadTexture("../textures/mur_contour.ppm");
    GLuint portalTextureSpecularID=loadTexture("../textures/mur_contour.ppm");

    /*Object * objectTr=new Object(GL_TRIANGLES);
    GLuint storedObjectTrID=scene->storeObject(objectTr);*/

//__________________________________________________________________________

    // Object building
    std::cout<<"    Generic objects building :"<<std::endl;


    // Construction du repère
    buildAxis(objectAxis);

    //Construction boundingBox
    //buildCube(objectBB);

    // Construction de la cible
    buildCircle(objectCible, 0.3, 20);

    //environnement
    std::string fileName="../objs/contour.obj";

    buildObjectGeometryFromOBJ(objectLaby, fileName, smoothObjectFlag, 10,10,10);

    /*std::cout << indicesObj[3] << " " << indicesObj[4] << indicesObj[5] << std::endl;

    std::cout << verticesObj[11*4] << " " << verticesObj[11*4+1] << " " << verticesObj[11*4+2] << " " << verticesObj[11*4+3] << std::endl;
    std::cout << verticesObj[10*4] << " " << verticesObj[10*4+1] << " " << verticesObj[10*4+2] << " " << verticesObj[10*4+3] << std::endl;
    std::cout << verticesObj[4] << " " << verticesObj[4+1] << " " << verticesObj[4+2] << " " << verticesObj[4+3] << std::endl << std::endl;

    std::cout << verticesObj[4] << " " << verticesObj[4+1] << " " << verticesObj[4+2] << " " << verticesObj[4+3] << std::endl;
    std::cout << verticesObj[0] << " " << verticesObj[1] << " " << verticesObj[2] << " " << verticesObj[3] << std::endl;
    std::cout << verticesObj[11*4] << " " << verticesObj[11*4+1] << " " << verticesObj[11*4+2] << " " << verticesObj[11*4+3] << std::endl << std::endl;

    for (int i=0; i<24; ++i)
    	std::cout << application->objVertices[i] << " " ;

    std::cout << std::endl;

    std::string fileNamePortal="../objs/portail.obj";
    std::vector<GLfloat> verticesObjPortal;
    std::vector<GLuint> indicesObjPortal;
    std::vector<GLfloat> normalsObjPortal;
    buildObjectGeometryFromOBJ(objectPortal, fileNamePortal, smoothObjectFlag, verticesObjPortal, indicesObjPortal, normalsObjPortal);*/


    /*std::string fileNamePortal="../objs/portail.obj";
    std::vector<GLfloat> verticesObjPortal;
    std::vector<GLuint> indicesObjPortal;
    std::vector<GLfloat> normalsObjPortal;
    buildObjectGeometryFromOBJ(objectPortal, fileNamePortal, smoothObjectFlag, verticesObjPortal, indicesObjPortal, normalsObjPortal);*/


    //__________________________________________________________________________

    // Objects we want to see
    std::cout<<"    Objects to draw setting"<<std::endl;


    //axis
    GLuint axisID=scene->addObjectToDraw(storedObjectAxisID);
    scene->setDrawnObjectShaderID(axisID, lightingShaderID);

    //BoundingBox
    GLuint BBID=scene->addObjectToDraw(storedObjectBBID);
    //scene->setDrawnObjectShaderID(BBID, lightingShaderID);

    GLfloat yellow[4]= {0.0, 0.8, 0.4, 1.0};
    scene->setDrawnObjectColor(BBID, yellow);


    //cible
    GLuint cibleID=scene->addObjectToDraw(storedObjectCibleID);
    scene->setDrawnObjectShaderID(cibleID, lightingShaderID);
    GLfloat blue[4]= {0.0, 0.3, 0.7, 1.0};
    scene->setDrawnObjectColor(cibleID, blue);

    //environnement
    GLfloat S[16];
    GLfloat s[3] = {3.0, 2.0, 3.0} ;
    setToScale(S, s);

    GLuint labyID=scene->addObjectToDraw(storedObjectLaby);
    //scene->setDrawnObjectModel(labyID, S);
    scene->setDrawnObjectColor(labyID, red);
    scene->setDrawnObjectShaderID(labyID, lightingShaderID);
    //std::cout<<"ID SHADER :"<<lightingShaderID<<std::endl;
    /*cible
    GLuint trID=scene->addObjectToDraw(storedObjectTrID);
    scene->setDrawnObjectShaderID(trID, lightingShaderID);
    GLfloat zarb[4]={0.4, 0.7, 0.2, 1.0};
    scene->setDrawnObjectColor(trID, zarb);*/

    std::cout<<scene->nbStoredObjects<<std::endl;

    //__________________________________________________________________________

    // Other informations
    // Background color creation
    GLfloat black[]= {0.0, 0.0, 0.0, 1.0};
    application->setBackgroundColor(black);

    //__________________________________________________________________________

    // Errors checking
    std::cout<<"    Errors cheking before the loop"<<std::endl;
    printGlErrors();
    std::cout<<std::endl;
    //__________________________________________________________________________

    // Loop start !
    std::cout<<"    Looping !! "<<std::endl;
    application->lastStartTime=getTime();
    application->initTimers();
    application->loop();
    printGlErrors();
    std::cout<<std::endl;
    //__________________________________________________________________________

    // Cleaning and finishing
    std::cout<<"    Cleaning before leaving"<<std::endl;
    delete application;

    return 0;
}