ThirdPersonCamera::ThirdPersonCamera(void)
{
	this->distanceFromObject = 5;
	this->distanceOnY = 2;
	glm::vec3 cameraPosition(0, distanceOnY, distanceFromObject);
	Camera::Reset(cameraPosition, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
}
ThirdPersonCamera::ThirdPersonCamera(glm::vec3 objectPosition, float distanceFromObject, float cameraHeight) : Camera()
{
	this->distanceFromObject = distanceFromObject;
	this->distanceOnY = cameraHeight;
	glm::vec3 cameraPosition(0, cameraHeight, distanceFromObject);
	Camera::Reset(cameraPosition, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
}
Beispiel #3
0
void render( void )
{
	glClear( GL_COLOR_BUFFER_BIT );

	static float scale = 0.0f;

	scale += 0.1f;

	Matrix matrix;
	matrix.rotate( 0.0f , scale , 0.0f );
	matrix.worldPosition( 0.0f , 0.0f , 5.0f );

	math::Vec3f cameraPosition( 0.0f , 0.0f , -3.0f );
	math::Vec3f cameraTarget( 0.0f , 0.0f , 2.0f );
	math::Vec3f cameraUp( 0.0f , 1.0f , 0.0f );
	matrix.setCamera( cameraPosition , cameraTarget , cameraUp );
	matrix.perspeciveProjection( 60.0f , WINDOW_WIDTH , WINDOW_HEIGHT , 1.0f , 100.0f );


	glUniformMatrix4fv( worldLocation , 1 , GL_TRUE , ( const GLfloat* ) matrix.getTranslation() );

	glEnableVertexAttribArray( 0 );
		glBindBuffer( GL_ARRAY_BUFFER , vertexBufferID );
		glVertexAttribPointer( 0 , 3 , GL_FLOAT , GL_FALSE , 0 , 0 );
		glBindBuffer( GL_ELEMENT_ARRAY_BUFFER , indexBufferID );

		glDrawElements( GL_TRIANGLES , 12 , GL_UNSIGNED_INT , 0 );
	glDisableVertexAttribArray( 0 );

	glutSwapBuffers();
}
Beispiel #4
0
//
// Framework Functions
//
void UpdateCameraThirdPerson()
{
	D3DXMATRIX rotationMatrix;
	D3DXMatrixRotationY(&rotationMatrix, -avatarYaw);
	D3DXVECTOR3 transformedReference;
	D3DXVECTOR4 vec4;
	D3DXVec3Transform(&vec4, &thirdPersonReference, &rotationMatrix);
	transformedReference.x = vec4.x;
	transformedReference.y = vec4.y;
	transformedReference.z = vec4.z;

	D3DXVECTOR3 cameraPosition(transformedReference.z + AvatarPosition.x, transformedReference.y + transformedReference.y, transformedReference.x + transformedReference.z);

	D3DXVECTOR3 up(0,1,0);
	D3DXMatrixLookAtLH(&mview, &cameraPosition, &AvatarPosition, &up);


	//Device->SetTransform(D3DTS_VIEW, &mview);

	D3DXMatrixPerspectiveFovLH(&mprojection, D3DX_PI / 4, aspectRatio, 0.1f, 5001.0f);

	D3DXMATRIX myaw, mpos;
	D3DXMatrixRotationY(&mpos, avatarYaw);
	D3DXMatrixTranslation(&mpos, AvatarPosition.x, AvatarPosition.y, AvatarPosition.z);
	D3DXMatrixMultiply(&mworld, &myaw, &mpos);

	//Device->SetTransform(D3DTS_WORLD, &mworld);
}
Beispiel #5
0
int main()
{
	tw::vec3f position(1.0f, 0.0f, -2.0f);

	tw::vec3f axis(0.0f, 1.0f, 0.0f);
	float32_t angle = tw::radians(45.0f);

	tw::vec3f scale(1.0f, 1.0f, 1.0f);

	tw::mat4f translationMat = tw::translation(position);
	tw::quatf rotationQuat = tw::rotation(axis, angle);
	tw::mat4f scalingMat = tw::scaling(scale);

	tw::mat4f model = translationMat * tw::mat4_cast(rotationQuat) * scalingMat;

	tw::vec3f cameraPosition(0.0f, 0.0f, 1.0f);
	tw::vec3f cameraCenter(0.0f, 0.0f, 0.0f);
	tw::vec3f cameraUp(0.0f, 1.0f, 0.0f);
	tw::mat4f view = tw::lookAt(cameraPosition, cameraCenter, cameraUp);

	tw::mat4f mv = view * model;

	tw::vec4f p(1.0f, 0.0f, 0.0f, 1.0f);
	p = mv * p;

	std::cout << p.x << " " << p.y << " " << p.z << " " << p.w << std::endl;

	std::cin.get();
	return 0;
}
Beispiel #6
0
//Initialization function
void OsgMainApp::initOsgWindow(int x,int y,int width,int height){

    __android_log_write(ANDROID_LOG_ERROR, "OSGANDROID",
            "Initializing geometry");

    //Pending
    _notifyHandler = new OsgAndroidNotifyHandler();
    _notifyHandler->setTag("Osg Viewer");
    osg::setNotifyHandler(_notifyHandler);

    osg::notify(osg::ALWAYS)<<"Testing"<<std::endl;

    _viewer = new osgViewer::Viewer();
    _viewer->setUpViewerAsEmbeddedInWindow(x, y, width, height);

    _root = new osg::Group();

    _viewer->realize();

    _state = _root->getOrCreateStateSet();
    _state->setMode(GL_LIGHTING, osg::StateAttribute::ON);
    _state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
    _state->setMode(GL_CULL_FACE, osg::StateAttribute::ON);

    PaddleManip = new test::PaddleManipulator(_viewer->getCamera());
    loadDefaultScene();

    _viewer->setSceneData(_root.get());

    _viewer->addEventHandler(PaddleManip);
    _viewer->addEventHandler(new osgViewer::StatsHandler);
    _viewer->addEventHandler(new osgGA::StateSetManipulator(_viewer->getCamera()->getOrCreateStateSet()));
    _viewer->addEventHandler(new osgViewer::ThreadingHandler);
    _viewer->addEventHandler(new osgViewer::LODScaleHandler);

    _manipulator = new osgGA::KeySwitchMatrixManipulator;

//    _manipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
//    _manipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
//    _manipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
//    _manipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
//    _manipulator->addMatrixManipulator( '5', "Orbit", new osgGA::OrbitManipulator() );
//    _manipulator->addMatrixManipulator( '6', "FirstPerson", new osgGA::FirstPersonManipulator() );
//    _manipulator->addMatrixManipulator( '7', "Spherical", new osgGA::SphericalManipulator() );
//
//    _viewer->setCameraManipulator( _manipulator.get() );

    _viewer->getViewerStats()->collectStats("scene", true);

    _initialized = true;
    double cameraHeight = std::sin(osg::DegreesToRadians(20.0)) * 12.0;
    osg::Vec3d cameraPosition(0, cameraHeight, 0);
    osg::Vec3d center(0, 0, 12);
    osg::Vec3d cameraDirection = center - cameraPosition; //osg::Quat(osg::DegreesToRadians(20.0), osg::Vec3d(0, 0, 1)) * osg::Vec3d(0, 0, 1);
    cameraDirection.normalize();
    _viewer->getCamera()->setViewMatrixAsLookAt(cameraPosition, center, cameraDirection ^ osg::Vec3d(1, 0, 0));
//    _viewer->getCamera()->setProjectionMatrixAsFrustum(-5.0, 5.0, -5.0, 5.0, 1.0, 20.0);

}
Beispiel #7
0
void Mg3dScene::setCameraPosition(const QVector3D & pos)
{
	if(pos != cameraPosition())
	{
		camera()->setEye(pos);
		updateGLContent();
		Q_EMIT cameraPositionChanged(pos);
	}
}
Beispiel #8
0
void WindowGadget::onRender( RenderContext & context, const RectInt & window )
{
	GameDocument * pDoc = (GameDocument *)document();
	if ( pDoc != NULL && pDoc->gadgetTarget() != NULL )
	{
		NounGadget * pTarget = pDoc->gadgetTarget();

		// get the hull of the object
		float scale = 1.0f / pTarget->hull().radius();
		// calculate the view direction from the players ship
		Vector3 view( cos(m_ActiveTime),-1,sin(m_ActiveTime) );
		view.normalize();
		
		Matrix33 cameraFrame( view );
		cameraFrame = cameraFrame * pTarget->frame();
		Vector3 cameraPosition( view * 4.0f );

		// end previous scene
		context.endScene();

		RenderContext::SaveState state( context );
		// set up new render context
		context.setPosition( cameraPosition );
		context.setFrame( cameraFrame );
		context.setWindow( window );
		context.setTime( pDoc->tick() * TICK_DURATION_S );

		DisplayDevice * pDisplay = context.display();
		ASSERT( pDisplay );

		// increase the ambient light so that the object is clearly visible
		pDisplay->setAmbient( WHITE );
		// remove all lights from the render device
		pDisplay->clearLights();

		// disable lights
		NodeLight::sm_bDisable = true;
		NodeSound::sm_bDisable = true;
		NounGadget::sm_bRenderGadgets = true;

		// render the target object
		pTarget->render( context, Matrix33::IDENTITY, Vector3::ZERO );

		// enable lights
		NodeLight::sm_bDisable = false;
		NodeSound::sm_bDisable = false;
		NounGadget::sm_bRenderGadgets = false;

		context.endScene();

		// restore the ambient light
		pDisplay->setAmbient( UNIVERSE_AMBIENT );
	}
}
	bool Renderer::Initialize()
	{
		m_renderTarget = new GDIRenderTarget(m_hwnd,m_frameWidth,m_frameHeight);
		if(m_renderTarget == nullptr)
		{
			return false;
		}
		m_renderTarget->Initialize();

		Color* renderTargetBuffer = m_renderTarget->GetColorBuffer();
		int stride = m_renderTarget->GetWidth();

		m_rasterizer = new Rasterizer(renderTargetBuffer,stride);
		if(m_rasterizer == nullptr)
		{
			return false;
		}
	
		//camera data and initialization 
		Vector3D viewTarget(0.0f,0.0f,0.0f);
		Vector3D upDirection(0.0f,1.0f,0.0f); 
		Vector3D cameraPosition(0.5f,0.5f,1.5f);

		float fov = PI / 2.0f;
		float aspectRatio = 16.0f / 9.0f;
		float nearPlane = -0.1f;
		float farPlane = -1000.0f;

		m_camera = new Camera(cameraPosition,viewTarget,upDirection,fov,aspectRatio,nearPlane,farPlane,m_frameWidth,m_frameHeight);
		if(m_camera == nullptr)
		{
			return false;
		}
		m_camera->Initialize();
		m_viewTransMatrix = m_camera->ComputeViewTransformMatrix();

		m_importer = new ImporterOBJ("testScene.obj");
		if(m_importer == nullptr)
		{
			return false;
		}
		if(!m_importer->ProcessFile())
			return false;

		m_scene = m_importer->GetScene();

		m_HRTimer = new HRTimer();
		if(m_HRTimer == nullptr)
			return false;

		return true;
	}
Beispiel #10
0
void Audio3DTest::initialize()
{
    setMultiTouch(true);
    _font = Font::create("res/common/arial18.gpb");
    // Load game scene from file
    Bundle* bundle = Bundle::create("res/common/box.gpb");
    _scene = bundle->loadScene();
    SAFE_RELEASE(bundle);

    // Get light node
    Node* lightNode = _scene->findNode("directionalLight1");
    Light* light = lightNode->getLight();

    // Initialize box model
    Node* boxNode = _scene->findNode("box");
    Model* boxModel = boxNode->getModel();
    Material* boxMaterial = boxModel->setMaterial("res/common/box.material");
    boxMaterial->getParameter("u_lightColor")->setValue(light->getColor());
    boxMaterial->getParameter("u_lightDirection")->setValue(lightNode->getForwardVectorView());

    // Remove the cube from the scene but keep a reference to it.
    _cubeNode = boxNode;
    _cubeNode->addRef();
    _scene->removeNode(_cubeNode);

    loadGrid(_scene);

    // Initialize cameraa
    Vector3 cameraPosition(5, 5, 1);
    if (Camera* camera = _scene->getActiveCamera())
    {
        camera->getNode()->getTranslation(&cameraPosition);
    }

    _fpCamera.initialize();
    _fpCamera.setPosition(cameraPosition);
    _scene->addNode(_fpCamera.getRootNode());
    _scene->setActiveCamera(_fpCamera.getCamera());

    _gamepad = getGamepad(0);
    GP_ASSERT(_gamepad);
    _gamepad->getForm()->setConsumeInputEvents(false);
}
Beispiel #11
0
void MainLoop(CPlatform * const  pPlatform)
{	//update the main application
	CVec3df cameraPosition(0, 0.0f, -2.1f);
	pPlatform->Tick();	

	if(pPlatform->GetKeyboard().keys[KB_B].IsToggledPress())
	{
		brightness += 0.1f;
		if(brightness > 1.0)
			brightness = -1.0f;
		printf("brightness : %f", brightness);
	}
	if(pPlatform->GetKeyboard().keys[KB_G].IsToggledPress())
	{
		gamma += 0.2f;
		if(gamma > 4.0)
			gamma = 0.2f;
		printf("gamma : %f", gamma);
	}
	if(pPlatform->GetKeyboard().keys[KB_C].IsToggledPress())
	{
		contrast += 0.1f;
		if(contrast > 2.0)
			contrast = -1.0f;
		printf("contrast : %f", contrast);
	}
	

	//first pass to texture
	program[0].Start();
	WRender::SetClearColour(0.0,0,0,0);
	WRender::BindFrameBuffer(WRender::FrameBuffer::DRAW, fbo);
	WRender::SetupViewport(0, 0, WIDTH_HEIGHT, WIDTH_HEIGHT);
	WRender::ClearScreenBuffer(COLOR_BIT | DEPTH_BIT);
	WRender::EnableDepthTest(true);
	transform.Push();			
	{
		CMatrix44 rotLat,rotLong;
		rotLat.Rotate(latitude, 1, 0, 0);
		rotLong.Rotate(longitude, 0, 1, 0);

		transform.Translate(cameraPosition);
		transform.ApplyTransform(rotLat);
		transform.ApplyTransform(rotLong);			
			
		transform.Push();					
		{
			transforms.mvp = transforms.proj * transform.GetCurrentMatrix();
			WRender::UpdateBuffer(WRender::UNIFORM, WRender::DYNAMIC, ubo, sizeof(Transforms), (void*)&transforms, 0);				
			//Sphere
			WRender::BindVertexArrayObject(vaoSphere);
			WRender::DrawArray(WRender::TRIANGLES, nSphereVertices, 0);
		}
		transform.Pop();
	}
	transform.Pop();		
	WRender::UnbindFrameBuffer(WRender::FrameBuffer::DRAW);
	WRender::SetDrawBuffer(WRender::DB_BACK);

	//second pass
	//texture to screen
	WRender::SetClearColour(1.0,0,0,0);
	WRender::SetupViewport(0, 0, 640, 640);
	WRender::ClearScreenBuffer(COLOR_BIT | DEPTH_BIT);
	WRender::BindVertexArrayObject(sqVao);		
	program[1].Start();
	if(pPlatform->GetKeyboard().keys[KB_SPACE].IsPressed())
	{
		program[1].SetFloat("brightness", 0.0f);
		program[1].SetFloat("inverse_gamma", 1.0f);
		program[1].SetFloat("contrast",	1.0f);
	}
	else
	{
		program[1].SetFloat("brightness",brightness);
		program[1].SetFloat("inverse_gamma",1.0f/gamma);
		program[1].SetFloat("contrast",contrast);
	}
	//float tranR[3] = {0.0f, -1.0f, 0};	
	WRender::BindTexture(texR,WRender::Texture::UNIT_0);
	//program[1].SetVec3("translate",tranR);		
	WRender::Draw(WRender::TRIANGLE_STRIP, WRender::U_BYTE, sizeof(sqIndices)/sizeof(unsigned char), 0);

	pPlatform->UpdateBuffers();
	if(pPlatform->GetKeyboard().keys[KB_UP].IsPressed())
		latitude += 90.0f * pPlatform->GetDT();
	if(pPlatform->GetKeyboard().keys[KB_DOWN].IsPressed())
		latitude -= 90.0f * pPlatform->GetDT();
		
	if(pPlatform->GetKeyboard().keys[KB_LEFT].IsPressed())//l
		longitude += 90.0f * pPlatform->GetDT();
	if(pPlatform->GetKeyboard().keys[KB_RIGHT].IsPressed())//r
		longitude -= 90.0f * pPlatform->GetDT();
}
Beispiel #12
0
// Does all the rendering stuff
JNIEXPORT void JNICALL
Java_edu_ethz_s3d_S3DRenderer_renderFrame(JNIEnv *, jobject)
{
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);

    // Clear color and depth buffer 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Get the state from QCAR and mark the beginning of a rendering section
    QCAR::State state = QCAR::Renderer::getInstance().begin();
    
    // Explicitly render the Video Background
    QCAR::Renderer::getInstance().drawVideoBackground();
       
#ifdef USE_OPENGL_ES_1_1
    // Set GL11 flags:
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glEnable(GL_TEXTURE_2D);
    glDisable(GL_LIGHTING);
        
#endif

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    // TODO: Only work, when there is exactly one trackable
    // Did we find any trackables this frame?
    for(int tIdx = 0; tIdx < state.getNumActiveTrackables(); tIdx++)
    {
        // Get the trackable:
        const QCAR::Trackable* trackable = state.getActiveTrackable(tIdx);
        QCAR::Matrix44F modelViewMatrix = QCAR::Tool::convertPose2GLMatrix(trackable->getPose());

        // Choose the texture based on the target name:
        int textureIndex;
        if (strcmp(trackable->getName(), "chips") == 0)
        {
            textureIndex = 0;
        }
        else if (strcmp(trackable->getName(), "stones") == 0)
        {
            textureIndex = 1;
        }
        else
        {
            textureIndex = 2;
        }

        const Texture* const thisTexture = textures[textureIndex];

#ifdef USE_OPENGL_ES_1_1
        // Load projection matrix:
        glMatrixMode(GL_PROJECTION);
        glLoadMatrixf(projectionMatrix.data);

        // Load model view matrix:
        glMatrixMode(GL_MODELVIEW);
        glLoadMatrixf(modelViewMatrix.data);
        glTranslatef(0.f, 0.f, kObjectScale);
        glScalef(kObjectScale, kObjectScale, kObjectScale);

        // Draw object:
        glBindTexture(GL_TEXTURE_2D, thisTexture->mTextureID);
        glTexCoordPointer(2, GL_FLOAT, 0, (const GLvoid*) &teapotTexCoords[0]);
        glVertexPointer(3, GL_FLOAT, 0, (const GLvoid*) &teapotVertices[0]);
        glNormalPointer(GL_FLOAT, 0,  (const GLvoid*) &teapotNormals[0]);
        glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT,
                       (const GLvoid*) &teapotIndices[0]);
#else

        // Calculate the projection matrix
        QCAR::Matrix44F modelViewProjection;
        SampleUtils::translatePoseMatrix(0.0f, 0.0f, kObjectScale, &modelViewMatrix.data[0]);
        SampleUtils::scalePoseMatrix(kObjectScale, kObjectScale, kObjectScale, &modelViewMatrix.data[0]);
        SampleUtils::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0], &modelViewProjection.data[0]);

        // Calculate the camera position
        QCAR::Matrix44F inverseModelView = SampleMath::Matrix44FTranspose(SampleMath::Matrix44FInverse(modelViewMatrix));
        QCAR::Vec3F cameraPosition(inverseModelView.data[12], inverseModelView.data[13], inverseModelView.data[14]);

        // Select the shader program
        glUseProgram(shaderProgramID);

        // Load the vertex attributes
        glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotVertices[0]);
        glVertexAttribPointer(vertexColorHandle,3,GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &color[0]);
        glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotNormals[0]);

        // Enable the vertex attributes
        glEnableVertexAttribArray(vertexHandle);
        glEnableVertexAttribArray(normalHandle);
        glEnableVertexAttribArray(vertexColorHandle);
        
        // Load the reconstruction data
        if (reconstructionHandler != NULL) {
        	// First delete the old texture
        	glDeleteTextures(1, &texId);
        	// Load the reconstruction texture and its corresponding data
        	texId = reconstructionHandler->getTexture();
            float slices[2] = { reconstructionHandler->getOverX(), reconstructionHandler->getOVerY() };
            glUniform2fv(glGetUniformLocation(shaderProgramID, "slicesOver"), 1, (const GLfloat*) slices);
            glUniform1f(glGetUniformLocation(shaderProgramID, "numberOfSlices"), reconstructionHandler->getNSlices());
        }
        else {
        	// Load the texture specifications for the white texture
            float slices[2] = { 2.f, 1.f };
            glUniform2fv(glGetUniformLocation(shaderProgramID, "slicesOver"), 1, (const GLfloat*) slices);
            glUniform1f(glGetUniformLocation(shaderProgramID, "numberOfSlices"), 2);
        }

        // Load the eye position into the shader program
        glUniform3fv(glGetUniformLocation(shaderProgramID, "eyePos"), 1, (const GLfloat*) &cameraPosition.data[0]);

        // Load the texture into texture0 and set uVolData to 0 to load it
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texId);
        glUniform1i(glGetUniformLocation(shaderProgramID, "uVolData"), 0);

        // Load the projection matrix into its uniform
        glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE,
                           (GLfloat*)&modelViewProjection.data[0] );

        // Draw the cube
        glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT,
                       (const GLvoid*) &teapotIndices[0]);

        SampleUtils::checkGlError("ImageTargets renderFrame");
