Beispiel #1
0
ofMatrix4x4 ofApp::getViewMatrix() {
	ofMatrix4x4 viewMatrix = ofMatrix4x4(
		globals.scale, 0.0, 0.0, 0.0, 
		0.0, -globals.scale, 0.0, 0.0, 
		0.0, 0.0, 1.0, 0.0, 
		0.0, 0.0, 0.0, 1.0);

	if (globals.invertX) viewMatrix(0,0) *= -1;
	if (globals.invertY) viewMatrix(1,1) *= -1;

	if (globals.flipXY) {
		viewMatrix = ofMatrix4x4(
			0.0, 1.0, 0.0, 0.0, 
			1.0, 0.0, 0.0, 0.0, 
			0.0, 0.0, 1.0, 0.0, 
			0.0, 0.0, 0.0, 1.0 ) * viewMatrix;
	}

	ofMatrix4x4 aspectMatrix; // identity matrix
	float aspectRatio = float(fbo.getWidth()) / float(fbo.getHeight());
	if (aspectRatio > 1.0) {
		aspectMatrix(0,0) /= aspectRatio;
	}
	else {
		aspectMatrix(1,1) *= aspectRatio;
	}

	return viewMatrix * aspectMatrix;
}
Beispiel #2
0
void doArcball(
	double * _viewMatrix, 
	double const * _rotationCenter, 
	double const * _projectionMatrix, 
	double const * _initialViewMatrix, 
	//double const * _currentViewMatrix,
	double const * _initialMouse, 
	double const * _currentMouse, 
	bool screenSpaceRadius,
	double radius)
{
	Eigen::Map<Eigen::Vector3d const> rotationCenter(_rotationCenter);
	Eigen::Map<Eigen::Matrix4d const> initialViewMatrix(_initialViewMatrix);
	//Eigen::Map<Eigen::Matrix4d const> currentViewMatrix(_currentViewMatrix);
	Eigen::Map<Eigen::Matrix4d const> projectionMatrix(_projectionMatrix);
	Eigen::Map<Eigen::Matrix4d> viewMatrix(_viewMatrix);

	Eigen::Vector2d initialMouse(_initialMouse);
	Eigen::Vector2d currentMouse(_currentMouse);
	
	Eigen::Quaterniond q;
	Eigen::Vector3d Pa, Pc;
	if (screenSpaceRadius) {
		double aspectRatio = projectionMatrix(1, 1) / projectionMatrix(0, 0);

		initialMouse(0) *= aspectRatio;
		currentMouse(0) *= aspectRatio;

		Pa = mapToSphere(initialMouse, radius);
		Pc = mapToSphere(currentMouse, radius);

		q.setFromTwoVectors(Pa - rotationCenter, Pc - rotationCenter);
	}
	else {
		Pa = mapToSphere(projectionMatrix.inverse(), initialMouse, rotationCenter, radius);
		Pc = mapToSphere(projectionMatrix.inverse(), currentMouse, rotationCenter, radius);

		Eigen::Vector3d a = Pa - rotationCenter, b = Pc - rotationCenter;

#if 0
		std::cout << "Mouse Initial Radius = " << sqrt(a.dot(a)) << " Current Radius = " << sqrt(b.dot(b)) << std::endl;
#endif

		q.setFromTwoVectors(a, b);
	}	

	Eigen::Matrix4d qMat4;
	qMat4.setIdentity();
	qMat4.topLeftCorner<3, 3>() = q.toRotationMatrix();

	Eigen::Matrix4d translate;
	translate.setIdentity();
	translate.topRightCorner<3, 1>() = -rotationCenter;

	Eigen::Matrix4d invTranslate;
	invTranslate.setIdentity();
	invTranslate.topRightCorner<3, 1>() = rotationCenter;
	
    viewMatrix = invTranslate * qMat4 * translate * initialViewMatrix;
}
Beispiel #3
0
void Graphics3D::render(const Matrix &view, const Matrix &proj, const Light *lighting, int flags)
{
    if (!getIsVisible()) return;
    if (!isValid()) return;
    if (lighting == nullptr) {
        lighting = defaultLight;
    }

    Matrix modl = referenceFrame->getModelMatrix();
    OpenGLShaderProgram *shaderProgram = shader->getShader();
    shaderProgram->use();
    
    OpenGLShaderProgram::Uniform modlMatrix(*shaderProgram, "M");
    OpenGLShaderProgram::Uniform viewMatrix(*shaderProgram, "V");
    OpenGLShaderProgram::Uniform projMatrix(*shaderProgram, "P");
    OpenGLShaderProgram::Uniform selectionHandle(*shaderProgram, "selectionHandle");


    modlMatrix.setMatrix4(modl.mat, 1, false);
    viewMatrix.setMatrix4(view.mat, 1, false);
    projMatrix.setMatrix4(proj.mat, 1, false);
    selectionHandle.set(flags ? uniqueHandle : 0);


    geometry->activate(shaderProgram);
    material->activate(shaderProgram);
    lighting->activate(shaderProgram);
    geometry->drawElements();
    geometry->deactivate(shaderProgram);
    material->deactivate(shaderProgram);
    lighting->deactivate(shaderProgram);
}
Beispiel #4
0
glm::mat4 Camera::viewMatrix() const
{
	if (m_cameraNode.expired())
		return glm::lookAt(m_cameraPosition, m_cameraPosition + m_cameraDirection, m_upVector);
	auto realNode = m_cameraNode.lock();
	return realNode->viewMatrix();
}
Beispiel #5
0
void SceneGraph::setupView() {


    auto use_cam = camera_;
    auto use_projector = projector_;
    if (render_mode_ == RenderInfo::SHADOW) {
        use_cam = shadow_camera_;
        use_projector = shadow_projector_;
    }

    T3_NULL_ASSERT(use_cam);

    const Mtx44& view_mtx = use_cam->viewMatrix();
    const Mtx44& proj_mtx = use_projector->projectionMatrix();
    auto view_projection = proj_mtx * view_mtx;
    pushAndSetMatrix(view_projection);
    
    cross::RenderSystem::setViewport(
        0, 
        0, 
        static_cast<int>(use_projector->screenSize().x_),
        static_cast<int>(use_projector->screenSize().y_)
	);
 
}
Beispiel #6
0
Matrix4x4f CameraUtility::getView() {
	float view[16];
	glGetFloatv(GL_MODELVIEW_MATRIX, view);
	Matrix4x4f viewMatrix(view);

	return viewMatrix;
}
PMatrix4x4 PRenderTransform::modelviewMatrix() const
{
    PMatrix4x4 ret;
    m_drawable->calculateModelCameraMatrix(viewMatrix(), ret.m_m);

    return ret;
}
PMatrix4x4 PRenderTransform::mvpMatrix() const
{
    pfloat32 mv[16];
    m_drawable->calculateModelCameraMatrix(viewMatrix(), mv);

    PMatrix4x4 ret;
    pMatrix4x4Multiply(projectionMatrix().m_m, mv, ret.m_m);
    
    return ret;
}
/*
 Inits the shader program for this object
 */
