Ejemplo n.º 1
0
void RenderWidget::keyPressEvent(QKeyEvent *event)
{
	if (!event->isAutoRepeat())
	{
		if(event->modifiers().testFlag(Qt::ControlModifier))
		{
			if(event->key() == Qt::Key_H)
			{
				_hud = !_hud;
			} 
			else if(event->key() == Qt::Key_R)
			{
				emit restart();
			} 
			else if(event->key() == Qt::Key_L)
			{
				_renderLock = true;
				assets.reloadAssets();
				setupRenderStructs();
				_renderLock = false;
			} 
			else if(event->key() == Qt::Key_B)
			{
				if (_renderDebug == 2)
				{
					_renderDebug = 0;
				} else {
					_renderDebug++;
				}
			}
		} else {
			if(event->key() == Qt::Key_Escape)
			{
				qApp->processEvents();
				close();
				makeCurrent();
				assets.clearAssets();
				doneCurrent();
			} else if(event->key() == Qt::Key_P)
			{
				emit togglePause();
			} else if(event->key() == Qt::Key_L)
			{
				emit toggleLimit();
			} else if(event->key() == Qt::Key_H)
			{
				_drawHelp = !_drawHelp;
			} else if(event->key() == Qt::Key_Q)
			{
				_keysDown.Q = true;
			} else if(event->key() == Qt::Key_W)
			{
				_keysDown.W = true;
			} else if(event->key() == Qt::Key_E)
			{
				_keysDown.E = true;
			} else if(event->key() == Qt::Key_A)
			{
				_keysDown.A = true;
			} else if(event->key() == Qt::Key_S)
			{
				_keysDown.S = true;
			} else if(event->key() == Qt::Key_D)
			{
				_keysDown.D = true;
			} else if(event->key() == Qt::Key_Plus)
			{
				_keysDown.Plus = true;
			} else if(event->key() == Qt::Key_Minus)
			{
				_keysDown.Minus = true;
			} else if(event->key() == Qt::Key_Space)
			{
				if (_camera.mode == 1)
				{
					_camera.mode = 0;
					_mouseStatus.origHoriz = _camera.rotHoriz;
					_mouseStatus.origVert = _camera.rotVert;

				} else
				{
					_camera.mode++;
					_mouseStatus.origPan = _camera.pan;
					_mouseStatus.origTilt = _camera.tilt;
				}
			} else if(event->key() == Qt::Key_Backslash)
			{
				makeCurrent();
				saveScreenShot(SCREENSHOT_WIDTH,SCREENSHOT_HEIGHT);
				assets.reloadAssets();
				setupRenderStructs();
				doneCurrent();
			}
		}
	}

	if(event->key() == Qt::Key_BracketRight)
	{
		if (_simRates.limitRate)
			emit decreaseRate();
	}
	if(event->key() == Qt::Key_BracketLeft)
	{
		if (_simRates.limitRate)
			emit increaseRate();
	}
}
Ejemplo n.º 2
0
OGLWidget::~OGLWidget()
{
	makeCurrent();
	doneCurrent();
}
Ejemplo n.º 3
0
GLWidget::GLWidget(QWidget *parent)
    : QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
{
    setWindowTitle(tr("OpenGL pbuffers 2"));

    pbuffer = new QGLPixelBuffer(1024, 1024, format(), this);

    rot_x = rot_y = rot_z = 0.0f;
    scale = 0.1f;
    anim = new QTimeLine(750, this);
    anim->setUpdateInterval(20);
    connect(anim, SIGNAL(valueChanged(qreal)), SLOT(animate(qreal)));
    connect(anim, SIGNAL(finished()), SLOT(animFinished()));

    svg_renderer = new QSvgRenderer(QLatin1String(":/res/bubbles.svg"), this);
    connect(svg_renderer, SIGNAL(repaintNeeded()), this, SLOT(draw()));

    logo = QImage(":/res/designer.png");
    logo = logo.convertToFormat(QImage::Format_ARGB32);

    makeCurrent(); // need a current context to create the display list
    tile_list = glGenLists(1);
    glNewList(tile_list, GL_COMPILE);
    glBegin(GL_QUADS);
    {
        glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
        glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
        glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
        glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);

        glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
        glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
        glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);
        glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);

        glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
        glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
        glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
        glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);

        glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
        glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
        glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
        glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);

        glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
        glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);
        glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
        glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);

        glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
        glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
        glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
        glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);
}
    glEnd();
    glEndList();

    wave = new GLfloat[logo.width()*logo.height()];
    memset(wave, 0, logo.width()*logo.height());
    startTimer(30); // wave timer

    pbuffer->makeCurrent();
    dynamicTexture = pbuffer->generateDynamicTexture();

    // bind the dynamic texture to the pbuffer - this is a no-op under X11
    hasDynamicTextureUpdate = pbuffer->bindToDynamicTexture(dynamicTexture);
}
Ejemplo n.º 4
0
    bool RenderTarget::copyToBuffer( GLenum mode, dp::sg::core::Image::PixelFormat pixelFormat, dp::sg::core::Image::PixelDataType pixelDataType, const dp::sg::core::BufferSharedPtr & buffer )
    {
      // FIXME use C++ object for current/noncurrent for exception safety
      makeCurrent();

      size_t components = 0;
      size_t bytesPerComponent = 0;

      // set up alignments
      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
      glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
      glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
      glPixelStorei(GL_PACK_ALIGNMENT, 1);
      glPixelStorei(GL_PACK_ROW_LENGTH, 0);
      glPixelStorei(GL_PACK_SKIP_ROWS, 0);
      glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

      // determine OpenGL format
      GLenum format = ~0;
      switch (pixelFormat)
      {
      case dp::PixelFormat::RGB:
        format = GL_RGB;
        components = 3;
      break;
      case dp::PixelFormat::RGBA:
        format = GL_RGBA;
        components = 4;
      break;
      case dp::PixelFormat::BGR:
        format = GL_BGR;
        components = 3;
      break;
      case dp::PixelFormat::BGRA:
        format = GL_BGRA;
        components = 4;
      break;
      case dp::PixelFormat::LUMINANCE:
        format = GL_LUMINANCE;
        components = 1;
      break;
      case dp::PixelFormat::ALPHA:
        format = GL_ALPHA;
        components = 1;
      break;
      case dp::PixelFormat::LUMINANCE_ALPHA:
        format = GL_LUMINANCE_ALPHA;
        components = 2;
      break;
      case dp::PixelFormat::DEPTH_COMPONENT:
        format = GL_DEPTH_COMPONENT;
        components = 1;
      break;
      case dp::PixelFormat::DEPTH_STENCIL:
        format = GL_DEPTH24_STENCIL8;
        components = 1;
      break;
      default:
        DP_ASSERT(0 && "unsupported PixelFormat");
      };

      GLenum dataType = ~0;
      switch (pixelDataType)
      {
      case dp::PixelFormat::PF_BYTE:
        dataType = GL_BYTE;
        bytesPerComponent = 1;
      break;
      case dp::PixelFormat::PF_UNSIGNED_BYTE:
        dataType = GL_UNSIGNED_BYTE;
        bytesPerComponent = 1;
      break;
      case dp::PixelFormat::PF_SHORT:
        dataType = GL_SHORT;
        bytesPerComponent = 2;
      break;
      case dp::PixelFormat::PF_UNSIGNED_SHORT:
        dataType = GL_UNSIGNED_SHORT;
        bytesPerComponent = 2;
      break;
      case dp::PixelFormat::PF_INT:
        dataType = GL_INT;
        bytesPerComponent = 4;
      break;
      case dp::PixelFormat::PF_UNSIGNED_INT:
        dataType = GL_UNSIGNED_INT;
        bytesPerComponent = 4;
      break;
      case dp::PixelFormat::PF_FLOAT32:
        dataType = GL_FLOAT;
        bytesPerComponent = 4;
      break;
      case dp::PixelFormat::PF_FLOAT16:
        dataType = GL_HALF_FLOAT;
        bytesPerComponent = 2;
      break;
      default:
        DP_ASSERT(0 && "unsupported PixelDataType");
      }

      BufferLock(buffer)->setSize(m_width * m_height * components * bytesPerComponent);

      // read the pixels
      glWindowPos2i(0,0);
      glReadBuffer( mode );

      bool isBufferGL = std::dynamic_pointer_cast<BufferGL>(buffer);
      if ( isBufferGL )
      {
        GLint oldPBO;
        glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &oldPBO);
        // FIXME it's necessary to check wheter the buffer object shared data with the current context...
        BufferGLLock bufferGL( sharedPtr_cast<BufferGL>( buffer ) );
        bufferGL->bind( GL_PIXEL_PACK_BUFFER );
        glReadPixels(0, 0, m_width, m_height, format, dataType, 0);
        glBindBuffer(GL_PIXEL_PACK_BUFFER, (GLuint)oldPBO);
      }
      else
      {
        Buffer::DataWriteLock bufferLock(buffer, Buffer::MAP_WRITE);
        glReadPixels(0, 0, m_width, m_height, format, dataType, bufferLock.getPtr());
      }

      makeNoncurrent();

      return true;
    }
