void StelQGLRenderer::drawWindow(StelViewportEffect* const effect)
{
	// At this point, FBOs have been released (if using FBOs), so we're drawing 
	// directly to the screen. The StelViewportEffect::drawToViewport call 
	// actually draws puts the rendered result onto the viewport.
	invariant();

	//Warn about any GL errors.
	checkGLErrors("drawWindow() start");
	
	//Effects are ignored when FBO is not supported.
	//That might be changed for some GPUs, but it might not be worth the effort.
	
	viewport.prepareToDrawViewport();

	if(NULL == effect)
	{
		// If using FBO, we still need to put it on the screen.
		if(viewport.useFBO())
		{
			StelTextureNew* screenTexture = getViewportTexture();
			const QSize size = screenTexture->getDimensions();

			glDisable(GL_BLEND);
			setGlobalColor(Vec4f(1.0f, 1.0f, 1.0f, 1.0f));
			screenTexture->bind();
			drawTexturedRect(0, 0, size.width(), size.height());
			delete screenTexture;
		}
		// If not using FBO, the result is already drawn to the screen.
	}
	else
	{
		effect->drawToViewport(this);
	}

	viewport.disablePainting();

	checkGLErrors("drawWindow() end");
	invariant();
}
void Terrain::createTextures(GLuint id) {

    checkGLErrors("before height map upload");

//    glGenTextures(1, &heightTexture_);
    glBindTexture(GL_TEXTURE_2D, id);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, width_, height_, 0, GL_LUMINANCE, GL_UNSIGNED_SHORT, heightValues_);
    glGenerateMipmap(GL_TEXTURE_2D);

    std::cout << "height map uploaded.." << std::endl;

    checkGLErrors("after height map upload");

    glBindTexture(GL_TEXTURE_2D, 0);

    checkGLErrors("after uploading material textures");
}
Example #3
0
int main(int argc, char **argv)
{
	GLContext ctx;
	if (!ctx.create(VideoMode(720, 480, 24, 0, 4), "12 Framebuffer", true, true))
	{
		APP_LOG << "Failed to open context\n";
		return EXIT_FAILURE;
	}
	APP_LOG << ctx.getDebugInfo();

	Renderer gfx;
	gfx.init(ctx);

	try
	{
		if (!load())
		{
			gfx.dispose();
			ctx.dispose();
			APP_LOG << "Failed to load content\n";
			return EXIT_FAILURE;
		}

		init(gfx, ctx);

		double dt = 0.0;
		while (ctx.isOpen())
		{
			double frame_t = ctx.getElapsedTime();
			update(gfx, ctx, dt);
			
			render(gfx, ctx, dt);
			ctx.display();
			ctx.pollEvents();

			if (ctx.isKeyPressed(SDL_SCANCODE_ESCAPE))
				ctx.close();

			if (checkGLErrors())
				ctx.close();
			dt = ctx.getElapsedTime() - frame_t;
		}
	}
	catch (std::exception &e)
	{
		APP_LOG << "An unexpected error occurred: " << e.what();
	}

	free();
	gfx.dispose();
	ctx.dispose();
	return EXIT_SUCCESS;
}
Example #4
0
void Shader::printShaderInfoLog(GLint shader)
{
	int infoLogLen = 0;
	int charsWritten = 0;
	GLchar *infoLog;

	glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLen);

	checkGLErrors("shaderinfolog");

	if (infoLogLen > 0)
	{
		infoLog = new GLchar[infoLogLen];

		glGetShaderInfoLog(shader,infoLogLen, &charsWritten, infoLog);
		std::cout << "InfoLog:" << std::endl << infoLog << std::endl;
		delete [] infoLog;
	}

	checkGLErrors("shaderinfolog");
}
Example #5
0
void Graphics::drawPhong(const Entity& e)
{
	sheikki_glBindVertexArray(e.model.VAO_id);
	glUseProgram(phongShader.getId());
	phongShader.passUniforms(e, perspective);
	glBindTexture(GL_TEXTURE_2D, e.GetTexture());
	glDrawElements(GL_TRIANGLES, 3*e.model.num_polygons, GL_UNSIGNED_INT, 0);

	glUseProgram(0);
	
	checkGLErrors("drawPhong");
}
Example #6
0
//The application main loop
void mainLoop()
{
	SDL_Event sdlEvent;
	int x,y;

	SDL_GetMouseState(&x,&y);
	game->mouse_position.set(x,y);

	while (1)
	{
		//render frame
		game->render();

		//update events
		while(SDL_PollEvent(&sdlEvent))
		{
			switch(sdlEvent.type)
				{
					case SDL_QUIT: return; break; //EVENT for when the user clicks the [x] in the corner
					case SDL_MOUSEBUTTONDOWN: //EXAMPLE OF sync mouse input
						game->onMouseButton( sdlEvent.button );
						break;
					case SDL_MOUSEBUTTONUP:
						//...
						break;
					case SDL_KEYDOWN: //EXAMPLE OF sync keyboard input
						game->onKeyPressed( sdlEvent.key );
						break;
				}
		}

		//read keyboard state and stored in keystate
		game->keystate = SDL_GetKeyState(NULL);

		//get mouse position and delta
		game->mouse_state = SDL_GetMouseState(&x,&y);
		game->mouse_delta.set( game->mouse_position.x - x, game->mouse_position.y - y );
		game->mouse_position.set(x,y);

		//update logic
		double elapsed_time = (SDL_GetTicks() - last_time) * 0.001; //0.001 converts from milliseconds to seconds
		last_time = SDL_GetTicks();
		game->update(elapsed_time); 

		//check errors in opengl only when working in debug
		#ifdef _DEBUG
			checkGLErrors();
		#endif
	}

	return;
}
Example #7
0
int main(int argc, char *argv[])
{

    argc = argc;
    argv = argv;

    if (!initGraphics())
    {
        fprintf(stderr, "Graphics initialization failed.\n");
        return EXIT_FAILURE;
    }

    appInit();

    while (gAppAlive)
    {
        struct timeval timeNow;

        while (XPending(sDisplay))
        {
            XEvent ev;
            XNextEvent(sDisplay, &ev);
            switch (ev.type)
            {
            case KeyPress:
                {
                    unsigned int keycode, keysym;
                    keycode = ((XKeyEvent *)&ev)->keycode;
                    keysym = XKeycodeToKeysym(sDisplay, keycode, 0);
                    if (keysym == XK_Return || keysym == XK_Escape)
                        gAppAlive = 0;
                }
                break;
            }
        }

        if (gAppAlive)
        {
            gettimeofday(&timeNow, NULL);
            appRender(timeNow.tv_sec * 1000 + timeNow.tv_usec / 1000,
                      sWindowWidth, sWindowHeight);
            checkGLErrors();
            eglSwapBuffers(sEglDisplay, sEglSurface);
            checkEGLErrors();
        }
    }

    appDeinit();
    deinitGraphics();

    return EXIT_SUCCESS;
}
Example #8
0
//----------------------------------------------------------------------------//
GLuint OpenGLES2Shader::compile(GLuint type, const std::string &source)
{
    // Create shader object
    checkGLErrors();
    GLuint shader = glCreateShader(type);

    if (shader == 0)
    {
        std::stringstream stringStream;
        stringStream << "Critical Error - Could not create shader object of type:" << type << ".";
        CEGUI_THROW(RendererException(stringStream.str().c_str()));
        return 0;
    }

    checkGLErrors();

    // Define shader source and compile

    const char* src = source.data();
    int len = source.size();

    glShaderSource(shader, 1, &src, &len);

    glCompileShader(shader);

    // Check for errors
    GLint status;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

    if (status != GL_TRUE)
    {
        outputShaderLog(shader);
        return 0;
    }

    checkGLErrors();

    return shader;
}
    void FieldViewerBase::toggleRenderMode()
    {
        //toggeling this causes crashes :-/
        if (PropertyManager::instance().getPropertyValue("UseRayTracer"))
        {
            _alphablendmode=2; 
            _oldnSlizes = PropertyManager::instance().getPropertyValue("NSLIZES");
            PropertyManager::instance().setPropertyValue("NSLIZES",1.0f);

            _fragmentShader->load();
            _vertexShader->load();
            _fragmentShader->createProgram();
            _vertexShader->createProgram();

            checkGLErrors("FieldViewerBase::konstruktor4");
            _fragmentShader->attachShader(_fragmentShader->_shaderId);
            _fragmentShader->attachShader(_vertexShader->_shaderId);
            checkGLErrors("FieldViewerBase::konstruktor5");
            _fragmentShader->linkProgram();
            checkGLErrors("FieldViewerBase::konstruktor6");
            

            PropertyManager::instance().setPropertyValue("UseRayTracer",1.0f);
        }
        else
        {
            _alphablendmode=0; 
            PropertyManager::instance().setPropertyValue("UseRayTracer",0.0f);

            PropertyManager::instance().setPropertyValue("NSLIZES",_oldnSlizes);
            _fragmentShader->unLoad();
            _vertexShader->unLoad();
            checkGLErrors("unload shader");

        }
           
        blend(_alphablendmode);
    }