void GLColoredBox::initShader(void)
{

    // Vertex shader source code. This draws the vertices in our window. We have 3 vertices since we're drawing an triangle.
    // Each vertex is represented by a vector of size 4 (x, y, z, w) coordinates.
    // static const string vertex_code = vs_string_CoordSystem;
    static const char * vs_source = vs_string_ColoredBox_410.c_str();

    // Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader.
    // static const string fragment_code = fs_string_CoordSystem;
    static const char * fs_source = fs_string_ColoredBox_410.c_str();

    // This next section we'll generate the OpenGL program and attach the shaders to it so that we can render our triangle.
    _program = glCreateProgram();

    // We create a shader with our fragment shader source code and compile it.
    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fs_source, NULL);
    glCompileShader(fs);

    // We create a shader with our vertex shader source code and compile it.
    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vs_source, NULL);
    glCompileShader(vs);

    // We'll attach our two compiled shaders to the OpenGL program.
    glAttachShader(_program, vs);
    glAttachShader(_program, fs);

    glLinkProgram(_program);

    glUseProgram(_program);


    _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model


    int projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader
    _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader
    _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader


    glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
    glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
    glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader


    glBindAttribLocation(_program, 0, "in_Position");
    glBindAttribLocation(_program, 1, "in_Color");





}
/*!
 Add the model view matrix, especially the three shader program objects to
 the shader program "program"
 */
bool GLObject::addModelViewMatrixToProgram(GLuint program)
{
    
    _projectionMatrixLocation = glGetUniformLocation(program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader
    _viewMatrixLocation = glGetUniformLocation(program, "viewMatrixBox"); // Get the location of our view matrix in the shader
    _modelMatrixLocation = glGetUniformLocation(program, "modelMatrixBox"); // Get the location of our model matrix in the shader
    _inverseViewMatrixLocation = glGetUniformLocation(program, "inverseViewMatrix");
    
    glUniformMatrix4fv(_projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
    glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
    glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader
    glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &g_invViewMatrix[0][0]);
    return true;
}
Beispiel #11
0
void Camera::passPerFrameUniforms(Shader *_shader) {
    glm::vec2 size = services.get<WindowManager>()->getSize();

    (*_shader)["viewPosition"] = position;

    // Pass the view and projection matrices to the shader
    (*_shader)["view"] = viewMatrix();

    (*_shader)["projection"] = projectionMatrix(size.x / size.y);

    (*_shader)["camera.FOV"] = FOV;
    (*_shader)["camera.nearPlane"] = 0.01f;
    (*_shader)["camera.farPlane"] = 100.0f;
}
Beispiel #12
0
    void Camera::rotateAroundTarget(const quat4f &q) {
        // force update of transform matrix
        aff3f vm = viewMatrix();

        vec3f t = viewM * target;

        viewM = Eigen::Translation3f(t) * q * Eigen::Translation3f(-t) * viewM;

        quat4f qa(viewM.linear());
        qa = qa.conjugate();
        setOrientation(qa);
        setPosition(- (qa * viewM.translation()));

        hasViewChanged = true;
    }
void OverlayRenderer::render(RenderContext& context, const float viewWidth, const float viewHeight) {
    if (m_vbo == NULL)
        m_vbo = new Vbo(GL_ARRAY_BUFFER, 0xFFFF);
    if (m_compass == NULL)
        m_compass = new CompassRenderer();

    glClear(GL_DEPTH_BUFFER_BIT);

    const Mat4f projection = orthoMatrix(0.0f, 1000.0f, -viewWidth / 2.0f, viewHeight / 2.0f, viewWidth / 2.0f, -viewHeight / 2.0f);
    const Mat4f view = viewMatrix(Vec3f::PosY, Vec3f::PosZ) * translationMatrix(500.0f * Vec3f::PosY);
    Renderer::ApplyTransformation ortho(context.transformation(), projection, view);

    const Mat4f compassTransformation = translationMatrix(Vec3f(-viewWidth / 2.0f + 50.0f, 0.0f, -viewHeight / 2.0f + 50.0f)) * scalingMatrix(2.0f);
    Renderer::ApplyModelMatrix applyCompassTranslate(context.transformation(), compassTransformation);

    m_compass->render(*m_vbo, context);
}
Beispiel #14
0
void TextureSticker::fullScreenTextureDepth(CGoGNGLuint texId, CGoGNGLuint dtexId)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Check if TextureSticker's elements have been initialized before
	if (!sm_isInitialized)
	{
		initializeElements();
		sm_isInitialized = true;
	}

	// Check if depth test is enabled

//	GLboolean wasDepthTestEnabled = glIsEnabled(GL_DEPTH_TEST);

	// Disable depth test if it was enabled
//	if (wasDepthTestEnabled == GL_TRUE)
//		glDisable(GL_DEPTH_TEST);

	// Bind texture mapping shader
	sm_depthtextureMappingShader->bind();

	// Set texture uniform
	sm_depthtextureMappingShader->setTextureUnit(GL_TEXTURE0);
	sm_depthtextureMappingShader->activeTexture(texId);
	sm_depthtextureMappingShader->setDepthTextureUnit(GL_TEXTURE1);
	sm_depthtextureMappingShader->activeDepthTexture(dtexId);


	// Set matrices uniforms
	glm::mat4 projMatrix = glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
	glm::mat4 viewMatrix(1.0f);
	sm_depthtextureMappingShader->updateMatrices(projMatrix, viewMatrix);

	// Draw quad
	sm_depthtextureMappingShader->enableVertexAttribs();
	glDrawArrays(GL_QUADS, 0, 4);
	sm_depthtextureMappingShader->disableVertexAttribs();

	// Unbind texture mapping shader
	sm_depthtextureMappingShader->unbind();

	// Re-enable depth test if it was enabled before
//	if (wasDepthTestEnabled == GL_TRUE)
//		glEnable(GL_DEPTH_TEST);
}
Beispiel #15
0
void Camera::drawCurve(QMatrix4x4 modelMatrix)
{
    Q_D(Camera);

    QMatrix4x4 modelViewProject = projectionMatrix() * viewMatrix() * modelMatrix;

    d->curveShader->bind();
    d->curveShader->setUniformValue("mvp", modelViewProject);

    foreach(BezierCurve* curve, d->curves)
        curve->drawCurve(d->curveShader);

    d->curvePointsShader->bind();
    d->curvePointsShader->setUniformValue("mvp", modelViewProject);

    foreach(BezierCurve* curve, d->curves)
        curve->drawControlPoints(d->curvePointsShader);
}
Beispiel #16
0
        void Compass::doRender(RenderContext& renderContext) {
            const Camera& camera = renderContext.camera();
            const Camera::Viewport& viewport = camera.unzoomedViewport();
            const int viewWidth = viewport.width;
            const int viewHeight = viewport.height;
            
            const Mat4x4f projection = orthoMatrix(0.0f, 1000.0f, -viewWidth / 2.0f, viewHeight / 2.0f, viewWidth / 2.0f, -viewHeight / 2.0f);
            const Mat4x4f view = viewMatrix(Vec3f::PosY, Vec3f::PosZ) * translationMatrix(500.0f * Vec3f::PosY);
            const ReplaceTransformation ortho(renderContext.transformation(), projection, view);
            
            const Mat4x4f compassTransformation = translationMatrix(Vec3f(-viewWidth / 2.0f + 55.0f, 0.0f, -viewHeight / 2.0f + 55.0f)) * scalingMatrix<4>(2.0f);
            const MultiplyModelMatrix compass(renderContext.transformation(), compassTransformation);
            const Mat4x4f cameraTransformation = cameraRotationMatrix(camera);

            glAssert(glClear(GL_DEPTH_BUFFER_BIT));
            renderBackground(renderContext);
            glAssert(glClear(GL_DEPTH_BUFFER_BIT));
            doRenderCompass(renderContext, cameraTransformation);
        }
