Esempio n. 1
0
void idle()
{
	calcFPS();
	glCheckError("idle");

	static Timer t;
	double dt = t.elapsed_time();
	NxSphere person;
	person.center = g_CameraPos;
	person.radius = 2.0f;

	if(IS_KEY_DOWN('w') || IS_KEY_DOWN('W'))
	{
		g_CameraPos += g_CameraForward*g_Speed*dt;
		if(gMyPhysX.getScene()->checkOverlapSphere(person,NX_ALL_SHAPES))
			g_CameraPos -= g_CameraForward*g_Speed*dt;
	}
	if(IS_KEY_DOWN('s') || IS_KEY_DOWN('S'))
	{
		g_CameraPos -= g_CameraForward*g_Speed*dt;
	}
	if(IS_KEY_DOWN('q') || IS_KEY_DOWN('Q'))
		g_CameraPos +=NxVec3(0.0f,1.0f,0.0f)*g_Speed*dt;
	if(IS_KEY_DOWN('e') || IS_KEY_DOWN('E'))
		g_CameraPos -=NxVec3(0.0f,1.0f,0.0f)*g_Speed*dt;
	if(IS_KEY_DOWN('a') || IS_KEY_DOWN('A'))
		g_CameraPos -= g_CameraRight*g_Speed*dt;
	if(IS_KEY_DOWN('d') || IS_KEY_DOWN('D'))
		g_CameraPos += g_CameraRight*g_Speed*dt;

	t.reset();
	glutPostRedisplay();
}
Esempio n. 2
0
	void idle() {
		if (!pause || single) {
			run();
			ticks++;
			single = false;
		}
		glutPostRedisplay();
		calcFPS();
	}