Ejemplo n.º 5
0
 bool RenderTarget::beginRendering()
 {
   makeCurrent();
   return true;
 }
Ejemplo n.º 6
0
PlotPolarWidget::~PlotPolarWidget()
{
    makeCurrent();
}
void OGLViewer::paintGL()
{
	// Make curent window
	makeCurrent();
	// Clear background and color buffer
	//glClearColor(0.25, 0.4, 0.5, 0.5);
	glClearColor(0.8, 0.62, 0.68, 1.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	this->paintBox();
	this->paintMesh();
	//////////////////////////////////////////////////////////////////////////
	// Particles
	//glEnable(GL_CULL_FACE);
	//glCullFace(GL_BACK); // cull back face
	//glDisable(GL_DEPTH_TEST); // enable depth-testing
	//glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	//glEnable(GL_BLEND);

	//
	GLuint ptc_vert_vbo;
	glGenBuffers(1, &ptc_vert_vbo);
	glBindBuffer(GL_ARRAY_BUFFER, ptc_vert_vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * ptc_size, ptc_verts, GL_STATIC_DRAW);

	// Bind velocity value
	GLuint ptc_vel_vbo;
	glGenBuffers(1, &ptc_vel_vbo);
	glBindBuffer(GL_ARRAY_BUFFER, ptc_vel_vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * ptc_size, ptc_vels, GL_STATIC_DRAW);

	// Bind life value
	GLuint ptc_life_vbo;
	glGenBuffers(1, &ptc_life_vbo);
	glBindBuffer(GL_ARRAY_BUFFER, ptc_life_vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 2 * ptc_size, ptc_life, GL_STATIC_DRAW);
	// Bind life value
	/*GLuint ptc_alive_vbo;
	glGenBuffers(1, &ptc_alive_vbo);
	glBindBuffer(GL_ARRAY_BUFFER, ptc_alive_vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(GLint) * ptc_size, ptc_alive, GL_STATIC_DRAW);*/

	glActiveTexture(GL_TEXTURE0);
	GLuint tid;
	glGenTextures(1, &tid);
	glBindTexture(GL_TEXTURE_2D, tid);
	glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, texW, texH);
	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, texW, texH,
		GL_RGBA, GL_UNSIGNED_BYTE, tex_pixels);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
		GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
		GL_LINEAR);

	// Bind VAO
	GLuint ptc_vao;
	glGenVertexArrays(1, &ptc_vao);
	glBindVertexArray(ptc_vao);
	glBindBuffer(GL_ARRAY_BUFFER, ptc_vert_vbo);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
	glEnableVertexAttribArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, ptc_vel_vbo);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
	glEnableVertexAttribArray(1);
	glBindBuffer(GL_ARRAY_BUFFER, ptc_life_vbo);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
	glEnableVertexAttribArray(2);
	/*glBindBuffer(GL_ARRAY_BUFFER, ptc_alive_vbo);
	glVertexAttribPointer(3, 1, GL_INT, GL_FALSE, 0, nullptr);
	glEnableVertexAttribArray(3);*/

	render_shader->use_program();

	// Apply uniform matrix
	//glUniformMatrix4fv(model_mat_loc, 1, GL_FALSE, poly_model_mat);
	glUniformMatrix4fv(render_shader->getUniformLocation("view_matrix"), 1, GL_FALSE, view_mat);
	glUniformMatrix4fv(render_shader->getUniformLocation("proj_matrix"), 1, GL_FALSE, proj_mat);
	/*for (int i = 0; i < ptc_size; i++)
	{
		cout << ptc_alive[i] << endl;
	}
	cout << "///////////" << endl;*/
	if (render_shader == ptc_shader)
	{
		glPointSize(5);
	}
	glDrawArrays(GL_POINTS, 0, ptc_size);
}
Ejemplo n.º 8
0
 void push(const Transform& transform)
 {
     individual.push_back(transform);
     Transform result = multiply(transform, current());
     makeCurrent(result);
 }
