Example #1
0
osg::Vec4f Raytracer::renderPixel(int x, int y, const osg::Vec3f& eye, const osg::Vec3f& dir)
{
    osg::Vec3f lightPos(-338.572, 0, 400);
    RTCRay ray;
    ray.primID = RTC_INVALID_GEOMETRY_ID;
    ray.geomID = RTC_INVALID_GEOMETRY_ID;
    ray.instID = RTC_INVALID_GEOMETRY_ID;
    ray.tnear = 0.0f;
    ray.tfar = 100000.0f;
    ray.org[0] = eye.x();
    ray.org[1] = eye.y();
    ray.org[2] = eye.z();
    ray.dir[0]=  dir.x();
    ray.dir[1] = dir.y();
    ray.dir[2] = dir.z();
    rtcIntersect(_scene, ray);
    if(ray.primID != -1)
    {
        osg::Vec3f pos = eye + dir*ray.tfar;
        osg::Vec4f diffuse = getSurfaceColor(ray.geomID, ray.primID,ray.u,ray.v);
        osg::Vec3 normal = getNormal(ray.geomID,ray.primID,ray.u,ray.v);
        osg::Vec3f lightDir = lightPos - pos;
        lightDir.normalize();

        float NdotL = std::max(normal * lightDir,0.0f);
        return diffuse * NdotL;

    }
    return _backgroundColor;
}
void DeferredShader::drawLighting(Scene & scene, Camera & camera)
{
	glEnable(GL_BLEND);
	for (unsigned int i = 0; i < scene.getLightVector().size(); ++i)
	{
		for(unsigned int j = 0; j < 5; ++j)
		{

		}

		glm::vec4 lightPos(scene.getLightVector()[i]->getPosition(),1.0);
		glm::vec4 viewPos(camera.getEyePoint(),1.0);

		lightPos = (lightPos * camera.getModelViewMatrix()) * camera.getProjectionMatrix();
		viewPos = (viewPos * camera.getModelViewMatrix()) * camera.getProjectionMatrix();

		shaderManager.setCgParam(lightPos,"lightPos",FRAGMENT);
		shaderManager.setCgParam(viewPos,"viewPos",FRAGMENT);
		shaderManager.setCgParam(scene.getLightVector()[i]->getColor(),"lightColor",FRAGMENT);
		shaderManager.setCgParam(scene.getLightVector()[i]->getRadius(),"radius",FRAGMENT);

		drawRec(camera);
	}
	glDisable(GL_BLEND);
}
Example #3
0
	void Render(double time)
	{
		gl.Clear().ColorBuffer().DepthBuffer();
		//
		auto camera = CamMatrixf::Orbiting(
			Vec3f(),
			4.5,
			Degrees(time * 35),
			Degrees(SineWave(time / 30.0) * 60)
		);

		auto model =
			ModelMatrixf::RotationY(FullCircles(time * 0.25)) *
			ModelMatrixf::RotationX(FullCircles(0.25));

		Vec4f lightPos(4.0f, 4.0f, -8.0f, 1.0f);

		prog.Use();
		camera_matrix.Set(camera);
		model_matrix.Set(model);
		light_pos_cam.Set(camera * lightPos);

		front_color.Set(Vec3f(0.3f, 0.2f, 0.0f));
		back_color.Set(Vec3f(0.2f, 0.1f, 0.0f));
		gl.PolygonMode(PolygonMode::Line);
		torus_instr.Draw(torus_indices);

		front_color.Set(Vec3f(0.9f, 0.8f, 0.1f));
		back_color.Set(Vec3f(1.0f, 0.9f, 0.8f));
		gl.PolygonMode(PolygonMode::Fill);
		torus_instr.Draw(torus_indices);
	}