void Terrain::uploadMaterial(QString fileName, GLuint textureID) {
    QImage material = QGLWidget::convertToGLFormat(QImage(fileName));

    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, material.width(), material.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, material.bits());
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);

    checkGLErrors("material upload");
}
Example #11
0
void Shader::passUniforms(const Entity& e, glm::mat4& perspective)
{
	glm::mat4 T = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -10.0f)); // camera position
	glm::mat4 MV = T * e.getPos() * e.getOrientation(); // adding object position
	glm::mat4 MVP = perspective * MV;
	glm::mat3 N(MV);
	N = glm::transpose(glm::inverse(N));

	// Pass the modelviewmatrix to shader
	glUniformMatrix4fv(GetMVPMatrix(), 1, GL_FALSE, glm::value_ptr(MVP));
	glUniformMatrix3fv(GetNMatrix(), 1, GL_FALSE, glm::value_ptr(N));
	glUniformMatrix4fv(GetMVMatrix(), 1, GL_FALSE, glm::value_ptr(MV));
	checkGLErrors("Shader::passUniforms");
}
Example #12
0
void Graphics::drawExplosion(const glm::vec3& position, float lifetime)
{
	glm::mat4 VP = perspective * glm::translate(glm::mat4(1.0f), glm::vec3(0,0,-10));
	glm::mat4 MVP = VP * glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f),glm::vec3(lifetime));
	sheikki_glBindVertexArray(models["sphere"].VAO_id);
	glUseProgram(explosionShader.getId());
	glBindTexture(GL_TEXTURE_2D, models["sphere"].GetTexture());
	explosionShader.passUniforms(MVP, lifetime);
	glDrawElements(GL_TRIANGLES, 3*models["sphere"].num_polygons, GL_UNSIGNED_INT, 0);

	glUseProgram(0);

	checkGLErrors("drawExplosion");
}
    void FieldViewerBase::draw_impl()
    {
        float y;
        float zOffset;
        float heightscale = 2.0f;
        int x;
        int i;
        const int BOX_SIZE = 7;

        GLfloat lightColor[] = { 1.0f, 1.0f, 1.0f, 0.5f };
        GLfloat lightPos[] = {0.0f,0.0f,0.0f};
        GLfloat ambientLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };
        GLfloat whiteSpecularMaterial[] = { 1.0, 1.0, 1.0 };
        GLfloat mShininess[] = { 128 };

        glLoadIdentity();

        CameraControl cam = sfs_visualizer::Application::instance().getEngine().Camera();

        // tell GL we want it to use this texture 
        if (_textures.size())
            glBindTexture(GL_TEXTURE_3D, _textures[0]);

        checkGLErrors("MatlabFieldViewer::draw_impl0");
       
        GLfloat global_ambient[] = { 1.0f, 1.0f, 1.0f, 1.0f };
        glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, global_ambient);

        GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 0.5f };
        glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
        glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

        glEnable(GL_TEXTURE_3D);

        glTranslatef(-1.0, -1.0, -1.0);
       
        float scale = 2.0f;
        glScalef(scale, scale, scale);
     
        //here we draw our slices
        float nslizes = PropertyManager::instance().getPropertyValue("NSLIZES");
        for (i = 0; i < nslizes; i++)
        {
            addQuadslice(i*(_sliceDist / nslizes));
        }

        glDisable(GL_TEXTURE_3D);
        drawBorder();
    }