Ejemplo n.º 9
0
MainWindow::~MainWindow()
{
    makeCurrent();
    delete shader;
    doneCurrent();
}
Ejemplo n.º 10
0
 void InputPreview::setInput(input::Interface *_input) {
   input_ = _input;
   makeCurrent();
 }
Ejemplo n.º 11
0
 bool InputPreview::initialize()
 {
   makeCurrent();
   return context() != nullptr;
 }
Ejemplo n.º 12
0
    void draw() {
        // Attempting to draw before we're visible and have a valid size will
        // produce GL errors.
        if (!isVisible() || _size.width() <= 0 || _size.height() <= 0) {
            return;
        }
        makeCurrent();
        
        gpu::Batch batch;
        batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLORS, { 0.0f, 0.0f, 0.0f, 1.0f });
        batch.clearDepthFramebuffer(1e4);
        batch.setViewportTransform({ 0, 0, _size.width() * devicePixelRatio(), _size.height() * devicePixelRatio() });
        batch.setProjectionTransform(_projectionMatrix);
        
        float t = _time.elapsed() * 1e-3f;
        glm::vec3 unitscale { 1.0f };
        glm::vec3 up { 0.0f, 1.0f, 0.0f };

        float distance = 3.0f;
        glm::vec3 camera_position{ distance * sinf(t), 0.0f, distance * cosf(t) };

        static const vec3 camera_focus(0);
        static const vec3 camera_up(0, 1, 0);
        glm::mat4 camera = glm::inverse(glm::lookAt(camera_position, camera_focus, up));
        batch.setViewTransform(camera);
        batch.setPipeline(_pipeline);
        batch.setModelTransform(Transform());

        auto geometryCache = DependencyManager::get<GeometryCache>();

        // Render grid on xz plane (not the optimal way to do things, but w/e)
        // Note: GeometryCache::renderGrid will *not* work, as it is apparenly unaffected by batch rotations and renders xy only
        {
            static const std::string GRID_INSTANCE = "Grid";
            static auto compactColor1 = toCompactColor(vec4{ 0.35f, 0.25f, 0.15f, 1.0f });
            static auto compactColor2 = toCompactColor(vec4{ 0.15f, 0.25f, 0.35f, 1.0f });
            static std::vector<glm::mat4> transforms;
            static gpu::BufferPointer colorBuffer;
            if (!transforms.empty()) {
                transforms.reserve(200);
                colorBuffer = std::make_shared<gpu::Buffer>();
                for (int i = 0; i < 100; ++i) {
                    {
                        glm::mat4 transform = glm::translate(mat4(), vec3(0, -1, -50 + i));
                        transform = glm::scale(transform, vec3(100, 1, 1));
                        transforms.push_back(transform);
                        colorBuffer->append(compactColor1);
                    }

                    {
                        glm::mat4 transform = glm::mat4_cast(quat(vec3(0, PI / 2.0f, 0)));
                        transform = glm::translate(transform, vec3(0, -1, -50 + i));
                        transform = glm::scale(transform, vec3(100, 1, 1));
                        transforms.push_back(transform);
                        colorBuffer->append(compactColor2);
                    }
                }
            }

            auto pipeline = geometryCache->getSimplePipeline();
            for (auto& transform : transforms) {
                batch.setModelTransform(transform);
                batch.setupNamedCalls(GRID_INSTANCE, [=](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) {
                    batch.setViewTransform(camera);
                    batch.setPipeline(_pipeline);
                    geometryCache->renderWireShapeInstances(batch, GeometryCache::Line, data.count(), colorBuffer);
                });
            }
        }

        {
            static const size_t ITEM_COUNT = 1000;
            static const float SHAPE_INTERVAL = (PI * 2.0f) / ITEM_COUNT;
            static const float ITEM_INTERVAL = SHAPE_INTERVAL / TYPE_COUNT;

            static const gpu::Element POSITION_ELEMENT{ gpu::VEC3, gpu::FLOAT, gpu::XYZ };
            static const gpu::Element NORMAL_ELEMENT{ gpu::VEC3, gpu::FLOAT, gpu::XYZ };
            static const gpu::Element COLOR_ELEMENT{ gpu::VEC4, gpu::NUINT8, gpu::RGBA };
            static const gpu::Element TRANSFORM_ELEMENT{ gpu::MAT4, gpu::FLOAT, gpu::XYZW };


            static std::vector<Transform> transforms;
            static std::vector<vec4> colors;
            static gpu::BufferPointer indirectBuffer;
            static gpu::BufferPointer transformBuffer;
            static gpu::BufferPointer colorBuffer;
            static gpu::BufferView colorView; 
            static gpu::BufferView instanceXfmView; 

            if (!transformBuffer) {
                transformBuffer = std::make_shared<gpu::Buffer>();
                colorBuffer = std::make_shared<gpu::Buffer>();
                indirectBuffer = std::make_shared<gpu::Buffer>();

                static const float ITEM_RADIUS = 20;
                static const vec3 ITEM_TRANSLATION{ 0, 0, -ITEM_RADIUS };
                for (size_t i = 0; i < TYPE_COUNT; ++i) {
                    GeometryCache::Shape shape = SHAPE[i];
                    GeometryCache::ShapeData shapeData = geometryCache->_shapes[shape];
                    {
                        gpu::Batch::DrawIndexedIndirectCommand indirectCommand;
                        indirectCommand._count = (uint)shapeData._indexCount;
                        indirectCommand._instanceCount = ITEM_COUNT;
                        indirectCommand._baseInstance = (uint)(i * ITEM_COUNT);
                        indirectCommand._firstIndex = (uint)shapeData._indexOffset / 2;
                        indirectCommand._baseVertex = 0;
                        indirectBuffer->append(indirectCommand);
                    }

                    //indirectCommand._count
                    float startingInterval = ITEM_INTERVAL * i;
                    for (size_t j = 0; j < ITEM_COUNT; ++j) {
                        float theta = j * SHAPE_INTERVAL + startingInterval;
                        auto transform = glm::rotate(mat4(), theta, Vectors::UP);
                        transform = glm::rotate(transform, (randFloat() - 0.5f) * PI / 4.0f, Vectors::UNIT_X);
                        transform = glm::translate(transform, ITEM_TRANSLATION);
                        transform = glm::scale(transform, vec3(randFloat() / 2.0f + 0.5f));
                        transformBuffer->append(transform);
                        transforms.push_back(transform);
                        auto color = vec4{ randomColorValue(64), randomColorValue(64), randomColorValue(64), 255 };
                        color /= 255.0f;
                        colors.push_back(color);
                        colorBuffer->append(toCompactColor(color));
                    }
                }
                colorView = gpu::BufferView(colorBuffer, COLOR_ELEMENT);
                instanceXfmView = gpu::BufferView(transformBuffer, TRANSFORM_ELEMENT);
            }

#if 1
            GeometryCache::ShapeData shapeData = geometryCache->_shapes[GeometryCache::Icosahedron];
            {
                batch.setViewTransform(camera);
                batch.setModelTransform(Transform());
                batch.setPipeline(_pipeline);
                batch.setInputFormat(getInstancedSolidStreamFormat());
                batch.setInputBuffer(gpu::Stream::COLOR, colorView);
                batch.setIndirectBuffer(indirectBuffer);
                shapeData.setupBatch(batch);
                batch.multiDrawIndexedIndirect(TYPE_COUNT, gpu::TRIANGLES);
            }
#else
            batch.setViewTransform(camera);
            batch.setPipeline(_pipeline);
            for (size_t i = 0; i < TYPE_COUNT; ++i) {
                GeometryCache::Shape shape = SHAPE[i];
                for (size_t j = 0; j < ITEM_COUNT; ++j) {
                    int index = i * ITEM_COUNT + j;
                    batch.setModelTransform(transforms[index]);
                    const vec4& color = colors[index];
                    batch._glColor4f(color.r, color.g, color.b, 1.0);
                    geometryCache->renderShape(batch, shape);
                }
            }
#endif
        }

        // Render unlit cube + sphere
        static auto startUsecs = usecTimestampNow(); 
        float seconds = getSeconds(startUsecs);

        seconds /= 4.0f;
        int shapeIndex = ((int)seconds) % TYPE_COUNT;
        bool wire = (seconds - floorf(seconds) > 0.5f);
        batch.setModelTransform(Transform());
        batch._glColor4f(0.8f, 0.25f, 0.25f, 1.0f);

        if (wire) {
            geometryCache->renderWireShape(batch, SHAPE[shapeIndex]);
        } else {
            geometryCache->renderShape(batch, SHAPE[shapeIndex]);
        }
        
        batch.setModelTransform(Transform().setScale(2.05f));
        batch._glColor4f(1, 1, 1, 1);
        geometryCache->renderWireCube(batch);

        _context->render(batch);
        _qGlContext.swapBuffers(this);
        
        fps.increment();
        if (fps.elapsed() >= 0.5f) {
            qDebug() << "FPS: " << fps.rate();
            fps.reset();
        }
    }