Example #4
0
void Window::initialize(void)
{
    //Setup the light
    Vector4 lightPos(0.0, 10.0, 15.0, 1.0);
    Globals::light.position = lightPos;
    Globals::light.quadraticAttenuation = 0.02;
    
}
//聚光灯(边缘软化)
void LightCasterStudy::render()
{
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	double currentTime = glfwGetTime();

	spotLightShader->UseProgram();

	vec3 lightPos(3.0f, 0.0f, 0.0f);
	vec3 viewPosition(0.0f, 0.0f, 5.0f);
	vec3 lightDirection(0.0f, 0.0f, -1.0f);
	auto tempValue = dot(normalize(viewPosition - vec3(1.0f, 0.0f, 0.0f)), normalize(-lightDirection));
	//glm::cos 中的参数为弧度,非角度(有点坑),需要用radians进行角度转换。
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, this->cubeDiffuseTexture);
	glUniform1i(glGetUniformLocation(spotLightShader->getProgram(), "material.diffuse"), 0);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, this->cubeSpecularTexture);
	glUniform1i(glGetUniformLocation(spotLightShader->getProgram(), "material.specular"), 1);
	glUniform1f(glGetUniformLocation(spotLightShader->getProgram(), "material.shininess"), 0.6f * 128.0f);
	glUniform3fv(glGetUniformLocation(spotLightShader->getProgram(), "light.direction"), 1, value_ptr(lightDirection));
	glUniform1f(glGetUniformLocation(spotLightShader->getProgram(), "light.cutOff"), glm::cos(glm::radians(12.5f)));
	glUniform3f(glGetUniformLocation(spotLightShader->getProgram(), "light.ambient"), 0.1f, 0.1f, 0.1f);
	glUniform3f(glGetUniformLocation(spotLightShader->getProgram(), "light.specular"), 1.0f, 1.0f, 1.0f);
	glUniform3f(glGetUniformLocation(spotLightShader->getProgram(), "light.diffuse"), 1.0f, 1.0f, 1.0f);
	glUniform3fv(glGetUniformLocation(spotLightShader->getProgram(), "light.position"), 1, value_ptr(viewPosition));
	glUniform1f(glGetUniformLocation(spotLightShader->getProgram(), "light.outerCutOff"), glm::cos(glm::radians(17.0f)));
	glUniform1f(glGetUniformLocation(spotLightShader->getProgram(), "light.constant"), 1.0f);
	glUniform1f(glGetUniformLocation(spotLightShader->getProgram(), "light.linear"), 0.09f);
	glUniform1f(glGetUniformLocation(spotLightShader->getProgram(), "light.quadratic"), 0.032f);
	glUniform3f(glGetUniformLocation(spotLightShader->getProgram(), "lightcolor"), 1.0f, 1.0f, 1.0f);
	glUniform3fv(glGetUniformLocation(spotLightShader->getProgram(), "viewPos"), 1, value_ptr(viewPosition));

	mat4 model(1.0);
	mat4 view(1.0);
	mat4 projection(1.0);
	RenderDelegate::getInstance()->printProgramInfoLog(spotLightShader->getProgram());
	view = lookAt(viewPosition, vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
	projection = perspective(radians(45.0f), 800.0f / 600.0f, 0.1f, 1000.0f);

	glUniformMatrix4fv(glGetUniformLocation(cubeShader->getProgram(), "view"), 1, GL_FALSE, value_ptr(view));
	glUniformMatrix4fv(glGetUniformLocation(cubeShader->getProgram(), "projection"), 1, GL_FALSE, value_ptr(projection));

	glBindVertexArray(this->cubeVAO);

	for(GLuint i = 0; i < 10; i++)
	{
		model = glm::translate(mat4(1.0f), cubePositions[i]);
		GLfloat angle = (i + 1) * currentTime * 5.0f;
		model = glm::rotate(model, radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
		glUniformMatrix4fv(glGetUniformLocation(cubeShader->getProgram(), "model"), 1, GL_FALSE, glm::value_ptr(model));
		glDrawArrays(GL_TRIANGLES, 0, 36);
	}
	glBindVertexArray(0);
	
}
void light::drawDim(vector3f distant)
{

    glPushMatrix();

    vector3f lightPos(location.matrix[12],location.matrix[13],location.matrix[14]);
    GLfloat pos[] = {location.matrix[12],location.matrix[13],location.matrix[14],1.0f};

    float distanceSquared = (lightPos-distant).LengthSquared();


    float attenuate; // = 1.0f;

    if (maxFade != 0) {
        if (distanceSquared < minFade)
            attenuate = scale;
        else if ((distanceSquared < maxFade) && (distanceSquared > minFade))
            attenuate = scale * (maxFade - distanceSquared) / (maxFade - minFade);
        else attenuate = 0.0f;
    } else attenuate = 1.0f;

    //cout << attenuate << "\n";

    GLfloat Kaf[] = {Ka[0] * attenuate, Ka[1] * attenuate, Ka[2] * attenuate, Ka[3],1.0f};
    GLfloat Kdf[] = {Kd[0] * attenuate, Kd[1] * attenuate, Kd[2] * attenuate, Kd[3],1.0f};
    GLfloat Ksf[] = {Ks[0] * attenuate, Ks[1] * attenuate, Ks[2] * attenuate, Ks[3],1.0f};

    if ((GL_LIGHTX >= GL_LIGHT0) && (GL_LIGHTX <= GL_LIGHT7))
    {
        glEnable(GL_LIGHTX);

        glLightfv(GL_LIGHTX, GL_POSITION, pos);
        glLightfv(GL_LIGHTX, GL_AMBIENT, Kaf);
        glLightfv(GL_LIGHTX, GL_DIFFUSE, Kdf);
        glLightfv(GL_LIGHTX, GL_SPECULAR,Ksf);
    }


    //glLoadIdentity();
//	lightobj->location=(location);



//	glEnable(GL_BLEND);
    //glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    //lightobj->draw();
    //glDisable(GL_BLEND);

    //glEnable(GL_LIGHTING);

    //lightobj->draw();

    glPopMatrix();
}
// This multiplies onto the current matrix stack an inverse look-at matrix
//    (equivalent to Invert( gluLookAt() ) -- if such an operation were possible)
void Scene::LightLookAtInverseMatrix( int i )
{
	Point lightPos( light[i]->GetCurrentPos() );
	Vector view = camera->GetAt()-lightPos;
	view.Normalize();
	Vector perp = abs( view.Dot( Vector::YAxis() ) ) < 0.95 ? view.Cross( Vector::YAxis() ) : view.Cross( Vector::XAxis() );
	perp.Normalize();
	Vector up = perp.Cross( view );
	Matrix4x4 mat = Matrix4x4::LookAt( lightPos, camera->GetAt(), up ).Invert();
	glMultMatrixf( mat.GetDataPtr() );
}
Example #8
0
Matrix4x4 Scene::GetLightLookAtMatrix( int i )
{
	Point lightPos( light[i]->GetCurrentPos() );
	Point at( camera->GetAt() );
	Vector view = at-lightPos;
	view.Normalize();
	Vector perp = abs( view.Dot( Vector::YAxis() ) ) < 0.95 ? view.Cross( Vector::YAxis() ) : view.Cross( Vector::XAxis() );
	perp.Normalize();
	Vector up = perp.Cross( view );
	return Matrix4x4::LookAt( lightPos, at, up );
	//return Matrix4x4::Identity();
}
// This multiplies onto the current matrix stack a look-at matrix (using
//   gluLookAt()) for light #i.
void Scene::LightLookAtMatrix( int i )
{
	Point lightPos( light[i]->GetCurrentPos() );
	Point at( camera->GetAt() );
	Vector view = at-lightPos;
	view.Normalize();
	Vector perp = abs( view.Dot( Vector::YAxis() ) ) < 0.95 ? view.Cross( Vector::YAxis() ) : view.Cross( Vector::XAxis() );
	perp.Normalize();
	Vector up = perp.Cross( view );
	gluLookAt( lightPos.X(), lightPos.Y(), lightPos.Z(), 
		       at.X(), at.Y(), at.Z(), 
			   up.X(), up.Y(), up.Z() );
}
Example #10
0
void Window::initialize(void)
{
    //Setup the light
    Vector4 lightPos(0.0, 10.0, 15.0, 1.0);
    Globals::light.position = lightPos;
    Globals::light.quadraticAttenuation = 0.02;
    
    //Initialize cube matrix:
    Globals::cube.toWorld.identity();
    
    //Setup the cube's material properties
    Color color(0x23ff27ff);
    Globals::cube.material.color = color;
}
    CascadedShadowMapper::CascadedShadowMapper(UCHAR cascades) 
        : m_cascades(cascades), m_ppTargets(NULL), /*m_camera(1024, 1024, 0.01, 1000),*/ m_pCascadesSettings(NULL), m_ppBlurChain(NULL)
    {

        /*
#ifdef CSM_DEBUG
        for(USHORT i = 0; i < m_cascades; ++i)
        {
            m_cascadeCameraActor[i] = chimera::g_pApp->GetLogic()->VCreateActor("staticcamera.xml");
            std::stringstream ss;
            ss << "cascadeCam";
            ss << i;
            m_cascadeCameraActor[i]->SetName(ss.str());
        }
#endif
        */
        m_intensity = util::Vec3(1,1,1);

        m_ambient = util::Vec3(0.1f, 0.1f, 0.1f);

        std::unique_ptr<ActorDescription> desc = CmGetApp()->VGetLogic()->VGetActorFactory()->VCreateActorDescription();
        CameraComponent* cc = desc->AddComponent<CameraComponent>(CM_CMP_CAMERA);
        cc->SetCamera(std::shared_ptr<ICamera>(new util::FPSCamera(1,1,1e-2f,1e3)));
        TransformComponent* tc = desc->AddComponent<TransformComponent>(CM_CMP_TRANSFORM);

        m_lightActorCamera = CmGetApp()->VGetLogic()->VCreateActor(std::move(desc));

        //util::Vec3 lightPos(1.0f,1.3f,0.6f);
        util::Vec3 lightPos(1.0f, 0.2, 0);
        lightPos.Normalize();
        lightPos.Scale(util::Vec3(1000.0f, 1000.0f, 1000.0f));
        tc->GetTransformation()->SetTranslation(lightPos.x, lightPos.y, lightPos.z);
        cc->GetCamera()->MoveToPosition(tc->GetTransformation()->GetTranslation());
        m_lightActorCamera->SetName("cascadeLightCamera");

        /*
        m_viewActor = chimera::g_pApp->GetLogic()->VCreateActor("rendercamera.xml");
        m_viewActor->SetName("cascadeViewCamera");
        m_viewActor->GetComponent<chimera::TransformComponent>(chimera::TransformComponent::COMPONENT_ID).lock()->GetTransformation()->SetTranslate(0,5,-5);
        m_viewActor->GetComponent<chimera::CameraComponent>(chimera::CameraComponent::COMPONENT_ID).lock()->GetCamera()->MoveToPosition(
            m_viewActor->GetComponent<chimera::TransformComponent>(chimera::TransformComponent::COMPONENT_ID).lock()->GetTransformation()->GetTranslation());

        */
        ADD_EVENT_LISTENER(this, &CascadedShadowMapper::SetSunPositionDelegate, CM_EVENT_SET_SUN_POSITION);
        ADD_EVENT_LISTENER(this, &CascadedShadowMapper::SetSunIntensityDelegate, CM_EVENT_SET_SUN_INTENSITY);
        ADD_EVENT_LISTENER(this, &CascadedShadowMapper::SetSunAmbientDelegate, CM_EVENT_SET_SUN_AMBIENT);
    }
Example #12
0
void Window::initialize(void)
{
	//Initialize skybox textures
	Globals::skybox = *new Skybox();
	Globals::skybox.top = new Texture("skybox_top.ppm");
	Globals::skybox.base = new Texture("skybox_base.ppm");
	Globals::skybox.front = new Texture("skybox_front.ppm");
	Globals::skybox.back = new Texture("skybox_back.ppm");
	Globals::skybox.right = new Texture("skybox_right.ppm");
	Globals::skybox.left = new Texture("skybox_left.ppm");

	Globals::bezier.flag = new Texture("Ucsd-logo.ppm");
	Globals::bezier2.flag = new Texture("Ucsd-logo.ppm");

    //Setup the light
    Vector4 lightPos(0.0, 10.0, 15.0, 1.0);
    Globals::light.position = lightPos;
    Globals::light.quadraticAttenuation = 0.0002;

	//Globals::camera.set(Vector3(0, 0, 1), Vector3(0, 0, 0), Vector3(0, 1, 0));
	
	//Patch 1
	Vector3 a = Vector3(-.5, -.25, .3);		Vector3 b = Vector3(-.5, 0, .1);	Vector3 c = Vector3(-.5, .25, .3);	Vector3 d = Vector3(-.5, .5, .2);
	Vector3 e = Vector3(-.25, -.25, .4);	Vector3 f = Vector3(-.25, 0, .2);	Vector3 g = Vector3(-.25, .25, .2);	Vector3 h = Vector3(-.25, .5, .4);
	Vector3 i = Vector3(0, -.25, .5);		Vector3 j = Vector3(0, 0, .4);		Vector3 k = Vector3(0, .25, .1);	Vector3 l = Vector3(0, .5, .4);
	Vector3 m = Vector3(.25, -.25, .2);		Vector3 n = Vector3(.25, 0, .2);	Vector3 o = Vector3(.25, .25, .5);	Vector3 p = Vector3(.25, .5, .4);
	
	//Patch 2
	Vector3 q = Vector3(.5, -.25, 2 * m[2] - i[2]);		Vector3 r = Vector3(.5, 0, 2*n[2] - j[2]);		Vector3 s = Vector3(.5, .25, 2*o[2] - k[2]);	Vector3 t = Vector3(.5, .5, 2*p[2] - l[2]);
	Vector3 u = Vector3(.75, -.25, .3);		Vector3 v = Vector3(.75, 0, .1);	Vector3 w = Vector3(.75, .25, .7);	Vector3 x = Vector3(.75, .5, .2);
	Vector3 y = Vector3(1, -.25, .8);		Vector3 z = Vector3(1, 0, .9);		Vector3 aa = Vector3(1, .25, .3);	Vector3 bb = Vector3(1, .5, .4);
	
	Globals::bezier.setCurve(0, a, b, c, d);
	Globals::bezier.setCurve(1, e, f, g, h);
	Globals::bezier.setCurve(2, i, j, k, l);
	Globals::bezier.setCurve(3, m, n, o, p);

	Globals::bezier2.setCurve(0, m, n, o, p);
	Globals::bezier2.setCurve(1, q, r, s, t);
	Globals::bezier2.setCurve(2, u, v, w, x);
	Globals::bezier2.setCurve(3, y, z, aa, bb);
	
	
	shader = new Shader("shader.vert", "shader.frag", true);
}
Example #13
0
void Graphics::Init()
{
	m_object->SetPosition(0,-50,0);
	m_objLoader->LoadOBJ(m_Device, m_DeviceContext, "DATA/Ninja.tt");
	m_object->Initialize(m_Device, m_DeviceContext, m_objLoader->GetVertices(), "Textures/Ninja_COLOR.png");

	m_objectT->SetPosition(0,-50,0);
	m_objLoader->LoadOBJ(m_Device, m_DeviceContext, "DATA/plane.tt");
	m_objectT->Initialize(m_Device, m_DeviceContext, m_objLoader->GetVertices(), "Textures/plane_COLOR.png");

	m_shadowMap = new ShadowMap(m_Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE);

	D3DXVECTOR3 lightPos(50,100,-200);
	D3DXVECTOR3 dir = D3DXVECTOR3(0,-50,0) - lightPos;

	m_Light->Initialize(1,0);
	m_Light->addDirectionalLight(lightPos, dir, 1, D3DXVECTOR3(255,255,255), 1, 1000);
}
Example #14
0
void gxLight::renderPass(gxRenderer* renderer, gxHWShader* shader)
{
#if defined (USE_ProgrammablePipeLine)
	shader->sendUniform4fv("light.diffuse", &m_cDiffuse.x);
	shader->sendUniform4fv("light.ambient", &m_cAmbient.x);
	shader->sendUniform4fv("light.specular", &m_cSpecular.x);
	shader->sendUniform1f("light.constant_attenuation", m_fConstantAttenuation);
	shader->sendUniform1f("light.linear_attenuation", m_fLinearAttenuation);
	shader->sendUniform1f("light.quadratic_attenuation", m_fQuadraticAttenuation);

	vector3f eye(renderer->getMainCameraEye());
	shader->sendUniform3fv("_WorldSpaceCameraPos", &eye.x);
	//vector3f lightPos(*renderer->getViewMatrix() * getWorldMatrix()->getPosition());
	vector3f lightPos(getWorldMatrix()->getPosition());

	shader->sendUniform4f("light.position", lightPos.x, lightPos.y, lightPos.z, (m_eType==LIGHT_POINT)?1.0f:0.0f);
#endif
}
void VR_Canvas::privRenderState(Camera * OrthoCamera)
{
	///////////////SetRenderState////////////////
	glViewport(0,0,1280,800);
	
	this->ModelView = this->LocalToWorld * OrthoCamera->getViewMatrix();
	Matrix mvp = this->ModelView * OrthoCamera->getProjMatrix();

	glEnable(GL_BLEND);
	glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
		
	Vect lightColor( 2.5f, 2.5f, 2.5f, 1.0f);
	Vect lightPos(0.0f, 0.0f, 5.0f);

	shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF, &ModelView, &OrthoCamera->getProjMatrix(), &lightPos, &lightColor, 0);
	/////////////////////////////////////////////

}
Example #16
0
	virtual bool onInit() {
        glm::vec3 lightPos(5.0f, 5.0f, 5.0f);
        glm::vec3 lightDist(0.0f, 0.0f, 0.0f);
        
		m_shadowMapPass = new ShadowMapPass(2048);
		m_shadowMapPass->setLight(lightPos, lightDist);

		// m_testMat = Material::CreateMaterial(Program::CreateFromFile("../assets/quad.vert", "../assets/depth_dump.frag"));
		// m_testMesh = Mesh::CreateQuadXY();

		// assert( m_testMat->setTexture("depthTex", m_shadowMapPass->getTexture()) == true );

		m_cam = new Camera();
		m_cam->setPosition(0, 3, 3);
		m_cam->setLookAt(0, 0, 0, 0, 1, 0);
		m_cam->setPerspective(45.0f, 4.0f / 3.0f, 0.1f, 10.0f);
		m_mat = Material::CreateMaterial(Program::CreateFromFile("../assets/shadow_map/pass2.vert", "../assets/shadow_map/pass2.frag"));
		assert( m_mat->setUniform("matProj", m_cam->getMatProjection()) == true );
		assert( m_mat->setUniform("matView", m_cam->getMatView()) == true );
        assert( m_mat->setUniform("lightViewProj", m_shadowMapPass->getViewProjMatrix()) == true );
        assert( m_mat->setUniform("lightPos", glm::vec4(lightPos, 1.0f)) == true );
        assert( m_mat->setUniform("lightDir", glm::vec4(glm::normalize(lightPos - lightDist), 0.0f)) == true );
        assert( m_mat->setUniform("lightColor", glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)) == true );
        assert( m_mat->setUniform("color", glm::vec4(0.7f, 0.7f, 0.7f, 1.0f)) == true);
		// assert( m_mat->setUniform("invViewProj", glm::inverse(m_cam->getMatProjection() * m_cam->getMatView())) == true);
		assert( m_mat->setTexture("depthTex", m_shadowMapPass->getTexture()) == true );

		m_box = Mesh::CreateFromFile("../assets/box.obj");
        m_box2 = Mesh::CreateFromFile("../assets/box.obj");
		m_boxMat = glm::mat4(1.0f);
        m_boxMat2 = glm::scale(glm::translate(glm::mat4(1.0f), glm::vec3(1.0f, 1.0f, 1.0f)), glm::vec3(0.5f, 0.5f, 0.5f));
		m_ground = Mesh::CreateQuadXY(10, true);
		m_groundMat = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, -0.5f, 0.0f));
		m_groundMat = glm::rotate(m_groundMat, (float)M_PI * 0.5f, glm::vec3(-1.0f, 0.0f, 0.0f));

		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);

		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LEQUAL);
		return true;
	}