void ParticleRenderer::setPositions(float *pos, int numParticles)
{
    m_pos = pos;
    m_numParticles = numParticles;

    if (!m_pbo)
    {
        glGenBuffers(1, (GLuint *)&m_pbo);
    }

    glBindBuffer(GL_ARRAY_BUFFER, m_pbo);
    glBufferData(GL_ARRAY_BUFFER, numParticles * 4 * sizeof(float), pos, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    checkGLErrors("Setting particle float position");
}
void ParticleRenderer::setPositions(double *pos, int numParticles)
{
    m_bFp64Positions = true;
    m_pos_fp64 = pos;
    m_numParticles = numParticles;

    if (!m_pbo)
    {
        glGenBuffers(1, (GLuint *)&m_pbo);
    }

    glBindBuffer(GL_ARRAY_BUFFER, m_pbo);
    glBufferData(GL_ARRAY_BUFFER, numParticles * 4 * sizeof(double), pos, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    checkGLErrors("Setting particle double position");
}
Example #16
0
void initGL(int *argc, char **argv)
{
    // First initialize OpenGL context, so we can properly set the GL for CUDA.
    // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
    glutInit(argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(720, 480);
    glutCreateWindow("CUDA n-body system");

    if (bFullscreen)
    {
        glutFullScreen();
    }

    GLenum err = glewInit();

    if (GLEW_OK != err)
    {
        printf("GLEW Error: %s\n", glewGetErrorString(err));
        cudaDeviceReset();
        exit(EXIT_FAILURE);
    }
    else if (!glewIsSupported("GL_VERSION_2_0 "
                              "GL_VERSION_1_5 "
                              "GL_ARB_multitexture "
                              "GL_ARB_vertex_buffer_object"))
    {
        fprintf(stderr, "Required OpenGL extensions missing.");
        exit(EXIT_FAILURE);
    }
    else
    {
#if   defined(WIN32)
        wglSwapIntervalEXT(0);
#elif defined(LINUX)
        glxSwapIntervalSGI(0);
#endif
    }

    glEnable(GL_DEPTH_TEST);
    glClearColor(0.0, 0.0, 0.0, 1.0);

    checkGLErrors("initGL");
}
Example #17
0
bool _test_shader_(char *shader, const _test_type_list_& list) {
	GLuint program = ParseShader(shader);
	if (program) {

		glUseProgram(program);

		glBegin(GL_QUADS);

		glVertex2s(-1, -1);

		glVertex2s(1, -1);

		glVertex2s(1, 1);

		glVertex2s(-1, 1);

		glEnd();

		checkGLErrors();

		glFlush();

		for (unsigned x = 0; x < list.size(); ++x) {
			float test[4], e[4], a[4];
			glReadPixels(x, 0, 1, 1, GL_RGBA, GL_FLOAT, test);
			glReadPixels(x, 1, 1, 1, GL_RGBA, GL_FLOAT, e);
			glReadPixels(x, 2, 1, 1, GL_RGBA, GL_FLOAT, a);
			if (test[0] != 1.0f) {
				std::cout << "OpenGL GLSL subtest #" << x << " failed" << std::endl;
				if (test[0] == 2.0f) { // expected/actual available
					std::cout << "expected " << e[0] << " " << e[1] << " " << e[2] << " " << e[3]
					          << ", actual " << a[0] << " " << a[1] << " " << a[2] << " " << a[3]
					          << ", diff " << a[0]-e[0] << " " << a[1]-e[1] << " " << a[2]-e[2] << " " << a[3]-e[3]
					          << std::endl;
				}
				return false;
			}
		}
		return true;
	}
	return false;
}
Example #18
0
void initGL()
{  
    glewInit();
    if (!glewIsSupported("GL_VERSION_2_0 "
                         "GL_VERSION_1_5 "
			             "GL_ARB_multitexture "
                         "GL_ARB_vertex_buffer_object")) 
    {
        fprintf(stderr, "Required OpenGL extensions missing.");
        cudaThreadExit();
        exit(-1);
    }

    glEnable(GL_DEPTH_TEST);
    glClearColor(0.0, 0.0, 0.0, 1.0);

    renderer = new ParticleRenderer;
    
    checkGLErrors("initGL");
}
Example #19
0
// Creates GLSL program from one vertex shader and one fragement shader
// I prefer to code them in different files so it takes in file names
// and reads them in
GLuint createGLSLProgram(const char* vertFile,const char* fragFile)
{

  GLuint prog = glCreateProgram();
  GLhandleARB frag, vert;
  char *vertSrc, *fragSrc;

  vert = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
  frag = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);

  vertSrc = textFileRead(vertFile);
  fragSrc = textFileRead(fragFile);

  const char* vs = vertSrc;
  const char* fs = fragSrc;

  //RUDD DEBUG
  if(verbose)
    printf("%s\n", fs);

  glShaderSourceARB(vert, 1, &vs, NULL);
  glShaderSourceARB(frag, 1, &fs, NULL);

  free(vertSrc);free(fragSrc);

  glCompileShaderARB(vert);
  glCompileShaderARB(frag);
  glAttachObjectARB(prog, vert);
  glAttachObjectARB(prog, frag);

  glLinkProgramARB(prog);
  glUseProgramObjectARB(prog);

  //  printShaderInfoLog(vert);
  //  printShaderInfoLog(frag);
  printProgramInfoLog(prog);

  checkGLErrors("Shader setup");

  return prog;
}
Example #20
0
//Initializes GPU for GPGPU computations
//Saves previous GPU state
//Viewing frustum goes from -1.0 to 1.0, texenv mode is replace
//\returns handle to fb
GLuint initGPGPU(int width, int height)
{

  //TODO: For error checking, i'm not using an FBO, I'll render to screen.
  glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT);
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  // TODO: Flipping the camera so I don't have ot look at upside pictures
  // (I know i'm going to forget about this and it's gonna bite me
  // in the ass.
  glOrtho(0.0, width, 0.0, height, -1.0, 1.0);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glViewport(0, 0, width, height);
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE);
  checkGLErrors("initGPGPU, Initializing and saving matrices");
}
Example #21
0
//------------------------------------------------------------------------------
static OpenSubdiv::FarMesh<OpenSubdiv::OsdVertex> *
createFarMesh( const char * shape, int level, bool adaptive, Scheme scheme=kCatmark ) {

    checkGLErrors("create osd enter");
    // generate Hbr representation from "obj" description
    std::vector<float> positions;
    OsdHbrMesh * hmesh = simpleHbr<OpenSubdiv::OsdVertex>(shape, scheme, positions,
                                                          g_displayStyle == kFaceVaryingColor);

    size_t nModel = g_bboxes.size();
    float x = nModel%g_modelCount - g_modelCount*0.5f;
    float y = nModel/g_modelCount - g_modelCount*0.5f;
    // align origins
    Matrix matrix;
    identity(matrix.value);
    translate(matrix.value, 3*x, 3*y, 0);
    g_transforms.push_back(matrix);
    g_positions.push_back(positions);

    OpenSubdiv::FarMeshFactory<OpenSubdiv::OsdVertex> meshFactory(hmesh, level, adaptive);
    OpenSubdiv::FarMesh<OpenSubdiv::OsdVertex> *farMesh = meshFactory.Create(true);

    // Hbr mesh can be deleted
    delete hmesh;

    // compute model bounding (vertex animation isn't taken into account)
    float min[4] = { FLT_MAX,  FLT_MAX,  FLT_MAX, 1};
    float max[4] = {-FLT_MAX, -FLT_MAX, -FLT_MAX, 1};
    for (size_t i=0; i <positions.size()/3; ++i) {
        float v[4] = {positions[i*3], positions[i*3+1], positions[i*3+2], 1 };
        for(int j=0; j<3; ++j) {
            min[j] = std::min(min[j], v[j]);
            max[j] = std::max(max[j], v[j]);
        }
    }
    g_bboxes.push_back(BBox(min, max));

    return farMesh;
}
Example #22
0
void GameManager::Render() 
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear screen and depth buffer

	RenderFPS();

	RenderEnviroment(true);

	RenderEnemies(true);

	RenderBullets(true);

	RenderPlayer(true);

	RenderParticles(true);

	RenderText(true);

	checkGLErrors();

	Utility::I()->SwapSDLGLBuffers();
}
// Generate the texture for error display
void Error3DViewerWidget::genErrorTextures() 
{
  static const GLint internalformat = GL_R3_G3_B2;
  GLubyte *texture;
  GLint tw,max_n;
  QString tmps;
  int i;

  // Only in error mapping mode and if not disabled
  if (!texture_enabled) 
    return;
  makeCurrent(); // make sure we use the correct GL context
  // Allocate texture names (IDs) if not present
  if (etex_id == NULL) {
    etex_id = (GLuint*) xa_malloc(sizeof(*etex_id)*model->mesh->num_faces);
    etex_sz = (int*) xa_malloc(sizeof(*etex_sz)*model->mesh->num_faces);
    glGenTextures(model->mesh->num_faces,etex_id);
  }
  // Get maximum texture size
  max_n = 0;
  for (i=0; i<model->mesh->num_faces; i++) {
    if (max_n < model->fe[i].sample_freq) max_n = model->fe[i].sample_freq;
  }
  max_n = 1<<ceilLog2(max_n); // round (towards infinity) to power of two
  // Test if OpenGL implementation can deal with maximum texture size
  // Unfortunately GL_PROXY_TEXTURE_2D fails on IRIX 6.2 for some SGI
  // machines, so use older GL_MAX_TEXTURE_SIZE method.
  glGetIntegerv(GL_MAX_TEXTURE_SIZE,&tw);
  checkGLErrors("error texture size check");
  if (tw < max_n) {
    tmps.sprintf("The OpenGL implementation does not support\n"
                 "the required texture size (%ix%i).\n"
                 "Using plain white color",max_n,max_n);
    QMessageBox::critical(this,"OpenGL texture size exceeded",tmps);
    // Displaying another window can change the current GL context 
    makeCurrent();
    for (i=0; i<model->mesh->num_faces; i++) {
      etex_sz[i] = 1; // avoid having divide by zero texture coords
    }
    return;
  }
  // What follows is a potentially slow operation
  QApplication::setOverrideCursor(Qt::waitCursor);
  // Allocate temporary texture storage
  texture = (GLubyte*) xa_malloc(sizeof(*texture)*3*(max_n+2)*(max_n+2));
  glPixelStorei(GL_UNPACK_ALIGNMENT,1); /* pixel rows aligned on bytes only */
  for (i=0; i<model->mesh->num_faces; i++) {
    glBindTexture(GL_TEXTURE_2D,etex_id[i]);
    etex_sz[i] = fillTexture(&(model->fe[i]),texture);
    glTexImage2D(GL_TEXTURE_2D,0,internalformat,etex_sz[i]+2,etex_sz[i]+2,1,
                 GL_RGB,GL_UNSIGNED_BYTE,texture);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
    // Default GL_TEXTURE_MIN_FILTER requires mipmaps!
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  }
  checkGLErrors("error texture generation");
  free(texture);
  QApplication::restoreOverrideCursor();
}
Example #24
0
void run()
{
	if(!initialize())
		shutdown("Failed to initialize");

	if(!loadContent())
		shutdown("Failed to load resources");	

	Mesh cubeMesh = Mesh::genUnitColoredCube();
	MeshBuffer cubeBuffer(cubeMesh);
	Model cube(cubeBuffer);

	Mesh waterMesh = Mesh::genUnitColoredPlane(Color(0.57f, 0.63f, 0.98f));
	MeshBuffer waterBuffer(waterMesh);
	Model water(waterBuffer);

	BufferObject quadVbo;
	float quadVertices[] = {
		-1.0f, -1.0f, 0.0f, 0.0f,
		+1.0f, -1.0f, 1.0f, 0.0f,
		+1.0f, +1.0f, 1.0f, 1.0f,
		+1.0f, +1.0f, 1.0f, 1.0f,
		-1.0f, +1.0f, 0.0f, 1.0f,
		-1.0f, -1.0f, 0.0f, 0.0f
	};
	quadVbo.create(GL_ARRAY_BUFFER, GL_STATIC_DRAW, sizeof(quadVertices), quadVertices);

	Mesh gridMesh;
	for(int i = 0; i <= 8; ++i)
	{
		float f = (i / 8.0) * 2.0f - 1.0f;
		int j = gridMesh.getPositionCount();
		gridMesh.addPosition(f * 3.0f, 0.0f, -3.0f);
		gridMesh.addPosition(f * 3.0f, 0.0f, +3.0f);
		gridMesh.addPosition(-3.0f, 0.0f, f * 3.0f);
		gridMesh.addPosition(+3.0f, 0.0f, f * 3.0f);
		gridMesh.addColor(Colors::White);
		gridMesh.addColor(Colors::White);
		gridMesh.addColor(Colors::White);
		gridMesh.addColor(Colors::White);
		gridMesh.addIndex(j + 0); gridMesh.addIndex(j + 1);
		gridMesh.addIndex(j + 2); gridMesh.addIndex(j + 3);
	}
	MeshBuffer gridBuffer(gridMesh);
	Model grid(gridBuffer);

	VertexArray vao;
	vao.create();
	vao.bind();

	mat4 perspectiveMatrix = glm::perspective(45.0f, windowWidth / float(windowHeight), 0.05f, 50.0f);
	
	// The geometry to be refracted and reflected are stored in these
	// In addition to RGB values, the world-space height is stored in the alpha-channel
	// of the refraction texture.
	// Fresnel equations is used to blend between the two textures
	RenderTexture refractionRT(windowWidth, windowHeight);
	RenderTexture reflectionRT(windowWidth, windowHeight);

	renderer.setClearColor(0.55f, 0.45f, 0.45f, 1.0f);
	renderer.setClearDepth(1.0);

	Timer timer;
	timer.start();
	double renderTime = 0.0;

	while(context.isOpen())
	{
		timer.step();
		double time = timer.getElapsedTime();
		update(time, timer.getDelta());
		double renderStart = timer.getElapsedTime();

		MatrixStack viewMatrix;
		viewMatrix.push();
		viewMatrix.translate(0.0f, 0.0f, -3.0f);
		viewMatrix.rotateX(xAxisRotation);
		viewMatrix.rotateY(yAxisRotation);

		renderer.setCullState(CullStates::CullNone);
		renderer.setDepthTestState(DepthTestStates::LessThanOrEqual);
		
		colorShader.begin();
		colorShader.setUniform("projection", perspectiveMatrix);
		cube.pushTransform();
		cube.translate(0.0f, 0.0f, 0.0f);
		cube.scale(0.5f);

		// Render the geometry to be refracted, store result in rt
		refractionRT.begin();
		renderer.clearColorAndDepth();
		colorShader.setUniform("view", viewMatrix.top());
		cube.draw(GL_TRIANGLES);
		grid.draw(GL_LINES);
		refractionRT.end();

		// Render the geometry to be reflected, store result in rt
		reflectionRT.begin();
		renderer.clearColorAndDepth();
		viewMatrix.push();
		viewMatrix.scale(1.0f, -1.0f, 1.0f); // Reflect about xz-plane
		colorShader.setUniform("view", viewMatrix.top());
		cube.draw(GL_TRIANGLES);
		viewMatrix.pop();
		reflectionRT.end();

		colorShader.end();
		cube.popTransform();

		// Render the water with the previous reflection/refraction texture
		waterShader.begin();
		waterShader.setUniform("time", time);
		glActiveTexture(GL_TEXTURE0 + 0);
		refractionRT.bindTexture();
		glActiveTexture(GL_TEXTURE0 + 1);
		reflectionRT.bindTexture();
		glActiveTexture(GL_TEXTURE0 + 2);
		waterNormals.bind();
		//waterShader.setUniform("view", viewMatrix.top());
		waterShader.setUniform("refraction_tex", 0);
		waterShader.setUniform("reflection_tex", 1);
		waterShader.setUniform("water_normals_tex", 2);
		//waterShader.setUniform("light0_pos", vec3(0.0f, 1.0f, 0.0f));
		//waterShader.setUniform("light0_col", vec3(1.0f, 0.8f, 0.5f));
		//waterShader.setUniform("ambient", vec3(67.0f/255.0f, 66.0f/255.0f, 63.0f/255.0f));
		quadVbo.bind();
		waterShader.setAttributefv("position", 2, 4, 0);
		waterShader.setAttributefv("texel", 2, 4, 2);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		quadVbo.unbind();
		reflectionRT.unbindTexture();
		refractionRT.unbindTexture();
		waterNormals.unbind();
		waterShader.end();
		glActiveTexture(GL_TEXTURE0 + 0);

		// Render unmirrored scene
		//colorShader.begin();
		//renderer.clearColorAndDepth();
		//renderer.setCullState(CullStates::CullNone);
		//renderer.setBlendState(BlendStates::AlphaBlend);
		//renderer.setDepthTestState(DepthTestStates::LessThanOrEqual);
		//colorShader.setUniform("projection", perspectiveMatrix);
		//colorShader.setUniform("view", viewMatrix.top());
		//cube.pushTransform();
		//cube.translate(0.0f, 0.4f, 0.0f);
		//cube.scale(0.5f);
		//cube.draw(GL_TRIANGLES);

		/*grid.pushTransform();
		grid.translate(0.0f, -0.5f, 0.0f);
		grid.draw(GL_LINES);
		grid.popTransform();*/

		// Draw mirrored scene to a rendertarget
		/*rt.begin();
		renderer.clearColorAndDepth();
		
		viewMatrix.push();
		viewMatrix.scale(1.0f, -1.0f, 1.0f);
		colorShader.setUniform("view", viewMatrix.top());
		cube.draw(GL_TRIANGLES);
		cube.popTransform();
		viewMatrix.pop();
		rt.end();*/

		// Enable stencil testing and mask out a section containing the water mesh
		//glEnable(GL_STENCIL_TEST);
		//glStencilFunc(GL_ALWAYS, 1, 0xFF); // Set any stencil to 1
		//glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
		//glStencilMask(0xFF); // Write to stencil buffer
		//glDepthMask(GL_FALSE); // Don't write to depth buffer
		//glClear(GL_STENCIL_BUFFER_BIT); // Clear stencil buffer (0 by default)

		//// Draw water mesh
		//water.pushTransform();
		//water.scale(3.0f);
		//water.draw(GL_TRIANGLES);
		//water.popTransform();
		//colorShader.end();

		//// Draw previous rendertarget as a quad masked into the water plane
		//glStencilFunc(GL_EQUAL, 1, 0xFF); // Pass test if stencil value is 1
		//glStencilMask(0x00); // Don't write anything to stencil buffer
		//glDepthMask(GL_TRUE);

		//glDisable(GL_STENCIL_TEST);

		viewMatrix.pop();

		context.display();
		renderTime = timer.getElapsedTime() - renderStart;
		if(renderTime < 0.013)
			context.sleep(0.013 - renderTime);

		if(checkGLErrors(std::cerr))
		{
			std::cin.get();
			context.close();
		}
	}

	waterNormals.dispose();
	colorShader.dispose();
	waterShader.dispose();
	vao.dispose();
	context.dispose();
}
Example #25
0
int main()
{
	sf::ContextSettings settings;
	settings.majorVersion = 4;
	settings.minorVersion = 3;
	settings.depthBits = 24;
	settings.stencilBits = 8;
	settings.antialiasingLevel = 0;

	sf::Window window(sf::VideoMode(800, 600), "SMOG Test", sf::Style::Close, settings);

	sf::ContextSettings actualSettings = window.getSettings();
	std::cout << "Window created:\n" <<
		 "\tMajor Version: " << actualSettings.majorVersion << "\n" <<
		 "\tMinor Version: " << actualSettings.minorVersion << "\n" <<
		 "\tDepth Bits   : " << actualSettings.depthBits << "\n" <<
		 "\tStencil Bits : " << actualSettings.stencilBits << "\n" <<
		 "\tAntialiasing : " << actualSettings.antialiasingLevel << std::endl;

	window.setVerticalSyncEnabled(true);

	initialiseGlew();

	sf::Vector2u windowSize = window.getSize();
	Viewport viewport(windowSize.x, windowSize.y);

	TextureCache::RegisterLoader<SFML_TextureLoader>();

	Scene scene;

//	FrameBuffer frameBuffer(800, 600);
//	frameBuffer.addTarget("diffuse", 4, Texture::UNSIGNED_BYTE_8);

	GBuffer gbuffer;

	// Scene setup
	for (int i = 0; i < 4; ++i)
	{
		SceneObject& sceneObject = scene.createSceneObject();
		RenderableComponent& rendComp = sceneObject.createComponent<RenderableComponent>();
		rendComp.renderable.reset(new Triangle);
#if 1
		rendComp.material = Material::Load("install/share/materials/textured.mtl");
#else
		std::stringstream ss;
		ss << "install/share/materials/color" << i << ".mtl";
#if 1
		rendComp.material = Material::Load(ss.str());
#else
		rendComp.material = Material::Load("install/share/materials/color.mtl");
		rendComp.material.set("color", RGB(
			(i == 0 || i == 1) ? 1.0f : 0.0f,
			(i == 0 || i == 2) ? 1.0f : 0.0f,
			(i == 0 || i == 3) ? 1.0f : 0.0f));
		rendComp.material.save(ss.str());
#endif
#endif
		sceneObject.transform().position = Vector3(
			(i % 2) ? 0.5f : -0.5f,
			(i > 1) ? 0.5f : -0.5f,
			0.0f);
		sceneObject.transform().scale = Vector3(0.5f, 0.5f, 1.0f);
	}

	Material material = Material::Load("install/share/materials/debug_gbuffer.mtl");
	Quad quad;

	

	// Main loop
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
			{
				window.close();
				break;
			}
            else if (event.type == sf::Event::Resized)
            {
            	viewport.resize(event.size.width, event.size.height);
            }
		}

		// Update
		scene.update(0.0f);

		// Bind the frame buffer
		//frameBuffer.bind();
		gbuffer.writeTo();
		glEnable(GL_DEPTH_TEST);
		glDepthMask(true);
		glDisable(GL_BLEND);
		glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Draw
		for(SceneObjects::iterator sit = scene.begin(); sit != scene.end(); ++sit)
		{
			Components::iterator_range range = sit->components<RenderableComponent>();
			for(Components::iterator cit = range.begin; cit != range.end; ++cit)
			{
				cit->as<RenderableComponent>().draw();
			}
		}
		glUseProgram(0);

		//frameBuffer.unbind();
		//frameBuffer.bindForRead();

		gbuffer.readFrom();
		
		glDisable(GL_DEPTH_TEST);
		glDepthMask(false);
		glEnable(GL_BLEND);
		glBlendFunc(GL_ONE, GL_ONE);
		glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		material.program().use();
		//frameBuffer.bindTargets(material.program());
		material.program().set("diffuse", Texture(gbuffer.target(GBuffer::kDiffuse)));
		quad.draw();
		glUseProgram(0);

		gbuffer.finish();

		//frameBuffer.unbind();

		window.display();