/*!
 Shader for the normal vector renderer
 */
void GLSphereRed::initShaderNormal(void)
{
    _program_normals = CreateShaderProgram(vs_string_simple_shader_410, fs_string_simple_shader_410);
    
    glUseProgram(_program_normals);
    
    unsigned int projectionMatrixLocation = glGetUniformLocation(_program_normals, "projectionMatrix"); // Get the location of our projection matrix in the shader
    _viewMatrixLocationN = glGetUniformLocation(_program_normals, "viewMatrix"); // Get the location of our view matrix in the shader
    _modelMatrixLocationN = glGetUniformLocation(_program_normals, "modelMatrix"); // Get the location of our model matrix in the shader
    
    
    glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
    glUniformMatrix4fv(_viewMatrixLocationN, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
    glUniformMatrix4fv(_modelMatrixLocationN, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader
    
    
    glBindAttribLocation(_program_normals, 0, "in_Position");
    glBindAttribLocation(_program_normals, 1, "in_Color");
    
    glUseProgram(0);
}
Beispiel #18
0
void
Camera::update()
{
  // Update proj matrix.
  StaticCamera::update();

  // Update view matrix.
  const auto pos = transform_.position();
  const auto forward = transform_.forwardVec();
  const auto up = transform_.upVec();
  view_ = Math::Matrix::CreateLookTo(pos, forward, up);

  // Update viewProj matrix.
  viewProj_ = viewMatrix() * projMaxtrix();

  // Update bounding frustum.
  auto frustum = DirectX::BoundingFrustum(projMaxtrix());
  frustum.Origin = transform_.position();
  frustum.Orientation = transform_.rotationQuaternion();
  frustum_ = frustum;
}
void NsRendererOGL3::BeginDraw(NsCamera * pCamera)
{
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

	glClearDepth(1);

	glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );

	glEnable( GL_DEPTH_TEST );
	glDepthMask( GL_TRUE );
	glDepthFunc( GL_LESS );

	glFrontFace( GL_CCW );
	glEnable( GL_CULL_FACE );
	glCullFace( GL_BACK );

	glPolygonMode( GL_FRONT, GL_FILL );

	ResetMatrices();

	NsMatrix4  projectionMatrix;
	projectionMatrix.BuildPerspectiveLH(
		pCamera->fovY,
		pCamera->aspect,
		pCamera->nearZ,
		pCamera->farZ
	);
	SetProjectionMatrix( projectionMatrix );

	NsMatrix4  viewMatrix(
		BuildLookAtMatrixLH(
			pCamera->viewOrigin,
			pCamera->GetLookDirection(),
			pCamera->GetUp()
	));

	SetViewMatrix( viewMatrix );
}
Beispiel #20
0
void TextureSticker::fullScreenShader(Utils::GLSLShader* shader)
{
	// Check if TextureSticker's elements have been initialized before
	if (!sm_isInitialized)
	{
		initializeElements();
		sm_isInitialized = true;
	}
	
	// Check if depth test is enabled
	GLboolean wasDepthTestEnabled = glIsEnabled(GL_DEPTH_TEST);
	
	// Disable depth test if it was enabled
	if (wasDepthTestEnabled == GL_TRUE)
		glDisable(GL_DEPTH_TEST);
	
	// Bind shader
	shader->bind();
	
	// Set matrices uniforms
	glm::mat4 projMatrix = glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
	glm::mat4 viewMatrix(1.0f);
	shader->updateMatrices(projMatrix, viewMatrix);

	// Draw quad
	shader->enableVertexAttribs();
	glDrawArrays(GL_QUADS, 0, 4);
	shader->disableVertexAttribs();
	
	// Unbind shader
	shader->unbind();

	// Re-enable depth test if it was enabled before
	if (wasDepthTestEnabled == GL_TRUE)
		glEnable(GL_DEPTH_TEST);
}
Beispiel #21
0
//
// Vulkan update.
//
VkBool32 Example::update(const vkts::IUpdateThreadContext& updateContext)
{
	for (size_t i = 0; i < allUpdateables.size(); i++)
	{
		allUpdateables[i]->update(updateContext.getDeltaTime(), updateContext.getDeltaTicks());
	}

	//

	VkResult result = VK_SUCCESS;

	//

	if (windowDimension != updateContext.getWindowDimension(windowIndex))
	{
		windowDimension = updateContext.getWindowDimension(windowIndex);

		result = VK_ERROR_OUT_OF_DATE_KHR;
	}

	//

	uint32_t currentBuffer;

	if (result == VK_SUCCESS)
	{
		result = swapchain->acquireNextImage(UINT64_MAX, imageAcquiredSemaphore->getSemaphore(), VK_NULL_HANDLE, currentBuffer);
	}

	if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR)
	{
		glm::mat4 projectionMatrix(1.0f);
		glm::mat4 viewMatrix(1.0f);

		const auto& dimension = updateContext.getWindowDimension(windowIndex);

		projectionMatrix = vkts::perspectiveMat4(45.0f, (float) dimension.x / (float) dimension.y, 1.0f, 100.0f);

		viewMatrix = camera->getViewMatrix();

		glm::vec3 lightDirection = glm::mat3(viewMatrix) * glm::vec3(0.0f, 1.0f, 2.0f);

		lightDirection = glm::normalize(lightDirection);

		if (!fragmentUniformBuffer->upload(0, 0, lightDirection))
		{
			vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not upload light direction.");

			return VK_FALSE;
		}
		if (!vertexViewProjectionUniformBuffer->upload(0 * sizeof(float) * 16, 0, projectionMatrix))
		{
			vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not upload matrices.");

			return VK_FALSE;
		}
		if (!vertexViewProjectionUniformBuffer->upload(1 * sizeof(float) * 16, 0, viewMatrix))
		{
			vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not upload matrices.");

			return VK_FALSE;
		}

		if (scene.get())
		{
			scene->updateRecursive(updateContext);
		}

		//

        VkSemaphore waitSemaphores = imageAcquiredSemaphore->getSemaphore();
        VkSemaphore signalSemaphores = renderingCompleteSemaphore->getSemaphore();


        VkPipelineStageFlags waitDstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;

        VkSubmitInfo submitInfo;

        memset(&submitInfo, 0, sizeof(VkSubmitInfo));

        submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;

        submitInfo.waitSemaphoreCount = 1;
        submitInfo.pWaitSemaphores = &waitSemaphores;
        submitInfo.pWaitDstStageMask = &waitDstStageMask;
        submitInfo.commandBufferCount = 1;
        submitInfo.pCommandBuffers = cmdBuffer[currentBuffer]->getCommandBuffers();
        submitInfo.signalSemaphoreCount = 1;
        submitInfo.pSignalSemaphores = &signalSemaphores;

		result = initialResources->getQueue()->submit(1, &submitInfo, VK_NULL_HANDLE);

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not submit queue.");

			return VK_FALSE;
		}

        waitSemaphores = renderingCompleteSemaphore->getSemaphore();

        VkSwapchainKHR swapchains = swapchain->getSwapchain();

        result = swapchain->queuePresent(initialResources->getQueue()->getQueue(), 1, &waitSemaphores, 1, &swapchains, &currentBuffer, nullptr);

		if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR)
		{
			result = initialResources->getQueue()->waitIdle();

			if (result != VK_SUCCESS)
			{
				vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not wait for idle queue.");

				return VK_FALSE;
			}
		}
		else
		{
			if (result == VK_ERROR_OUT_OF_DATE_KHR)
			{
				terminateResources(updateContext);

				if (!buildResources(updateContext))
				{
					vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not build resources.");

					return VK_FALSE;
				}
			}
			else
			{
				vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not present queue.");

				return VK_FALSE;
			}
		}
	}
	else
	{
		if (result == VK_ERROR_OUT_OF_DATE_KHR)
		{
			terminateResources(updateContext);

			if (!buildResources(updateContext))
			{
				vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not build resources.");

				return VK_FALSE;
			}
		}
		else
		{
			vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not acquire next image.");

			return VK_FALSE;
		}
	}

	//

    result = imageAcquiredSemaphore->reset();

    if (result != VK_SUCCESS)
    {
        vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not reset semaphore.");

        return VK_FALSE;
    }

    result = renderingCompleteSemaphore->reset();

    if (result != VK_SUCCESS)
    {
        vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not reset semaphore.");

        return VK_FALSE;
    }

	return VK_TRUE;
}
/*
 Inits the shader program for this object
 */