Example #17
0
void Light::SetupLight(int lightIndex){
    glEnable(GL_LIGHT0+lightIndex);
    // Setup and enable light 0
    glLightfv(GL_LIGHT0+lightIndex,GL_AMBIENT, glm::value_ptr(GetAmbient()));
    glLightfv(GL_LIGHT0+lightIndex,GL_DIFFUSE, glm::value_ptr(GetDiffuse()));
    glLightfv(GL_LIGHT0+lightIndex,GL_SPECULAR, glm::value_ptr(GetSpecular()));
	glLighti(GL_LIGHT0+lightIndex, GL_SPOT_CUTOFF, spotCutoff); 
	glLightfv(GL_LIGHT0+lightIndex,GL_SPOT_DIRECTION, glm::value_ptr(spotDirection));
    float w = 0;
    if (GetLightType()==PointLight){
        w = 1;
    } else if (GetLightType()==DirectionalLight){
        w = 0;
    }
    SceneObject *sceneObject = GetOwner();
    assert(sceneObject != NULL);
    glm::vec4 lightPos(sceneObject->GetTransform()->GetPosition(), w);

    glLightfv(GL_LIGHT0+lightIndex,GL_POSITION, glm::value_ptr(lightPos));
}
Example #18
0
int scene::loadLight(string lightid){
    int id = atoi(lightid.c_str());
    if(id!=lights.size()){
        cout << "ERROR: LIGHT ID does not match expected number of lights" << endl;
        return -1;
    }else{
        cout << "Loading Light " << id << "..." << endl;
        light newLight;
        string line;
        
        //load light type 
        utilityCore::safeGetline(fp_in,line);
        if (!line.empty() && fp_in.good()){
            if(strcmp(line.c_str(), "point")==0){
                cout << "Creating new point light..." << endl;
				newLight.type = POINT;
            }
        }
       
		//load static properties
		for(int i=0; i<3; i++){
			string line;
            utilityCore::safeGetline(fp_in,line);
			vector<string> tokens = utilityCore::tokenizeString(line);
			if(strcmp(tokens[0].c_str(), "INTENSITY")==0){
				newLight.intensity = atof(tokens[1].c_str());				  
			}else if(strcmp(tokens[0].c_str(), "COLOR")==0){
				glm::vec3 lightColor( atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str()) );
				newLight.color = lightColor;
			}else if(strcmp(tokens[0].c_str(), "POS")==0){
				glm::vec3 lightPos( atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str()) );
				newLight.position = lightPos;
			}
			
		}

        lights.push_back(newLight);
        return 1;
    }
}
	void Render(double time)
	{
		gl.Clear().ColorBuffer().DepthBuffer();
		//
		Vec3f lightPos(-1.0f, 2.0f, 2.0f);
		lightPos *= (1.0f - SineWave(time/5.0f)*0.4f);
		light_pos.Set(lightPos);

		tex_projection_matrix.Set(
			CamMatrixf::PerspectiveX(Degrees(15), 1.0, 1, 20) *
			CamMatrixf::LookingAt(lightPos, Vec3f())
		);

		// set the model matrix
		model_matrix.Set(
			ModelMatrixf::RotationY(FullCircles(time * 0.1))
		);

		cube.Bind();
		gl.CullFace(Face::Front);
		cube_instr.Draw(cube_indices);
	}