Ejemplo n.º 13
0
	GLWidget( QGLFormat & format, QWidget * parent = 0 ) :
		QGLWidget( format, parent )
		{ makeCurrent(); glewInit(); }
Ejemplo n.º 14
0
    QTestWindow() {
        setSurfaceType(QSurface::OpenGLSurface);

        QSurfaceFormat format;
        // Qt Quick may need a depth and stencil buffer. Always make sure these are available.
        format.setDepthBufferSize(16);
        format.setStencilBufferSize(8);
        format.setVersion(4, 5);
        format.setProfile(QSurfaceFormat::OpenGLContextProfile::CompatibilityProfile);
        format.setOption(QSurfaceFormat::DebugContext);

        setFormat(format);

        _context = new QOpenGLContext;
        _context->setFormat(format);
        _context->create();

        show();
        makeCurrent();

        {
            QOpenGLDebugLogger* logger = new QOpenGLDebugLogger(this);
            logger->initialize(); // initializes in the current context, i.e. ctx
            logger->enableMessages();
            connect(logger, &QOpenGLDebugLogger::messageLogged, this, [&](const QOpenGLDebugMessage & debugMessage) {
                qDebug() << debugMessage;
            });
            //        logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
        }
        qDebug() << (const char*)glGetString(GL_VERSION);

#ifdef WIN32
        glewExperimental = true;
        GLenum err = glewInit();
        if (GLEW_OK != err) {
            /* Problem: glewInit failed, something is seriously wrong. */
            const GLubyte * errStr = glewGetErrorString(err);
            qDebug("Error: %s\n", errStr);
        }
        qDebug("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

        if (wglewGetExtension("WGL_EXT_swap_control")) {
            int swapInterval = wglGetSwapIntervalEXT();
            qDebug("V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF"));
        }
        glGetError();
#endif

        _textRenderer[0] = TextRenderer::getInstance(SANS_FONT_FAMILY, 12, false);
        _textRenderer[1] = TextRenderer::getInstance(SERIF_FONT_FAMILY, 12, false,
            TextRenderer::SHADOW_EFFECT);
        _textRenderer[2] = TextRenderer::getInstance(MONO_FONT_FAMILY, 48, -1,
            false, TextRenderer::OUTLINE_EFFECT);
        _textRenderer[3] = TextRenderer::getInstance(INCONSOLATA_FONT_FAMILY, 24);

        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glClearColor(0.2f, 0.2f, 0.2f, 1);
        glDisable(GL_DEPTH_TEST);

        makeCurrent();

        setFramePosition(QPoint(-1000, 0));
        resize(QSize(800, 600));
    }