void GLSphereRed::initShader(void)
{
    
#ifdef _WIN32
    // This loads the shader program from a file
    _program = LoadAndCreateShaderProgram("../data/shaders/redsphere1.vs", "../data/shaders/redsphere1.fs");
#else
    // This loads the shader program from a file
    _program = LoadAndCreateShaderProgram("/Users/geethanjalijeevanatham/Desktop/Helloworld/myopenGL/model/testing/assignment2/Problem2/Problem2/data/shaders/redsphere1.vs", "/Users/geethanjalijeevanatham/Desktop/Helloworld/myopenGL/model/testing/assignment2/Problem2/Problem2/data/shaders/redsphere1.fs");
#endif
    glUseProgram(_program);
    
    
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Vertex information / names
    
    glBindAttribLocation(_program, 0, "in_Position");
    glBindAttribLocation(_program, 1, "in_Normal");
    glBindAttribLocation(_program, 2, "in_Color");
    
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Define the model view matrix.
    
    
    _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model
    
    
    _projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader
    _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader
    _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader
    _inverseViewMatrixLocation = glGetUniformLocation(_program, "inverseViewMatrix");
    
    
    glUniformMatrix4fv(_projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
    glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
    glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader
    glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Material
    _material._diffuse_material = glm::vec3(1.0, 0.0, 0.0);
    _material._ambient_material = glm::vec3(1.0, 0.0, 0.0);
    _material._specular_material = glm::vec3(1.0, 1.0, 1.0);
    _material._shininess = 150.0;
    
    
    _material._ambientColorPos = glGetUniformLocation(_program, "ambient_color");
    _material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color");
    _material._specularColorPos = glGetUniformLocation(_program, "specular_color");
    _material._shininessIdx = glGetUniformLocation(_program, "shininess");
    
    
    // Send the material to your shader program
    glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] );
    glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]);
    glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]);
    glUniform1f(_material._shininessIdx, _material._shininess);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Light
    
    // define the position of the light and send the light position to your shader program
    _light_source1._lightPos = glm::vec4(2.0,0.0,2.0,0.0);
    _light_source1._ambient_intensity = 0.0;
    _light_source1._specular_intensity = 1.0;
    _light_source1._diffuse_intensity = 1.0;
    _light_source1._attenuation_coeff = 0.02;
    
    
    
    // Read all the index values from the shader program
    _light_source1._ambientIdx = glGetUniformLocation(_program, "ambient_intensity");
    _light_source1._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity");
    _light_source1._specularIdx = glGetUniformLocation(_program, "specular_intensity");
    _light_source1._attenuation_coeffIdx = glGetUniformLocation(_program, "attenuationCoefficient");
    _light_source1._lightPosIdx = glGetUniformLocation(_program, "light_position");
    
    
    // Send the light information to your shader program
    glUniform1f(_light_source1._ambientIdx, _light_source1._ambient_intensity );
    glUniform1f(_light_source1._diffuseIdx, _light_source1._diffuse_intensity);
    glUniform1f(_light_source1._specularIdx, _light_source1._specular_intensity);
    glUniform1f(_light_source1._attenuation_coeffIdx, _light_source1._attenuation_coeff);
    glUniform4fv(_light_source1._lightPosIdx, 1, &_light_source1._lightPos[0]);
    
    
    
    
    glUseProgram(0);
    
    
}
Beispiel #23
0
void AutoBlend::init()
{
    // Add widget
    auto toolsWidgetContainer = new QWidget();
    widget = new Ui::AutoBlendWidget();
    widget->setupUi(toolsWidgetContainer);
    widgetProxy = new QGraphicsProxyWidget(this);
    widgetProxy->setWidget(toolsWidgetContainer);

    // Place at bottom left corner
    auto delta = widgetProxy->sceneBoundingRect().bottomLeft() -
    scene()->views().front()->rect().bottomLeft();
    widgetProxy->moveBy(-delta.x(), -delta.y());

    // Fill categories box
    {
        for(auto cat : document->categories.keys()){
            widget->categoriesBox->insertItem(widget->categoriesBox->count(), cat);
        }

        int idx = widget->categoriesBox->findText(document->categoryOf(document->firstModelName()));
        widget->categoriesBox->setCurrentIndex(idx);
    }

    // Create gallery of shapes
    gallery = new Gallery(this, QRectF(0,0,this->bounds.width(), 220));

    // Create container that holds results
    results = new Gallery(this, QRectF(0,0, this->bounds.width(),
                          bounds.height() - gallery->boundingRect().height()),
                          QRectF(0,0,256,256), true);

    results->moveBy(0, gallery->boundingRect().height());

    // Gallery on top of results
    gallery->setZValue(results->zValue() + 10);

    auto dropShadow = new QGraphicsDropShadowEffect();
	dropShadow->setOffset(0, 5);
    dropShadow->setColor(QColor(0, 0, 0, 150));
	dropShadow->setBlurRadius(10);
	gallery->setGraphicsEffect(dropShadow);

	// Connect UI with actions
	{
		connect(widget->categoriesBox, &QComboBox::currentTextChanged, [&](QString text){
			document->currentCategory = text;
		});

        connect(widget->analyzeButton, &QPushButton::pressed, [&](){
            document->computePairwise(widget->categoriesBox->currentText());
		});

		// Default view angle
		{
			// Camera target and initial position
			auto camera = new Eigen::Camera();
			auto frame = camera->frame();
			frame.position = Eigen::Vector3f(-1, 0, 0.5);
			camera->setTarget(Eigen::Vector3f(0, 0, 0.5));
            camera->setFrame(frame);

            int deltaZoom = document->extent().length() * 1.0;

            // Default view angle
            double theta1 = acos(-1) * 0.75;
            double theta2 = acos(-1) * 0.10;
            camera->rotateAroundTarget(Eigen::Quaternionf(Eigen::AngleAxisf(theta1, Eigen::Vector3f::UnitY())));
            camera->zoom(-(4+deltaZoom));
            camera->rotateAroundTarget(Eigen::Quaternionf(Eigen::AngleAxisf(theta2, Eigen::Vector3f::UnitX())));
			auto cp = camera->position();
			cameraPos = QVector3D(cp[0], cp[1], cp[2]);

			// Camera settings
			camera->setViewport(128, 128);
			Eigen::Matrix4f p = camera->projectionMatrix();
			Eigen::Matrix4f v = camera->viewMatrix().matrix();
			p.transposeInPlace();
			v.transposeInPlace();
			cameraMatrix = QMatrix4x4(p.data()) * QMatrix4x4(v.data());
        }

		connect(document, &Document::categoryAnalysisDone, [=](){
			if (gallery == nullptr) return;

			// Fill gallery
			gallery->clearThumbnails();

			auto catModels = document->categories[document->currentCategory].toStringList();
			for (auto targetName : catModels)
			{
				auto targetModel = document->cacheModel(targetName);
				auto t = gallery->addTextItem(targetName);

				QVariantMap data = t->data;
				data["targetName"].setValue(targetName);
				t->setData(data);

				t->setCamera(cameraPos, cameraMatrix);
				t->setFlag(QGraphicsItem::ItemIsSelectable);

				// Add parts of target shape
				for (auto n : targetModel->nodes){
					t->addAuxMesh(toBasicMesh(targetModel->getMesh(n->id), n->vis_property["color"].value<QColor>()));
				}

                scene()->update(t->sceneBoundingRect());
            }

            scene()->update(this->sceneBoundingRect());
            QTimer::singleShot(500, [=]{ gallery->update(); });
		});

		// Do blend
		connect(widget->blendButton, SIGNAL(pressed()), SLOT(doBlend())); 
    }
}
/*
 Inits the shader program for this object
 */