Example #20
0
void drawPly(){
	CPLYLoader ply;
	//读取Ply数据
	ply.LoadModel("lizhenxiout-repaired.ply");

	mygl.ClearColor(255,255,255);
	mygl.PenColor(255,0,0);

	mygl.ViewPort(0,0,640,480);
	mygl.MatrixMode(MY_PROJECTION);
	mygl.LoadIdentity();
	mygl.Ortho(-1000,1000,-1000,1000,-1000,1000);

	mygl.MatrixMode(MY_MODELVIEW);
	mygl.LoadIdentity();
	//mygl.RotateY(70);
	//mygl.Translate(500,0,500);
	//mygl.Scale(0.5,0.5,0.5);
	
	//设置材质
	Point::ka = 0.15;
	Point::ks = 0.8;
	Point::kd = 0.15;
	//设置光照
	Vector eye(1,1,0);
	Vector lightPos(1,1,1);
	//color(blue,green,red);
	Color lightColor = {0,255,0};
	//mygl.setLight(eye,lightPos,lightColor,10,10,1);
	
	for(int i=0; i<ply.m_totalConnectedPoints*3; i+=3){
		Point p(ply.mp_vertexXYZ[i],ply.mp_vertexXYZ[i+1],ply.mp_vertexXYZ[i+2]);
		mygl.DrawPexil(p);
	}
	mygl.bmp.SaveBmp("plyBmp.bmp");
}
Example #21
0
	HaloExample(void)
	 : make_shape()
	 , shape_indices(make_shape.Indices())
	 , shape_instr(make_shape.Instructions())
	 , vs_shape(ObjectDesc("Shape VS"))
	 , vs_plane(ObjectDesc("Plane VS"))
	 , fs_shape(ObjectDesc("Shape FS"))
	 , fs_plane(ObjectDesc("Plane FS"))
	 , vs_halo(ObjectDesc("Halo VS"))
	 , gs_halo(ObjectDesc("Halo GS"))
	 , fs_halo(ObjectDesc("Halo FS"))
	 , shape_projection_matrix(shape_prog, "ProjectionMatrix")
	 , shape_camera_matrix(shape_prog, "CameraMatrix")
	 , shape_model_matrix(shape_prog, "ModelMatrix")
	 , plane_projection_matrix(plane_prog, "ProjectionMatrix")
	 , plane_camera_matrix(plane_prog, "CameraMatrix")
	 , halo_projection_matrix(halo_prog, "ProjectionMatrix")
	 , halo_camera_matrix(halo_prog, "CameraMatrix")
	 , halo_model_matrix(halo_prog, "ModelMatrix")
	{
		vs_shape.Source(
			"#version 140\n"
			"in vec4 Position;"
			"in vec3 Normal;"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"uniform vec3 LightPos;"
			"out vec3 vertNormal;"
			"out vec3 vertViewNormal;"
			"out vec3 vertLight;"
			"void main(void)"
			"{"
			"	gl_Position = ModelMatrix * Position;"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertViewNormal = mat3(CameraMatrix)*vertNormal;"
			"	vertLight = LightPos - gl_Position.xyz;"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		vs_shape.Compile();

		fs_shape.Source(
			"#version 140\n"
			"in vec3 vertNormal;"
			"in vec3 vertViewNormal;"
			"in vec3 vertLight;"
			"uniform mat4 CameraMatrix;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float ltlen = sqrt(length(vertLight));"
			"	float ltexp = dot("
			"		normalize(vertNormal),"
			"		normalize(vertLight)"
			"	);"
			"	float lview = dot("
			"		normalize(vertLight),"
			"		normalize(vec3("
			"			CameraMatrix[0][2],"
			"			CameraMatrix[1][2],"
			"			CameraMatrix[2][2] "
			"		))"
			"	);"
			"	float depth = normalize(vertViewNormal).z;"
			"	vec3 ftrefl = vec3(0.9, 0.8, 0.7);"
			"	vec3 scatter = vec3(0.9, 0.6, 0.1);"
			"	vec3 bklt = vec3(0.8, 0.6, 0.4);"
			"	vec3 ambient = vec3(0.5, 0.4, 0.3);"
			"	fragColor = vec4("
			"		pow(max(ltexp, 0.0), 8.0)*ftrefl+"
			"		( ltexp+1.0)/ltlen*pow(depth,2.0)*scatter+"
			"		(-ltexp+1.0)/ltlen*(1.0-depth)*scatter+"
			"		(-lview+1.0)*0.6*(1.0-abs(depth))*bklt+"
			"		0.2*ambient,"
			"		1.0"
			"	);"
			"}"
		);
		fs_shape.Compile();

		shape_prog.AttachShader(vs_shape);
		shape_prog.AttachShader(fs_shape);
		shape_prog.Link();

		vs_plane.Source(
			"#version 140\n"
			"in vec4 Position;"
			"in vec3 Normal;"
			"uniform mat4 ProjectionMatrix, CameraMatrix;"
			"uniform vec3 LightPos;"
			"out vec3 vertNormal;"
			"out vec3 vertLight;"
			"void main(void)"
			"{"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		Position;"
			"	vertNormal = Normal;"
			"	vertLight = LightPos-Position.xyz;"
			"}"
		);
		vs_plane.Compile();

		fs_plane.Source(
			"#version 140\n"
			"in vec3 vertNormal;"
			"in vec3 vertLight;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = sqrt(length(vertLight));"
			"	float e = dot("
			"		vertNormal,"
			"		normalize(vertLight)"
			"	);"
			"	float d = l > 0.0 ? e / l : 0.0;"
			"	float i = 0.2 + 2.5 * d;"
			"	fragColor = vec4(0.8*i, 0.7*i, 0.4*i, 1.0);"
			"}"
		);
		fs_plane.Compile();

		plane_prog.AttachShader(vs_plane);
		plane_prog.AttachShader(fs_plane);
		plane_prog.Link();

		vs_halo.Source(
			"#version 150\n"
			"in vec4 Position;"
			"in vec3 Normal;"
			"uniform mat4 ModelMatrix, CameraMatrix;"
			"out vec3 vertNormal;"
			"out float vd;"
			"void main(void)"
			"{"
			"	gl_Position = "
			"		CameraMatrix *"
			"		ModelMatrix *"
			"		Position;"
			"	vertNormal = ("
			"		CameraMatrix *"
			"		ModelMatrix *"
			"		vec4(Normal, 0.0)"
			"	).xyz;"
			"	vd = vertNormal.z;"
			"}"
		);
		vs_halo.Compile();

		gs_halo.Source(
			"#version 150\n"
			"layout(triangles) in;"
			"layout(triangle_strip, max_vertices = 12) out;"

			"in vec3 vertNormal[];"
			"in float vd[];"

			"uniform mat4 CameraMatrix, ProjectionMatrix;"
			"uniform vec3 LightPos;"

			"out float geomAlpha;"

			"void main(void)"
			"{"
			"	for(int v=0; v!=3; ++v)"
			"	{"
			"		int a = v, b = (v+1)%3, c = (v+2)%3;"
			"		vec4 pa = gl_in[a].gl_Position;"
			"		vec4 pb = gl_in[b].gl_Position;"
			"		vec4 pc = gl_in[c].gl_Position;"
			"		vec4 px, py;"
			"		vec3 na = vertNormal[a];"
			"		vec3 nb = vertNormal[b];"
			"		vec3 nc = vertNormal[c];"
			"		vec3 nx, ny;"
			"		if(vd[a] == 0.0 && vd[b] == 0.0)"
			"		{"
			"			px = pa;"
			"			nx = na;"
			"			py = pb;"
			"			ny = nb;"
			"		}"
			"		else if(vd[a] > 0.0 && vd[b] < 0.0)"
			"		{"
			"			float x = vd[a]/(vd[a]-vd[b]);"
			"			float y;"
			"			px = mix(pa, pb, x);"
			"			nx = mix(na, nb, x);"
			"			if(vd[c] < 0.0)"
			"			{"
			"				y = vd[a]/(vd[a]-vd[c]);"
			"				py = mix(pa, pc, y);"
			"				ny = mix(na, nc, y);"
			"			}"
			"			else"
			"			{"
			"				y = vd[c]/(vd[c]-vd[b]);"
			"				py = mix(pc, pb, y);"
			"				ny = mix(nc, nb, y);"
			"			}"
			"		}"
			"		else continue;"
			"		vec4 gx1 = vec4(px.xyz, 1.0);"
			"		vec4 gy1 = vec4(py.xyz, 1.0);"
			"		vec4 gx2 = vec4(px.xyz + nx*0.3, 1.0);"
			"		vec4 gy2 = vec4(py.xyz + ny*0.3, 1.0);"
			"		gl_Position = ProjectionMatrix * gy1;"
			"		geomAlpha = 1.0;"
			"		EmitVertex();"
			"		gl_Position = ProjectionMatrix * gx1;"
			"		geomAlpha = 1.0;"
			"		EmitVertex();"
			"		gl_Position = ProjectionMatrix * gy2;"
			"		geomAlpha = 0.0;"
			"		EmitVertex();"
			"		gl_Position = ProjectionMatrix * gx2;"
			"		geomAlpha = 0.0;"
			"		EmitVertex();"
			"		EndPrimitive();"
			"		break;"
			"	}"
			"}"
		);
		gs_halo.Compile();

		fs_halo.Source(
			"#version 150\n"
			"in float geomAlpha;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	fragColor = vec4("
			"		0.5, 0.4, 0.3,"
			"		pow(geomAlpha, 2.0)"
			"	);"
			"}"
		);
		fs_halo.Compile();

		halo_prog.AttachShader(vs_halo);
		halo_prog.AttachShader(gs_halo);
		halo_prog.AttachShader(fs_halo);
		halo_prog.Link();

		// bind the VAO for the shape
		shape.Bind();

		// bind the VBO for the shape vertices
		shape_verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);

			VertexAttribSlot location;
			if(VertexArrayAttrib::QueryCommonLocation(
				MakeGroup(shape_prog, halo_prog),
				"Position",
				location
			))
			{
				VertexArrayAttrib attr(location);
				attr.Setup<GLfloat>(n_per_vertex);
				attr.Enable();
			}
			else OGLPLUS_ABORT("Inconsistent 'Position' location");
		}

		// bind the VBO for the shape normals
		shape_normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Normals(data);
			Buffer::Data(Buffer::Target::Array, data);

			shape_prog.Use();
			VertexArrayAttrib attr(shape_prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VAO for the plane
		plane.Bind();

		// bind the VBO for the plane vertices
		plane_verts.Bind(Buffer::Target::Array);
		{
			GLfloat data[4*3] = {
				-9.0f, 0.0f,  9.0f,
				-9.0f, 0.0f, -9.0f,
				 9.0f, 0.0f,  9.0f,
				 9.0f, 0.0f, -9.0f
			};
			Buffer::Data(Buffer::Target::Array, 4*3, data);
			plane_prog.Use();
			VertexArrayAttrib attr(plane_prog, "Position");
			attr.Setup<Vec3f>();
			attr.Enable();
		}

		// bind the VBO for the plane normals
		plane_normals.Bind(Buffer::Target::Array);
		{
			GLfloat data[4*3] = {
				-0.1f, 1.0f,  0.1f,
				-0.1f, 1.0f, -0.1f,
				 0.1f, 1.0f,  0.1f,
				 0.1f, 1.0f, -0.1f
			};
			Buffer::Data(Buffer::Target::Array, 4*3, data);
			plane_prog.Use();
			VertexArrayAttrib attr(plane_prog, "Normal");
			attr.Setup<Vec3f>();
			attr.Enable();
		}

		Vec3f lightPos(2.0f, 2.5f, 9.0f);

		ProgramUniform<Vec3f>(shape_prog, "LightPos").Set(lightPos);
		ProgramUniform<Vec3f>(plane_prog, "LightPos").Set(lightPos);

		gl.ClearColor(0.2f, 0.2f, 0.2f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.ClearStencil(0);

		gl.Enable(Capability::DepthTest);
		gl.BlendFunc(BlendFn::SrcAlpha, BlendFn::One);
	}
Example #22
0
int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // tell GLFW to capture our mouse
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // configure global opengl state
    // -----------------------------
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    // build and compile shaders
    // -------------------------
    Shader shader("3.2.2.point_shadows.vs", "3.2.2.point_shadows.fs");
    Shader simpleDepthShader("3.2.2.point_shadows_depth.vs", "3.2.2.point_shadows_depth.fs", "3.2.2.point_shadows_depth.gs");

    // load textures
    // -------------
    unsigned int woodTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str());

    // configure depth map FBO
    // -----------------------
    const unsigned int SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024;
    unsigned int depthMapFBO;
    glGenFramebuffers(1, &depthMapFBO);
    // create depth cubemap texture
    unsigned int depthCubemap;
    glGenTextures(1, &depthCubemap);
    glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubemap);
    for (unsigned int i = 0; i < 6; ++i)
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    // attach depth texture as FBO's depth buffer
    glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
    glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthCubemap, 0);
    glDrawBuffer(GL_NONE);
    glReadBuffer(GL_NONE);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);


    // shader configuration
    // --------------------
    shader.use();
    shader.setInt("diffuseTexture", 0);
    shader.setInt("depthMap", 1);

    // lighting info
    // -------------
    glm::vec3 lightPos(0.0f, 0.0f, 0.0f);

    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // per-frame time logic
        // --------------------
        float currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // input
        // -----
        processInput(window);

        // move light position over time
        lightPos.z = sin(glfwGetTime() * 0.5) * 3.0;

        // render
        // ------
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // 0. create depth cubemap transformation matrices
        // -----------------------------------------------
        float near_plane = 1.0f;
        float far_plane = 25.0f;
        glm::mat4 shadowProj = glm::perspective(glm::radians(90.0f), (float)SHADOW_WIDTH / (float)SHADOW_HEIGHT, near_plane, far_plane);
        std::vector<glm::mat4> shadowTransforms;
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f)));

        // 1. render scene to depth cubemap
        // --------------------------------
        glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
        glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
        glClear(GL_DEPTH_BUFFER_BIT);
        simpleDepthShader.use();
        for (unsigned int i = 0; i < 6; ++i)
            simpleDepthShader.setMat4("shadowMatrices[" + std::to_string(i) + "]", shadowTransforms[i]);
        simpleDepthShader.setFloat("far_plane", far_plane);
        simpleDepthShader.setVec3("lightPos", lightPos);
        renderScene(simpleDepthShader);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // 2. render scene as normal 
        // -------------------------
        glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        shader.use();
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
        glm::mat4 view = camera.GetViewMatrix();
        shader.setMat4("projection", projection);
        shader.setMat4("view", view);
        // set lighting uniforms
        shader.setVec3("lightPos", lightPos);
        shader.setVec3("viewPos", camera.Position);
        shader.setInt("shadows", shadows); // enable/disable shadows by pressing 'SPACE'
        shader.setFloat("far_plane", far_plane);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, woodTexture);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubemap);
        renderScene(shader);

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}
Example #23
0
	ReflectionExample(void)
	 : torus_indices(make_torus.Indices())
	 , torus_instr(make_torus.Instructions())
	 , vs_norm(ObjectDesc("Vertex-Normal"))
	 , vs_refl(ObjectDesc("Vertex-Reflection"))
	 , gs_refl(ObjectDesc("Geometry-Reflection"))
	{
		namespace se = oglplus::smart_enums;
		// Set the normal object vertex shader source
		vs_norm.Source(
			"#version 330\n"
			"in vec4 Position;"
			"in vec3 Normal;"
			"out vec3 geomColor;"
			"out vec3 geomNormal;"
			"out vec3 geomLight;"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"uniform vec3 LightPos;"
			"void main(void)"
			"{"
			"	gl_Position = ModelMatrix * Position;"
			"	geomColor = Normal;"
			"	geomNormal = mat3(ModelMatrix)*Normal;"
			"	geomLight = LightPos-gl_Position.xyz;"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		// compile it
		vs_norm.Compile();

		// Set the reflected object vertex shader source
		// which just passes data to the geometry shader
		vs_refl.Source(
			"#version 330\n"
			"in vec4 Position;"
			"in vec3 Normal;"
			"out vec3 vertNormal;"
			"void main(void)"
			"{"
			"	gl_Position = Position;"
			"	vertNormal = Normal;"
			"}"
		);
		// compile it
		vs_refl.Compile();

		// Set the reflected object geometry shader source
		// This shader creates a reflection matrix that
		// relies on the fact that the reflection is going
		// to be done by the y-plane
		gs_refl.Source(
			"#version 330\n"
			"layout(triangles) in;"
			"layout(triangle_strip, max_vertices = 6) out;"

			"in vec3 vertNormal[];"

			"uniform mat4 ProjectionMatrix;"
			"uniform mat4 CameraMatrix;"
			"uniform mat4 ModelMatrix;"

			"out vec3 geomColor;"
			"out vec3 geomNormal;"
			"out vec3 geomLight;"
			"uniform vec3 LightPos;"

			"mat4 ReflectionMatrix = mat4("
			"	1.0, 0.0, 0.0, 0.0,"
			"	0.0,-1.0, 0.0, 0.0,"
			"	0.0, 0.0, 1.0, 0.0,"
			"	0.0, 0.0, 0.0, 1.0 "
			");"
			"void main(void)"
			"{"
			"	for(int v=0; v!=gl_in.length(); ++v)"
			"	{"
			"		vec4 Position = gl_in[v].gl_Position;"
			"		gl_Position = ModelMatrix * Position;"
			"		geomColor = vertNormal[v];"
			"		geomNormal = mat3(ModelMatrix)*vertNormal[v];"
			"		geomLight = LightPos - gl_Position.xyz;"
			"		gl_Position = "
			"			ProjectionMatrix *"
			"			CameraMatrix *"
			"			ReflectionMatrix *"
			"			gl_Position;"
			"		EmitVertex();"
			"	}"
			"	EndPrimitive();"
			"}"
		);
		// compile it
		gs_refl.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"in vec3 geomColor;"
			"in vec3 geomNormal;"
			"in vec3 geomLight;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = length(geomLight);"
			"	float d = l > 0.0 ? dot("
			"		geomNormal, "
			"		normalize(geomLight)"
			"	 ) / l : 0.0;"
			"	float i = 0.2 + max(d, 0.0) * 2.0;"
			"	fragColor = vec4(abs(geomNormal)*i, 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the normal rendering program
		prog_norm.AttachShader(vs_norm);
		prog_norm.AttachShader(fs);
		// link it
		prog_norm.Link();

		// attach the shaders to the reflection rendering program
		prog_refl.AttachShader(vs_refl);
		prog_refl.AttachShader(gs_refl);
		prog_refl.AttachShader(fs);
		// link it
		prog_refl.Link();

		// bind the VAO for the torus
		torus.Bind();

		// bind the VBO for the torus vertices
		torus_verts.Bind(se::Array());
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Positions(data);
			// upload the data
			Buffer::Data(se::Array(), data);

			// setup the vertex attribs array for the vertices
			typedef VertexAttribArray VAA;
			VertexAttribSlot
				loc_norm = VAA::GetLocation(prog_norm, "Position"),
				loc_refl = VAA::GetLocation(prog_refl, "Position");

			assert(loc_norm == loc_refl);
			VertexAttribArray attr(loc_norm);
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VBO for the torus normals
		torus_normals.Bind(se::Array());
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Normals(data);
			// upload the data
			Buffer::Data(se::Array(), data);

			// setup the vertex attribs array for the normals
			typedef VertexAttribArray VAA;
			VertexAttribSlot
				loc_norm = VAA::GetLocation(prog_norm, "Normal"),
				loc_refl = VAA::GetLocation(prog_refl, "Normal");

			assert(loc_norm == loc_refl);
			VertexAttribArray attr(loc_norm);
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VAO for the plane
		plane.Bind();

		// bind the VBO for the plane vertices
		plane_verts.Bind(se::Array());
		{
			GLfloat data[4*3] = {
				-2.0f, 0.0f,  2.0f,
				-2.0f, 0.0f, -2.0f,
				 2.0f, 0.0f,  2.0f,
				 2.0f, 0.0f, -2.0f
			};
			// upload the data
			Buffer::Data(se::Array(), 4*3, data);
			// setup the vertex attribs array for the vertices
			prog_norm.Use();
			VertexAttribArray attr(prog_norm, "Position");
			attr.Setup<Vec3f>();
			attr.Enable();
		}

		// bind the VBO for the torus normals
		plane_normals.Bind(se::Array());
		{
			GLfloat data[4*3] = {
				-0.1f, 1.0f,  0.1f,
				-0.1f, 1.0f, -0.1f,
				 0.1f, 1.0f,  0.1f,
				 0.1f, 1.0f, -0.1f
			};
			// upload the data
			Buffer::Data(se::Array(), 4*3, data);
			// setup the vertex attribs array for the normals
			prog_norm.Use();
			VertexAttribArray attr(prog_norm, "Normal");
			attr.Setup<Vec3f>();
			attr.Enable();
		}
		VertexArray::Unbind();

		Vec3f lightPos(2.0f, 2.0f, 3.0f);
		prog_norm.Use();
		SetUniform(prog_norm, "LightPos", lightPos);
		prog_refl.Use();
		SetUniform(prog_refl, "LightPos", lightPos);
		//
		gl.ClearColor(0.2f, 0.2f, 0.2f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.ClearStencil(0);
	}
Example #24
0
void NGLScene::initializeGL()
{
  // we must call this first before any other GL commands to load and link the
  // gl commands from the lib, if this is not done program will crash
  ngl::NGLInit::instance();

  glClearColor(0.4f, 0.4f, 0.4f, 1.0f);			   // Grey Background
  // enable depth testing for drawing
  glEnable(GL_DEPTH_TEST);
  // enable multisampling for smoother drawing
  glEnable(GL_MULTISAMPLE);
  // This is a static camera so it only needs to be set once
  // First create Values for the camera position
  ngl::Vec3 from(2,2,2);
  ngl::Vec3 to(0,0,0);
  ngl::Vec3 up(0,1,0);
  // now load to our new camera
  m_view=ngl::lookAt(from,to,up);
  // set the shape using FOV 45 Aspect Ratio based on Width and Height
  // The final two are near and far clipping planes of 0.5 and 10
  m_project=ngl::perspective(45.0f,720.0f/576.0f,0.05f,350.0f);
  // now to load the shader and set the values
  // grab an instance of shader manager
  ngl::ShaderLib *shader=ngl::ShaderLib::instance();
  // we are creating a shader called Phong
  shader->createShaderProgram("Phong");
  // now we are going to create empty shaders for Frag and Vert
  shader->attachShader("PhongVertex",ngl::ShaderType::VERTEX);
  shader->attachShader("PhongFragment",ngl::ShaderType::FRAGMENT);
  // attach the source
  shader->loadShaderSource("PhongVertex","shaders/PhongVert.glsl");
  shader->loadShaderSource("PhongFragment","shaders/PhongFrag.glsl");
  // compile the shaders
  shader->compileShader("PhongVertex");
  shader->compileShader("PhongFragment");
  // add them to the program
  shader->attachShaderToProgram("Phong","PhongVertex");
  shader->attachShaderToProgram("Phong","PhongFragment");

  // now we have associated this data we can link the shader
  shader->linkProgramObject("Phong");
  // and make it active ready to load values
  (*shader)["Phong"]->use();
  ngl::Vec4 lightPos(-2.0f,5.0f,2.0f,0.0f);
  shader->setUniform("light.position",lightPos);
  shader->setUniform("light.ambient",0.0f,0.0f,0.0f,1.0f);
  shader->setUniform("light.diffuse",1.0f,1.0f,1.0f,1.0f);
  shader->setUniform("light.specular",0.8f,0.8f,0.8f,1.0f);
  // gold like phong material
  shader->setUniform("material.ambient",0.274725f,0.1995f,0.0745f,0.0f);
  shader->setUniform("material.diffuse",0.75164f,0.60648f,0.22648f,0.0f);
  shader->setUniform("material.specular",0.628281f,0.555802f,0.3666065f,0.0f);
  shader->setUniform("material.shininess",51.2f);
  shader->setUniform("viewerPos",from);

  // now load our texture shader
  shader->createShaderProgram("TextureShader");

  shader->attachShader("TextureVertex",ngl::ShaderType::VERTEX);
  shader->attachShader("TextureFragment",ngl::ShaderType::FRAGMENT);
  shader->loadShaderSource("TextureVertex","shaders/TextureVertex.glsl");
  shader->loadShaderSource("TextureFragment","shaders/TextureFragment.glsl");

  shader->compileShader("TextureVertex");
  shader->compileShader("TextureFragment");
  shader->attachShaderToProgram("TextureShader","TextureVertex");
  shader->attachShaderToProgram("TextureShader","TextureFragment");

  // link the shader no attributes are bound
  shader->linkProgramObject("TextureShader");
  (*shader)["TextureShader"]->use();

  // now create our texture object
  createTextureObject();
  // now the fbo
  createFramebufferObject();
  // now create the primitives to draw
  ngl::VAOPrimitives *prim=ngl::VAOPrimitives::instance();
  prim->createTrianglePlane("plane",2,2,20,20,ngl::Vec3(0,1,0));
  prim->createSphere("sphere",0.4f,80);
  startTimer(1);
  GLint maxAttach = 0;
  glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxAttach);

}
Example #25
0
	void Scene::Render(const ogl::MvpMatrix &matrix, const ogl::Camera &camera, float aspect)
	{		
		
		glm::mat4 model = matrix.model;
	    glm::mat4 view  = matrix.view;
	    glm::mat4 proj  = matrix.proj;

		glm::vec3 lightPos(0.0f, 0.0f, 0.0f);
		// Move light position over time
		//lightPos.z = sin(glfwGetTime() * 0.5) * 3.0;
		glm::vec3 camPos = camera.GetPos();

		GLfloat near_plane = 1.0f;
		GLfloat far_plane = 25.0f;
		glm::mat4 shadowProj = glm::perspective(90.0f, aspect, near_plane, far_plane);
		
		std::vector<glm::mat4> shadowTransforms;
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 1.0,  0.0,  0.0), glm::vec3(0.0, -1.0,  0.0)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(-1.0,  0.0,  0.0), glm::vec3(0.0, -1.0,  0.0)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0,  1.0,  0.0), glm::vec3(0.0,  0.0,  1.0)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0, -1.0,  0.0), glm::vec3(0.0,  0.0, -1.0)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0,  0.0,  1.0), glm::vec3(0.0, -1.0,  0.0)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0,  0.0, -1.0), glm::vec3(0.0, -1.0,  0.0)));
		
		// 1. Render scene to depth cubemap
		glUseProgram(shadow_prog);

		glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
		glClear(GL_DEPTH_BUFFER_BIT);

		for (GLuint i = 0; i < 6; ++i)
		    glUniformMatrix4fv(glGetUniformLocation(shadow_prog, ("shadowTransforms[" + std::to_string(i) + "]").c_str()), 1, GL_FALSE, &( shadowTransforms[i] )[0][0] );
		
		glUniform1f(glGetUniformLocation( shadow_prog, "far_plane"), far_plane);
		glUniform3fv(glGetUniformLocation(shadow_prog, "lightPos"), 1, &lightPos[0]);
		RenderScene(shadow_prog);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

		glUseProgram(0);

		//////////////////////////////////////////////////////////////////////////////////////
		glUseProgram(scene_prog);
	    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glUniformMatrix4fv(glGetUniformLocation(scene_prog, "view"),  1, GL_FALSE, &view[0][0]);
		glUniformMatrix4fv(glGetUniformLocation(scene_prog, "proj"),  1, GL_FALSE, &proj[0][0]);
		glUniform3fv(glGetUniformLocation(scene_prog, "lightPos"), 1, &lightPos[0]);
		glUniform3fv(glGetUniformLocation(scene_prog, "viewPos"), 1, &camPos[0]);

		// Enable/Disable shadows by pressing 'SPscene_progACE'
		glUniform1i(glGetUniformLocation(scene_prog, "shadows"), shadowFlag);
		glUniform1f(glGetUniformLocation(scene_prog, "far_plane"), far_plane);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, woodTex);
		glUniform1i(glGetUniformLocation(scene_prog, "diffuseTexture"), 0);

		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubemap);
		glUniform1i(glGetUniformLocation(scene_prog, "depthMap"), 1);

		RenderScene(scene_prog);

		glUseProgram(0);
	

	}
    ReflectionExample()
      : make_plane(
          Vec3f(), Vec3f(3.0f, 0.0f, 0.0f), Vec3f(0.0f, 0.0f, -3.0f), 15, 15)
      , plane_instr(make_plane.Instructions())
      , plane_indices(make_plane.Indices())
      , make_shape()
      , shape_instr(make_shape.Instructions())
      , shape_indices(make_shape.Indices())
      , plane_vs(ObjectDesc("Plane vertex"))
      , shape_vs(ObjectDesc("Shape vertex"))
      , plane_fs(ObjectDesc("Plane fragment"))
      , shape_fs(ObjectDesc("Shape fragment"))
      , plane_projection_matrix(plane_prog)
      , plane_camera_matrix(plane_prog)
      , plane_model_matrix(plane_prog)
      , shape_projection_matrix(shape_prog)
      , shape_camera_matrix(shape_prog)
      , shape_model_matrix(shape_prog)
      , width(800)
      , height(600)
      , tex_size_div(2) {
        plane_vs.Source(
          "#version 140\n"
          "uniform vec3 LightPosition;"
          "uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
          "in vec4 Position;"
          "out vec3 vertLightDir;"
          "out vec4 vertTexCoord;"
          "void main()"
          "{"
          "	gl_Position = ModelMatrix*Position;"
          "	vertLightDir = LightPosition - gl_Position.xyz;"
          "	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
          "	vertTexCoord = gl_Position;"
          "}");
        plane_vs.Compile();

        plane_fs.Source(
          "#version 140\n"
          "uniform sampler2DRect ReflectTex;"
          "uniform vec3 Normal;"
          "in vec3 vertLightDir;"
          "in vec4 vertTexCoord;"
          "out vec3 fragColor;"
          "const int n = 5;"
          "const int ns = (n*n);"
          "const float blur = 0.15/n;"
          "void main()"
          "{"
          "	float d = dot(Normal, normalize(vertLightDir));"
          "	float intensity = 0.5 + pow(1.4*d, 2.0);"
          "	vec3 color = vec3(0.0, 0.0, 0.0);"
          "	int n = 2;"
          "	float pct = 0.5/vertTexCoord.w;"
          "	for(int y=-n; y!=(n+1); ++y)"
          "	for(int x=-n; x!=(n+1); ++x)"
          "	{"
          "		vec2 coord = vertTexCoord.xy;"
          "		coord += vec2(blur*x, blur*y);"
          "		coord *= pct;"
          "		coord += vec2(0.5, 0.5);"
          "		coord *= textureSize(ReflectTex);"
          "		color += texture(ReflectTex, coord).rgb/ns;"
          "	}"
          "	fragColor = color*intensity;"
          "}");
        plane_fs.Compile();

        plane_prog.AttachShader(plane_vs);
        plane_prog.AttachShader(plane_fs);
        plane_prog.Link();
        plane_prog.Use();

        plane_projection_matrix.BindTo("ProjectionMatrix");
        plane_camera_matrix.BindTo("CameraMatrix");
        plane_model_matrix.BindTo("ModelMatrix");

        Vec3f lightPos(3.0f, 0.5f, 2.0f);
        Uniform<Vec3f>(plane_prog, "LightPosition").Set(lightPos);
        Uniform<Vec3f>(plane_prog, "Normal").Set(make_plane.Normal());

        plane.Bind();

        plane_verts.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_plane.Positions(data);
            Buffer::Data(Buffer::Target::Array, data);
            VertexArrayAttrib attr(plane_prog, "Position");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }
        //
        Texture::Active(1);
        gl.Bound(Texture::Target::Rectangle, depth_tex)
          .MinFilter(TextureMinFilter::Linear)
          .MagFilter(TextureMagFilter::Linear)
          .WrapS(TextureWrap::ClampToEdge)
          .WrapT(TextureWrap::ClampToEdge);

        Texture::Active(0);
        ProgramUniformSampler(plane_prog, "ReflectTex").Set(0);
        gl.Bound(Texture::Target::Rectangle, reflect_tex)
          .MinFilter(TextureMinFilter::Linear)
          .MagFilter(TextureMagFilter::Linear)
          .WrapS(TextureWrap::ClampToEdge)
          .WrapT(TextureWrap::ClampToEdge);

        gl.Bound(Framebuffer::Target::Draw, fbo)
          .AttachTexture(FramebufferAttachment::Color, reflect_tex, 0)
          .AttachTexture(FramebufferAttachment::Depth, depth_tex, 0);

        shape_vs.Source(
          "#version 140\n"
          "uniform vec3 LightPosition;"
          "uniform mat4 ProjectionMatrix, ModelMatrix, CameraMatrix;"
          "in vec4 Position;"
          "in vec3 Normal;"
          "out vec3 vertNormal;"
          "out vec3 vertLightDir;"
          "out vec3 vertLightRefl;"
          "out vec3 vertViewDir;"
          "out vec3 vertColor;"
          "void main()"
          "{"
          "	gl_Position = ModelMatrix * Position;"
          "	vertLightDir = LightPosition - gl_Position.xyz;"
          "	vertNormal = mat3(ModelMatrix)*Normal;"
          "	vertLightRefl = reflect("
          "		-normalize(vertLightDir),"
          "		normalize(vertNormal)"
          "	);"
          "	vertViewDir = (vec4(0.0, 0.0, 1.0, 1.0)*CameraMatrix).xyz;"
          "	vertColor = vec3(1, 1, 1) - vertNormal;"
          "	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
          "}");
        shape_vs.Compile();

        shape_fs.Source(
          "#version 140\n"
          "in vec3 vertNormal;"
          "in vec3 vertLightDir;"
          "in vec3 vertLightRefl;"
          "in vec3 vertViewDir;"
          "in vec3 vertColor;"
          "out vec3 fragColor;"

          "void main()"
          "{"
          "	float l = length(vertLightDir);"
          "	float d = dot("
          "		normalize(vertNormal), "
          "		normalize(vertLightDir)"
          "	) / l;"
          "	float s = dot("
          "		normalize(vertLightRefl),"
          "		normalize(vertViewDir)"
          "	);"
          "	vec3 lt = vec3(1.0, 1.0, 1.0);"
          "	fragColor = "
          "		vertColor * 0.4 + "
          "		(lt + vertColor)*pow(max(2.5*d, 0.0), 3) + "
          "		lt * pow(max(s, 0.0), 64);"
          "}");
        shape_fs.Compile();

        shape_prog.AttachShader(shape_vs);
        shape_prog.AttachShader(shape_fs);
        shape_prog.Link();
        shape_prog.Use();

        shape_projection_matrix.BindTo("ProjectionMatrix");
        shape_camera_matrix.BindTo("CameraMatrix");
        shape_model_matrix.BindTo("ModelMatrix");

        Uniform<Vec3f>(shape_prog, "LightPosition").Set(lightPos);

        shape.Bind();

        shape_verts.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_shape.Positions(data);
            Buffer::Data(Buffer::Target::Array, data);
            VertexArrayAttrib attr(shape_prog, "Position");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }

        shape_normals.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_shape.Normals(data);
            Buffer::Data(Buffer::Target::Array, data);
            VertexArrayAttrib attr(shape_prog, "Normal");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }
        //
        gl.ClearColor(0.5f, 0.5f, 0.4f, 0.0f);
        gl.ClearDepth(1.0f);
        gl.Enable(Capability::DepthTest);
        gl.Enable(Capability::CullFace);
    }