Esempio n. 3
0
void GLRenderWidget::initialize(QWidget *parent)
{
	createGLContext(parent);

	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable( GL_TEXTURE_2D );
	//setuping opengl surface engine
    ASSERT_WITH_CODE(initShaders() == true && initSceneRenderTraget() == true, "Critical error occurred during OpenGL initialization! \r\nProgram will stop in 30 seconds or terminate it manually...", Sleep(30000);exit(1));
    ASSERT_WITH_CODE(MqsOpenGlSurface::initOpenGl(GLContext) == true, "Critical error occurred during OpenGL initialization! \r\nProgram will stop in 30 seconds or terminate it manually...", Sleep(30000);exit(1));

    setMouseTracking(true);

	//setuping timers
	QTimer *fps_timer = new QTimer(this);
	connect(fps_timer, SIGNAL(timeout()), this, SLOT(calcFPS()));
	fps_timer->start(1000);

	QTimer *render_timer = new QTimer(this);
	connect(render_timer, SIGNAL(timeout()), this, SLOT(paintGL()));
    render_timer->start(30);

	connect(this, SIGNAL(initMainScene()), parent, SLOT(initScene()));
	emit initMainScene();

	// create textures for FBO
	glGenTextures(1, &render_rgb_texture_id);
	glGenTextures(1, &render_depth_texture_id);
    glGenFramebuffers(1, &_fboId);
    glGenBuffers(2, _rgb_pbo);
    glGenBuffers(2, _yuv_y_pbo);
    glGenBuffers(2, _yuv_u_pbo);
    glGenBuffers(2, _yuv_v_pbo);

	traceerr("OpenGl render initialized successfully...");
}
Esempio n. 4
0
void idle()
{
	calcFPS();
	glCheckError("idle");

	static Timer t;
	double dt = t.elapsed_time();

	if(IS_KEY_DOWN('w') || IS_KEY_DOWN('W'))
		g_CameraPos += g_CameraForward*g_Speed*dt;
	if(IS_KEY_DOWN('s') || IS_KEY_DOWN('S'))
		g_CameraPos -= g_CameraForward*g_Speed*dt;
	if(IS_KEY_DOWN('q') || IS_KEY_DOWN('Q'))
		g_CameraPos +=NxVec3(0.0f,1.0f,0.0f)*g_Speed*dt;
	if(IS_KEY_DOWN('e') || IS_KEY_DOWN('E'))
		g_CameraPos -=NxVec3(0.0f,1.0f,0.0f)*g_Speed*dt;
	if(IS_KEY_DOWN('a') || IS_KEY_DOWN('A'))
		g_CameraPos -= g_CameraRight*g_Speed*dt;
	if(IS_KEY_DOWN('d') || IS_KEY_DOWN('D'))
		g_CameraPos += g_CameraRight*g_Speed*dt;

	t.reset();
	glutPostRedisplay();
}
Esempio n. 5
0
void C_API Program::Render(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	glInitNames();

	if (m_ShowText)
	{
		begin2D(m_window_width, m_window_height);

		glColor3f(1.0f, 1.0f, 1.0f);
		glPrintf(10, m_window_height-20, "Object Loaded In %f Seconds", m_LoadedObj.fLoadTimeInSecs);
		glPrintf(10, m_window_height-40, "Vertices: %u", m_LoadedObj.nVertexCount);
		glPrintf(10, m_window_height-60, "Normals:  %u", m_LoadedObj.nNormalCount);
		glPrintf(10, m_window_height-80, "UVs:      %u", m_LoadedObj.nUVCount);
		glPrintf(10, 20, "FPS: %i", calcFPS());

		end2D();
	}

	if (m_LoadedObj.pMesh != NULL)
	{
		glPushMatrix();

		glTranslatef(0.0f, 0.0f, m_Zoom);
		glRotatef(-(m_AngleY), 1.0f, 0.0f, 0.0f);
		glRotatef(-(m_AngleX), 0.0f, 1.0f, 0.0f);

		Mesh::RenderMode renderMode;

		if (m_Wireframe)
		{
			renderMode = Mesh::Wireframe;
			glLineWidth(1.0f);

			// Wireframe Line Color:
			glColor3f(0.6f, 0.6f, 0.77f);
		}
		else
		{
			renderMode = Mesh::Solid;
			glLineWidth(2.0f);
		}

		// Render Everything:
		if (m_LoadedObj.nDrawByGroupID == -1)
		{
			// First Pass, Normal Rendering:
			if ((m_LoadedObj.nNormalCount > 0) && (!m_Wireframe))
			{
				glEnable(GL_LIGHTING);
				glEnable(GL_LIGHT0);
			}

			m_LoadedObj.pMesh->SetRenderMode(renderMode);
			Mesh::GroupMap::const_iterator GroupIndex = m_LoadedObj.pMesh->Groups().begin();
			Mesh::GroupMap::const_iterator LastGroup  = m_LoadedObj.pMesh->Groups().end();

			GLuint name = 0;

			while (GroupIndex != LastGroup)
			{
				glPushName(name);
					m_LoadedObj.pMesh->Render(GroupIndex);
				glPopName();

				++name;
				++GroupIndex;
			}

			if ((m_LoadedObj.nNormalCount > 0) && (!m_Wireframe))
			{
				glDisable(GL_LIGHT0);
				glDisable(GL_LIGHTING);
			}

			// Second Pass, Draw Group Outline:
			if (m_LoadedObj.nSelectedGroup != -1)
			{
				glColor3f(0.2f, 0.8f, 0.35f); // Give It A Cool Maya Style Outline Color.
				m_LoadedObj.pMesh->SetRenderMode(Mesh::Wireframe);
				m_LoadedObj.pMesh->Render(m_LoadedObj.pMesh->Groups().find(m_vMeshGroups[m_LoadedObj.nSelectedGroup]));
			}
		}
		else // Render The Selected Group Only:
		{
			if ((m_LoadedObj.nNormalCount > 0) && (!m_Wireframe))
			{
				glEnable(GL_LIGHTING);
				glEnable(GL_LIGHT0);
			}

			m_LoadedObj.pMesh->SetRenderMode(renderMode);
			m_LoadedObj.pMesh->Render(m_LoadedObj.pMesh->Groups().find(m_vMeshGroups[m_LoadedObj.nDrawByGroupID]));

			if ((m_LoadedObj.nNormalCount > 0) && (!m_Wireframe))
			{
				glDisable(GL_LIGHT0);
				glDisable(GL_LIGHTING);
			}
		}

		glPopMatrix();
	}

	glFlush();
	glutSwapBuffers();
}
Esempio n. 6
0
int main(void)
{
    GLFWwindow* window;


    int width = 1024;
    int height = 768;

    glfwSetErrorCallback (glfw_error_callback);
    if(!glfwInit ()) {
        fprintf (stderr, "ERROR: could not start GLFW3\n");
        return 1;
    }

	glfwWindowHint(GLFW_SAMPLES, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    // to use this: http://stackoverflow.com/questions/17923782/simple-opengl-image-library-soil-uses-deprecated-functionality
//	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 
	glfwWindowHint(GLFW_OPENGL_PROFILE,	GLFW_OPENGL_COMPAT_PROFILE);

    /*glfwWindowHint(GLFW_SAMPLES, 1); // 2x antialiasing
    int stencil_bits = 8;

    glfwWindowHint(GLFW_STENCIL_BITS, 8); // request a stencil buffer for object selection*/
    glfwWindowHint(GLFW_ALPHA_BITS, 8);
    
    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(width, height, "Game", NULL, NULL);
    glfwRestoreWindow(window);
    if (!window)
    {
        glfwTerminate();
        return -1; 
    }
    /* Make the window's context current */
    glfwMakeContextCurrent(window);
    
  
    // start GLEW extension handler
    glewExperimental = GL_TRUE;
    
    GLenum err = glewInit();
    if(err != GLEW_OK)
    {
        cout << "GLEW error: " << glewGetErrorString(err);
        exit(1); // or handle the error in a nicer way
    }
    GLenum glErr = glGetError();
    if (glErr != GL_NO_ERROR)
    {
        cout << "Caught GLEW init error in GL" << endl;
    }

    printOpenGLError();
            
    // get version info
    const GLubyte* gl_renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* gl_version = glGetString (GL_VERSION); // version as a string
    int gl_alpha;
    glGetIntegerv(GL_ALPHA_BITS, &gl_alpha);
    printf ("Renderer: %s\n", gl_renderer);
    printf ("OpenGL version supported %s\n", gl_version);
    printf ("Alphabits: %d", gl_alpha);
    
    glfwSwapInterval(1);
    
    printOpenGLError();
    cout << "Setting GL" << endl;
        
    //glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
    glClearColor(0.9f, 0.9f, 0.99f, 1.0f);
    glEnable(GL_DEPTH_TEST);
    glClearDepth(1.0f);
    glDepthFunc(GL_LESS);
	glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_CULL_FACE);

    glfwSetCharCallback(window, &Input::glfw_character_callback);
    glfwSetKeyCallback(window, &Input::glfw_key_callback);
    
    // create new Lua state
    lua_State *lua_state;
    lua_state = luaL_newstate();
    luaL_openlibs(lua_state);
 
    // load Lua libraries
    /*static const luaL_Reg lualibs[] =
    {
        { "base", luaopen_base },
        { "io", luaopen_io },
        { "string", luaopen_string },
        { NULL, NULL}
    };
 
    const luaL_Reg *lib = lualibs;
    for(; lib->func != NULL; lib++)
    {
        lib->func(lua_state);
        lua_settop(lua_state, 0);
    }*/
    
    lua_pushcfunction(lua_state, lua_set_camera);
    lua_setglobal(lua_state, "camera");
        
    lua_pushcfunction(lua_state, lua_drawcube);
    lua_setglobal(lua_state, "drawblock");
    
    lua_pushcfunction(lua_state, lua_load_renderer);
    lua_setglobal(lua_state, "load_renderer");
    
    lua_pushcfunction(lua_state, lua_drawbatch);
    lua_setglobal(lua_state, "drawbatch");
    
    lua_pushcfunction(lua_state, lua_time);
    lua_setglobal(lua_state, "time");
    
    run(lua_state, "class.lua");
    run(lua_state, "entity.lua");
    run(lua_state, "world.lua");
    run(lua_state, "component.lua");
    run(lua_state, "block.lua");
    run(lua_state, "physics.lua");
    run(lua_state, "load.lua");
    
    //camera = new CameraArcBall(glm::vec3(5,5,5), glm::vec3(0,0,0));
    
    //renderer.push_back(new RenderCube("assets/textures/grass.jpg", "assets/textures/dirt.jpg")); // default renderer?
        
    cout << "Starting main loop:" << endl;
    
    glm::vec3 size = glm::vec3(2);
    
    RenderQuad quad("assets/textures/jap.png", "inversion");
    RenderRect rect("assets/textures/tex16.png", "inversion2");
    
    BatchedRenderCube batch("assets/textures/dirt.jpg");
    
    cout << "[initmain]" << endl;
    printOpenGLError();
    
    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window) && !glfwGetKey(window, GLFW_KEY_ESCAPE))
    {
        glfwGetWindowSize(window, &width, &height);
        glViewport(0, 0, width, height);
        
        //glClearStencil(0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT /*| GL_STENCIL_BUFFER_BIT*/);
        
        // update input and actions
        Input::instance().update(window);
        
        // update view and projection
        camera->update(window);
        
        if(glfwGetKey(window, 'U'))
            run(lua_state, "action.lua");
        
        run(lua_state, "update.lua");
        run(lua_state, "render.lua");
        
        if(glfwGetKey(window, 'F'))
            std::cout << "FPS: " << calcFPS(glfwGetTime()) << std::endl;
        if(glfwGetKey(window, 'Q'))
            screenshot();
            
        quad.draw(camera, glm::vec3(0, 0, 0));
        
        if(glfwGetKey(window, GLFW_KEY_ENTER))
            rect.draw(camera, glm::vec2(width, height));
            
        printOpenGLError();
        
        /* Swap front and back buffers */
        glfwSwapBuffers(window);
        /* Poll for and process events */
        glfwPollEvents();
    }
	// Cleanup VBO and shader
	//glDeleteBuffers(1, &vertexbuffer);
	//glDeleteProgram(shader.id());
    
    // close the Lua state
    lua_close(lua_state);
    glfwTerminate();
    return 0;
}
Esempio n. 7
0
int main (int argc, char* argv[]) {

    srand (static_cast<unsigned>(time(0)));

    // Magic
    glewExperimental = GL_TRUE;
    
    // Init GLEW and GLFW
    if(initializeOpenGL() == -1) {
        return -1;
    }

    scene = new Scene();
    utilHandler = new Utils();

    createPreDefinedVoronoiPoints();

    scene->setPreComputedVoronoiPoints(sVoronoiPoints);
    
    // Create geometries and add them to the scene

    // Floor
    floor_rect = new Rectangle(1.0f, 1.0f, Vector3<float>(0.0f, 0.0f, 0.0f));
    floor_rect->rotate(Vector3<float>(1.0f, 0.0f, 0.0f), 90.0f);
    floor_rect->scale(Vector3<float>(2.5f, 1.0f, 2.0f));
    floor_rect->translate(Vector3<float>(0.0f, -0.35f, 0.0f));

    // HalfEdge mesh
    mesh = new HalfEdgeMesh(Vector4<float>(0.2f, 0.8f, 0.2f, 0.4f));
    mesh->addVoronoiPoint(Vector3<float>(0.0f, 0.0f, 0.0f));
    mesh->setDebugMode(true);

    // The following meshes has pre-defined voronoi patterns
    
    //mesh->createMesh("pillar");
    //mesh->createMesh("icosphere");
    //mesh->createMesh("bunnySmall_reduced");
    //mesh->createMesh("cube");
    mesh->createMesh("cow_2");

    mesh->markCurrentVoronoiPoint(currentVoronoiIndex, Vector4<float>(1.0f, 1.0f, 1.0f, 1.0f));
    scene->addGeometry(floor_rect, STATIC);
    scene->addGeometry(mesh, STATIC);

    initializeScene();

    //Set functions to handle mouse input
    glfwSetMouseButtonCallback(window, mouseButton);
    glfwSetCursorPosCallback(window, mouseMotion);
    glfwSetScrollCallback(window, mouseScroll);
    glfwSetKeyCallback(window, keyboardInput);

    // render-loop
    do {
        calcFPS(1.0, windowTitle);
        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // render all geometries
        scene->render();
        scene->stepSimulation();

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while ( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
           glfwWindowShouldClose(window) == 0 );

    // Clean-up
    delete scene;

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
Esempio n. 8
0
/*!
onPaint does all the rendering for one frame from scratch with OpenGL (in core
profile).
*/
bool onPaint()
{  
    // Clear the color & depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // View transform: move the coordinate system away from the camera
    _viewMatrix.identity();
    _viewMatrix.translate(0, 0, _camZ);

    // View transform: rotate the coordinate system increasingly by the mouse
    _viewMatrix.rotate(_rotX + _deltaX, 1,0,0);
    _viewMatrix.rotate(_rotY + _deltaY, 0,1,0);

    // Transform light position & direction into view space
    SLVec3f lightPosVS = _viewMatrix * _lightPos;

    // The light dir is not a position. We only take the rotation of the mv matrix.
    SLMat3f viewRot    = _viewMatrix.mat3();
    SLVec3f lightDirVS = viewRot * _lightDir;

    // Rotate the model so that we see the square from the front side
    // or the earth from the equator.
    _modelMatrix.identity();
    _modelMatrix.rotate(90, -1,0,0);

    // Build the combined model-view and model-view-projection matrix
    SLMat4f mvp(_projectionMatrix);
    SLMat4f mv(_viewMatrix * _modelMatrix);
    mvp.multiply(mv);

    // Build normal matrix
    SLMat3f nm(mv.inverseTransposed());

    // Pass the matrix uniform variables
    glUniformMatrix4fv(_mvMatrixLoc,  1, 0, (float*)&mv);
    glUniformMatrix3fv(_nMatrixLoc,   1, 0, (float*)&nm);
    glUniformMatrix4fv(_mvpMatrixLoc, 1, 0, (float*)&mvp);

    // Pass lighting uniforms variables
    glUniform4fv(_globalAmbiLoc,     1, (float*)&_globalAmbi);
    glUniform3fv(_lightPosVSLoc,     1, (float*)&lightPosVS);
    glUniform3fv(_lightDirVSLoc,     1, (float*)&lightDirVS);
    glUniform4fv(_lightAmbientLoc,   1, (float*)&_lightAmbient);
    glUniform4fv(_lightDiffuseLoc,   1, (float*)&_lightDiffuse);
    glUniform4fv(_lightSpecularLoc,  1, (float*)&_lightSpecular);
    glUniform4fv(_matAmbientLoc,     1, (float*)&_matAmbient);
    glUniform4fv(_matDiffuseLoc,     1, (float*)&_matDiffuse);
    glUniform4fv(_matSpecularLoc,    1, (float*)&_matSpecular);
    glUniform4fv(_matEmissiveLoc,    1, (float*)&_matEmissive);
    glUniform1f (_matShininessLoc,   _matShininess);
    glUniform1i (_texture0Loc,       0);
     
    //////////////////////
    // Draw with 2 VBOs //
    //////////////////////

    // Enable all of the vertex attribute arrays
    glEnableVertexAttribArray(_pLoc);
    glEnableVertexAttribArray(_nLoc);
    glEnableVertexAttribArray(_tLoc);

    // Activate VBOs
    glBindBuffer(GL_ARRAY_BUFFER, _vboV);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vboI);

    // Activate Texture
    glBindTexture(GL_TEXTURE_2D, _textureID);

    // For VBO only offset instead of data pointer
    GLsizei stride  = sizeof(VertexPNT);
    GLsizei offsetN = sizeof(SLVec3f);
    GLsizei offsetT = sizeof(SLVec3f) + sizeof(SLVec3f);
    glVertexAttribPointer(_pLoc, 3, GL_FLOAT, GL_FALSE, stride, 0);
    glVertexAttribPointer(_nLoc, 3, GL_FLOAT, GL_FALSE, stride, (void*)offsetN);
    glVertexAttribPointer(_tLoc, 2, GL_FLOAT, GL_FALSE, stride, (void*)offsetT);
   
    ////////////////////////////////////////////////////////
    // Draw cube model triangles by indexes
    glDrawElements(GL_TRIANGLES, _numI, GL_UNSIGNED_INT, 0);
    ////////////////////////////////////////////////////////

    // Deactivate buffers
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    // Disable the vertex arrays
    glDisableVertexAttribArray(_pLoc);
    glDisableVertexAttribArray(_nLoc);
    glDisableVertexAttribArray(_tLoc);

    // Check for errors from time to time
    GETGLERROR;

    // Fast copy the back buffer to the front buffer. This is OS dependent.
    glfwSwapBuffers(window);

    // Calculate frames per second
    char title[255];
    static float lastTimeSec = 0;
    float timeNowSec = (float)glfwGetTime();
    float fps = calcFPS(timeNowSec-lastTimeSec);
    sprintf(title, "Sphere, %d x %d, fps: %4.0f", _resolution, _resolution, fps);
    glfwSetWindowTitle(window, title);
    lastTimeSec = timeNowSec;

    // Return true to get an immediate refresh
    return true;
}
Esempio n. 9
0
int main()
{
	init();

  GLenum buffer[1];
  float dt;

  cam->translate(vec3(0,0,2));

	while(running)
	{
    calcFPS(dt);

    //timeStamps[0] = glfwGetTime();
    glGenQueries(7, queryID);
    glQueryCounter(queryID[0], GL_TIMESTAMP);

		modifyCamera(dt);
    cam->setup();

    // RENDER GEOMETRY PASS
    glEnable(GL_DEPTH_TEST);

    fboFullRes->bind();
    glClearColor(0.2, 0.3, 0.5, 1.0);
    glClearDepth(1.0);
		glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    geometryShader->bind();

    glUniformMatrix4fv(geometryShader->getViewMatrixLocation(), 1, false, glm::value_ptr(cam->getViewMatrix()));
    glUniformMatrix4fv(geometryShader->getProjMatrixLocation(), 1, false, glm::value_ptr(cam->getProjMatrix()));

    mdl->draw();
    //model->draw();

    //timeStamps[1] = glfwGetTime();
    glQueryCounter(queryID[1], GL_TIMESTAMP);

    glDisable(GL_DEPTH_TEST);

    //glColorMask(1, 0, 0, 0);
    //glDepthFunc(GL_ALWAYS);

    if(!fullres)
    {
      glActiveTexture(GL_TEXTURE0);
      glBindTexture(GL_TEXTURE_2D, fboFullRes->getBufferHandle(FBO_DEPTH));

      // Downsample depth
      fboHalfRes->bind();

      buffer[0] = GL_COLOR_ATTACHMENT0;
      glDrawBuffers(1, buffer);

      downsampleShader->bind();
      fsquad->draw();

    }

    //timeStamps[2] = glfwGetTime();
    glQueryCounter(queryID[2], GL_TIMESTAMP);

    // AO pass

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, noiseTexture);

    if(!fullres)
    {
      glActiveTexture(GL_TEXTURE0);
      glBindTexture(GL_TEXTURE_2D, fboHalfRes->getBufferHandle(FBO_AUX0));

      buffer[0] = GL_COLOR_ATTACHMENT1;
      glDrawBuffers(1, buffer);

      hbaoHalfShader->bind();
      //ssaoShader->bind();

      fsquad->draw();
    }
    else
    {
      glActiveTexture(GL_TEXTURE0);
      glBindTexture(GL_TEXTURE_2D, fboFullRes->getBufferHandle(FBO_DEPTH));

      buffer[0] = GL_COLOR_ATTACHMENT1;
      glDrawBuffers(1, buffer);

      hbaoFullShader->bind();
      fsquad->draw();
    }

    //timeStamps[3] = glfwGetTime();
    glQueryCounter(queryID[3], GL_TIMESTAMP);

    // Upsample

    if(!fullres)
    {
      glActiveTexture(GL_TEXTURE0);
      glBindTexture(GL_TEXTURE_2D, fboFullRes->getBufferHandle(FBO_DEPTH));

      glActiveTexture(GL_TEXTURE1);
      glBindTexture(GL_TEXTURE_2D, fboHalfRes->getBufferHandle(FBO_AUX1));

      fboFullRes->bind();

      buffer[0] = GL_COLOR_ATTACHMENT1;
      glDrawBuffers(1, buffer);

      upsampleShader->bind();

      fsquad->draw();
    }

    //timeStamps[4] = glfwGetTime();
    glQueryCounter(queryID[4], GL_TIMESTAMP);

    if(blur)
    {
      // BLUR 

      glActiveTexture(GL_TEXTURE0);
      glBindTexture(GL_TEXTURE_2D, fboFullRes->getBufferHandle(FBO_AUX1));

      // X
      buffer[0] = GL_COLOR_ATTACHMENT2;
      glDrawBuffers(1, buffer);

      blurXShader->bind();

      fsquad->draw();

      // Y
      buffer[0] = GL_COLOR_ATTACHMENT1;
      glDrawBuffers(1, buffer);

      blurYShader->bind();

      glActiveTexture(GL_TEXTURE0);
      glBindTexture(GL_TEXTURE_2D, fboFullRes->getBufferHandle(FBO_AUX2));

      fsquad->draw();

    }

    //timeStamps[5] = glfwGetTime();
    glQueryCounter(queryID[5], GL_TIMESTAMP);

    fboFullRes->unbind();

    // RENDER TO SCREEN PASS

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, fboFullRes->getBufferHandle(FBO_AUX0));

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, fboFullRes->getBufferHandle(FBO_AUX1));

    //glClearColor(1.0, 1.0, 1.0, 0.0);
    //glClear(GL_COLOR_BUFFER_BIT);
    glViewport(0, 0, WIDTH, HEIGHT);

    compositShader->bind();

    fsquad->draw();
		
		glfwSwapBuffers();

		if(!glfwGetWindowParam(GLFW_OPENED))
			running = false;

    //timeStamps[6] = glfwGetTime();
    glQueryCounter(queryID[6], GL_TIMESTAMP);

    // wait until the results are available
    GLint stopTimerAvailable = 0;
    bool stop = false;

    while (!stop) {
      stop = true;
      for(int i=0; i<7; ++i)
      {
        glGetQueryObjectiv(queryID[1], GL_QUERY_RESULT_AVAILABLE, &stopTimerAvailable);
        if(!stopTimerAvailable)
          stop = false;
      }
    }
	}

	cleanUp();

	return 0;
}
Esempio n. 10
0
void QImageGrabberMjpeg::replyDataAvailable()
{
    if (currentState != GrabbingOn) {
        currentState = GrabbingOn;
        emit stateChanged(currentState);
    }
    QString cLine;
    if (mjpgState == MjpgBoundary) {
        if (streamType == StreamTypeUnknown) {
            if (reply->bytesAvailable() >= 50) {
                cLine = reply->readLine(51);
                if (cLine.startsWith("mjpeg")) {
                    streamType = StreamTypeWebcamXP;
                    bool ok = false;
                    currentImageSize = cLine.mid(5,8).toInt(&ok);
                    if (ok) {
                        imageBuffer->seek(0);
                        mjpgState = MjpgJpg;
                        qWarning() << currentImageSize << "CI" << cLine;
                    } else {
                        qWarning() << QString("Could not convert %1 to number").arg(cLine.mid(5,7));
                    }
                    // we need to seek a bit
                } else {
                    streamType = StreamTypeMjpgStreamer;
                }
            } else { // to few bytes came so return the next readyíread will take us further
                return;
            }
        }

        if (mjpgState == MjpgBoundary) {
            if (streamType == StreamTypeWebcamXP) {
                if (reply->bytesAvailable() >= 50) {
                    QByteArray borderArray = reply->read(51);
                    if (!borderArray.startsWith("mjpeg")) {
                        qWarning() << "invalid border" << borderArray;
                        return;
                    } else {
                        bool ok = false;
                        currentImageSize = borderArray.mid(5,8).toInt(&ok);
                        if (ok) {
                            imageBuffer->seek(0);
                            mjpgState = MjpgJpg;
                            qWarning() << currentImageSize << "CI" << borderArray;
                        } else {
                            qWarning() << QString("Could not convert %1 to number").arg(QString(borderArray.mid(5,7)));
                        }
                    }
                } else {  // too few bytes came so return the next readyíread will take us further
                    return;
                }
            } else if(streamType == StreamTypeMjpgStreamer) {
                bool quitNext = false;
                while(reply->canReadLine()) {
                    QString cLine = reply->readLine();
                    if (quitNext)
                        break;
                    if (cLine.startsWith("Content-Length:")) {
                        bool ok = false;
                        currentImageSize = cLine.mid(16).toInt(&ok);
                        if (!ok) {
                            qWarning() << QString("Could not convert %1 to number").arg(cLine.mid(16));
                            return;
                        }
                    } else if (cLine.startsWith("X-Timestamp:")) {
                        if (m_timestampRegexp.indexIn(cLine) > -1) {
                            m_timestampInMs =
                                    m_timestampRegexp.cap(1).toLong() * 1000 +
                                    m_timestampRegexp.cap(2).toLong();
                        }
                        mjpgState = MjpgJpg;
                        quitNext = true;
                    }
                }
            }
        }
    }

    if (mjpgState == MjpgJpg) {
        imageBuffer->write(reply->read(currentImageSize - imageBuffer->pos()));
        if (imageBuffer->pos() == currentImageSize) {
            bool ok = false;
            imageReader->setDevice(imageBuffer);
            imageBuffer->seek(0);
            ok = imageReader->read(currentImage);
            imageBuffer->seek(0);
            if (ok == true) {
                emit newImageGrabbed(currentImage);
                calcFPS(requestTime.msecsTo(QTime::currentTime()));
                requestTime = QTime::currentTime();
            } else {
                qWarning() << "Image read fail" << imageReader->errorString();
            }
            mjpgState = MjpgBoundary;
        }
    }
}