void GLSphereDirect::initShader(void)
{
#ifdef _WIN32
    // This loads the shader program from a file
	_program = LoadAndCreateShaderProgram("../data/shaders/p1.vs", "../data/shaders/p1.fs");
#else
	 // This loads the shader program from a file
	_program = LoadAndCreateShaderProgram("../../data/shaders/p1.vs", "../../data/shaders/p1.fs");
#endif
    glUseProgram(_program);


    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Vertex information / names

    glBindAttribLocation(_program, 0, "in_Position");
    glBindAttribLocation(_program, 1, "in_Normal");
    glBindAttribLocation(_program, 2, "in_Color");


    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Define the model view matrix.


    _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model


    _projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader
    _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader
    _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader



    glUniformMatrix4fv(_projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
    glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
    glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader


    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Material
    _material._diffuse_material = glm::vec3(0.0, 0.0, 1.0);
    _material._ambient_material = glm::vec3(0.0, 0.0, 0.0);
    _material._specular_material = glm::vec3(1.0, 1.0, 1.0);
    _material._shininess = 1.0;


    _material._ambientColorPos = glGetUniformLocation(_program, "ambient_color");
    _material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color");
    _material._specularColorPos = glGetUniformLocation(_program, "specular_color");
    _material._shininessIdx = glGetUniformLocation(_program, "shininess");


    // Send the material to your shader program
    glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] );
    glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]);
    glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]);
    glUniform1f(_material._shininessIdx, _material._shininess);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Light


    //Normal light
	// define the position of the light and send the light position to your shader program
	_light_source0._lightPos = glm::vec4(0.0, 0.0, 30.0, 1.0);
    _light_source0._ambient_intensity = 0.1;
    _light_source0._specular_intensity = 0.1;
    _light_source0._diffuse_intensity = 10.0;


	// Read all the index values from the shader program
    _light_source0._ambientIdx = glGetUniformLocation(_program, "ambient_intensity0");
    _light_source0._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity0");
    _light_source0._specularIdx = glGetUniformLocation(_program, "specular_intensity0");
    _light_source0._lightPosIdx = glGetUniformLocation(_program, "light_position0");


    // Send the light information to your shader program
    glUniform1f(_light_source0._ambientIdx, _light_source0._ambient_intensity );
    glUniform1f(_light_source0._diffuseIdx, _light_source0._diffuse_intensity);
    glUniform1f(_light_source0._specularIdx, _light_source0._specular_intensity);
    glUniform4fv(_light_source0._lightPosIdx, 1, &_light_source0._lightPos[0]);


	//Spotlight
    // define the position of the light and send the light position to your shader program
    _light_source1._lightPos = glm::vec4(0.0, 0.0, 30, 0.0);
    _light_source1._ambient_intensity = 0.3;
    _light_source1._specular_intensity = 2.0;
    _light_source1._diffuse_intensity = 5.0;
    _light_source1._attenuation_coeff = 0.02;

    _light_source1._cone_angle = 6.0; // in degree
    _light_source1._cone_direction = glm::vec3(-2.0, 0.0, -25.0); // this must be aligned with the object and light position.


    // Read all the index values from the shader program
    _light_source1._ambientIdx = glGetUniformLocation(_program, "ambient_intensity");
    _light_source1._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity");
    _light_source1._specularIdx = glGetUniformLocation(_program, "specular_intensity");
    _light_source1._attenuation_coeffIdx = glGetUniformLocation(_program, "attenuationCoefficient");
    _light_source1._lightPosIdx = glGetUniformLocation(_program, "light_position");
    _light_source1._cone_angleIdx = glGetUniformLocation(_program, "cone_angle");
    _light_source1._cone_directionIdx = glGetUniformLocation(_program, "cone_direction");

    // Send the light information to your shader program
    glUniform1f(_light_source1._ambientIdx, _light_source1._ambient_intensity );
    glUniform1f(_light_source1._diffuseIdx, _light_source1._diffuse_intensity);
    glUniform1f(_light_source1._specularIdx, _light_source1._specular_intensity);
    glUniform1f(_light_source1._attenuation_coeffIdx, _light_source1._attenuation_coeff);
    glUniform4fv(_light_source1._lightPosIdx, 1, &_light_source1._lightPos[0]);

    glUniform1f(_light_source1._cone_angleIdx, _light_source1._cone_angle);
    glUniform3fv(_light_source1._cone_directionIdx, 1, &_light_source1._cone_direction[0]);



    glUseProgram(0);

}
Beispiel #25
0
		void GLSpriteRenderer::Render() {
			SPADES_MARK_FUNCTION();
			lastImage = NULL;
			program->Use();
			
			projectionViewMatrix(program);
			rightVector(program);
			upVector(program);
			texture(program);
			viewMatrix(program);
			fogDistance(program);
			fogColor(program);
			
			positionAttribute(program);
			spritePosAttribute(program);
			colorAttribute(program);
			
			projectionViewMatrix.SetValue(renderer->GetProjectionViewMatrix());
			viewMatrix.SetValue(renderer->GetViewMatrix());
			
			fogDistance.SetValue(renderer->GetFogDistance());
			
			Vector3 fogCol = renderer->GetFogColor();
			fogColor.SetValue(fogCol.x,fogCol.y,fogCol.z);
			
			const client::SceneDefinition& def = renderer->GetSceneDef();
			rightVector.SetValue(def.viewAxis[0].x,
								 def.viewAxis[0].y,
								 def.viewAxis[0].z);
			upVector.SetValue(def.viewAxis[1].x,
							  def.viewAxis[1].y,
							  def.viewAxis[1].z);
			texture.SetValue(0);
			
			device->ActiveTexture(0);
			
			device->EnableVertexAttribArray(positionAttribute(), true);
			device->EnableVertexAttribArray(spritePosAttribute(), true);
			device->EnableVertexAttribArray(colorAttribute(), true);
			
			
			for(size_t i = 0; i < sprites.size(); i++){
				Sprite& spr = sprites[i];
				if(spr.image != lastImage){
					Flush();
					lastImage = spr.image;
					SPAssert(vertices.empty());
				}
				
				Vertex v;
				v.x = spr.center.x;
				v.y = spr.center.y;
				v.z = spr.center.z;
				v.radius = spr.radius;
				v.angle = spr.angle;
				v.r = spr.color.x;
				v.g = spr.color.y;
				v.b = spr.color.z;
				v.a = spr.color.w;
				
				uint32_t idx = (uint32_t)vertices.size();
				v.sx = -1; v.sy = -1;
				vertices.push_back(v);
				v.sx = 1; v.sy = -1;
				vertices.push_back(v);
				v.sx = -1; v.sy = 1;
				vertices.push_back(v);
				v.sx = 1; v.sy = 1;
				vertices.push_back(v);
				
				indices.push_back(idx);
				indices.push_back(idx + 1);
				indices.push_back(idx + 2);
				indices.push_back(idx + 1);
				indices.push_back(idx + 3);
				indices.push_back(idx + 2);
			}
		
			Flush();
			
			device->EnableVertexAttribArray(positionAttribute(), false);
			device->EnableVertexAttribArray(spritePosAttribute(), false);
			device->EnableVertexAttribArray(colorAttribute(), false);
		}