Ejemplo n.º 15
0
void GLWidget::cleanup()
{
    makeCurrent();
    doneCurrent();
}
Ejemplo n.º 16
0
void AnimeGLWidget::deleteTexture(GLuint texId)
{
    makeCurrent();
    m_pTextureCacheManager->remove(texId);
    doneCurrent();
}
Ejemplo n.º 17
0
/* Clear the image display area. */
void MidasGL::midas_clear()
{
  makeCurrent();
  glClear(GL_COLOR_BUFFER_BIT);
}
bool GLHelper::setUp(const ShaderDesc* shaderDescs, size_t numShaders) {
    bool result;

    mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if (mDisplay == EGL_NO_DISPLAY) {
        fprintf(stderr, "eglGetDisplay error: %#x\n", eglGetError());
        return false;
    }

    EGLint majorVersion;
    EGLint minorVersion;
    result = eglInitialize(mDisplay, &majorVersion, &minorVersion);
    if (result != EGL_TRUE) {
        fprintf(stderr, "eglInitialize error: %#x\n", eglGetError());
        return false;
    }

    EGLint numConfigs = 0;
    EGLint configAttribs[] = {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_NONE
    };
    result = eglChooseConfig(mDisplay, configAttribs, &mConfig, 1,
            &numConfigs);
    if (result != EGL_TRUE) {
        fprintf(stderr, "eglChooseConfig error: %#x\n", eglGetError());
        return false;
    }

    EGLint contextAttribs[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };
    mContext = eglCreateContext(mDisplay, mConfig, EGL_NO_CONTEXT,
            contextAttribs);
    if (mContext == EGL_NO_CONTEXT) {
        fprintf(stderr, "eglCreateContext error: %#x\n", eglGetError());
        return false;
    }

    bool resultb = createNamedSurfaceTexture(0, 1, 1, &mDummyGLConsumer,
            &mDummySurface);
    if (!resultb) {
        return false;
    }

    resultb = makeCurrent(mDummySurface);
    if (!resultb) {
        return false;
    }

    resultb = setUpShaders(shaderDescs, numShaders);
    if (!resultb) {
        return false;
    }

    return true;
}
Ejemplo n.º 19
0
GLSimpleWaveformWidget::~GLSimpleWaveformWidget(){
    if (QGLContext::currentContext() != context()) {
        makeCurrent();
    }
}
Ejemplo n.º 20
0
		void GLRenderWindow::lockGLContext()
		{
			contex_mutex_.lock();
			makeCurrent();
		}