#if 1
		checkGLErrors();
#endif
	}
	
	uchar pixels[800*600*4];

//	const Texture& target = frameBuffer.target("diffuse");
//	target.bind();
	uint target = gbuffer.target(GBuffer::kDiffuse);
	glBindTexture(GL_TEXTURE_2D, target);
	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels);
	glBindTexture(GL_TEXTURE_2D, 0);
//	target.unbind();

	sf::Image image;
	image.create(800, 600, pixels);
	image.saveToFile("screenshot.png");

	TextureCache::CleanUp();

#if 1
	checkGLErrors();
#endif

	return 0;
}
Example #26
0
//------------------------------------------------------------------------------
static void
display() {

    // set effect
    g_effect.displayStyle = g_displayStyle;
    g_effect.screenSpaceTess = (g_screenSpaceTess != 0);
    g_effect.displayPatchColor = (g_displayPatchColor != 0);

    // prepare view matrix
    float aspect = g_width/(float)g_height;
    float modelview[16], projection[16];
    identity(modelview);
    translate(modelview, -g_pan[0], -g_pan[1], -g_dolly);
    rotate(modelview, g_rotate[1], 1, 0, 0);
    rotate(modelview, g_rotate[0], 0, 1, 0);
    rotate(modelview, -90, 1, 0, 0);
    translate(modelview, -g_center[0], -g_center[1], -g_center[2]);
    perspective(projection, 45.0f, aspect, 0.01f, 500.0f);

    g_effect.SetMatrix(modelview, projection);
    g_effect.SetTessLevel((float)(1 << g_tessLevel));
    g_effect.SetLighting();

    // -----------------------------------------------------------------------
    // prepare draw items

    Stopwatch s;
    s.Start();

    OpenSubdiv::OsdUtilDrawItem<MyDrawDelegate::EffectHandle, MyDrawContext>::Collection items;
    OpenSubdiv::OsdUtilDrawItem<MyDrawDelegate::EffectHandle, MyDrawContext>::Collection cachedDrawItems;

    int numModels = g_modelCount*g_modelCount;
    items.reserve(numModels);

    for (int i = 0; i < numModels; ++i) {
        // Here, client can pack arbitrary mesh and effect into drawItems.

        items.push_back(OpenSubdiv::OsdUtilDrawItem<MyDrawDelegate::EffectHandle, MyDrawContext>(
                            g_batch, &g_effect, g_batch->GetPatchArrays(i)));
    }

    if (g_batching) {
        // create cached draw items
        OpenSubdiv::OsdUtil::OptimizeDrawItem(items, cachedDrawItems, &g_drawDelegate);
    }

    s.Stop();
    float prepCpuTime = float(s.GetElapsed() * 1000.0f);

    // -----------------------------------------------------------------------
    // draw items
    s.Start();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glViewport(0, 0, g_width, g_height);

    // primitive counting
    glBeginQuery(GL_PRIMITIVES_GENERATED, g_queries[0]);
#if defined(GL_VERSION_3_3)
    glBeginQuery(GL_TIME_ELAPSED, g_queries[1]);
#endif
    g_drawDelegate.ResetNumDrawCalls();

    if (g_displayStyle == kWire) glDisable(GL_CULL_FACE);

    if (g_batching) {
        OpenSubdiv::OsdUtil::DrawCollection(cachedDrawItems, &g_drawDelegate);
    } else {
        OpenSubdiv::OsdUtil::DrawCollection(items, &g_drawDelegate);
    }

    if (g_displayStyle == kWire) glEnable(GL_CULL_FACE);

    glEndQuery(GL_PRIMITIVES_GENERATED);
#if defined(GL_VERSION_3_3)
    glEndQuery(GL_TIME_ELAPSED);
#endif

    s.Stop();
    float drawCpuTime = float(s.GetElapsed() * 1000.0f);

    // -----------------------------------------------------------------------

    GLuint numPrimsGenerated = 0;
    GLuint timeElapsed = 0;
    glGetQueryObjectuiv(g_queries[0], GL_QUERY_RESULT, &numPrimsGenerated);
#if defined(GL_VERSION_3_3)
    glGetQueryObjectuiv(g_queries[1], GL_QUERY_RESULT, &timeElapsed);
#endif
    float drawGpuTime = timeElapsed / 1000.0f / 1000.0f;

    if (g_hud.IsVisible()) {
        g_fpsTimer.Stop();
        g_totalTime += g_fpsTimer.GetElapsed();
        double fps = 1.0/g_fpsTimer.GetElapsed();
        g_fpsTimer.Start();
        g_hud.DrawString(10, -200, "Draw Calls : %d", g_drawDelegate.GetNumDrawCalls());
        g_hud.DrawString(10, -180, "Tess level : %d", g_tessLevel);
        g_hud.DrawString(10, -160, "Primitives : %d", numPrimsGenerated);
        g_hud.DrawString(10, -120, "GPU Kernel : %.3f ms", g_gpuTime);
        g_hud.DrawString(10, -100, "CPU Kernel : %.3f ms", g_cpuTime);
        g_hud.DrawString(10, -80,  "GPU Draw   : %.3f ms", drawGpuTime);
        g_hud.DrawString(10, -60,  "CPU Draw   : %.3f ms", drawCpuTime);
        g_hud.DrawString(10, -40,  "CPU Prep   : %.3f ms", prepCpuTime);
        g_hud.DrawString(10, -20,  "FPS        : %3.1f", fps);

        g_hud.Flush();
    }

    checkGLErrors("display leave");
    glFinish();
}
Example #27
0
void Graphics::reshape(int w, int h)
{
	glViewport(0,0,(GLsizei)w,(GLsizei)h);
	checkGLErrors("reshape");
}
Example #28
0
void Shader::init()
{
	assert(!initialized);
	GLuint f, v;

	char *vs,*fs;

	v = glCreateShader(GL_VERTEX_SHADER);
	f = glCreateShader(GL_FRAGMENT_SHADER);	

	// load shaders & get length of each
	GLint vlen;
	GLint flen;
	vs = loadFile(vertex_shader_path.c_str(),vlen);
	fs = loadFile(fragment_shader_path.c_str(),flen);

	std::cout << "Vertex shader " << vertex_shader_path << " loaded." << std::endl;
	std::cout << "Fragment shader " << fragment_shader_path << " loaded." << std::endl;

	const char * vv = vs;
	const char * ff = fs;

	glShaderSource(v, 1, &vv,&vlen);
	glShaderSource(f, 1, &ff,&flen);

	GLint compiled;

	glCompileShader(v);
	glGetShaderiv(v, GL_COMPILE_STATUS, &compiled);
	if (!compiled)
	{
		std::cout << "Vertex shader not compiled." << std::endl;
		printShaderInfoLog(v);
	} 

	glCompileShader(f);
	glGetShaderiv(f, GL_COMPILE_STATUS, &compiled);
	if (!compiled)
	{
		std::cout << "Fragment shader not compiled." << std::endl;
		printShaderInfoLog(f);
	} 

	id = glCreateProgram();

	glAttachShader(id,v);
	glAttachShader(id,f);


	glLinkProgram(id);
	glUseProgram(id);

	printShaderInfoLog(f);
	printShaderInfoLog(v);

	delete [] vs; 
	delete [] fs;

	checkGLErrors("initShaders");

	initialized=true;
}
//------------------------------------------------------------------------------
int main(int argc, char ** argv)
{
    bool fullscreen = false;
    std::string str;
    for (int i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-d"))
            g_level = atoi(argv[++i]);
        else if (!strcmp(argv[i], "-c"))
            g_repeatCount = atoi(argv[++i]);
        else if (!strcmp(argv[i], "-f"))
            fullscreen = true;
        else {
            std::ifstream ifs(argv[1]);
            if (ifs) {
                std::stringstream ss;
                ss << ifs.rdbuf();
                ifs.close();
                str = ss.str();
                g_shapes.push_back(ShapeDesc(argv[1], str.c_str(), kCatmark));
            }
        }
    }
    initShapes();

    if (not glfwInit()) {
        printf("Failed to initialize GLFW\n");
        return 1;
    }

    static const char windowTitle[] = "OpenSubdiv vtrViewer";

#define CORE_PROFILE
#ifdef CORE_PROFILE
    setGLCoreProfile();
#endif

    if (fullscreen) {

        g_primary = glfwGetPrimaryMonitor();

        // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
        // settle for the first one in the list
        if (not g_primary) {
            int count=0;
            GLFWmonitor ** monitors = glfwGetMonitors(&count);

            if (count)
                g_primary = monitors[0];
        }

        if (g_primary) {
            GLFWvidmode const * vidmode = glfwGetVideoMode(g_primary);
            g_width = vidmode->width;
            g_height = vidmode->height;
        }
    }

    if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle,
                                       fullscreen and g_primary ? g_primary : NULL, NULL))) {
        printf("Failed to open window.\n");
        glfwTerminate();
        return 1;
    }
    glfwMakeContextCurrent(g_window);

    // accommocate high DPI displays (e.g. mac retina displays)
    glfwGetFramebufferSize(g_window, &g_width, &g_height);
    glfwSetFramebufferSizeCallback(g_window, reshape);

    glfwSetKeyCallback(g_window, keyboard);
    glfwSetCursorPosCallback(g_window, motion);
    glfwSetMouseButtonCallback(g_window, mouse);
    glfwSetWindowCloseCallback(g_window, windowClose);