#endif

    }

    glDisable(GL_DEPTH_TEST);

#ifdef USE_OPENGL_ES_1_1        
    glDisable(GL_TEXTURE_2D);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
#else
    glDisableVertexAttribArray(vertexHandle);
    glDisableVertexAttribArray(normalHandle);
    glDisableVertexAttribArray(vertexColorHandle);
#endif

    QCAR::Renderer::getInstance().end();

    glDisable(GL_BLEND);
}
void updateScene(double currentTime, double deltaTime)
{

  float speed = user_avatar->getSpeed();  // speed of user_avatar
  float orientation = user_avatar->getOrientation();
  SbVec3f originalPosition = user_avatar->getPosition();  // save current user_avatar->position

  // UP KEY
  // user_avatar->speed: acceleration
  if(keyboard[KeyRec::UP].isDown)
  {
    if(speed < maxSpeed)
    {
      speed += (float)deltaTime*speedUp;
      if(speed>maxSpeed)
        speed = maxSpeed;
    }
  }else
  {
    if(speed > 0)
    {
      speed -= (float)deltaTime*slowDown;
      if(speed<0)
        speed = 0;
    }
  }

  // KEY DOWN
    // user_avatar->speed: braking
  if(keyboard[KeyRec::DOWN].isDown)
  {
    if(speed > minSpeed)
    {
      speed -= (float)deltaTime*speedUp;
      if(speed < minSpeed)
        speed = minSpeed;
    }
  }else
  {
    if(speed < 0)
    {
      speed += (float)deltaTime*slowDown;
      if(speed > 0)
        speed = 0;
    }
  }

  // KEY LEFT
  // rotation speed: turn left
  if(keyboard[KeyRec::LEFT].isDown)
  {
    user_avatar->rotationSpeed += (float)deltaTime*rotSpeedUp;
    if(user_avatar->rotationSpeed > maxRotSpeed)
      user_avatar->rotationSpeed = maxRotSpeed;
  }else
  {
    if(user_avatar->rotationSpeed > 0)
    {
      user_avatar->rotationSpeed -= (float)deltaTime*rotSlowDown;
      if(user_avatar->rotationSpeed < 0)
        user_avatar->rotationSpeed = 0;
    }
  }

  // KEY RIGHT
  // rotation speed: turn right
  if(keyboard[KeyRec::RIGHT].isDown)
  {
    user_avatar->rotationSpeed -= (float)deltaTime*rotSpeedUp;
    if(user_avatar->rotationSpeed < minRotSpeed)
      user_avatar->rotationSpeed = minRotSpeed;
  }else
  {
    if(user_avatar->rotationSpeed < 0)
    {
      user_avatar->rotationSpeed += (float)deltaTime*rotSlowDown;
      if(user_avatar->rotationSpeed > 0)
        user_avatar->rotationSpeed = 0;
    }
  }

  // user_avatar->orientation
  // note: negative values must be used when going back
  if(speed >= 0)
    orientation += (float)deltaTime*user_avatar->rotationSpeed;
  else
    orientation -= (float)deltaTime*user_avatar->rotationSpeed;

  // set new user_avatar->orientation
  user_avatar->setOrientation(orientation);


  // set new user_avatar->position
  float distance = speed*(float)deltaTime;
  SbVec3f pos = user_avatar->getPosition();
  SbVec3f distanceVec(distance*sinf(orientation), 0.f, distance*cosf(orientation));
  pos -= distanceVec;
  user_avatar->setPosition(pos);

  STOP_AT_BORDER( pos , speed );
  user_avatar->direction = user_avatar->getPosition() - originalPosition;
  BCAST_POSITION( deltaTime );


  if(!gui::free_camera)
    {

      // 3rd person camera
      float tilt = -.20f;          // camera tilt (in radians)
      float cameraDistance = 15;   // initial camera distance from the user_avatar
      float cameraHeight = 8.0f;  // camera height from the user_avatar

      SbRotation cameraOrientation, cameraTilt;
      cameraOrientation.setValue(SbVec3f(0, 1, 0), orientation);
      cameraTilt.setValue(SbVec3f(1, 0, 0), tilt);
      camera->orientation = cameraTilt*cameraOrientation;

      if(speed < 0)
	{
	  cameraDistance = 18.0f-speed*0.44f;  // camera distance increases when going back
	}

      SbVec3f cameraPosition(user_avatar->getPosition());
      cameraPosition += SbVec3f(cameraDistance*sinf(orientation),
				cameraHeight, cameraDistance*cosf(orientation));
      camera->position.setValue(cameraPosition);
    }

}
Beispiel #14
0
	void SpellSystem::affect(Entity& entity)
	{
		Spell*	spell;

		if ((spell = dynamic_cast<Spell*>(entity[ecs::AComponent::ComponentType::SPELL])) != nullptr)
		{
			Spell::SpellType	spellType = spell->getSpellType();
			if (spellType == lastSpellType)
				return;
			GraphicUtil&	graphics = GraphicUtil::getInstance();
			ecs::Position cameraPosition(graphics.getSceneManager()->getActiveCamera()->getAbsolutePosition(),
										graphics.getSceneManager()->getActiveCamera()->getTarget());
			if (spellType == Spell::SpellType::NOTHING)
			{
				switch (lastSpellType)
				{
				case ecs::Spell::BLIND:
					graphics.getBlindFx()->hide();
					break;
				case ecs::Spell::PARANOIA:
					PlayerManager::getInstance().loadNormalTeamTexture();
					break;
				case ecs::Spell::CONFUSION:
					graphics.getFPSCamera()->loadDefaultKeys();
					break;
				case ecs::Spell::DEAF:
					Audio::getInstance().setIsDeaf(false);
					break;
				case ecs::Spell::PARKINSON:
					Target::getInstance().setIsTrembling(false);
					break;
				case ecs::Spell::SLOW:
					graphics.getFPSCamera()->setSpeed(0.5f, 100.0f);
					break;
				default:
					break;
				}
			}
			else
			{
				switch (spellType)
				{
				case ecs::Spell::BLIND:
					GraphicUtil::getInstance().getBlindFx()->display();
					break;
				case ecs::Spell::PARANOIA:
					PlayerManager::getInstance().loadInvertTeamTexture();
					break;
				case ecs::Spell::CONFUSION:
					graphics.getFPSCamera()->loadInvertKeys();
					break;
				case ecs::Spell::DEAF:
					Audio::getInstance().setIsDeaf(true);
					break;
				case ecs::Spell::PARKINSON:
					Target::getInstance().setIsTrembling(true);
					break;
				case ecs::Spell::SLOW:
					graphics.getFPSCamera()->setSpeed(0.1f, 50.0f);
					break;
				default:
					break;
				}
			}
			lastSpellType = spellType;
		}
	}