Beispiel #26
0
Ibl::Matrix44f
Camera::viewProjMatrix() const
{
    return viewMatrix() * projMatrix();
}
Beispiel #27
0
void
Camera::cacheCameraTransforms() const
{
    _cameraTransformCache->set(viewMatrix(), projMatrix(), viewProjMatrix(),  translation(), zNear(), zFar(), 1.0f);
}
/*
 Inits the shader program for this object
 */
void GLSphere::initShader(void)
{
    
    // Vertex shader source code. This draws the vertices in our window. We have 3 vertices since we're drawing an triangle.
    // Each vertex is represented by a vector of size 4 (x, y, z, w) coordinates.
    // static const string vertex_code = vs_string_CoordSystem;
    static const char * vs_source = vs_string_GLSphere_410.c_str();
    
    // Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader.
    // static const string fragment_code = fs_string_CoordSystem;
    static const char * fs_source = fs_string_GLSphere_410.c_str();
    
    // This next section we'll generate the OpenGL program and attach the shaders to it so that we can render our triangle.
    _program = glCreateProgram();
    
    // We create a shader with our fragment shader source code and compile it.
    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fs_source, NULL);
    glCompileShader(fs);
    CheckShader(fs, GL_FRAGMENT_SHADER);
    
    // We create a shader with our vertex shader source code and compile it.
    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vs_source, NULL);
    glCompileShader(vs);
    CheckShader(vs, GL_VERTEX_SHADER);
    
    // We'll attach our two compiled shaders to the OpenGL program.
    glAttachShader(_program, vs);
    glAttachShader(_program, fs);
    
    glLinkProgram(_program);
    
    glUseProgram(_program);
    
    
    _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model
    
    
    int projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader
    _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader
    _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader
    _inverseViewMatrixLocation = glGetUniformLocation(_program, "inverseViewMatrix");
    
    _light_source0._lightPosIdx = glGetUniformLocation(_program, "light_position");
    
    
    glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
    glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
    glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader
     glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Material
    _material._diffuse_material = glm::vec3(1.0, 0.5, 0.0);
    _material._ambient_material = glm::vec3(1.0, 0.5, 0.0);
    _material._specular_material = glm::vec3(1.0, 1.0, 1.0);
    _material._shininess = 12.0;
    
    
    _material._ambientColorPos = glGetUniformLocation(_program, "ambient_color");
    _material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color");
    _material._specularColorPos = glGetUniformLocation(_program, "specular_color");
    _material._shininessIdx = glGetUniformLocation(_program, "shininess");
    
    
    // Send the material to your shader program
    glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] );
    glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]);
    glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]);
    glUniform1f(_material._shininessIdx, _material._shininess);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Light
    
    // define the position of the light and send the light position to your shader program
    _light_source0._lightPos = glm::vec4(50.0,50.0,0.0,1.0);
    _light_source0._ambient_intensity = 0.5;
    _light_source0._specular_intensity = 1.0;
    _light_source0._diffuse_intensity = 1.0;
 
    

    _light_source0._ambientIdx = glGetUniformLocation(_program, "ambient_intensity");
    _light_source0._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity");
    _light_source0._specularIdx = glGetUniformLocation(_program, "specular_intensity");
   
    

    // Send the light information to your shader program
    glUniform1f(_light_source0._ambientIdx, _light_source0._ambient_intensity );
    glUniform1f(_light_source0._diffuseIdx, _light_source0._diffuse_intensity);
    glUniform1f(_light_source0._specularIdx, _light_source0._specular_intensity);
    
    glUniform4fv(_light_source0._lightPosIdx, 1, &_light_source0._lightPos[0]);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Vertex information / names
    // bind the to the shader program
    glBindAttribLocation(_program, 0, "in_Position");
    glBindAttribLocation(_program, 1, "in_Normal");
    glBindAttribLocation(_program, 2, "in_Color");
    
    
    
     glUseProgram(0);
    
}
		void GLSoftSpriteRenderer::Render() {
			SPADES_MARK_FUNCTION();
			lastImage = NULL;
			program->Use();

			device->Enable(IGLDevice::Blend, true);
			device->BlendFunc(IGLDevice::One, IGLDevice::OneMinusSrcAlpha);

			projectionViewMatrix(program);
			rightVector(program);
			frontVector(program);
			viewOriginVector(program);
			upVector(program);
			texture(program);
			depthTexture(program);
			viewMatrix(program);
			fogDistance(program);
			fogColor(program);
			zNearFar(program);

			positionAttribute(program);
			spritePosAttribute(program);
			colorAttribute(program);

			projectionViewMatrix.SetValue(renderer->GetProjectionViewMatrix());
			viewMatrix.SetValue(renderer->GetViewMatrix());

			fogDistance.SetValue(renderer->GetFogDistance());

			Vector3 fogCol = renderer->GetFogColor();
			fogCol *= fogCol; // linearize
			fogColor.SetValue(fogCol.x, fogCol.y, fogCol.z);

			const client::SceneDefinition &def = renderer->GetSceneDef();
			rightVector.SetValue(def.viewAxis[0].x, def.viewAxis[0].y, def.viewAxis[0].z);
			upVector.SetValue(def.viewAxis[1].x, def.viewAxis[1].y, def.viewAxis[1].z);
			frontVector.SetValue(def.viewAxis[2].x, def.viewAxis[2].y, def.viewAxis[2].z);

			viewOriginVector.SetValue(def.viewOrigin.x, def.viewOrigin.y, def.viewOrigin.z);
			texture.SetValue(0);
			depthTexture.SetValue(1);
			zNearFar.SetValue(def.zNear, def.zFar);

			device->ActiveTexture(1);
			device->BindTexture(IGLDevice::Texture2D,
			                    renderer->GetFramebufferManager()->GetDepthTexture());
			device->ActiveTexture(0);

			device->EnableVertexAttribArray(positionAttribute(), true);
			device->EnableVertexAttribArray(spritePosAttribute(), true);
			device->EnableVertexAttribArray(colorAttribute(), true);

			thresLow = tanf(def.fovX * .5f) * tanf(def.fovY * .5f) * 1.8f;
			thresRange = thresLow * .5f;

			// full-resolution sprites
			{
				GLProfiler::Context measure(renderer->GetGLProfiler(), "Full Resolution");
				for (size_t i = 0; i < sprites.size(); i++) {
					Sprite &spr = sprites[i];
					float layer = LayerForSprite(spr);
					if (layer == 1.f)
						continue;
					if (spr.image != lastImage) {
						Flush();
						lastImage = spr.image;
						SPAssert(vertices.empty());
					}

					Vertex v;
					v.x = spr.center.x;
					v.y = spr.center.y;
					v.z = spr.center.z;
					v.radius = spr.radius;
					v.angle = spr.angle;
					v.r = spr.color.x;
					v.g = spr.color.y;
					v.b = spr.color.z;
					v.a = spr.color.w;

					float fade = 1.f - layer;
					v.r *= fade;
					v.g *= fade;
					v.b *= fade;
					v.a *= fade;

					uint32_t idx = (uint32_t)vertices.size();
					v.sx = -1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = -1;
					v.sy = 1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = 1;
					vertices.push_back(v);

					indices.push_back(idx);
					indices.push_back(idx + 1);
					indices.push_back(idx + 2);
					indices.push_back(idx + 1);
					indices.push_back(idx + 3);
					indices.push_back(idx + 2);
				}

				Flush();
			}

			// low-res sprites
			IGLDevice::UInteger lastFb = device->GetInteger(IGLDevice::FramebufferBinding);
			int sW = device->ScreenWidth(), sH = device->ScreenHeight();
			int lW = (sW + 3) / 4, lH = (sH + 3) / 4;
			int numLowResSprites = 0;
			GLColorBuffer buf = renderer->GetFramebufferManager()->CreateBufferHandle(lW, lH, true);
			device->BindFramebuffer(IGLDevice::Framebuffer, buf.GetFramebuffer());
			device->ClearColor(0.f, 0.f, 0.f, 0.f);
			device->Clear(IGLDevice::ColorBufferBit);
			device->BlendFunc(IGLDevice::One, IGLDevice::OneMinusSrcAlpha);
			device->Viewport(0, 0, lW, lH);
			{
				GLProfiler::Context measure(renderer->GetGLProfiler(), "Low Resolution");
				for (size_t i = 0; i < sprites.size(); i++) {
					Sprite &spr = sprites[i];
					float layer = LayerForSprite(spr);
					if (layer == 0.f)
						continue;
					if (spr.image != lastImage) {
						Flush();
						lastImage = spr.image;
						SPAssert(vertices.empty());
					}

					numLowResSprites++;

					Vertex v;
					v.x = spr.center.x;
					v.y = spr.center.y;
					v.z = spr.center.z;
					v.radius = spr.radius;
					v.angle = spr.angle;
					v.r = spr.color.x;
					v.g = spr.color.y;
					v.b = spr.color.z;
					v.a = spr.color.w;

					float fade = layer;
					v.r *= fade;
					v.g *= fade;
					v.b *= fade;
					v.a *= fade;

					uint32_t idx = (uint32_t)vertices.size();
					v.sx = -1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = -1;
					v.sy = 1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = 1;
					vertices.push_back(v);

					indices.push_back(idx);
					indices.push_back(idx + 1);
					indices.push_back(idx + 2);
					indices.push_back(idx + 1);
					indices.push_back(idx + 3);
					indices.push_back(idx + 2);
				}
				Flush();
			}

			// finalize

			device->ActiveTexture(1);
			device->BindTexture(IGLDevice::Texture2D, 0);
			device->ActiveTexture(0);
			device->BindTexture(IGLDevice::Texture2D, 0);
			device->EnableVertexAttribArray(positionAttribute(), false);
			device->EnableVertexAttribArray(spritePosAttribute(), false);
			device->EnableVertexAttribArray(colorAttribute(), false);

			// composite downsampled sprite
			device->BlendFunc(IGLDevice::One, IGLDevice::OneMinusSrcAlpha);
			if (numLowResSprites > 0) {
				GLProfiler::Context measure(renderer->GetGLProfiler(), "Finalize");
				GLQuadRenderer qr(device);

				// do gaussian blur
				GLProgram *program =
				  renderer->RegisterProgram("Shaders/PostFilters/Gauss1D.program");
				static GLProgramAttribute blur_positionAttribute("positionAttribute");
				static GLProgramUniform blur_textureUniform("mainTexture");
				static GLProgramUniform blur_unitShift("unitShift");
				program->Use();
				blur_positionAttribute(program);
				blur_textureUniform(program);
				blur_unitShift(program);
				blur_textureUniform.SetValue(0);
				device->ActiveTexture(0);
				qr.SetCoordAttributeIndex(blur_positionAttribute());
				device->Enable(IGLDevice::Blend, false);

				// x-direction
				GLColorBuffer buf2 =
				  renderer->GetFramebufferManager()->CreateBufferHandle(lW, lH, true);
				device->BindTexture(IGLDevice::Texture2D, buf.GetTexture());
				device->BindFramebuffer(IGLDevice::Framebuffer, buf2.GetFramebuffer());
				blur_unitShift.SetValue(1.f / lW, 0.f);
				qr.Draw();
				buf.Release();

				// x-direction
				GLColorBuffer buf3 =
				  renderer->GetFramebufferManager()->CreateBufferHandle(lW, lH, true);
				device->BindTexture(IGLDevice::Texture2D, buf2.GetTexture());
				device->BindFramebuffer(IGLDevice::Framebuffer, buf3.GetFramebuffer());
				blur_unitShift.SetValue(0.f, 1.f / lH);
				qr.Draw();
				buf2.Release();

				buf = buf3;

				device->Enable(IGLDevice::Blend, true);

				// composite
				program = renderer->RegisterProgram("Shaders/PostFilters/PassThrough.program");
				static GLProgramAttribute positionAttribute("positionAttribute");
				static GLProgramUniform colorUniform("colorUniform");
				static GLProgramUniform textureUniform("mainTexture");
				static GLProgramUniform texCoordRange("texCoordRange");

				positionAttribute(program);
				textureUniform(program);
				texCoordRange(program);
				colorUniform(program);

				program->Use();

				textureUniform.SetValue(0);
				texCoordRange.SetValue(0.f, 0.f, 1.f, 1.f);
				colorUniform.SetValue(1.f, 1.f, 1.f, 1.f);

				qr.SetCoordAttributeIndex(positionAttribute());
				device->BindFramebuffer(IGLDevice::Framebuffer, lastFb);
				device->BindTexture(IGLDevice::Texture2D, buf.GetTexture());
				device->Viewport(0, 0, sW, sH);
				qr.Draw();
				device->BindTexture(IGLDevice::Texture2D, 0);

			} else {
				device->Viewport(0, 0, sW, sH);

				device->BindFramebuffer(IGLDevice::Framebuffer, lastFb);
			}

			buf.Release();
		}