Example #27
0
	GlassExample(void)
	 : make_plane(Vec3f(2.0f, 0.0f, 0.0f), Vec3f(0.0f, 0.0f, -2.0f))
	 , plane_instr(make_plane.Instructions())
	 , plane_indices(make_plane.Indices())
	 , make_shape()
	 , shape_instr(make_shape.Instructions())
	 , shape_indices(make_shape.Indices())
	 , plane_vs(ObjectDesc("Plane vertex"))
	 , shape_vs(ObjectDesc("Shape vertex"))
	 , plane_fs(ObjectDesc("Plane fragment"))
	 , shape_fs(ObjectDesc("Shape fragment"))
	 , plane_proj_matrix(plane_prog)
	 , plane_camera_matrix(plane_prog)
	 , plane_model_matrix(plane_prog)
	 , shape_proj_matrix(shape_prog)
	 , shape_camera_matrix(shape_prog)
	 , shape_model_matrix(shape_prog)
	 , shape_clip_plane(shape_prog)
	 , shape_clip_direction(shape_prog)
	 , width(512)
	 , height(512)
	 , tex_side(512)
	{
		plane_vs.Source(
			"#version 140\n"
			"uniform vec3 LightPosition;"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"in vec4 Position;"
			"in vec2 TexCoord;"
			"out vec3 vertLightDir;"
			"out vec2 vertTexCoord;"
			"void main(void)"
			"{"
			"	gl_Position = "
			"		ModelMatrix* "
			"		Position;"
			"	vertLightDir = normalize("
			"		LightPosition - gl_Position.xyz"
			"	);"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		gl_Position;"
			"	vertTexCoord = TexCoord;"
			"}"
		);
		plane_vs.Compile();

		plane_fs.Source(
			"#version 140\n"
			"uniform vec3 Normal;"
			"in vec3 vertLightDir;"
			"in vec2 vertTexCoord;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float checker = ("
			"		int(vertTexCoord.x*18) % 2+"
			"		int(vertTexCoord.y*18) % 2"
			"	) % 2;"
			"	vec3 color = mix("
			"		vec3(0.2, 0.4, 0.9),"
			"		vec3(0.2, 0.2, 0.7),"
			"		checker"
			"	);"
			"	float d = dot("
			"		Normal, "
			"		vertLightDir"
			"	);"
			"	float intensity = 0.5 + pow(1.4*d, 2.0);"
			"	fragColor = vec4(color*intensity, 1.0);"
			"}"
		);
		plane_fs.Compile();

		plane_prog.AttachShader(plane_vs);
		plane_prog.AttachShader(plane_fs);
		plane_prog.Link();
		plane_prog.Use();
		plane_proj_matrix.BindTo("ProjectionMatrix");
		plane_camera_matrix.BindTo("CameraMatrix");
		plane_model_matrix.BindTo("ModelMatrix");

		Vec3f lightPos(3.0f, 3.0f, 3.0f);
		Uniform<Vec3f>(plane_prog, "LightPosition").Set(lightPos);
		Uniform<Vec3f>(plane_prog, "Normal").Set(make_plane.Normal());

		gl.Bind(plane);

		gl.Bind(Buffer::Target::Array, plane_verts);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_plane.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(plane_prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		gl.Bind(Buffer::Target::Array, plane_texcoords);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_plane.TexCoordinates(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(plane_prog, "TexCoord");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		shape_vs.Source(
			"#version 140\n"
			"uniform vec3 LightPosition;"
			"uniform mat4 ProjectionMatrix, ModelMatrix, CameraMatrix;"
			"uniform vec4 ClipPlane;"
			"uniform float ClipDirection;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"out vec3 vertNormal;"
			"out vec3 vertLightDir;"
			"out vec3 vertLightRefl;"
			"out vec3 vertViewDir;"
			"out vec2 vertTexCoord;"
			"void main(void)"
			"{"
			"	gl_Position = "
			"		ModelMatrix *"
			"		Position;"
			"	gl_ClipDistance[0] = "
			"		ClipDirection* "
			"		dot(ClipPlane, gl_Position);"
			"	vertLightDir = LightPosition - gl_Position.xyz;"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertLightRefl = reflect("
			"		-normalize(vertLightDir),"
			"		normalize(vertNormal)"
			"	);"
			"	vertViewDir = (vec4(0.0, 0.0, 1.0, 1.0)*CameraMatrix).xyz;"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"	vec3 TexOffs = mat3(CameraMatrix)*vertNormal*0.05;"
			"	vertTexCoord = "
			"		vec2(0.5, 0.5) +"
			"		(gl_Position.xy/gl_Position.w)*0.5 +"
			"		(TexOffs.z<0.0 ? TexOffs.xy : -TexOffs.xy);"
			"}"
		);
		shape_vs.Compile();

		shape_fs.Source(
			"#version 140\n"
			"uniform sampler2D RefractTex;"
			"in vec3 vertNormal;"
			"in vec3 vertLightDir;"
			"in vec3 vertLightRefl;"
			"in vec3 vertViewDir;"
			"in vec2 vertTexCoord;"
			"out vec4 fragColor;"

			"float adj_lt(float i)"
			"{"
			"	return i > 0.0 ? i : -0.7*i;"
			"}"

			"void main(void)"
			"{"
			"	float l = length(vertLightDir);"
			"	float d = dot("
			"		normalize(vertNormal), "
			"		normalize(vertLightDir)"
			"	) / l;"
			"	float s = dot("
			"		normalize(vertLightRefl),"
			"		normalize(vertViewDir)"
			"	);"
			"	vec3 lt = vec3(1.0, 1.0, 1.0);"
			"	vec3 tex = texture(RefractTex, vertTexCoord).rgb;"
			"	fragColor = vec4("
			"		tex * 0.5 + "
			"		(lt + tex) * 1.5 * adj_lt(d) + "
			"		lt * pow(adj_lt(s), 64), "
			"		1.0"
			"	);"
			"}"
		);
		shape_fs.Compile();

		shape_prog.AttachShader(shape_vs);
		shape_prog.AttachShader(shape_fs);
		shape_prog.Link();
		shape_prog.Use();
		shape_proj_matrix.BindTo("ProjectionMatrix");
		shape_camera_matrix.BindTo("CameraMatrix");
		shape_model_matrix.BindTo("ModelMatrix");
		shape_clip_plane.BindTo("ClipPlane");
		shape_clip_direction.BindTo("ClipDirection");

		Uniform<Vec3f>(shape_prog, "LightPosition").Set(lightPos);

		gl.Bind(shape);

		gl.Bind(Buffer::Target::Array, shape_verts);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(shape_prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		gl.Bind(Buffer::Target::Array, shape_normals);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Normals(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(shape_prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}
		//
		Texture::Active(0);
		UniformSampler(shape_prog, "RefractTex").Set(0);
		{
			gl.Bound(Texture::Target::_2D, refract_tex)
				.MinFilter(TextureMinFilter::Linear)
				.MagFilter(TextureMagFilter::Linear)
				.WrapS(TextureWrap::MirroredRepeat)
				.WrapT(TextureWrap::MirroredRepeat)
				.Image2D(
					0,
					PixelDataInternalFormat::RGB,
					tex_side, tex_side,
					0,
					PixelDataFormat::RGB,
					PixelDataType::UnsignedByte,
					nullptr
				);
		}
		//
		gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
	}
// The MAIN function, from here we start our application and run our Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    ////Shader shader("shadow_mapping.vs", "shadow_mapping.frag");
    Shader simpleDepthShader("shadow_mapping_depth.vs", "shadow_mapping_depth.frag");
	Shader shaderGeometryPass("g_buffer.vs", "g_buffer.frag");
	Shader shaderLightingPass("deferred_shading.vs", "deferred_shading.frag");
    // Set texture samples
    ////shader.Use();
    ////glUniform1i(glGetUniformLocation(shader.Program, "diffuseTexture"), 0);
    ////glUniform1i(glGetUniformLocation(shader.Program, "shadowMap"), 1);

	// Set samplers
	shaderLightingPass.Use();
	glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gPosition"), 0);
	glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gNormal"), 1);
	glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gAlbedoSpec"), 2);
	glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gDepthViewer"), 3);
	glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "gShadowMap"), 4);

	shaderGeometryPass.Use();
	glUniform1i(glGetUniformLocation(shaderGeometryPass.Program, "texture_diffuse1"), 0);
	glUniform1i(glGetUniformLocation(shaderGeometryPass.Program, "texture_specular1"), 1);

    GLfloat planeVertices[] = {
        // Positions            // Normals           // Texture Coords
         25.0f, -0.5f,  25.0f,  0.0f,  1.0f,  0.0f,  25.0f, 0.0f,
        -25.0f, -0.5f, -25.0f,  0.0f,  1.0f,  0.0f,  0.0f,  25.0f,
        -25.0f, -0.5f,  25.0f,  0.0f,  1.0f,  0.0f,  0.0f,  0.0f,

         25.0f, -0.5f,  25.0f,  0.0f,  1.0f,  0.0f,  25.0f, 0.0f,
         25.0f, -0.5f, -25.0f,  0.0f,  1.0f,  0.0f,  25.0f, 25.0f,
        -25.0f, -0.5f, -25.0f,  0.0f,  1.0f,  0.0f,  0.0f,  25.0f
    };
    // Setup plane VAO
    GLuint planeVBO;
    glGenVertexArrays(1, &planeVAO);
    glGenBuffers(1, &planeVBO);
    glBindVertexArray(planeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
    glBindVertexArray(0);

    // Light source
    glm::vec3 lightPos(-2.0f, 4.0f, -1.0f);

    // Load textures
    woodTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str());

    // Configure depth map FBO
    const GLuint SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024;
    GLuint depthMapFBO;
    glGenFramebuffers(1, &depthMapFBO);
    // - Create depth texture
	GLuint gShadowMap;
	glGenTextures(1, &gShadowMap);
	glBindTexture(GL_TEXTURE_2D, gShadowMap);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, gShadowMap, 0);
    glDrawBuffer(GL_NONE);
    glReadBuffer(GL_NONE);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);


	// Set up G-Buffer
	// 3 textures:
	// 1. Positions (RGB)
	// 2. Color (RGB) + Specular (A)
	// 3. Normals (RGB)
	//// 4. gDepthViewer (DEPTH)
	GLuint gBuffer;
	glGenFramebuffers(1, &gBuffer);
	glBindFramebuffer(GL_FRAMEBUFFER, gBuffer);
	GLuint gPosition, gNormal, gAlbedoSpec, gDepthViewer;
	// - Position color buffer
	glGenTextures(1, &gPosition);
	glBindTexture(GL_TEXTURE_2D, gPosition);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gPosition, 0);
	// - Normal color buffer
	glGenTextures(1, &gNormal);
	glBindTexture(GL_TEXTURE_2D, gNormal);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0);
	// - Color + Specular color buffer
	glGenTextures(1, &gAlbedoSpec);
	glBindTexture(GL_TEXTURE_2D, gAlbedoSpec);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gAlbedoSpec, 0);


	// - Depth Map from viewer buffer
	glGenTextures(1, &gDepthViewer);
	glBindTexture(GL_TEXTURE_2D, gDepthViewer);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, gDepthViewer, 0);

	// - Tell OpenGL which color attachments we'll use (of this framebuffer) for rendering
	GLuint attachments[4] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; //////check!

	glDrawBuffers(4, attachments);




    glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

        // Change light position over time
        lightPos.z = cos(glfwGetTime()) * 2.0f;

        // 1. Render depth of scene to texture (from light's perspective)
        // - Get light projection/view matrix.
        glm::mat4 lightProjection, lightView;
        glm::mat4 lightSpaceMatrix;
        GLfloat near_plane = 1.0f, far_plane = 9.5f;
        //lightProjection = glm::ortho(-10.0f, 10.0f, -10.0f, 10.0f, near_plane, far_plane);
        lightProjection = glm::perspective(65.0f, (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT, near_plane, far_plane); // Note that if you use a perspective projection matrix you'll have to change the light position as the current light position isn't enough to reflect the whole scene.
        lightView = glm::lookAt(lightPos, glm::vec3(0.0f), glm::vec3(1.0));
        lightSpaceMatrix = lightProjection * lightView;
        // - now render scene from light's point of view
        simpleDepthShader.Use();
        glUniformMatrix4fv(glGetUniformLocation(simpleDepthShader.Program, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(lightSpaceMatrix));
        glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
        glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
            glClear(GL_DEPTH_BUFFER_BIT);
            RenderScene(simpleDepthShader);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

		/*
        // 2. Render scene as normal
        glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        shader.Use();
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
        glm::mat4 view = camera.GetViewMatrix();
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        // Set light uniforms
        glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]);
        glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]);
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(lightSpaceMatrix));
        // Enable/Disable shadows by pressing 'SPACE'
        glUniform1i(glGetUniformLocation(shader.Program, "shadows"), shadows);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, woodTexture);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, depthMap);
        RenderScene(shader);
		*/

		glBindFramebuffer(GL_FRAMEBUFFER, gBuffer);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		shaderGeometryPass.Use();
		glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
		glm::mat4 view = camera.GetViewMatrix();
		glUniformMatrix4fv(glGetUniformLocation(shaderGeometryPass.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(shaderGeometryPass.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
		glUniformMatrix4fv(glGetUniformLocation(shaderGeometryPass.Program, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(lightSpaceMatrix));
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, woodTexture);
		RenderScene(shaderGeometryPass);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		shaderLightingPass.Use();
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, gPosition);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, gNormal);
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, gAlbedoSpec);



		glActiveTexture(GL_TEXTURE3);
		glBindTexture(GL_TEXTURE_2D, gDepthViewer);
		glActiveTexture(GL_TEXTURE4);
		glBindTexture(GL_TEXTURE_2D, gShadowMap);


		// Also send light relevant uniforms

		glUniform3fv(glGetUniformLocation(shaderLightingPass.Program, "lightPos"), 1, &lightPos[0]);
		glUniform3fv(glGetUniformLocation(shaderLightingPass.Program, "viewPos"), 1, &camera.Position[0]);
		glUniform1i(glGetUniformLocation(shaderLightingPass.Program, "draw_mode"), draw_mode);
		RenderQuad();


        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Example #29
0
void CWater::RenderWater(CVec3f cameraPos, CFloat elapsedTime )
{
	if( g_fogBlurPass )
	{
		glDisable( GL_CULL_FACE );
		glBegin( GL_QUADS );
		glVertex3f(m_sidePoint[0].x, m_sidePoint[0].y, m_sidePoint[0].z);
		glVertex3f(m_sidePoint[1].x, m_sidePoint[1].y, m_sidePoint[1].z);
		glVertex3f(m_sidePoint[2].x, m_sidePoint[2].y, m_sidePoint[2].z);
		glVertex3f(m_sidePoint[3].x, m_sidePoint[3].y, m_sidePoint[3].z);
		glEnd();
		glEnable( GL_CULL_FACE );
	}
	else
	{
		glDisable( GL_CULL_FACE );
 		// Turn on the first texture unit and bind the REFLECTION texture
		glActiveTexture(GL_TEXTURE0);
		glEnable(GL_TEXTURE_2D); 
		glBindTexture(GL_TEXTURE_2D, m_waterTexture[WATER_REFLECTION_ID]);

		// Turn on the second texture unit and bind the REFRACTION texture
		glActiveTexture(GL_TEXTURE1);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, m_waterTexture[WATER_REFRACTION_ID]);

		// Turn on the third texture unit and bind the NORMAL MAP texture
		glActiveTexture(GL_TEXTURE2);
		glEnable(GL_TEXTURE_2D); 
		glBindTexture(GL_TEXTURE_2D, m_normalMapImg->GetId() );

		// Turn on the fourth texture unit and bind the DUDV MAP texture
		glActiveTexture(GL_TEXTURE3);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, m_dudvMapImg->GetId() );

		// Turn on the fifth texture unit and bind the DEPTH texture
		glActiveTexture(GL_TEXTURE4);
		glEnable(GL_TEXTURE_2D); 
		glBindTexture(GL_TEXTURE_2D, m_waterTexture[WATER_DEPTH_ID]);

		// Set the variable "reflection" to correspond to the first texture unit
		GLint uniform = glGetUniformLocationARB(g_render.m_waterProgram, "reflection"); 
		glUniform1iARB(uniform, 0); //second paramter is the texture unit 

		// Set the variable "refraction" to correspond to the second texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "refraction");
		glUniform1iARB(uniform, 1); 

		// Set the variable "normalMap" to correspond to the third texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "normalMap");
		glUniform1iARB(uniform, 2);

		// Set the variable "dudvMap" to correspond to the fourth texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "dudvMap"); 
		glUniform1iARB(uniform, 3);

		// Set the variable "depthMap" to correspond to the fifth texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "depthMap");
		glUniform1iARB(uniform, 4); 

		// Give the variable "waterColor" a blue color
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "waterColor");
		glUniform4fARB(uniform, 0.1f, 0.2f, 0.3f, 1.0f); 

		// We don't use lighting, but we do need to calculate
		// the diffuse and specular lighting on the water to increase realism.
		// position the light so it's near the light in the sky box texture.
		CVec3f lightPos(m_fWaterLPos[0], m_fWaterLPos[1], m_fWaterLPos[2]);

		// Give the variable "lightPos" our hard coded light position
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "lightPos");
		glUniform4fARB(uniform, lightPos.x, lightPos.y, lightPos.z, 1.0f); 

		// Give the variable "cameraPos" our camera position
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "cameraPos");
		glUniform4fARB(uniform, cameraPos.x, cameraPos.y, cameraPos.z, 1.0f); 
	
		// Create a static variable for the movement of the water
		static float move = 0.0f;

		// Use this variable for the normal map and make it slower
		// than the refraction map's speed.  We want the refraction
		// map to be jittery, but not the normal map's waviness.
		float move2 = move * kNormalMapScale;

		// Set the refraction map's UV coordinates to our global g_WaterUV
		float refrUV = m_fWaterUV;

		// Set our normal map's UV scale and shrink it by kNormalMapScale
		float normalUV = m_fWaterUV * kNormalMapScale;

		// Move the water by our global speed
		move += m_fWaterSpeed * elapsedTime;

		glUseProgram( g_render.m_waterProgram );

	   // Draw our huge water quad
		glBegin(GL_QUADS);

		// The back left vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0.0f, m_fWaterUV);				// Reflection texture				
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0.0f, refrUV - move);			// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, 0.0f, normalUV + move2);		// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[0].x, m_sidePoint[0].y, m_sidePoint[0].z);

		// The front left vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0.0f, 0.0f);					// Reflection texture
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0.0f, 0.0f - move);			// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, 0.0f, 0.0f + move2);			// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[1].x, m_sidePoint[1].y, m_sidePoint[1].z);

		// The front right vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, m_fWaterUV, 0.0f);				// Reflection texture
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, refrUV, 0.0f - move);			// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, normalUV, 0.0f + move2);		// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[2].x, m_sidePoint[2].y, m_sidePoint[2].z);

		// The back right vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, m_fWaterUV, m_fWaterUV);		// Reflection texture
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, refrUV, refrUV - move);		// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, normalUV, normalUV + move2);	// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[3].x, m_sidePoint[3].y, m_sidePoint[3].z);

		glEnd();
		// Turn the fifth multi-texture pass off
		glActiveTexture(GL_TEXTURE4);		
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the fourth multi-texture pass off
		glActiveTexture(GL_TEXTURE3);		
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the third multi-texture pass off
		glActiveTexture(GL_TEXTURE2);
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the second multi-texture pass off
		glActiveTexture(GL_TEXTURE1);
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the first multi-texture pass off
		glActiveTexture(GL_TEXTURE0);	
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		glEnable( GL_CULL_FACE );
		glDisable(GL_TEXTURE_2D);
	}

}
Example #30
0
void NGLScene::initializeGL()
{
  // we must call this first before any other GL commands to load and link the
  // gl commands from the lib, if this is not done program will crash
  ngl::NGLInit::instance();

  glClearColor(0.4f, 0.4f, 0.4f, 1.0f);			   // Grey Background
  // enable depth testing for drawing
  glEnable(GL_DEPTH_TEST);
  // enable multisampling for smoother drawing
  glEnable(GL_MULTISAMPLE);
  // Now we will create a basic Camera from the graphics library
  // This is a static camera so it only needs to be set once
  // First create Values for the camera position
  ngl::Vec3 from(8,8,8);
  ngl::Vec3 to(0,0,0);
  ngl::Vec3 up(0,1,0);
  m_view=ngl::lookAt(from,to,up);
  // set the shape using FOV 45 Aspect Ratio based on Width and Height
  // The final two are near and far clipping planes of 0.5 and 10
  m_project=ngl::perspective(60,720.0f/576.0f,0.5,150);
  // now to load the shader and set the values
  // grab an instance of shader manager
  ngl::ShaderLib *shader=ngl::ShaderLib::instance();
  // we are creating a shader called Phong
  shader->createShaderProgram("Phong");
  // now we are going to create empty shaders for Frag and Vert
  shader->attachShader("PhongVertex",ngl::ShaderType::VERTEX);
  shader->attachShader("PhongFragment",ngl::ShaderType::FRAGMENT);
  // attach the source
  shader->loadShaderSource("PhongVertex","shaders/PhongVertex.glsl");
  shader->loadShaderSource("PhongFragment","shaders/PhongFragment.glsl");
  // compile the shaders
  shader->compileShader("PhongVertex");
  shader->compileShader("PhongFragment");
  // add them to the program
  shader->attachShaderToProgram("Phong","PhongVertex");
  shader->attachShaderToProgram("Phong","PhongFragment");

  // now we have associated this data we can link the shader
  shader->linkProgramObject("Phong");
  // and make it active ready to load values
  (*shader)["Phong"]->use();
  shader->setUniform("Normalize",1);

  ngl::Vec4 lightPos(0.0f,0.0f,-2.0f,0.0f);
  shader->setUniform("light.position",lightPos);
  shader->setUniform("light.ambient",0.0f,0.0f,0.0f,1.0f);
  shader->setUniform("light.diffuse",1.0f,1.0f,1.0f,1.0f);
  shader->setUniform("light.specular",0.8f,0.8f,0.8f,1.0f);
  // gold like phong material
  shader->setUniform("material.ambient",0.274725f,0.1995f,0.0745f,0.0f);
  shader->setUniform("material.diffuse",0.75164f,0.60648f,0.22648f,0.0f);
  shader->setUniform("material.specular",0.628281f,0.555802f,0.3666065f,0.0f);
  shader->setUniform("material.shininess",51.2f);

  ngl::VAOPrimitives *prim=ngl::VAOPrimitives::instance();

  prim->createSphere("sphere",0.1f,10);
  m_emitter.reset(  new Emitter(ngl::Vec3(0,0,0),2000));
  m_text.reset( new ngl::Text(QFont("Arial",14)));
  m_text->setScreenSize(width(),height());
  // as re-size is not explicitly called we need to do this.
  glViewport(0,0,width(),height());
  m_fpsTimer =startTimer(0);
  m_timer.start();

}