Beispiel #15
0
void Renderer::paintGL()
{
	if (!_shaderProgram)
	{
		glClearColor(0.5, 0.25, 0.4, _background.alphaF());
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		return;
	}

	emit reportSignal(MInfo, "Rendering frame");
	glClearColor(_background.redF(), _background.greenF(), _background.blueF(), _background.alphaF());
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// for each object that was split or loaded separately
	QMatrix4x4 modelMatrix = CreateMatrix(_desc[PositionModel]);
	QMatrix4x4 cameraMatrix = CreateMatrix(_desc[PositionCamera]);
	QMatrix4x4 perspectiveMatrix;
	float ratio = size().width() / (float)size().height();
	perspectiveMatrix.setToIdentity();
	perspectiveMatrix.perspective(90, ratio, .5f, 10000.0f);
	QMatrix4x4 mvp = perspectiveMatrix * cameraMatrix * modelMatrix;

	auto test1 = mvp*QVector3D(0, 0, 0);
	auto test2 = mvp*QVector3D(0, 0, 0.5);
	///////////////////////////////////////
	/////////// setting uniform values
	///////////////////////////////////////
	_shaderProgram->setUniformValue("modelToCamera", mvp);
	_shaderProgram->setUniformValue("viewMatrix", cameraMatrix);
	_shaderProgram->setUniformValue("modelMatrix", modelMatrix);
	QVector3D cameraPosition(_desc[PositionCamera]._xPos, _desc[PositionCamera]._yPos, _desc[PositionCamera]._zPos);
	_shaderProgram->setUniformValue("cameraPosition", cameraPosition);
	//const float * df = _mesh.Diffuse();
	//_shaderProgram->setUniformValue("MaterialDiffuseColor", QVector3D(df[0],df[1],df[2]) );
	// set 
	QVector3D lightPos(_desc[PositionLight]._xPos, _desc[PositionLight]._yPos, _desc[PositionLight]._zPos);
	_shaderProgram->setUniformValue("LightPosition_worldspace", lightPos);
	
	///////////////////////////////////////
	/////////// setting arrays
	///////////////////////////////////////

	// take vertex array from opengl context
	_shaderProgram->enableAttributeArray(VERTEX_LOCATION);
	_shaderProgram->enableAttributeArray(NORMAL_LOCATION);
	_shaderProgram->enableAttributeArray(BARYCENTRIC_LOCATION);

	_shaderProgram->setAttributeBuffer(VERTEX_LOCATION, GL_FLOAT, 3*VERTEX_LOCATION * sizeof(GLfloat), 3, 3 * NEntries * sizeof(GLfloat));

	_shaderProgram->setAttributeBuffer(NORMAL_LOCATION, GL_FLOAT, 3*NORMAL_LOCATION * sizeof(GLfloat), 3, 3 * NEntries * sizeof(GLfloat));

	_shaderProgram->setAttributeBuffer(BARYCENTRIC_LOCATION, GL_FLOAT, 3*BARYCENTRIC_LOCATION * sizeof(GLfloat), 3, 3 * NEntries * sizeof(GLfloat));

	_shaderProgram->setUniformValue("wireframe", 0);
	///////////////////////////////////////
	/////////// Actual drawing
	///////////////////////////////////////
	switch (_renderStyle)
	{
	case RenderPoints:
	{
		int size = 0;
		for (int i = 0; i < _renderData.size(); i++)
		{
			size += _renderData[i]._mesh.NVertices();
		}
		glDrawArrays(GL_POINTS, 0, size );
		break;
	}
	case RenderWireframe:
	{
		_shaderProgram->setUniformValue("wireframe", 1);
		//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		glDrawElements(GL_TRIANGLES, _indices, GL_UNSIGNED_INT, 0);
		break;
	}
	default:
	{
		auto test = glGetString(GL_VERSION);
		glDrawElements(GL_TRIANGLES, _indices, GL_UNSIGNED_INT, 0);
		break;
	}
	}

	//for (int i = 0; i < total; ++i) {
	//	//textures[i]->bind();
	//	glDrawArrays(GL_TRIANGLE_STRIP, i * 3, 3);
	//}
}
Beispiel #16
0
void MainLoop(CPlatform * const  pPlatform)
{	//update the main application
	CVec3df cameraPosition( 0.0f, 0.0f, distance );

	pPlatform->Tick();	
	WRender::ClearScreenBuffer(COLOR_BIT | DEPTH_BIT);
	WRender::EnableDepthTest(true);

	WRender::ActiveTexture(WRender::Texture::UNIT_0);
	WRender::BindTexture(cubemap_tex);

	transform.Push();			
	{
		CMatrix44 rotLat,rotLong,inverse_camera, model_matrix;

		rotLat.Rotate(latitude, 1, 0, 0);
		rotLong.Rotate(longitude, 0, 1, 0);

		transform.Translate(cameraPosition);
		transform.ApplyTransform(rotLat);
		transform.ApplyTransform(rotLong);			
		
		transform.Push();					
		{
			transform.Scale(10.0f,10.0f,10.0f);
			transforms.mv = transform.GetCurrentMatrix();
			transforms.mvp = transforms.proj * transforms.mv;
			CMatrix33 normal;

			normal = transforms.mv;
			normal = normal.Invert();
			normal = normal.Transpose();			
			transforms.nrm[ 0] = normal.x.x;			transforms.nrm[ 1] = normal.x.y;			transforms.nrm[ 2] = normal.x.z;
			transforms.nrm[ 4] = normal.y.x;			transforms.nrm[ 5] = normal.y.y;			transforms.nrm[ 6] = normal.y.z;
			transforms.nrm[ 8] = normal.z.x;			transforms.nrm[ 9] = normal.z.y;			transforms.nrm[10] = normal.z.z;

			WRender::UpdateBuffer(WRender::UNIFORM, WRender::DYNAMIC, ubo, sizeof(Transforms), (void*)&transforms, 0);				
			WRender::EnableCulling(true);
			WRender::CullMode(WRender::FRONT_FACE);
			program_cube.Start();			
			DrawShape(box);
		}
		transform.Pop();


		transform.Push();					
		{
			transform.Translate(0.0f, 0, 0);
			transforms.mv = transform.GetCurrentMatrix();
			transforms.mvp = transforms.proj * transforms.mv;
			CMatrix33 normal;

			normal = transforms.mv;
			normal = normal.Invert();
			normal = normal.Transpose();			
			transforms.nrm[ 0] = normal.x.x;			transforms.nrm[ 1] = normal.x.y;			transforms.nrm[ 2] = normal.x.z;
			transforms.nrm[ 4] = normal.y.x;			transforms.nrm[ 5] = normal.y.y;			transforms.nrm[ 6] = normal.y.z;
			transforms.nrm[ 8] = normal.z.x;			transforms.nrm[ 9] = normal.z.y;			transforms.nrm[10] = normal.z.z;

			WRender::UpdateBuffer(WRender::UNIFORM, WRender::DYNAMIC, ubo, sizeof(Transforms), (void*)&transforms, 0);				
			WRender::EnableCulling(true);			
			WRender::CullMode(WRender::BACK_FACE);
			program_cube.Start();
			DrawShape(sphere);
		}
		transform.Pop();		
		
	}
	transform.Pop();		

	pPlatform->UpdateBuffers();
	if (pPlatform->GetKeyboard().keys[KB_LEFTSHIFT].IsPressed()){
		if(pPlatform->GetKeyboard().keys[KB_UP].IsPressed())
			distance += 1.0f * pPlatform->GetDT();
		if(pPlatform->GetKeyboard().keys[KB_DOWN].IsPressed())
			distance -= 1.0f * pPlatform->GetDT();
	}else{
		if(pPlatform->GetKeyboard().keys[KB_UP].IsPressed())
			latitude += 90.0f * pPlatform->GetDT();
		if(pPlatform->GetKeyboard().keys[KB_DOWN].IsPressed())
			latitude -= 90.0f * pPlatform->GetDT();
		
		if(pPlatform->GetKeyboard().keys[KB_LEFT].IsPressed())//l
			longitude += 90.0f * pPlatform->GetDT();
		if(pPlatform->GetKeyboard().keys[KB_RIGHT].IsPressed())//r
			longitude -= 90.0f * pPlatform->GetDT();
	}
}
Beispiel #17
0
void Setup(CPlatform * const  pPlatform)
{
	float vertices[3] = {0,0,0};
	WRender::RenderBuffer::SDescriptor rboDesc = {WRender::RenderBuffer::RGBA8, WIDTH_HEIGHT, WIDTH_HEIGHT, 0};

	const char* pV = 0;
	const char* pF = 0;
	
	glswInit();
	glswSetPath("../resources/", ".glsl");

	//setup the textures
	WRender::Texture::SDescriptor desc = {WRender::Texture::TEX_2D, WRender::Texture::RGB8, WIDTH_HEIGHT, WIDTH_HEIGHT, 0, 0, WRender::Texture::DONT_GEN_MIPMAP};
	WRender::Texture::SDescriptor descDepth = {WRender::Texture::TEX_2D, WRender::Texture::DEPTH_COMPONENT, WIDTH_HEIGHT, WIDTH_HEIGHT, 0, 0, WRender::Texture::DONT_GEN_MIPMAP};
	
	WRender::Texture::SParam param[] ={	
		{ WRender::Texture::MIN_FILTER, WRender::Texture::LINEAR},
		{ WRender::Texture::MAG_FILTER, WRender::Texture::LINEAR},
		{ WRender::Texture::WRAP_S, WRender::Texture::REPEAT},
		{ WRender::Texture::WRAP_T, WRender::Texture::REPEAT},
	};

	WRender::CreateBaseTexture(texR, desc);
	WRender::CreateBaseTexture(texG, desc);
	WRender::CreateBaseTexture(texB, desc);
	WRender::CreateBaseTexture(texD, descDepth);

	WRender::SetTextureParams(texR,param,4);
	WRender::SetTextureParams(texG,param,4);
	WRender::SetTextureParams(texB,param,4);
	WRender::SetTextureParams(texD,param,4);

	//Setup Render Buffer
	WRender::CreateRenderBuffer(rbo,rboDesc);

	//setup Frame Buffer
	WRender::CreateFrameBuffer(fbo);
	WRender::AddTextureRenderBuffer(fbo, texR, WRender::ATT_CLR0, 0);	
	//WRender::AddTextureRenderBuffer(fbo, texG, WRender::ATT_CLR1, 0);
	WRender::AddTextureRenderBuffer(fbo, texB, WRender::ATT_CLR2, 0);
	WRender::AddRenderBuffer(fbo, rbo, WRender::ATT_CLR3);
	WRender::AddTextureRenderBuffer(fbo, texD, WRender::ATT_DEPTH, 0); //FOR DEPTH INDEX DOESN'T MATTER
	WRender::CheckFrameBuffer(fbo);

	//setup blitting FBO
	WRender::CreateFrameBuffer(fboForBlitting);
	WRender::AddTextureRenderBuffer(fboForBlitting, texG, WRender::ATT_CLR0, 0);
	WRender::CheckFrameBuffer(fboForBlitting);

	//setup shaders	
	pV = glswGetShaders("shaders.Version+shaders.MRT.Stage1.Vertex");
	pF = glswGetShaders("shaders.Version+shaders.MRT_2.Stage1.Fragment");
	CShader vertexShader(CShader::VERT, &pV, 1);
	CShader fragmentShader(CShader::FRAG, &pF, 1);

	pV = glswGetShaders("shaders.Version+shaders.MRT.Stage2.Vertex");
	pF = glswGetShaders("shaders.Version+shaders.MRT.Stage2.Fragment");
	CShader vertexShaderStage2(CShader::VERT, &pV, 1);
	CShader fragmentShaderStage2(CShader::FRAG, &pF, 1);

	program[0].Initialise();
	program[0].AddShader(&vertexShader);
	program[0].AddShader(&fragmentShader);
	program[0].Link();

	program[1].Initialise();
	program[1].AddShader(&vertexShaderStage2);
	program[1].AddShader(&fragmentShaderStage2);
	program[1].Link();
	//quickly set the uniforms
	program[1].Start();
	program[1].SetTextureUnit("mrt",0);
	program[1].Stop();

	// setup vertex buffers etc	
	//axis 
	vao = WRender::CreateVertexArrayObject();
	ab = WRender::CreateBuffer(WRender::ARRAY, WRender::STATIC, sizeof(vertices), vertices);
	
	WRender::BindVertexArrayObject(vao);
	WRender::VertexAttribute va[1] = {
		{ab, 0, 3, WRender::FLOAT, 0, sizeof(float)*3, 0, 0},				//vertices
	};
	WRender::SetAttributeFormat( va, 1, 0);
	WRender::UnbindVertexArrayObject();//needed

	//square
	sqVao = WRender::CreateVertexArrayObject();	
	sqEab = WRender::CreateBuffer(WRender::ELEMENTS, WRender::STATIC, sizeof(sqIndices), sqIndices);
	sqAb = WRender::CreateBuffer(WRender::ARRAY, WRender::STATIC, sizeof(sqVertices), sqVertices);
	WRender::BindVertexArrayObject(sqVao);
	WRender::BindBuffer(WRender::ELEMENTS, sqEab);
	WRender::VertexAttribute sqVa[2] = {
		{sqAb, 0, 3, WRender::FLOAT, 0, sizeof(float)*5, 0, 0},				//vertices
		{sqAb, 1, 2, WRender::FLOAT, 0, sizeof(float)*5, sizeof(float)*3, 0},	//texture coordinates
	};
	WRender::SetAttributeFormat( sqVa, 2, 0);
	WRender::UnbindVertexArrayObject();

	//variables for camera 
	float latitude = 0.0f, longitude = 0.0f;
	CVec3df cameraPosition(0, 0.0f, -3.0f);	
	Transforms transforms;
	Transform::CreateProjectionMatrix(transforms.proj, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 10.0f);	//for rendering first time aorund
	WRender::EnableDepthTest(true);
}
Beispiel #18
0
int main()
{
    initCrashSystem();
    initMemorySystem();

    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window *window = SDL_CreateWindow("",
                                          SDL_WINDOWPOS_UNDEFINED,
                                          SDL_WINDOWPOS_UNDEFINED,
                                          640,
                                          640,
                                           SDL_WINDOW_OPENGL
                                          |SDL_WINDOW_RESIZABLE
                                          |SDL_WINDOW_SHOWN);

    SDL_GLContext context = createContext(window);

    SDL_GL_SetSwapInterval(1);

    bool running = true;
    float frametime = 0.0f;

    Renderer *renderer = NEW(Renderer, NEW(GLBackend));
    ResourceManager *resMgr = renderer->getResourceManager();
    Scene *scene = NEW(Scene, renderer);
    Scene *quadScene = NEW(Scene, renderer);

    RenderTarget *target = NEW(RenderTarget, renderer);

    RenderTarget *textureTarget = NEW(RenderTarget, renderer);
    Framebuffer *framebuffer = textureTarget->addFramebuffer();
    framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBAU8_Norm_InternalFormat);
    framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::Red32F_InternalFormat);
    framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBU8_Norm_InternalFormat);
    framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBAU8_Norm_InternalFormat);
    framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBU8_Norm_InternalFormat);
    framebuffer->addColor(resMgr->createTexture(Texture::Texture2D), Texture::RGBU8_Norm_InternalFormat);
    framebuffer->finish();

    ResPtr<Model> model = resMgr->load("res/models/dragon.json").cast<Model>();


    ResPtr<Mesh> quadMesh = resMgr->createMesh(resMgr->load("res/shaders/quad vertex.json").cast<Shader>(), Mesh::Triangles, 6);
    VertexBuffer *quadVB = quadMesh->addPositions(renderer, MeshComponent(2, MeshComponent::Float32))->getVertexBuffer();

    quadVB->alloc(sizeof(glm::vec2)*6);
    glm::vec2 *quadPositions = (glm::vec2 *)quadVB->map(false, true);
    quadPositions[0] = glm::vec2(-1.0f, -1.0f);
    quadPositions[1] = glm::vec2( 1.0f, -1.0f);
    quadPositions[2] = glm::vec2(-1.0f,  1.0f);
    quadPositions[3] = glm::vec2(-1.0f,  1.0f);
    quadPositions[4] = glm::vec2( 1.0f, -1.0f);
    quadPositions[5] = glm::vec2( 1.0f,  1.0f);
    quadVB->unmap();


    ResPtr<Material> quadMaterial = resMgr->createMaterial(
    resMgr->load("res/shaders/quad fragment.json").cast<Shader>());
    quadMaterial->mUniforms["colorTexture"] = framebuffer->getColorTexture(0);
    quadMaterial->mUniforms["depthTexture"] = framebuffer->getColorTexture(1);
    quadMaterial->mUniforms["normalTexture"] = framebuffer->getColorTexture(2);
    quadMaterial->mUniforms["materialTexture"] = framebuffer->getColorTexture(3);
    quadMaterial->mUniforms["ambientTexture"] = framebuffer->getColorTexture(4);
    quadMaterial->mUniforms["specularTexture"] = framebuffer->getColorTexture(5);
    quadMaterial->mUniforms["lightDirection"] = glm::vec3(0.0f);


    ResPtr<Model> quadModel = resMgr->createModel();
    quadModel->mLODs.push_back(LOD(quadMesh, quadMaterial, 0.0f));
    quadModel->sortLODs();

    quadScene->createEntity(quadModel);


    scene->mSkyboxTexture = resMgr->load("res/textures/enviroment texture.json").cast<Texture>();


    Entity *entity = scene->createEntity(model);

    float t = 0.0f;

    bool fullscreen = false;

    glm::vec3 cameraPosition(0.0f, 0.0f, 5.0f);
    glm::vec2 cameraAngle(3.1415f, 0.0f);
    float cameraSpeed = 3.0f;
    float cameraRotateSpeed = 1.0f;

    while (running)
    {
        Uint64 start = SDL_GetPerformanceCounter();

        SDL_Event event;

        while (SDL_PollEvent(&event))
        {
            switch (event.type)
            {
                case SDL_QUIT:
                {
                    running = false;
                    break;
                }
                case SDL_KEYDOWN:
                {
                    switch (event.key.keysym.scancode)
                    {
                        case SDL_SCANCODE_ESCAPE:
                        {
                            running = false;
                            break;
                        }
                        case SDL_SCANCODE_F1:
                        {
                            fullscreen = not fullscreen;

                            SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP*fullscreen);
                        }
                        default: {}
                    }
                }
            }
        }

        const Uint8 *pressed = SDL_GetKeyboardState(NULL);

        glm::vec3 direction(std::cos(cameraAngle.y) * std::sin(cameraAngle.x),
                            std::sin(cameraAngle.y),
                            std::cos(cameraAngle.y) * std::cos(cameraAngle.x));

        glm::vec3 right(std::sin(cameraAngle.x - 3.1415f / 2.0f),
                        0.0f,
                        std::cos(cameraAngle.x - 3.1415f / 2.0f));

        glm::vec3 up = glm::cross(right, direction);

        if (pressed[SDL_SCANCODE_LEFT])
        {
            cameraAngle.x += cameraRotateSpeed * frametime;
        } else if (pressed[SDL_SCANCODE_RIGHT])
        {
            cameraAngle.x -= cameraRotateSpeed * frametime;
        } else if (pressed[SDL_SCANCODE_UP])
        {
            cameraAngle.y += cameraRotateSpeed * frametime;
        } else if (pressed[SDL_SCANCODE_DOWN])
        {
            cameraAngle.y -= cameraRotateSpeed * frametime;
        } else if (pressed[SDL_SCANCODE_A])
        {
            cameraPosition -= right * frametime * cameraSpeed;
        } else if (pressed[SDL_SCANCODE_D])
        {
            cameraPosition += right * frametime * cameraSpeed;
        } else if (pressed[SDL_SCANCODE_W])
        {
            cameraPosition += direction * frametime * cameraSpeed;
        } else if (pressed[SDL_SCANCODE_S])
        {
            cameraPosition -= direction * frametime * cameraSpeed;
        }

        scene->mProjectionTransform.reset();

        int windowWidth;
        int windowHeight;
        SDL_GetWindowSize(window, &windowWidth, &windowHeight);
        target->setWidthAndHeight(windowWidth, windowHeight);
        textureTarget->setWidthAndHeight(windowWidth, windowHeight);

        scene->mProjectionTransform.perspective(45.0f, float(windowWidth)/float(windowHeight), 0.1f, 100.0f);

        scene->mViewTransform.reset();
        scene->mViewTransform.lookAt(cameraPosition,
                                     cameraPosition+direction,
                                     up);

        t += frametime;

        entity->mTransform.reset();
        entity->mTransform.scale(glm::vec3(0.5f));

        entity->mTransform.rotate(45.0f*t, glm::vec3(0.0f, 1.0f, 0.0f));

        renderer->render(textureTarget, scene);

        quadMaterial->mUniforms["lightDirection"]
        = glm::mat3(scene->mViewTransform.getMatrix()) * glm::vec3(-1.0f, 1.0f, -1.0f);

        renderer->render(target, quadScene);

        SDL_GL_SwapWindow(window);

        resMgr->deleteUnusedResources();

        Uint64 end = SDL_GetPerformanceCounter();

        frametime = float(end - start) / float(SDL_GetPerformanceFrequency());

        char title[256];
        std::memset(title, 0, 256);
        std::snprintf(title, 256, "Frametime: %.4f, Framerate: %.0f", frametime, 1.0f/frametime);
        SDL_SetWindowTitle(window, title);
    }

    model = nullRes<Model>();
    quadMesh = nullRes<Mesh>();
    quadMaterial = nullRes<Material>();
    quadModel = nullRes<Model>();

    DELETE(RenderTarget, textureTarget);
    DELETE(RenderTarget, target);

    DELETE(Scene, quadScene);
    DELETE(Scene, scene);

    DELETE(Renderer, renderer);

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);

    SDL_Quit();

    deinitMemorySystem();

    return 0;
}
Beispiel #19
0
	void ParticleRenderer::render(const mat4& modelView, std::vector<Particle*>& particles) {
		shader->enable();
		applyModelView(modelView);
		glm::vec3 cameraPosition(glm::inverse(modelView)[3]);

		const unsigned int particlesAmount = particles.size();
		unsigned int offset = 0;

		for (unsigned int i = 0; i < particlesAmount; i++) {
			Particle* p = particles[i];
			const vec3& position = p->getPosition();
			p->setDistanceToCamera(glm::length2(position - cameraPosition));
		}

		std::sort(particles.begin(), particles.end());

		for (unsigned int i = 0; i < particlesAmount; i++) {
			Particle *p = particles[i];
			const vec3& position = p->getPosition();
			const vec4& color = p->getColor();
			const vec4& uv = p->getUV();
			const GLuint tid = p->getTexture();

			float ts = 0.0f;
			if (tid > 0)
			{
				bool found = false;
				for (unsigned int i = 0; i < textureSlots.size(); i++)
				{
					if (textureSlots[i] == tid)
					{
						ts = (float)(i + 1);
						found = true;
						break;
					}
				}

				if (!found)
				{
					if (textureSlots.size() >= PARTICLE_MAX_TEXTURES)
					{
						flush(offset, i);
						offset = i;
					}
					textureSlots.push_back(tid);
					ts = (float)(textureSlots.size());
				}
			}

			positionData[4 * i + 0] = position.x;
			positionData[4 * i + 1] = position.y;
			positionData[4 * i + 2] = position.z;

			positionData[4 * i + 3] = p->getSize();

			colorData[4 * i + 0] = color.x;
			colorData[4 * i + 1] = color.y;
			colorData[4 * i + 2] = color.z;
			colorData[4 * i + 3] = color.w;

			uvData[4 * i + 0] = uv.x;
			uvData[4 * i + 1] = uv.y;
			uvData[4 * i + 2] = uv.z;
			uvData[4 * i + 3] = uv.w;

			textureData[i] = ts;
		}

		flush(offset, particlesAmount);
		shader->disable();
	}