void Camera::lookAt (const tf::Transform &tnf)
{
	tfScalar mrt[16];
	tnf.getOpenGLMatrix (mrt);
	// Column-major
	viewMatrix(0, 0) = mrt[0];
	viewMatrix(1, 0) = mrt[1];
	viewMatrix(2, 0) = mrt[2];
	viewMatrix(3, 0) = mrt[3];
	viewMatrix(0, 1) = mrt[4];
	viewMatrix(1, 1) = mrt[5];
	viewMatrix(2, 1) = mrt[6];
	viewMatrix(3, 1) = mrt[7];
	viewMatrix(0, 2) = mrt[8];
	viewMatrix(1, 2) = mrt[9];
	viewMatrix(2, 2) = mrt[10];
	viewMatrix(3, 2) = mrt[11];
	viewMatrix(0, 3) = mrt[12];
	viewMatrix(1, 3) = mrt[13];
	viewMatrix(2, 3) = mrt[14];
	viewMatrix(3, 3) = mrt[15];

	// Rotate 180 around Z-axis and Y-axis
	Eigen::Matrix4f rotfix = Eigen::Matrix4f::Identity();
	rotfix (1,1) = -1;
	rotfix (2,2) = -1;
	rotfix (3,3) = 1;
	viewMatrix = rotfix * viewMatrix;
}