#if defined(OSD_USES_GLEW)
#ifdef CORE_PROFILE
    // this is the only way to initialize glew correctly under core profile context.
    glewExperimental = true;
#endif
    if (GLenum r = glewInit() != GLEW_OK) {
        printf("Failed to initialize glew. Error = %s\n", glewGetErrorString(r));
        exit(1);
    }
#ifdef CORE_PROFILE
    // clear GL errors which was generated during glewInit()
    glGetError();
#endif
#endif

    initGL();

    glfwSwapInterval(0);

    initHUD();
    rebuildOsdMeshes();

    checkGLErrors("before loop");
    while (g_running) {
        idle();
        display();

        glfwPollEvents();
        glfwSwapBuffers(g_window);

        glFinish();
    }

    uninitGL();
    glfwTerminate();
}
Example #30
0
int main()
{
	srand(time(0));

	TROLLOERROR e;
	if(e = Root::initSingleton(1024, 768))
	{
		std::cerr << TROLLOErrorString(e) << '\n';
		Root::destroySingleton();
		return -1;
	}
	Root& root = Root::getSingleton();

	root.modelManager.addFromTROLLO("ship", "resources/ship.trollo", root.textureManager.getTexture("default"));
	btVector3 pos(0,50,-100);

	Entity* et = root.entityStorage.addEntity(root.modelManager.getModel("ship"), pos);
	root.engine->addEntity(*et);

	btQuaternion q;
	for(int i = 0; i < 750; ++i)
	{
		q.setX((rand()%50) - 100);
		q.setY((rand()%50) - 100);
		q.setZ((rand()%50) - 100);
		q.setW((rand()%50) - 100);

		pos.setX(-50.0f + (rand()%100));
		pos.setZ(-100.0f + (rand()%100) - 50);
		pos.setY(60.0f + (rand()%100) - 50);
		et = root.entityStorage.addEntity(root.modelManager.getModel("ship"), pos, q);
		root.engine->addEntity(*et);
	}

	checkGLErrors("Preloop");
	bool running = true;

	float time = -100.0f;
	double prevTime = glfwGetTime();
	float frame = 0;

	char title[128];
	while(running)
	{
		++frame;
	
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		double t = glfwGetTime();
		if(1.0f + prevTime <= t)
		{
			float spf = (t - prevTime)*1000 / frame;
			sprintf(title, "ms per frame : %f", spf);
			glfwSetWindowTitle(title);
			prevTime = t;
			frame = 0;
		}

		root.engine->tick();
		root.renderManager.renderAll();
		root.textRenderer.renderText(title, 0.0f, -0.85f);

		checkGLErrors("loop");

		glfwSwapBuffers();
		running = running && (!glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED));

	}
	glUseProgram(0);

	Root::destroySingleton();

	return 0;

}