Beispiel #20
0
void ViewEngineering::onRender( RenderContext & context, const RectInt & window )
{
	GameDocument * pDoc = (GameDocument *)document();
	if ( pDoc == NULL )
		return;

	UniverseContext * pContext = pDoc->context();
	ASSERT( pContext );
	NounShip * pShip = pDoc->ship();
	ASSERT( pShip );

	// get the time elapsed
	float t = context.elapsed();
	// calculate the distance from the ship based upon it's radius
	float cameraDistance = pShip->radius() * 2.5f;
	// calculate the camera frame and position
	Matrix33 cameraFrame( pShip->frame() );
	cameraFrame.rotate( PI / 4, ViewGame::s_CameraTime * (PI / 4), 0 );
	Vector3	cameraPosition( pShip->worldPosition() - (cameraFrame.k * cameraDistance) );

	if ( ViewGame::s_CameraTime < CAMERA_SNAP_TIME )
	{
		// if ship is moving, keep it from jumping around while the camera is animating
		if ( m_Adjust )
		{
			Vector3 position( pShip->worldPosition() );
			Vector3 adjust( position - m_AdjustPosition );
			m_AdjustPosition = position;

			ViewGame::s_CameraPosition += adjust;
		}
		else
		{
			m_AdjustPosition = pShip->worldPosition();
			m_Adjust = true;
		}

		float d = ViewGame::s_CameraTime / CAMERA_SNAP_TIME;
		// move the camera
		Vector3 deltaPosition( cameraPosition - ViewGame::s_CameraPosition );
		ViewGame::s_CameraPosition += deltaPosition * d;

		// update the camera frame
		ViewGame::s_CameraFrame.i += (cameraFrame.i - ViewGame::s_CameraFrame.i) * d;
		ViewGame::s_CameraFrame.j += (cameraFrame.j - ViewGame::s_CameraFrame.j) * d;
		ViewGame::s_CameraFrame.k += (cameraFrame.k - ViewGame::s_CameraFrame.k) * d;
		ViewGame::s_CameraFrame.orthoNormalizeXY();
	}
	else
	{
		// animation is over, snap directly to the desired frame/position
		ViewGame::s_CameraFrame = cameraFrame;
		ViewGame::s_CameraPosition = cameraPosition;
		m_Adjust = false;
	}

	m_UpdateStatus += t;
	if ( m_UpdateStatus > 1.0f )
	{
		m_UpdateStatus = 0.0f;

		// update the ship status
		String shipStatus;
		shipStatus += String().format("Hull:<X;75;Color;ff00ffff>%d%%</Color>\n", int(pShip->damageRatioInv() * 100) );
		shipStatus += String().format("Energy:<X;75;Color;ff00ffff>%d / %d</Color>\n", pShip->energy(), pShip->maxEnergy() );
		shipStatus += String().format("Velocity:<X;75;Color;ff00ffff>%.1f / %.1f</Color>\n", pShip->velocity(), pShip->maxVelocity() );
		shipStatus += String().format("Signature:<X;75;Color;ff00ffff>%.1f</Color>\n", pShip->signature() );

		shipStatus += "\nSYSTEMS:\n";

		// display armor status
		for(int i=0;i<pShip->childCount();i++)
			if ( WidgetCast<GadgetArmor>( pShip->child(i) ) )
			{
				GadgetArmor * pArmor = (GadgetArmor *)pShip->child(i);
				shipStatus += String().format("%s<X;100>%d%%\n", 
					pArmor->nounContext()->name(), 
					(pArmor->armor() * 100 ) / pArmor->strength() );
			}
		// display shield status
		for(i=0;i<pShip->childCount();i++)
			if ( WidgetCast<GadgetShield>( pShip->child(i) ) )
			{
				GadgetShield * pShield = (GadgetShield *)pShip->child(i);
				shipStatus += String().format("%s<X;100>%d%%\n", 
					pShield->nounContext()->name(), 
					(pShield->charge() * 100 ) / pShield->maxCharge() );
			}

		for(i=0;i<pShip->childCount();i++)
			if ( WidgetCast<NounGadget>( pShip->child(i) ) )
			{
				NounGadget * pGadget = (NounGadget *)pShip->child(i);
				if ( WidgetCast<GadgetArmor>( pGadget ) )
					continue;
				if ( WidgetCast<GadgetShield>( pGadget ) )
					continue;
				
				shipStatus += String().format("%s<X;100>%d%%\n", 
					pGadget->nounContext()->name(), 
					int( pGadget->damageRatioInv() * 100 ) );
			}

		m_pShipStatus->setText( shipStatus );
	}
	
	if ( m_pLayoutRepair->visible() )
	{
		for(int i=0;i<pShip->repairCount();i++)
			GetButton<ButtonGadget>( m_pRepairQueue, i )->setGadget( pShip->repair( i ) );

		// remove excess buttons
		m_pRepairQueue->cullChildren( pShip->repairCount() );
	}

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

	// update the active zone
	pContext->setActiveZone( ViewGame::s_CameraPosition );

	// create our render context
	RenderContext engineeringContext( context );
	engineeringContext.setPosition( ViewGame::s_CameraPosition );
	engineeringContext.setFrame(  ViewGame::s_CameraFrame );
	engineeringContext.setTime( pContext->tick() * TICK_DURATION_S );

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

	// render the universe
	pContext->render( engineeringContext, 
		~ViewGame::s_CameraFrame, ViewGame::s_CameraFrame * (-ViewGame::s_CameraPosition) );
}
void render(GLFWwindow* window)
{
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);

    inputHandling(window);

    /********** Section camera view **********/

    glm::vec3 cameraPosition(0,2,7);

    glm::vec4 cameraPositionTransformed =
            glm::rotate(glm::mat4(1.0f), angleX, glm::vec3(0,1,0)) *
            glm::rotate(glm::mat4(1.0f), angleY, glm::vec3(1,0,0))* glm::vec4(cameraPosition, 1.0f);

    cameraPosition = glm::vec3(XYZ(cameraPositionTransformed));

    // come from http://www.opengl-tutorial.org/fr/beginners-tutorials/tutorial-3-matrices/

	glm::mat4 Projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 50.0f);

     // Camera matrix
     glm::mat4 ViewCamera = glm::lookAt(
                    cameraPosition, // Camera is at (4,3,3), in World Space
                    glm::vec3(0,0,0), // and looks at the origin
                    glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                    );


     glm::mat4 Model = glm::mat4(1.0f);


     glm::mat4 mvpCamera = Projection * ViewCamera * Model; // Remember, matrix multiplication is the other way around

     //glProgramUniformMatrix4fv(gs.programView, 23, 1, GL_FALSE, &mvpCamera[0][0]);



    /********** Section lumière **********/

    glm::vec3 lightPosition(0, 5.f, 15.f);

    glm::vec4 lightPositionTransformed =
            glm::rotate(glm::mat4(1.0f), anglePhiLight, glm::vec3(0,1,0)) *
            glm::rotate(glm::mat4(1.0f), angleTetaLight, glm::vec3(1,0,0)) * glm::vec4(lightPosition,1.0f);

    /*** calcul du mvp de la caméra lumière (déplacement de la lumière donc calcule ici) ***/

    lightPosition = glm::vec3(XYZ(lightPositionTransformed));

	Projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 50.0f);

    // Light Camera matrix
    glm::mat4 ViewLightCamera = glm::lookAt(
                   lightPosition, // Camera is at (4,3,3), in World Space
                   glm::vec3(0,0,0), // and looks at the origin
                   glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                   );

    // Our ModelViewProjection : multiplication of our 3 matrices
    glm::mat4 mvpLightCamera = Projection * ViewLightCamera * Model; // Remember, matrix multiplication is the other way around

    //glProgramUniformMatrix4fv(gs.programView, 22, 1, GL_FALSE, &mvpLightCamera[0][0]);



	float color[3] = { 0, 1, 0 };

	glProgramUniform3fv(gs.programView, 3, 1, color);
	glProgramUniform3fv(gs.programView, 4, 1, glm::value_ptr(lightPosition));


    
    glBindFramebuffer(GL_FRAMEBUFFER, gs.fbo);
	glViewport(0, 0, width, height);

	glClear(GL_COLOR_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

	glUseProgram(gs.programView);
	glBindVertexArray(gs.vao);

    {
		glProgramUniformMatrix4fv(gs.programView, 22, 1, GL_FALSE, &mvpLightCamera[0][0]);
		glProgramUniformMatrix4fv(gs.programView, 23, 1, GL_FALSE, &mvpLightCamera[0][0]);

		glProgramUniform3fv(gs.programView, 3, 1, color);
		glProgramUniform3fv(gs.programView, 4, 1, glm::value_ptr(lightPosition));

        glDrawArrays(GL_TRIANGLES, 0, nbVertex*4);
    }
	//glBindFramebuffer(GL_FRAMEBUFFER, 0);
    //glBindVertexArray(0);
    //glUseProgram(0);




    
	
    
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glViewport(0, 0, width, height);

	glClear(GL_COLOR_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

    //glUseProgram(gs.programView);
    //glBindVertexArray(gs.vao);
    {
		glProgramUniformMatrix4fv(gs.programView, 23, 1, GL_FALSE, &mvpCamera[0][0]);
		glProgramUniformMatrix4fv(gs.programView, 22, 1, GL_FALSE, &mvpLightCamera[0][0]);

		glProgramUniform3fv(gs.programView, 3, 1, color);
		glProgramUniform3fv(gs.programView, 4, 1, glm::value_ptr(lightPosition));

        glDrawArrays(GL_TRIANGLES, 0, nbVertex*4);
    }

    glBindVertexArray(0);
    glUseProgram(0);

}
Beispiel #22
0
int main(int argc, char* argv[])
{
	Graphics::WindowConfig wc;
	wc.width = 1280;
	wc.height = 720;
	wc.resizable = false;
	wc.mode = Graphics::WindowMode::WINDOW;

	Graphics::ContextConfig cc;
	cc.msaaSamples = 4;
	cc.debugContext = true;
	cc.glewExperimental = true;
	cc.coreProfileContext = true;
#ifdef _DEBUG
	cc.synchronousDebugOutput = true;
#else
	cc.synchronousDebugOutput = false;
#endif

	Graphics::RenderingSystem renderingSystem;

	if (!renderingSystem.Init(wc, cc))
	{
		fprintf(stderr, "Error while initializing renderingsystem.\n");
		return 1;
	}

	auto deferredShader = renderingSystem.CreateShaderProgram(
		Graphics::ShaderInfo::VSFS("shaders/deferred.vs", "shaders/deferred.fs", "shaders/")
		);

	auto deferredLightShader = renderingSystem.CreateShaderProgram(
		Graphics::ShaderInfo::VSFS("shaders/deferredlight.vs", "shaders/deferredlight.fs", "shaders/")
		);

	auto copyShader = renderingSystem.CreateShaderProgram(
		Graphics::ShaderInfo::VSFS("shaders/copy.vs", "shaders/copy.fs", "shaders/")
		);

	// Full-screen quad
	auto quadVertexBuffer = renderingSystem.CreateBuffer();
	renderingSystem.UpdateBuffer(quadVertexBuffer, MeshUtils::quadVertices.data(), MeshUtils::quadVertices.size() * sizeof(float), Graphics::BufferType::STATIC);

	// Postprocessing
	PostProcess_SSAO ssaoPP;
	ssaoPP.Init(renderingSystem, quadVertexBuffer);

	// Rendertargets
	auto gBufferRT = renderingSystem.CreateRenderTarget(Graphics::RenderTargetOptions::SRGB8DepthRGB8(wc.width, wc.height));
	auto tempRT = renderingSystem.CreateRenderTarget(Graphics::RenderTargetOptions::SRGB8Depth(wc.width, wc.height));

	// For per-frame shader data
	PerFrameUBO perFrameUBO;
	perFrameUBO.nearPlane = 0.1f;
	perFrameUBO.farPlane = 100.0f;
	perFrameUBO.proj = glm::perspective(45.0f, wc.width / (float)wc.height, perFrameUBO.nearPlane, perFrameUBO.farPlane);
	perFrameUBO.flags = PerFrameUBO::Flags::NormalMapping | PerFrameUBO::Flags::ParallaxMapping;

	auto perFrameUBOHandle = renderingSystem.CreateBuffer();
	renderingSystem.UpdateBuffer(perFrameUBOHandle, NULL, sizeof(perFrameUBO), Graphics::BufferType::DYNAMIC);
	renderingSystem.BindUniformBuffer(Constants::PER_FRAME_UBO_BINDING_INDEX, perFrameUBOHandle);

	// Used for per-drawcall shader data 
	auto perDrawUBOHandle = renderingSystem.CreateBuffer();
	renderingSystem.UpdateBuffer(perDrawUBOHandle, NULL, sizeof(DrawUBO), Graphics::BufferType::DYNAMIC);
	renderingSystem.BindUniformBuffer(Constants::PER_DRAW_UBO_BINDING_INDEX, perDrawUBOHandle);

	// Animates the lights and updates uniform buffer with lightdata
	LightManager<10> lightManager;
	lightManager.Init(renderingSystem);

	// To avoid having to load all textures at startup
	TextureLoader textureLoader;

	// Load the scene.
	// This can take a while for big scenes, so it'll poll the window to keep it responsive.
	std::vector<Renderable> renderables;
	if (!GetRenderables(dataFolder, textureLoader, renderingSystem, renderables /*out*/))
	{
		return 0;
	}

	// Used for culling
	std::vector<bool> isCulled;
	FrustumCuller<Renderable> frustumCuller;

	glm::vec3 cameraPosition(0, 2, 0);
	glm::quat cameraOrientation;

	uint8_t ssaoState = 1;
	const std::array<const char*, 3> ssaoText = {{ "Off", "On", "Occlusion only" }};

	bool parallaxMappingEnabled = true;
	bool normalMappingEnabled = true;

	int frames = 0;
	double timeAccum = 0.0;
	double lastTime = 0.0;

	while (!renderingSystem.CloseRequested())
	{
		double time = renderingSystem.GetTime();
		double dt = time - lastTime;
		lastTime = time;
		timeAccum += dt;

		// Sort renderables by material (could only be done once since it's not dynamic)
		std::sort(renderables.begin(), renderables.end(), [](const Renderable& a, const Renderable& b)
		{
			return a.GetMaterial() < b.GetMaterial();
		});

		// Update movement
		glm::vec3 movement(0, 0, 0);
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::W)) movement.z -= 1.0f;
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::S)) movement.z += 1.0f;
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::A)) movement.x -= 1.0f;
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::D)) movement.x += 1.0f;
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::Q)) movement.y -= 1.0f;
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::E)) movement.y += 1.0f;

		float movementScale = 3.0f;
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::SHIFT))
			movementScale *= 4.0f;

		if (glm::length(movement) > 0)
			movement = glm::normalize(movement) * movementScale * float(dt);

		cameraPosition += movement * cameraOrientation;

		// Mouse look
		static glm::vec2 lastCursor = renderingSystem.GetCursorPosition();
		auto cursor = renderingSystem.GetCursorPosition();
		glm::vec2 diff = lastCursor - cursor;
		lastCursor = cursor;

		if (renderingSystem.IsMouseButtonDown(Graphics::RenderingSystem::MouseButton::Right))
		{
			renderingSystem.SetCursorEnabled(false);
			diff *= 0.1f;
			cameraOrientation = cameraOrientation * glm::rotate(glm::quat(), -diff.x, glm::vec3(0, 1, 0)); // Yaw
			cameraOrientation = glm::rotate(glm::quat(), -diff.y, glm::vec3(1, 0, 0)) * cameraOrientation; // Pitch
		}
		else renderingSystem.SetCursorEnabled(true);

		// Update per-frame UBO
		perFrameUBO.view = glm::toMat4(cameraOrientation) * glm::translate(glm::mat4(1.0f), -cameraPosition);
		perFrameUBO.cameraPosition = glm::vec4(cameraPosition, 1.0);
		perFrameUBO.time = time;
		perFrameUBO.flags = 0;

		if (parallaxMappingEnabled)
			perFrameUBO.flags |= PerFrameUBO::Flags::ParallaxMapping;

		if(normalMappingEnabled)
			perFrameUBO.flags |= PerFrameUBO::Flags::NormalMapping;

		if (ssaoState == 2)
			perFrameUBO.flags |= PerFrameUBO::Flags::SSAOState;

		renderingSystem.UpdateBuffer(perFrameUBOHandle, &perFrameUBO, sizeof(perFrameUBO), Graphics::BufferType::DYNAMIC);

		// Update lights
		lightManager.Update(time, cameraPosition);

		// Do frustum-culling
		frustumCuller.Cull(renderables, isCulled, perFrameUBO.proj * perFrameUBO.view);