Ejemplo n.º 21
0
LifeWidget::~LifeWidget()
{
    makeCurrent();
}
Ejemplo n.º 22
0
SDLWindow::SDLWindow(const GWindow::Settings& settings) {

#if defined(G3D_OSX)
	NSApplicationWrapper wrapper;

	// Hack to get our window/process to the front...
	ProcessSerialNumber psn = { 0, kCurrentProcess};    
	TransformProcessType (&psn, kProcessTransformToForegroundApplication);
	SetFrontProcess (&psn);

	_pool = new NSAutoreleasePoolWrapper();
#endif

	if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO | 
                 SDL_INIT_JOYSTICK) < 0 ) {

        fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
		debugPrintf("Unable to initialize SDL: %s\n", SDL_GetError());
        Log::common()->printf("Unable to initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}

    // Set default icon if available
    if (settings.defaultIconFilename != "nodefault") {

        try {

            GImage defaultIcon;
            defaultIcon.load(settings.defaultIconFilename);

            setIcon(defaultIcon);
        } catch (const GImage::Error& e) {
            // Throw away default icon
            fprintf(stderr, "GWindow's default icon failed to load: %s (%s)", e.filename.c_str(), e.reason.c_str());
		    debugPrintf("GWindow's default icon failed to load: %s (%s)", e.filename.c_str(), e.reason.c_str());
            Log::common()->printf("GWindow's default icon failed to load: %s (%s)", e.filename.c_str(), e.reason.c_str());            
        }
    }

    if (! settings.fullScreen) {
        // This doesn't really work very well due to SDL bugs so we fix up 
        // the position after the window is created.
        if (settings.center) {
            System::setEnv("SDL_VIDEO_CENTERED", "");
        } else {
            System::setEnv("SDL_VIDEO_WINDOW_POS", format("%d,%d", settings.x, settings.y));
        }
    }

    _mouseVisible = true;
    _inputCapture = false;

	// Request various OpenGL parameters
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,      settings.depthBits);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,    1);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,    settings.stencilBits);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE,        settings.rgbBits);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,      settings.rgbBits);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,       settings.rgbBits);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,      settings.alphaBits);
	SDL_GL_SetAttribute(SDL_GL_STEREO,          settings.stereo);

    #if SDL_FSAA
        if (settings.fsaaSamples > 1) {
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 
                                settings.fsaaSamples);
        }
    #endif

	// Create a width x height OpenGL screen 
    int flags = 
        SDL_HWSURFACE |
        SDL_OPENGL |
        (settings.fullScreen ? SDL_FULLSCREEN : 0) |
        (settings.resizable ? SDL_RESIZABLE : 0) |
        (settings.framed ? 0 : SDL_NOFRAME);

	if (SDL_SetVideoMode(settings.width, settings.height, 0, flags) == NULL) {
        debugAssert(false);
        Log::common()->printf("Unable to create OpenGL screen: %s\n", 
                              SDL_GetError());
		error("Critical Error", 
              format("Unable to create OpenGL screen: %s\n", 
                     SDL_GetError()).c_str(), true);
		SDL_Quit();
		exit(2);
	}

    // See what video mode we really got
    _settings = settings;
    int depthBits, stencilBits, redBits, greenBits, blueBits, alphaBits;
    glGetIntegerv(GL_DEPTH_BITS, &depthBits);
    glGetIntegerv(GL_STENCIL_BITS, &stencilBits);

    glGetIntegerv(GL_RED_BITS,   &redBits);
    glGetIntegerv(GL_GREEN_BITS, &greenBits);
    glGetIntegerv(GL_BLUE_BITS,  &blueBits);
    glGetIntegerv(GL_ALPHA_BITS, &alphaBits);
    int actualFSAABuffers = 0, actualFSAASamples = 0;

    #if SDL_FSAA
        SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &actualFSAABuffers);
        SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &actualFSAASamples);
    #else
        (void)actualFSAABuffers;
        (void)actualFSAASamples;
    #endif
    _settings.rgbBits     = iMin(iMin(redBits, greenBits), blueBits);
    _settings.alphaBits   = alphaBits;
    _settings.stencilBits = stencilBits;
    _settings.depthBits   = depthBits;
    _settings.fsaaSamples = actualFSAASamples;

    SDL_version ver;
    SDL_VERSION(&ver);
    _version = format("%d,%0d.%0d", ver.major, ver.minor, ver.patch);

    SDL_EnableUNICODE(1);
    setCaption("G3D");

    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    SDL_GetWMInfo(&info);

    _glContext = glGetCurrentContext();

    #if defined(G3D_WIN32)
        // Extract SDL HDC/HWND on Win32
        _Win32HWND  = info.window;
        _Win32HDC   = wglGetCurrentDC();
    #elif defined(G3D_LINUX)
        // Extract SDL's internal Display pointer on Linux        
        _X11Display = info.info.x11.display;
        _X11Window  = info.info.x11.window;
        _X11WMWindow  = info.info.x11.wmwindow;

        if (glXGetCurrentDisplay != NULL) {
            G3D::_internal::x11Display = glXGetCurrentDisplay();
        } else {
            G3D::_internal::x11Display = info.info.x11.display;
        }

        if (glXGetCurrentDrawable != NULL) {
            // A Drawable appears to be either a Window or a Pixmap
            G3D::_internal::x11Window  = glXGetCurrentDrawable();
        } else {
            G3D::_internal::x11Window  = info.info.x11.window;
        }
    #endif

    // Adjust window position
    #ifdef G3D_WIN32
        if (! settings.fullScreen) {
            int W = screenWidth();
            int H = screenHeight();
            int x = iClamp(settings.x, 0, W);
            int y = iClamp(settings.y, 0, H);

            if (settings.center) {
                x = (W - settings.width) / 2;
                y = (H - settings.height) / 2;
            }

            SetWindowPos(_Win32HWND, NULL, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
        }
    #endif

	#ifdef G3D_LINUX
		 if (! settings.fullScreen) {
            int W = screenWidth(_X11Display);
            int H = screenHeight(_X11Display);
            int x = iClamp(settings.x, 0, W);
            int y = iClamp(settings.y, 0, H);

            if (settings.center) {
                x = (W  - settings.width) / 2;
                y = (H - settings.height) / 2;
            }
			XMoveWindow(_X11Display, _X11WMWindow, x, y);
        }
	#endif


	// Check for joysticks
    int j = SDL_NumJoysticks();
    if ((j < 0) || (j > 10)) {
        // If there is no joystick adapter on Win32,
        // SDL returns ridiculous numbers.
        j = 0;
    }

	if (j > 0) {
        SDL_JoystickEventState(SDL_ENABLE);
        // Turn on the joysticks

        joy.resize(j);
        for (int i = 0; i < j; ++i) {
            joy[i] = SDL_JoystickOpen(i);
            debugAssert(joy[i]);
        }
	}

    GLCaps::init();

	// Register this window as the current window
	makeCurrent();

#	if defined(G3D_LINUX)
		// If G3D is using the default assertion hooks, replace them with our own that use
		// SDL functions to release the mouse, since we've been unable to implement
		// a non-SDL way of releasing the mouse using the X11 handle directly.
		if (assertionHook() == _internal::_handleDebugAssert_) {
			setFailureHook(SDL_handleDebugAssert_);
		}

		if (failureHook() == _internal::_handleErrorCheck_) {
			setFailureHook(SDL_handleErrorCheck_);
		}
#	endif
}
Ejemplo n.º 23
0
    std::vector<uint8_t> RenderTarget::getImagePixels( GLenum mode, dp::PixelFormat pixelFormat, dp::DataType pixelDataType )
    {
      // FIXME use C++ object for current/noncurrent for exception safety
      makeCurrent();

      size_t components = 0;
      size_t bytesPerComponent = 0;

      // set up alignments
      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
      glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
      glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
      glPixelStorei(GL_PACK_ALIGNMENT, 1);
      glPixelStorei(GL_PACK_ROW_LENGTH, 0);
      glPixelStorei(GL_PACK_SKIP_ROWS, 0);
      glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

      // determine OpenGL format
      GLenum format = ~0;
      switch (pixelFormat)
      {
      case dp::PixelFormat::RGB:
        format = GL_RGB;
        components = 3;
        break;
      case dp::PixelFormat::RGBA:
        format = GL_RGBA;
        components = 4;
        break;
      case dp::PixelFormat::BGR:
        format = GL_BGR;
        components = 3;
        break;
      case dp::PixelFormat::BGRA:
        format = GL_BGRA;
        components = 4;
        break;
      case dp::PixelFormat::LUMINANCE:
        format = GL_LUMINANCE;
        components = 1;
        break;
      case dp::PixelFormat::ALPHA:
        format = GL_ALPHA;
        components = 1;
        break;
      case dp::PixelFormat::LUMINANCE_ALPHA:
        format = GL_LUMINANCE_ALPHA;
        components = 2;
        break;
      case dp::PixelFormat::DEPTH_COMPONENT:
        format = GL_DEPTH_COMPONENT;
        components = 1;
        break;
      case dp::PixelFormat::DEPTH_STENCIL:
        format = GL_DEPTH_STENCIL;
        components = 1;
        break;
      case dp::PixelFormat::STENCIL_INDEX:
        format = GL_STENCIL_INDEX;
        components = 1;
        break;
      default:
        DP_ASSERT(0 && "unsupported PixelFormat");
      };

      GLenum dataType = ~0;
      switch (pixelDataType)
      {
      case dp::DataType::INT_8:
        dataType = GL_BYTE;
        bytesPerComponent = 1;
        break;
      case dp::DataType::UNSIGNED_INT_8:
        dataType = GL_UNSIGNED_BYTE;
        bytesPerComponent = 1;
        break;
      case dp::DataType::INT_16:
        dataType = GL_SHORT;
        bytesPerComponent = 2;
        break;
      case dp::DataType::UNSIGNED_INT_16:
        dataType = GL_UNSIGNED_SHORT;
        bytesPerComponent = 2;
        break;
      case dp::DataType::INT_32:
        dataType = GL_INT;
        bytesPerComponent = 4;
        break;
      case dp::DataType::UNSIGNED_INT_32:
        dataType = GL_UNSIGNED_INT;
        bytesPerComponent = 4;
        break;
      case dp::DataType::FLOAT_32:
        dataType = GL_FLOAT;
        bytesPerComponent = 4;
        break;
      case dp::DataType::FLOAT_16:
        dataType = GL_HALF_FLOAT;
        bytesPerComponent = 2;
        break;
      default:
        DP_ASSERT(0 && "unsupported PixelDataType");
      }

      size_t imageSizeInBytes = m_width * m_height * components * bytesPerComponent;
      std::vector<uint8_t> output(imageSizeInBytes);

      if ( imageSizeInBytes )
      {
        // read the pixels
        glWindowPos2i(0,0);
        glReadBuffer( mode );

        glReadPixels(0, 0, m_width, m_height, format, dataType, &output[0]);
      }

      makeNoncurrent();

      return output;
    }