#if 1
		// Draw to G-buffer
		{
			// Bind G-buffer
			renderingSystem.BindRenderTarget(gBufferRT);

			// Clear it
			renderingSystem.ClearScreen(Graphics::ClearState::AllBuffers());

			// Prepare to fill it
			renderingSystem.UseShaderProgram(deferredShader);
			renderingSystem.BindUniformBuffer(Constants::PER_FRAME_UBO_BINDING_INDEX, perFrameUBOHandle);
			renderingSystem.BindUniformBuffer(Constants::PER_DRAW_UBO_BINDING_INDEX, perDrawUBOHandle);

			// Draw objects
			DrawRenderables(renderingSystem, renderables, isCulled, perDrawUBOHandle);
		}

		// Do lighting to temporary rendertarget (all lights in one pass -- extremly wasteful; 
		// would really want to cull and then draw individual bounding spheres/quads or similar).
		{
			// Prepare G-buffer textures
			renderingSystem.BindRenderTargetTexture(0, gBufferRT, Graphics::RenderTargetTexture::Color);
			renderingSystem.BindRenderTargetTexture(1, gBufferRT, Graphics::RenderTargetTexture::Depth);
			renderingSystem.BindRenderTargetTexture(2, gBufferRT, Graphics::RenderTargetTexture::Aux);

			// Prepare target RT
			renderingSystem.BindRenderTarget(tempRT);
			renderingSystem.ClearScreen(Graphics::ClearState::AllBuffers());

			// Draw fullscreen quad
			renderingSystem.UseShaderProgram(deferredLightShader);
			renderingSystem.Draw(quadVertexBuffer, Graphics::BufferHandle::Invalid(), 6);

			// Bind tempRT's color texture
			renderingSystem.BindRenderTargetTexture(0, tempRT, Graphics::RenderTargetTexture::Color);
		}

		// Bind default framebuffer
		renderingSystem.BindRenderTarget(Graphics::DefaultRenderTarget());
		renderingSystem.ClearScreen(Graphics::ClearState::AllBuffers());

		// Bind depth- and normal-textures for postprocessing (color is from lighting pass)
		renderingSystem.BindRenderTargetTexture(1, gBufferRT, Graphics::RenderTargetTexture::Depth);
		renderingSystem.BindRenderTargetTexture(2, gBufferRT, Graphics::RenderTargetTexture::Aux); // Normals

		if (ssaoState > 0)
			ssaoPP.Run(Graphics::DefaultRenderTarget());
		else
		{
			renderingSystem.UseShaderProgram(copyShader);
			renderingSystem.Draw(quadVertexBuffer, Graphics::BufferHandle::Invalid(), 6);
		}
#endif
		renderingSystem.SubmitFrame();
		++frames;

		// Print FPS
		if (timeAccum > 1.0)
		{
			printf("FPS: %f\n", frames / timeAccum);
			frames = 0;
			timeAccum = 0.0;
		}

		textureLoader.LoadOne(renderingSystem, dataFolder);

		// Poll window-events
		renderingSystem.PollEvents();

		// Enable/Disable features
		if (renderingSystem.WasPressed(Graphics::RenderingSystem::Key::F1))
		{
			ssaoState = (ssaoState + 1) % 3;
			printf("SSAO: %s\n", ssaoText[ssaoState]);
		}

		if (renderingSystem.WasPressed(Graphics::RenderingSystem::Key::F2))
		{
			normalMappingEnabled = !normalMappingEnabled;
			printf("Normal-mapping: %s\n", normalMappingEnabled ? "ON" : "OFF");
		}

		if (renderingSystem.WasPressed(Graphics::RenderingSystem::Key::F3))
		{
			parallaxMappingEnabled = !parallaxMappingEnabled;
			printf("Parallax-mapping: %s\n", parallaxMappingEnabled ? "ON" : "OFF");
		}

		// Hot reload of shaders
		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::SPACE))
			renderingSystem.ReloadShaders();

		if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::ESCAPE))
			break;
	}

	renderingSystem.Shutdown();

	return 0;
}
void SDLContext::renderScene( GridModel* model, KinectTool* _tool_mesh, 
							glm::mat4& view, glm::mat4& obj, TextureMappedFont* font1, 
							TextureMappedFont* font2, TextureMappedFont* font3)
{
	
	float side = inp->GetModelSide();

	float ratio  = float(SCREEN_WIDTH) / float(SCREEN_HEIGHT);

	sceneView = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, -0.5f, -4.0f));
	sceneView = glm::rotate(sceneView, sceneRot, glm::vec3(0.0f, 1.0f, 0.0f));
	sceneView = glm::translate(sceneView, -headTracking->GetHeadPosition());

	//sceneView = glm::lookAt(headTracking->GetHeadPosition() + glm::vec3(0.0f, 0.2f, 4.0f), headTracking->GetHeadPosition(), glm::vec3(0.0f, 1.0f, 0.0f)); 
	//sceneView = glm::rotate(sceneView, sceneRot, glm::vec3(0.0f, 1.0f, 0.0f));

	headTracking->RetrieveMatrices(inp->GetObjectPosition(), leftProj, leftEye, rightProj, rightEye);

	glm::vec3 cameraPosition (0.0f, 0.0f, depth*side);
	
	glm::mat4 cameraView = glm::translate(glm::mat4(1.0f), cameraPosition);