Ejemplo n.º 24
0
MyGL::~MyGL()
{
    makeCurrent();

    vao.destroy();
}
GLBox::~GLBox()
{
    makeCurrent();
    glDeleteLists( object, 1 );
}
Ejemplo n.º 26
0
void GLWidget::setWireframeMode(const bool state)
{
    makeCurrent();
    wireframeMode = state;
    updateGL();
}
Ejemplo n.º 27
0
void GLWidget::draw()
{
    QPainter p(this); // used for text overlay

    // save the GL state set for QPainter
    p.beginNativePainting();
    saveGLState();

    // render the 'bubbles.svg' file into our pbuffer
    QPainter pbuffer_painter(pbuffer);
    svg_renderer->render(&pbuffer_painter);
    pbuffer_painter.end();
    glFlush();

    // rendering directly to a texture is not supported on X11 and
    // some Windows implementations, unfortunately
    if (!hasDynamicTextureUpdate)
        pbuffer->updateDynamicTexture(dynamicTexture);

    makeCurrent();
    // draw into the GL widget
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-1, 1, -1, 1, 10, 100);
    glTranslatef(0.0f, 0.0f, -15.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glViewport(0, 0, width(), height());

    glBindTexture(GL_TEXTURE_2D, dynamicTexture);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_MULTISAMPLE);
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // draw background
    glPushMatrix();
    glScalef(1.7f, 1.7f, 1.7f);
    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    glCallList(tile_list);
    glPopMatrix();

    const int w = logo.width();
    const int h = logo.height();

    glRotatef(rot_x, 1.0f, 0.0f, 0.0f);
    glRotatef(rot_y, 0.0f, 1.0f, 0.0f);
    glRotatef(rot_z, 0.0f, 0.0f, 1.0f);
    glScalef(scale/w, scale/w, scale/w);

    glDepthFunc(GL_LESS);
    glEnable(GL_DEPTH_TEST);

    // draw the Qt icon
    glTranslatef(-w+1, -h+1, 0.0f);
    for (int y=h-1; y>=0; --y) {
        uint *p = (uint*) logo.scanLine(y);
        uint *end = p + w;
        int  x = 0;
        while (p < end) {
            glColor4ub(qRed(*p), qGreen(*p), qBlue(*p), uchar(qAlpha(*p)*.9));
            glTranslatef(0.0f, 0.0f, wave[y*w+x]);
            if (qAlpha(*p) > 128)
                glCallList(tile_list);
            glTranslatef(0.0f, 0.0f, -wave[y*w+x]);
            glTranslatef(2.0f, 0.0f, 0.0f);
            ++x;
            ++p;
        }
        glTranslatef(-w*2.0f, 2.0f, 0.0f);
    }

    // restore the GL state that QPainter expects
    restoreGLState();
    p.endNativePainting();

    // draw the overlayed text using QPainter
    p.setPen(QColor(197, 197, 197, 157));
    p.setBrush(QColor(197, 197, 197, 127));
    p.drawRect(QRect(0, 0, width(), 50));
    p.setPen(Qt::black);
    p.setBrush(Qt::NoBrush);
    const QString str1(tr("A simple OpenGL pbuffer example."));
    const QString str2(tr("Use the mouse wheel to zoom, press buttons and move mouse to rotate, double-click to flip."));
    QFontMetrics fm(p.font());
    p.drawText(width()/2 - fm.width(str1)/2, 20, str1);
    p.drawText(width()/2 - fm.width(str2)/2, 20 + fm.lineSpacing(), str2);
}
Ejemplo n.º 28
0
void gemglutwindow :: swapBuffers(void) {
  if(makeCurrent()) // FIXME: is this needed?
    glutSwapBuffers();
}
Ejemplo n.º 29
0
GLWidget::~GLWidget()
{
    makeCurrent();
    glDeleteLists(object, 1);
}
	WindowGL33::WindowGL33(std::string title, int width, int height, bool fullscreen, unsigned int multisampling) :
			m_title { title }, m_multisampling { multisampling }
	{
		if (fullscreen)
		{
			// Initialize window to default values
			m_windowedWidth = 800;
			m_windowedHeight = 600;
			// Initialize fullscreen resolution
			m_fullscreenWidth = width;
			m_fullscreenHeight = height;
			m_isFullscreen = true;
		}
		else
		{
			// Initialize window to default values
			m_windowedWidth = width;
			m_windowedHeight = height;
			// Initialize fullscreen resolution to screen resolution
			const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
			m_fullscreenWidth = mode->width;
			m_fullscreenHeight = mode->height;
			m_isFullscreen = false;
		}

		glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
		glfwWindowHint(GLFW_SAMPLES, multisampling);
		glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

		if (fullscreen)
			m_pWndHandle = glfwCreateWindow(m_fullscreenWidth, m_fullscreenHeight, title.c_str(),
					glfwGetPrimaryMonitor(), nullptr);
		else
			m_pWndHandle = glfwCreateWindow(m_windowedWidth, m_windowedHeight, title.c_str(), nullptr, nullptr);
		if (!m_pWndHandle)
		{
			std::cerr << "Failed to create new window!";
			glfwTerminate();
		}

		// Remember window
		s_windows.insert( { m_pWndHandle, this });

		m_windowedX = getX();
		m_windowedY = getY();

		makeCurrent();

		// Initialize GLEW
		glewExperimental = true; // For core profile
		if (glewInit() != GLEW_OK)
		{
			std::cerr << "Failed to initialize GLEW!";
			glfwTerminate();
		}

		// Enable multisampling?
		if (m_multisampling > 0)
			m_rc.setMultisampling(true);

		// Wrap context in vao
		glGenVertexArrays(1, &m_vertexArrayId);
		glBindVertexArray(m_vertexArrayId);

		// Register OpenGL Debug callback if available
		if (GLEW_ARB_debug_output)
			glDebugMessageCallbackARB((GLDEBUGPROCARB)WindowGL33::debugCallback, nullptr);
	}