#ifndef STEREO
	render->Draw(model, _tool_mesh, cameraView, obj, font1, font2, font3, leftProj, 0);
	
	if (showScene) {
		glViewport(SCREEN_WIDTH/2 - SCENE_PREVIW_SIZE/2,SCREEN_HEIGHT - SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE);
		
		glEnable(GL_SCISSOR_TEST); 
		glScissor(SCREEN_WIDTH/2 - SCENE_PREVIW_SIZE/2,SCREEN_HEIGHT - SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE);

		render->Draw(model, _tool_mesh, sceneView, obj, font1, font2, font3, sceneProj, 3);

		glDisable(GL_SCISSOR_TEST); 

		glViewport(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
	}

	SDL_GL_SwapWindow(window);

#else
	// STEREO
	render->Draw(model, _tool_mesh, leftEye*cameraView, obj, font1, font2, font3, leftProj, 0);
	
	if (showScene) {
		glm::mat4 leftSceneView = glm::translate(glm::mat4(1.0f), glm::vec3(-0.065f/2.0f, 0.0f, 0.0f));

		glViewport(SCREEN_WIDTH/2 - SCENE_PREVIW_SIZE/2,SCREEN_HEIGHT - SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE);
		
		glEnable(GL_SCISSOR_TEST); 
		glScissor(SCREEN_WIDTH/2 - SCENE_PREVIW_SIZE/2,SCREEN_HEIGHT - SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE);

		render->Draw(model, _tool_mesh, leftSceneView*sceneView, obj, font1, font2, font3, sceneProj, 3);

		glDisable(GL_SCISSOR_TEST); 

		glViewport(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
	}

	SDL_GL_SwapWindow(window);

	SDL_GL_MakeCurrent(windowRight, context);

	render->Draw( model, _tool_mesh, rightEye*cameraView, obj, font1, font2 , font3, rightProj, 1);

	if (showScene) {
		glm::mat4 rightSceneView = glm::translate(glm::mat4(1.0f), glm::vec3(0.065f/2.0f, 0.0f, 0.0f));

		glViewport(SCREEN_WIDTH/2 - SCENE_PREVIW_SIZE/2,SCREEN_HEIGHT - SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE);

		glEnable(GL_SCISSOR_TEST); 
		glScissor(SCREEN_WIDTH/2 - SCENE_PREVIW_SIZE/2,SCREEN_HEIGHT - SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE,SCENE_PREVIW_SIZE);

		render->Draw(model, _tool_mesh, rightSceneView*sceneView, obj, font1, font2, font3, sceneProj, 3);
		
		glDisable(GL_SCISSOR_TEST); 

		glViewport(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
	}

	SDL_GL_SwapWindow(windowRight);
#endif

	if (shadowRendering) {
		SDL_GL_MakeCurrent(windowShadow, context);

		glViewport(0,0,800,600);

		render->Draw( model, _tool_mesh, shadowView, obj, font1, font2 , font3, shadowProj, -1);

		SDL_GL_SwapWindow(windowShadow);

		glViewport(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
	}
	
	SDL_GL_MakeCurrent(window, context);

	// FPS Control
	int tick = SDL_GetTicks();
	int deltaTick = tick - lastTick;
	float frameTime = ((float) deltaTick)/1000.0f;
	FPS = FPS*0.9f + (1.0f/frameTime)*0.1f;
	lastTick = tick;

	if (tick - lastFPSTick > FPSPeriod) {
		//std::cout << "FPS: " << FPS << std::endl;
		lastFPSTick = tick;
	}

	sceneRot += sceneRotSpeed*frameTime;

	depth = depth*(speed - frameTime)/speed + wantedDepth*frameTime/speed;
}
void CameraManager::SetupPerspectiveModelView() {

	// select the view matrix
	glMatrixMode(GL_MODELVIEW);
	// set it to '1'
	glLoadIdentity();

	// our values represent the angles in degrees, but 3D 
	// math typically demands angular values are in radians.
	float pitch = m_cameraPitch * RADIANS_PER_DEGREE;
	float yaw = m_cameraYaw * RADIANS_PER_DEGREE;

	// create a quaternion defining the angular rotation 
	// around the up vector
	btQuaternion rotation(m_upVector, yaw);

	// set the camera's position to 0,0,0, then move the 'z' 
	// position to the current value of m_cameraDistance.
	btVector3 cameraPosition(0, 0, 0);
	//cameraPosition[2] = -m_cameraDistance;
	cameraPosition[2] = m_cameraDistance;

	// Translation
	m_cameraTarget[0] = m_cameraPosX;
	m_cameraTarget[1] = m_cameraPosY;

	// create a Bullet Vector3 to represent the camera 
	// position and scale it up if its value is too small.
	btVector3 forward(cameraPosition[0], cameraPosition[1], cameraPosition[2]);
	if (forward.length2() < SIMD_EPSILON) {
		forward.setValue(1.f, 0.f, 0.f);
	}

	// figure out the 'right' vector by using the cross 
	// product on the 'forward' and 'up' vectors
	btVector3 right = m_upVector.cross(forward);

	// create a quaternion that represents the camera's roll
	btQuaternion roll(right, -pitch);

	// turn the rotation (around the Y-axis) and roll (around 
	// the forward axis) into transformation matrices and 
	// apply them to the camera position. This gives us the 
	// final position
	cameraPosition = btMatrix3x3(rotation) * btMatrix3x3(roll) * cameraPosition;

	// save our new position in the member variable, and 
	// shift it relative to the target position (so that we 
	// orbit it)
	m_cameraPosition[0] = cameraPosition.getX();
	m_cameraPosition[1] = cameraPosition.getY();
	m_cameraPosition[2] = cameraPosition.getZ();
	m_cameraPosition += m_cameraTarget;

	// create a view matrix based on the camera's position and where it's
	// looking
	//printf("Camera Position = %f, %f, %f\n", cameraPosition[0], cameraPosition[1], cameraPosition[2]);
	// the view matrix is now set
	gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], m_cameraTarget[0], m_cameraTarget[1], m_cameraTarget[2], m_upVector.getX(), m_upVector.getY(), m_upVector.getZ());

}
btVector3	GL_DialogDynamicsWorld::getRayTo(int x,int y)
{
	float cameraDistance = m_screenHeight/2.f;//m_screenWidth/2;//1.f;
	btVector3 cameraTargetPosition(0,0,0);
	btVector3 cameraUp(0,-1,0);

	if (1)//_ortho)
	{

		btScalar aspect;
		btVector3 extents;
		if (m_screenWidth> m_screenHeight) 
		{
			
			aspect = m_screenWidth / (btScalar)m_screenHeight;
			extents.setValue(aspect * 1.0f, 1.0f,0);
		} else 
		{
			cameraDistance = m_screenWidth/2.f;
			aspect = m_screenHeight / (btScalar)m_screenWidth;
			extents.setValue(1.0f, aspect*1.f,0);
		}
		
	

		extents *= cameraDistance;
		btVector3 lower = cameraTargetPosition - extents;
		btVector3 upper = cameraTargetPosition + extents;

		btScalar u = x / btScalar(m_screenWidth);
		btScalar v = (m_screenHeight - y) / btScalar(m_screenHeight);
		
		btVector3	p(0,0,0);
		p.setValue(
			(1.0f - u) * lower.getX() + u * upper.getX(),
			-((1.0f - v) * lower.getY() + v * upper.getY()),
			cameraTargetPosition.getZ());
		return p;
	}

	float top = 1.f;
	float bottom = -1.f;
	float nearPlane = 1.f;
	float tanFov = (top-bottom)*0.5f / nearPlane;
	float fov = 2 * atanf (tanFov);

	btVector3 cameraPosition(0,0,-100);
	btVector3	rayFrom = cameraPosition;
	btVector3 rayForward = (cameraTargetPosition-cameraPosition);
	rayForward.normalize();
	float farPlane = 10000.f;
	rayForward*= farPlane;

	btVector3 rightOffset;
	btVector3 vertical = cameraUp;

	btVector3 hor;
	hor = rayForward.cross(vertical);
	hor.normalize();
	vertical = hor.cross(rayForward);
	vertical.normalize();

	float tanfov = tanf(0.5f*fov);


	hor *= 2.f * farPlane * tanfov;
	vertical *= 2.f * farPlane * tanfov;

	btScalar aspect;
	
	if (m_screenWidth > m_screenHeight) 
	{
		aspect = m_screenWidth / (btScalar)m_screenHeight;
		
		hor*=aspect;
	} else 
	{
		aspect = m_screenHeight / (btScalar)m_screenWidth;
		vertical*=aspect;
	}


	btVector3 rayToCenter = rayFrom + rayForward;
	btVector3 dHor = hor * 1.f/float(m_screenWidth);
	btVector3 dVert = vertical * 1.f/float(m_screenHeight);


	btVector3 rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical;
	rayTo += btScalar(x) * dHor;
	rayTo -= btScalar(y) * dVert;
	//rayTo += y * dVert;

	return rayTo;
}
void BulletOpenGLApplication::UpdateCamera() {
	// exit in erroneous situations
	if (m_screenWidth == 0 && m_screenHeight == 0)
		return;
	
	// select the projection matrix
	glMatrixMode(GL_PROJECTION);
	// set it to the matrix-equivalent of 1
	glLoadIdentity();
	// determine the aspect ratio of the screen
	float aspectRatio = m_screenWidth / (float)m_screenHeight;
	// create a viewing frustum based on the aspect ratio and the
	// boundaries of the camera
	glFrustum (-aspectRatio * m_nearPlane, aspectRatio * m_nearPlane, -m_nearPlane, m_nearPlane, m_nearPlane, m_farPlane);
	// the projection matrix is now set

	// select the view matrix
	glMatrixMode(GL_MODELVIEW);
	// set it to '1'
	glLoadIdentity();

	// our values represent the angles in degrees, but 3D 
	// math typically demands angular values are in radians.
	float pitch = m_cameraPitch * RADIANS_PER_DEGREE;
	float yaw = m_cameraYaw * RADIANS_PER_DEGREE;

	// create a quaternion defining the angular rotation 
	// around the up vector
	btQuaternion rotation(m_upVector, yaw);

	// set the camera's position to 0,0,0, then move the 'z' 
	// position to the current value of m_cameraDistance.
	btVector3 cameraPosition(0,0,0);
	cameraPosition[2] = -m_cameraDistance;

	// create a Bullet Vector3 to represent the camera 
	// position and scale it up if its value is too small.
	btVector3 forward(cameraPosition[0], cameraPosition[1], cameraPosition[2]);
	if (forward.length2() < SIMD_EPSILON) {
		forward.setValue(1.f,0.f,0.f);
	}

	// figure out the 'right' vector by using the cross 
	// product on the 'forward' and 'up' vectors
	btVector3 right = m_upVector.cross(forward);

	// create a quaternion that represents the camera's roll
	btQuaternion roll(right, - pitch);

	// turn the rotation (around the Y-axis) and roll (around 
	// the forward axis) into transformation matrices and 
	// apply them to the camera position. This gives us the 
	// final position
	cameraPosition = btMatrix3x3(rotation) * btMatrix3x3(roll) * cameraPosition;

	// save our new position in the member variable, and 
	// shift it relative to the target position (so that we 
	// orbit it)
	m_cameraPosition[0] = cameraPosition.getX();
	m_cameraPosition[1] = cameraPosition.getY();
	m_cameraPosition[2] = cameraPosition.getZ();
	m_cameraPosition += m_cameraTarget;

	// create a view matrix based on the camera's position and where it's
	// looking
	gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], m_cameraTarget[0], m_cameraTarget[1], m_cameraTarget[2], m_upVector.getX(), m_upVector.getY(), m_upVector.getZ());
	// the view matrix is now set
}