Exemplo n.º 1
0
/**
* CActor::setPosition
* @date Modified Mar 07, 2006
*/
void CActor::setOrientation(D3DXVECTOR3 &vOrient)
{
	// make sure the length of the orientation is about one
	float fLength= D3DXVec3Dot(&vOrient, &vOrient);
	if(fLength > 1.02f || fLength < 0.98f)
	{
		// normalize the orientation vector
		fLength = fastSqrtf(fLength);
		fLength = 1.0f/fLength;
		vOrient *= fLength;
	}

	// find the new right axis of the matrix with the current up vector
	D3DXVECTOR3 vRight(m_ActorMatrix._21/m_vScale.x, m_ActorMatrix._22/m_vScale.y, m_ActorMatrix._23/m_vScale.z);
	D3DXVec3Cross(&vRight, &vRight, &vOrient);
	D3DXVec3Normalize(NULL, &vRight, &vRight);

	// set the matrix with the scale back in it
	m_ActorMatrix._11 = vRight.x*m_vScale.x;
	m_ActorMatrix._12 = vRight.y*m_vScale.y;
	m_ActorMatrix._13 = vRight.z*m_vScale.z;

	m_ActorMatrix._31 = vOrient.x*m_vScale.x;
	m_ActorMatrix._32 = vOrient.y*m_vScale.y;
	m_ActorMatrix._33 = vOrient.z*m_vScale.z;
}
Exemplo n.º 2
0
void M2EffectRender::UpdateParicles()
{

	if (!ParticleData_.gpEffect10) return;

	//if (fElapsedTime > 0.1f) fElapsedTime = 0.1f;

	D3DXVECTOR3 vEye;
	GetCamera()->getFrom(vEye);
	D3DXMATRIX mView;
	memcpy(&mView, GetCamera()->getViewMatrix(), SIZE16);	
		
	D3DXVECTOR3 vRight( mView._13, mView._23, mView._33 );
	D3DXVECTOR3 vUp( mView._12, mView._22, mView._32 );
	D3DXVECTOR3 vFoward( mView._11, mView._21, mView._31 );

	

	D3DXVec3Normalize( &vRight, &vRight );
	D3DXVec3Normalize( &vUp, &vUp );
	D3DXVec3Normalize( &vFoward, &vFoward );

	//gpvRight->SetFloatVector( ( float* )&vRight );
	//gpvUp->SetFloatVector( ( float* )&vUp );
	//gpvForward->SetFloatVector( ( float* )&vFoward );
	ParticleData_.gpvEyePt->SetFloatVector( ( float* )&vEye );

	ParticleVertex* pVerts = NULL;

	M2ParticleSystem* ps ;
	for (size_t i=0; i < Owner_->header.nParticleEmitters; ++i)
	{
		ps = &Owner_->particleSystems[i];
		ID3D11Resource* pRes = ParticleData_.ParticleBuffers.at(i);
		D3D11_MAPPED_SUBRESOURCE Data;

		HRESULT hr = GetApp()->GetContext()->Map( pRes, 0, D3D11_MAP_WRITE_DISCARD, 0, &Data );	

		if (FAILED(hr))
			assert(false);

		pVerts = (ParticleVertex*)Data.pData;	


		CopyParticlesToVertexBuffer(i, ps, pVerts, vEye, -vFoward, vUp );

		GetApp()->GetContext()->Unmap(pRes, 0);
	}

}
Exemplo n.º 3
0
void M2EffectRender::CopyRibbonsToVertexBuffer( int index, M2RibbonEmitter& Ribbon, RibbonVertex* pVB )
{
	
	noVec3 vRight(0,0,-1);
	noVec3 vUp(0,1,0);

	UINT iVBIndex = 0;

	uint32 gNumActiveParticles  = 0;	
			
	for (size_t i=0; i< 1 ; i++) 
	{
		std::list<M2RibbonSegment>::iterator it = Ribbon.segs.begin();
		float l = 0;
		for (; it != Ribbon.segs.end(); ++it) {
			float u = l/Ribbon.length;
						

			pVB[iVBIndex].pos = it->pos + Ribbon.tabove * it->up;
			pVB[iVBIndex].uv = noVec2(u, 0);
			pVB[iVBIndex].color = Ribbon.tcolor;

			pVB[++iVBIndex].pos = it->pos - Ribbon.tbelow * it->up;
			pVB[iVBIndex].uv = noVec2(u,1);
			pVB[iVBIndex].color = Ribbon.tcolor;

			++iVBIndex;
			gNumActiveParticles ++;
			l += it->len;
		}			

		if (Ribbon.segs.size() > 1) {
						
			// last segment...?
			--it;
			pVB[iVBIndex].pos = it->pos + Ribbon.tabove * it->up + (it->len/it->len0) * it->back;
			pVB[iVBIndex].uv = noVec2(1, 0);
			pVB[iVBIndex].color = Ribbon.tcolor;

			pVB[++iVBIndex].pos = it->pos - Ribbon.tbelow * it->up + (it->len/it->len0) * it->back;
			pVB[iVBIndex].uv = noVec2(1,1);
			pVB[iVBIndex].color = Ribbon.tcolor;

			gNumActiveParticles++;
		}
	}	

	RibbonData_.gNumActiveParticles.at(index) = gNumActiveParticles;
 }
Exemplo n.º 4
0
void VFreeCamera::ProcessInput(float fTimeDiff)
{
  hkvVec3 vMoveDelta = hkvVec3::ZeroVector();

  // Handle movement.
  hkvVec3 vForward(hkvNoInitialization), vRight(hkvNoInitialization), vUp(hkvNoInitialization);
  GetCurrentMoveAxes(vForward, vRight, vUp);

  float fMaxSpeed = m_fMoveSpeed;
  if (m_pInputMap->GetTrigger(CONTROL_SPEED_FAST))
    fMaxSpeed *= 3.0f;
  else if (m_pInputMap->GetTrigger(CONTROL_SPEED_FASTER))
    fMaxSpeed *= 9.0f;

  // Accumulate move directions (multiply in order to take analog input into account).
  vMoveDelta += vForward * m_pInputMap->GetTrigger(CONTROL_MOVE_FORWARD);
  vMoveDelta -= vForward * m_pInputMap->GetTrigger(CONTROL_MOVE_BACKWARD);
  vMoveDelta -= vRight * m_pInputMap->GetTrigger(CONTROL_MOVE_RIGHT);
  vMoveDelta += vRight * m_pInputMap->GetTrigger(CONTROL_MOVE_LEFT);
  vMoveDelta += vUp *  m_pInputMap->GetTrigger(CONTROL_MOVE_UP);
  vMoveDelta -= vUp * m_pInputMap->GetTrigger(CONTROL_MOVE_DOWN);
  vMoveDelta *= fMaxSpeed;
   
  // Clamp movement, so that moving diagonally is not faster than moving straight when using digital input.
  const float fSpeed = vMoveDelta.getLength();
  if (fSpeed > fMaxSpeed)
    vMoveDelta.setLength(fMaxSpeed);
  vMoveDelta *= fTimeDiff;

  // Look around.
  const float dx = m_pInputMap->GetTrigger(CONTROL_HORIZONTAL_LOOK);
  const float dy = m_pInputMap->GetTrigger(CONTROL_VERTICAL_LOOK);

  hkvVec3 vOrientation = GetOrientation();
  vOrientation.x += -dx * m_fSensitivity;
  vOrientation.y = hkvMath::clamp(vOrientation.y + dy * m_fSensitivity, -89.5f, 89.5f);
  SetOrientation(vOrientation);

  // Apply delta.
  if (GetPhysicsObject() != NULL)
  {
    IncMotionDeltaWorldSpace(vMoveDelta);
  }
  else
  {
    IncPosition(vMoveDelta);
  }
}
Exemplo n.º 5
0
BOOL VWallmarkManager::TryAlignWallmark(
    const hkvVec3& vCenter,
    const hkvVec3& vNormal,
    float fSize, float fRotation,
    hkvVec3& vNewCenter,
    hkvMat3 &alignment,
    float fEpsilon
    )
{
  VISION_PROFILE_FUNCTION(PROFILING_WALLMARK_CREATION);

  hkvVec3 vNewNormal(hkvNoInitialization);
  float fTraceRad = fSize;
  if (!IsTracePointOnPlane(vCenter,vNormal,fTraceRad,fEpsilon,vNewNormal))
    return false;

  hkvVec3 vRight(hkvNoInitialization),vUp(hkvNoInitialization),vRotRight(hkvNoInitialization),vRotUp(hkvNoInitialization), vDummy(hkvNoInitialization);
  if (hkvMath::Abs (vNewNormal.x)>0.5f)
    vRight.set(0.f,1.f,0.f);
  else
    vRight.set(1.f,0.f,0.f);
  vUp = vNewNormal.cross(vRight);
  vRight = vNewNormal.cross(vUp);

  float fSin = hkvMath::sinDeg (fRotation);
  float fCos = hkvMath::cosDeg (fRotation);

  vRotRight = vRight *  fCos + vUp * fSin;
  vRotUp    = vRight * -fSin + vUp * fCos;

  vRotRight.setLength(fSize*0.5f);
  vRotUp.setLength(fSize*0.5f);
  alignment.setAxisXYZ (vNewNormal,vRotRight,vRotUp);
  vNewCenter = vCenter + vNewNormal*fEpsilon;

  // check corners:
  if (!IsTracePointOnPlane(vCenter+vRotRight+vRotUp,vNewNormal,fTraceRad,fEpsilon,vDummy))
    return false;
  if (!IsTracePointOnPlane(vCenter+vRotRight-vRotUp,vNewNormal,fTraceRad,fEpsilon,vDummy))
    return false;
  if (!IsTracePointOnPlane(vCenter-vRotRight+vRotUp,vNewNormal,fTraceRad,fEpsilon,vDummy))
    return false;
  if (!IsTracePointOnPlane(vCenter-vRotRight-vRotUp,vNewNormal,fTraceRad,fEpsilon,vDummy))
    return false;

  return TRUE;
}
Exemplo n.º 6
0
        //----------------------------------------------------------
		/// Set Look At
		///
		/// Set the camera orientation, target and position
		/// @param Position
		/// @param Look target
		/// @param Up direction
		//----------------------------------------------------------
		void Transform::SetLookAt(const Core::Vector3& invPos, const Core::Vector3& invTarget, const Core::Vector3& invUp)
		{
            Core::Vector3 vUp(invUp);
            
            Core::Vector3 vForward(invTarget - invPos);
            vForward.Normalise();
            
            Core::Vector3 vRight(Vector3::CrossProduct(vUp, vForward));
            vUp = Core::Vector3::CrossProduct(vForward, vRight);
            
            vUp.Normalise();
            vRight.Normalise();
            
            Core::Quaternion cRot(vRight, vUp, vForward);
            cRot.Normalise();
            
            SetPositionScaleOrientation(invPos, mvScale, cRot);
		}
Exemplo n.º 7
0
 int totalNQueens(int n) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     vector<bool> vCol(n);
     vector<bool> vLeft(2 * n - 1);
     vector<bool> vRight(2 * n - 1);
     
     int ans = 0;
     
     for (int i = 0; i < n; i++) {
         vCol[i] = false;
     }
     for (int i = 0; i < 2 * n - 1; i++) {
         vLeft[i] = vRight[i] = false;
     }
     
     vector<int> a;
     DFS(ans, a, vCol, vLeft, vRight, 0, n);
     
     return ans;
 }
Exemplo n.º 8
0
	const mtx& mtx::view(const vec3& pos, const vec3& at, const vec3& up)
	{
		vec3 vLook(at - pos);
		vLook.normalize();

		vec3 vRight(up.cross(vLook));
		vRight.normalize();

		vec3 vUp(vLook.cross(vRight));
		vUp.normalize();

		_11 = vRight.x ; _12 = vUp.x ; _13 = vLook.x ; _14 = 0.0f;
		_21 = vRight.y ; _22 = vUp.y ; _23 = vLook.y ; _24 = 0.0f;
		_31 = vRight.z ; _32 = vUp.z ; _33 = vLook.z ; _34 = 0.0f;

		_41 = -vRight.dot(pos);
		_42 = -vUp.dot(pos);
		_43 = -vLook.dot(pos);
		_44 = 1.0f;

		return *this;
	}
Exemplo n.º 9
0
void CubeReflector::updateFace( const ReflectParams &params, U32 faceidx )
{
   GFXDEBUGEVENT_SCOPE( CubeReflector_UpdateFace, ColorI::WHITE );

   // store current matrices
   GFXTransformSaver saver;   

   // set projection to 90 degrees vertical and horizontal
   F32 left, right, top, bottom;
   MathUtils::makeFrustum( &left, &right, &top, &bottom, M_HALFPI_F, 1.0f, mDesc->nearDist );
   GFX->setFrustum( left, right, bottom, top, mDesc->nearDist, mDesc->farDist );

   // We don't use a special clipping projection, but still need to initialize 
   // this for objects like SkyBox which will use it during a reflect pass.
   gClientSceneGraph->setNonClipProjection( GFX->getProjectionMatrix() );

   // Standard view that will be overridden below.
   VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);

   switch( faceidx )
   {
   case 0 : // D3DCUBEMAP_FACE_POSITIVE_X:
      vLookatPt = VectorF( 1.0f, 0.0f, 0.0f );
      vUpVec    = VectorF( 0.0f, 1.0f, 0.0f );
      break;
   case 1 : // D3DCUBEMAP_FACE_NEGATIVE_X:
      vLookatPt = VectorF( -1.0f, 0.0f, 0.0f );
      vUpVec    = VectorF( 0.0f, 1.0f, 0.0f );
      break;
   case 2 : // D3DCUBEMAP_FACE_POSITIVE_Y:
      vLookatPt = VectorF( 0.0f, 1.0f, 0.0f );
      vUpVec    = VectorF( 0.0f, 0.0f,-1.0f );
      break;
   case 3 : // D3DCUBEMAP_FACE_NEGATIVE_Y:
      vLookatPt = VectorF( 0.0f, -1.0f, 0.0f );
      vUpVec    = VectorF( 0.0f, 0.0f, 1.0f );
      break;
   case 4 : // D3DCUBEMAP_FACE_POSITIVE_Z:
      vLookatPt = VectorF( 0.0f, 0.0f, 1.0f );
      vUpVec    = VectorF( 0.0f, 1.0f, 0.0f );
      break;
   case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
      vLookatPt = VectorF( 0.0f, 0.0f, -1.0f );
      vUpVec    = VectorF( 0.0f, 1.0f, 0.0f );
      break;
   }

   // create camera matrix
   VectorF cross = mCross( vUpVec, vLookatPt );
   cross.normalizeSafe();

   MatrixF matView(true);
   matView.setColumn( 0, cross );
   matView.setColumn( 1, vLookatPt );
   matView.setColumn( 2, vUpVec );
   matView.setPosition( mObject->getPosition() );
   matView.inverse();

   GFX->setWorldMatrix(matView);

   renderTarget->attachTexture( GFXTextureTarget::Color0, cubemap, faceidx );
   GFX->setActiveRenderTarget( renderTarget );
   GFX->clear( GFXClearStencil | GFXClearTarget | GFXClearZBuffer, gCanvasClearColor, 1.0f, 0 );

   SceneRenderState reflectRenderState
   (
      gClientSceneGraph,
      SPT_Reflect,
      SceneCameraState::fromGFX()
   );

   reflectRenderState.getMaterialDelegate().bind( REFLECTMGR, &ReflectionManager::getReflectionMaterial );
   reflectRenderState.setDiffuseCameraTransform( params.query->cameraMatrix );
   reflectRenderState.disableAdvancedLightingBins(true);

   // render scene
   LIGHTMGR->registerGlobalLights( &reflectRenderState.getCullingFrustum(), false );
   gClientSceneGraph->renderSceneNoLights( &reflectRenderState, mDesc->objectTypeMask );
   LIGHTMGR->unregisterAllLights();

   // Clean up.
   renderTarget->resolve();   
}
Exemplo n.º 10
0
void ParticleSystem::draw()
{
	/*
	// just draw points:
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_LIGHTING);
	glColor4f(1,1,1,1);
	glBegin(GL_POINTS);
	for (ParticleList::iterator it = particles.begin(); it != particles.end(); ++it) {
	glVertex3fv(it->tpos);
	}
	glEnd();
	glEnable(GL_LIGHTING);
	glEnable(GL_TEXTURE_2D);
	*/

	// setup blend mode
	switch (blend) {
	case 0:
		glDisable(GL_BLEND);
		glDisable(GL_ALPHA_TEST);
		break;
	case 1:
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_COLOR, GL_ONE);
		glDisable(GL_ALPHA_TEST);
		break;
	case 2:
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glDisable(GL_ALPHA_TEST);
		break;
	case 3:
		glDisable(GL_BLEND);
		glEnable(GL_ALPHA_TEST);
		break;
	case 4:
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE);
		glDisable(GL_ALPHA_TEST);
		break;
	}

	//glDisable(GL_LIGHTING);
	//glDisable(GL_CULL_FACE);
	//glDepthMask(GL_FALSE);

	//  glPushName(texture);
	_texture->bind();

	/*
	if (supportPointSprites && rows==1 && cols==1) {
	// This is how will our point sprite's size will be modified by
	// distance from the viewer
	float quadratic[] = {0.1f, 0.0f, 0.5f};
	//float quadratic[] = {0.88f, 0.001f, 0.000004f};
	glPointParameterfvARB( GL_POINT_DISTANCE_ATTENUATION_ARB, quadratic);

	// Query for the max point size supported by the hardware
	float maxSize = 512.0f;
	//glGetFloatv(GL_POINT_SIZE_MAX_ARB, &maxSize );

	// Clamp size to 100.0f or the sprites could get a little too big on some
	// of the newer graphic cards. My ATI card at home supports a max point
	// size of 1024.0f!
	//if( maxSize > 100.0f )
	//  maxSize = 100.0f;

	glPointSize(maxSize);

	// The alpha of a point is calculated to allow the fading of points
	// instead of shrinking them past a defined threshold size. The threshold
	// is defined by GL_POINT_FADE_THRESHOLD_SIZE_ARB and is not clamped to
	// the minimum and maximum point sizes.
	glPointParameterfARB(GL_POINT_FADE_THRESHOLD_SIZE_ARB, 60.0f);

	glPointParameterfARB(GL_POINT_SIZE_MIN_ARB, 1.0f );
	glPointParameterfARB(GL_POINT_SIZE_MAX_ARB, maxSize );

	// Specify point sprite texture coordinate replacement mode for each texture unit
	glTexEnvf(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
	// Render point sprites...
	glEnable(GL_POINT_SPRITE_ARB);

	glBegin(GL_POINTS);
	{
	for (ParticleList::iterator it = particles.begin(); it != particles.end(); ++it) {
	glPointSize(it->size);
	glTexCoord2fv(tiles[it->tile].tc[0]);
	glColor4fv(it->color);
	glVertex3fv(it->pos);
	}
	}
	glEnd();

	glDisable(GL_POINT_SPRITE_ARB);
	glTexEnvf(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_FALSE);

	} else { // Old slow method */

	Vec3D vRight(1, 0, 0);
	Vec3D vUp(0, 1, 0);

	// position stuff
	const float f = 1;//0.707106781f; // sqrt(2)/2
	Vec3D bv0 = Vec3D(-f, +f, 0);
	Vec3D bv1 = Vec3D(+f, +f, 0);
	Vec3D bv2 = Vec3D(+f, -f, 0);
	Vec3D bv3 = Vec3D(-f, -f, 0);

	if (billboard) {
		float modelview[16];
		glGetFloatv(GL_MODELVIEW_MATRIX, modelview);

		vRight = Vec3D(modelview[0], modelview[4], modelview[8]);
		vUp = Vec3D(modelview[1], modelview[5], modelview[9]); // Spherical billboarding
		//vUp = Vec3D(0,1,0); // Cylindrical billboarding
	}
	/*
	* type:
	* 0   "normal" particle
	* 1  large quad from the particle's origin to its position (used in Moonwell water effects)
	* 2  seems to be the same as 0 (found some in the Deeprun Tram blinky-lights-sign thing)
	*/
	if (type == 0 || type == 2) {
		//! \todo figure out type 2 (deeprun tram subway sign)
		// - doesn't seem to be any different from 0 -_-
		// regular particles

		if (billboard) {
			glBegin(GL_QUADS);
			//! \todo per-particle rotation in a non-expensive way?? :|
			for (ParticleList::iterator it = particles.begin(); it != particles.end(); ++it) {
				if (tiles.size() - 1 < it->tile) // Alfred, 2009.08.07, error prevent
					break;
				const float size = it->size;// / 2;
				glColor4fv(it->color);

				glTexCoord2fv(tiles[it->tile].tc[0]);
				glVertex3fv(it->pos - (vRight + vUp) * size);

				glTexCoord2fv(tiles[it->tile].tc[1]);
				glVertex3fv(it->pos + (vRight - vUp) * size);

				glTexCoord2fv(tiles[it->tile].tc[2]);
				glVertex3fv(it->pos + (vRight + vUp) * size);

				glTexCoord2fv(tiles[it->tile].tc[3]);
				glVertex3fv(it->pos - (vRight - vUp) * size);
			}
			glEnd();

		}
		else {
			glBegin(GL_QUADS);
			for (ParticleList::iterator it = particles.begin(); it != particles.end(); ++it) {
				if (tiles.size() - 1 < it->tile) // Alfred, 2009.08.07, error prevent
					break;
				glColor4fv(it->color);

				glTexCoord2fv(tiles[it->tile].tc[0]);
				glVertex3fv(it->pos + it->corners[0] * it->size);

				glTexCoord2fv(tiles[it->tile].tc[1]);
				glVertex3fv(it->pos + it->corners[1] * it->size);

				glTexCoord2fv(tiles[it->tile].tc[2]);
				glVertex3fv(it->pos + it->corners[2] * it->size);

				glTexCoord2fv(tiles[it->tile].tc[3]);
				glVertex3fv(it->pos + it->corners[3] * it->size);
			}
			glEnd();
		}
	}
	else if (type == 1) { // Sphere particles
		// particles from origin to position
		/*
		bv0 = mbb * Vec3D(0,-1.0f,0);
		bv1 = mbb * Vec3D(0,+1.0f,0);


		bv0 = mbb * Vec3D(-1.0f,0,0);
		bv1 = mbb * Vec3D(1.0f,0,0);
		*/

		glBegin(GL_QUADS);
		for (ParticleList::iterator it = particles.begin(); it != particles.end(); ++it) {
			if (tiles.size() - 1 < it->tile) // Alfred, 2009.08.07, error prevent
				break;
			glColor4fv(it->color);

			glTexCoord2fv(tiles[it->tile].tc[0]);
			glVertex3fv(it->pos + bv0 * it->size);

			glTexCoord2fv(tiles[it->tile].tc[1]);
			glVertex3fv(it->pos + bv1 * it->size);

			glTexCoord2fv(tiles[it->tile].tc[2]);
			glVertex3fv(it->origin + bv1 * it->size);

			glTexCoord2fv(tiles[it->tile].tc[3]);
			glVertex3fv(it->origin + bv0 * it->size);
		}
		glEnd();

	}
	//}

	//glEnable(GL_LIGHTING);
	//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	//glDepthMask(GL_TRUE);
	//glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
Exemplo n.º 11
0
void VFmodManager::RunTick(float fTimeDelta)
{
  if (!IsInitialized())
    return;

  VISION_PROFILE_FUNCTION(PROFILING_FMOD_OVERALL);

  // profiling scope
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PUREUPDATE);

    VASSERT(m_pEventSystem!=NULL);
    
    // update Fmod listener attributes
    VisObject3D_cl *pListener = m_pListenerObject ? m_pListenerObject : Vision::Camera.GetMainCamera();
    if (!pListener)
      return;

    hkvVec3 vCamPos = pListener->GetPosition();
    hkvVec3 vDir(pListener->GetObjDir()),
            vRight(pListener->GetObjDir_Right()),
            vUp(pListener->GetObjDir_Up());

    vUp = -vUp; // compensate for coordinate system
    m_pEventSystem->set3DListenerAttributes(0, (FMOD_VECTOR *)&vCamPos, NULL, (FMOD_VECTOR *)&vDir, (FMOD_VECTOR *)&vUp); // no speed (yet)
    
    
    // update all sound objects 
    SoundInstances().Update();

    // update all events 
    Events().Update();

    // update Fmod event system
    m_fTimeLeftOver += fTimeDelta;
    if (m_fTimeLeftOver > m_config.fTimeStep)
    { 
      m_pEventSystem->update();
#ifdef VFMOD_SUPPORTS_NETWORK
      if (m_config.bUseNetworkSystem)
        FMOD::NetEventSystem_Update();
#endif
      m_fTimeLeftOver = hkvMath::mod (m_fTimeLeftOver, m_config.fTimeStep);
    }
  } 
  
  // do not purge sounds/ events in vForge, in order to allow toggling playback via hotspot button
  if (Vision::Editor.IsInEditor())
    return;  

  if (m_bAnyStopped)
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PURGE);

    // all sounds/ events that have finished playing are removed from handling
    SoundInstances().PurgeNotPlaying();
    Events().PurgeNotPlaying();

    m_bAnyStopped = false; // reset any stopped flag
  }
}
Exemplo n.º 12
0
void TextExplainNode::UpdateText(Node* rootWidget, const string* text, int cfgId)
{
    
    auto node_TextExplain = rootWidget->getChildByName<Node*>("Node_TextExplain");
    node_TextExplain->setVisible(true);
    
    auto layout_FullScreen = node_TextExplain->getChildByName<Layout*>("Layout_FullScreen");

    layout_FullScreen->setVisible(true);
    layout_FullScreen->setTouchEnabled(true);
    layout_FullScreen->setSwallowTouches(false);
    layout_FullScreen->addClickEventListener([=](Ref* sender)
     {
         node_TextExplain->setVisible(false);
         layout_FullScreen->setVisible(false);
         layout_FullScreen->setTouchEnabled(false);
     });

    auto layout_Background = node_TextExplain->getChildByName<Layout*>("Layout_Background");
    auto text_Explain = layout_Background->getChildByName<Text*>("Text_Explain");
    text_Explain->setString(text->c_str());
    
    auto layout_restrain = layout_Background->getChildByName<Layout*>("Layout_Restrain");
    if ( cfgId == 0 || (cfgId / 1000000 != 205) ) {
        layout_restrain->setVisible(false);
        return;
    }
    layout_restrain->setVisible(true);
    
    auto layout_propMain = layout_restrain->getChildByName<Layout*>("Layout_PropMain");
    UIUtils::getInstance()->showProperImg(layout_propMain, cfgId, false);
    
    CfgDataRow dataRow(cfgId);
    // 属性配置表的id与item的属性字段id不统一,故作如下转换
    auto properId = (int)ProCfgId::CfgBaseId + dataRow.GetValue(CfgField::PropertyID)->asInt();
    CfgDataRow proDataRow(properId);
    
    // 1001 ~ 1005
    float result = 1.0;
    vector<int> vLeft(2, 0);
    vector<int> vRight(2, 0);
    int leftIdx = 0;
    int rightIdx = 0;
    for (int proId = 1001; proId <= 1005; ++proId) {
        switch (proId) {
            case (int)ProCfgId::MeleeCo :
                result = proDataRow.GetValue(CfgField::MeleeCo_F)->asFloat();
                break;
            case (int)ProCfgId::FighterCo :
                result = proDataRow.GetValue(CfgField::FighterCo_F)->asFloat();
                break;
            case (int)ProCfgId::MagicCo :
                result = proDataRow.GetValue(CfgField::MagicCo_F)->asFloat();
                break;
            case (int)ProCfgId::RangedCo :
                result = proDataRow.GetValue(CfgField::RangedCo_F)->asFloat();
                break;
            case (int)ProCfgId::FlyingCo :
                result = proDataRow.GetValue(CfgField::FlyingCo_F)->asFloat();
                break;
        }
        
        if (result < 1) {
            vLeft[leftIdx++] = proId;
        }
        else if(result > 1) {
            vRight[rightIdx++] = proId;
        }
    }
    
    int i = 1;
    for(int proId : vLeft) {
        auto leftProNode = layout_restrain->getChildByName(StringUtils::format("Layout_PropLeft%d", i++));
        UIUtils::getInstance()->showRealProper(leftProNode, proId, false);
    }
    
    i = 1;
    for(int proId : vRight) {
        auto RightProNode = layout_restrain->getChildByName(StringUtils::format("Layout_PropRight%d", i++));
        UIUtils::getInstance()->showRealProper(RightProNode, proId, false);
    }
    
    // 技能、buff、属性描述
    auto text_Buff = layout_restrain->getChildByName<Text *>("Text_Buff");
    auto text_Skill = layout_restrain->getChildByName<Text *>("Text_Skill");
    auto text_Attr = layout_restrain->getChildByName<Text *>("Text_Attr");
    
    auto vi_skill = dataRow.GetValue(CfgField::SkillID_V)->asValueVector();
    auto iter_skill = vi_skill.begin();
    auto skillId = iter_skill->asInt();
    
    CfgDataRow dataRow_Skill(skillId);
    
    auto langText = MultiLanguage::getInstance()->GetText((int)LanguageIdEnum::SkillId);
    langText += MultiLanguage::getInstance()->GetText(dataRow_Skill.GetValue(CfgField::Name)->asInt());
    text_Skill->setString(langText);
    
    auto bufferData = dataRow_Skill.GetValue(CfgField::BuffID_V)->asValueVector();
    if (!bufferData.empty()) {
        auto iter_buff = bufferData.begin();
        auto bufferId = iter_buff->asInt();
        langText = MultiLanguage::getInstance()->GetText((int)LanguageIdEnum::BufferId);
        CfgDataRow dataRow_Buffer(bufferId);
        langText += MultiLanguage::getInstance()->GetText(dataRow_Buffer.GetValue(CfgField::Name)->asInt());
        text_Buff->setString(langText);
        text_Buff->setVisible(true);
    }else
    {
        text_Buff->setVisible(false);
    }
    
    langText = MultiLanguage::getInstance()->GetText((int)LanguageIdEnum::LifeId);
    langText += StringUtils::format("%d", dataRow.GetValue(CfgField::Hp)->asInt());
    
    langText += " " + MultiLanguage::getInstance()->GetText((int)LanguageIdEnum::PowerId);
    langText += StringUtils::format("%d", dataRow.GetValue(CfgField::Atk)->asInt());
    
    langText += " " + MultiLanguage::getInstance()->GetText((int)LanguageIdEnum::SpeedId);
    langText += StringUtils::format("%g", dataRow.GetValue(CfgField::Spd_F)->asFloat());
    
    text_Attr->setString(langText);
    
}
Exemplo n.º 13
0
void VFmodManager::RunTick(float fTimeDelta)
{
  VISION_PROFILE_FUNCTION(PROFILING_FMOD_OVERALL);

  if (!IsInitialized())
  {
    if (!IsOutputDevicePresent())
      InitDevice();

    return; 
  }

  // profiling scope
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PUREUPDATE);

    VASSERT(m_pEventSystem!=NULL);

    // update Fmod listener attributes
    VisObject3D_cl *pListener = m_pListenerObject;
    if (pListener == NULL)
    {
      // The listener is the main camera. Check for teleportation since the last Fmod update, in
      // which case we won't use the position difference to calculate the listener speed.
      VisContextCamera_cl* pCamera = Vision::Camera.GetMainCamera();
      VisRenderContext_cl* pContext = VisRenderContext_cl::GetMainRenderContext();
      if (pCamera != NULL && pContext != NULL)
      {
        if (m_bLastListenerPositionValid && pCamera->GetLastTeleported() > m_iFrameOfLastUpdate)
          m_bLastListenerPositionValid = false;

        m_iFrameOfLastUpdate = pContext->GetLastRenderedFrame();
        pListener = pCamera;
      }
    }

    if (!pListener)
      return;

    hkvVec3 vCamPos = pListener->GetPosition();
    hkvVec3 vDir(pListener->GetObjDir()),
            vRight(pListener->GetObjDir_Right()),
            vUp(pListener->GetObjDir_Up());

    // Determine the camera velocity based on the previous known position
    hkvVec3 vCamVel(m_bLastListenerPositionValid && (fTimeDelta > 0.f) ? (vCamPos - m_vLastListenerPosition) * (1.f / fTimeDelta) : hkvVec3::ZeroVector());
    m_vLastListenerPosition = vCamPos;
    m_bLastListenerPositionValid = true;

    vUp = -vUp; // compensate for coordinate system
    m_pEventSystem->set3DListenerAttributes(0, (FMOD_VECTOR *)&vCamPos, (FMOD_VECTOR *)&vCamVel, (FMOD_VECTOR *)&vDir, (FMOD_VECTOR *)&vUp);

    // update all sound objects 
    SoundInstances().Update(fTimeDelta);

    // update all events 
    Events().Update(fTimeDelta);

    // update Fmod event system
    m_fTimeLeftOver += fTimeDelta;
    if (m_fTimeLeftOver > m_config.fTimeStep)
    { 
      m_pEventSystem->update();

#ifdef VFMOD_SUPPORTS_NETWORK
      if (m_config.bUseNetworkSystem)
        FMOD::NetEventSystem_Update();
#endif
      m_fTimeLeftOver = hkvMath::mod (m_fTimeLeftOver, m_config.fTimeStep);
    }
  }

  // do not purge sounds/ events in vForge, in order to allow toggling playback via hotspot button
  if (Vision::Editor.IsInEditor())
    return;  

  if (m_bAnyStopped)
  {
    VISION_PROFILE_FUNCTION(PROFILING_FMOD_PURGE);

    // all sounds/ events that have finished playing are removed from handling
    SoundInstances().PurgeNotPlaying();
    Events().PurgeNotPlaying();

    m_bAnyStopped = false; // reset any stopped flag
  }
}
Exemplo n.º 14
0
//-----------------------------------------------------------------------------
void CPUTCameraControllerFPS::Update(float deltaSeconds)
{
    if( !mpCamera )
    {
        return;
    }
    float speed = mfMoveSpeed * deltaSeconds;
    if (keyPressed[KEY_SHIFT] == CPUT_KEY_DOWN || keyPressed[KEY_CTRL] == CPUT_KEY_DOWN) {
        speed *= 0.1f;
    }

    float4x4 *pParentMatrix = mpCamera->GetParentMatrix();

    float3 vRight(pParentMatrix->getXAxis());
    float3 vUp(pParentMatrix->getYAxis());
    float3 vLook(pParentMatrix->getZAxis());
    float3 vPositionDelta(0.0f);
    int    rotateX = 0;
    int    rotateY = 0;
    bool   bRotate = false;
    // Added the ability to toggle on/off rotation mode
    if (keyPressed[KEY_SPACE] == CPUT_KEY_DOWN) {
        bRotate = true;
    }
    if(keyPressed[KEY_W] == CPUT_KEY_DOWN) {
        vPositionDelta +=  vLook *  speed;
        rotateY = -1;
    }
    if(keyPressed[KEY_A] == CPUT_KEY_DOWN) {
        vPositionDelta += vRight * -speed;
        rotateX = -1;
    }
    if(keyPressed[KEY_S] == CPUT_KEY_DOWN) {
        vPositionDelta +=  vLook * -speed;
        rotateY = 1;
    }
    if(keyPressed[KEY_D] == CPUT_KEY_DOWN) {
        vPositionDelta += vRight *  speed;
        rotateX = 1;
    }
    if(keyPressed[KEY_E] == CPUT_KEY_DOWN) {
        vPositionDelta +=    vUp *  speed;
    }
    if(keyPressed[KEY_Q] == CPUT_KEY_DOWN) {
        vPositionDelta +=    vUp * -speed;
    }
    if (bRotate && (rotateX || rotateY))
    {
        // this lets you rotate the camera with the keyboard if you don't have a mouse. like if you only have one
        // usb slot available on a mobile.
        float nDeltaX = (float)(rotateX) * speed * 10.0f;
        float nDeltaY = (float)(rotateY) * speed * 10.0f;

        float4x4 rotationX = float4x4RotationX(nDeltaY*mfLookSpeed);
        float4x4 rotationY = float4x4RotationY(nDeltaX*mfLookSpeed);

        float3 position = mpCamera->GetPosition();
        mpCamera->SetPosition(0.0f, 0.0f, 0.0f); // Rotate about camera center
        float4x4 parent      = *mpCamera->GetParentMatrix();
        float4x4 orientation = rotationX  *parent * rotationY;
        orientation.orthonormalize();
        mpCamera->SetParentMatrix( orientation );
        mpCamera->SetPosition( position.x, position.y, position.z ); // Move back to original position
    }
    else
    {
        float x,y,z;
        mpCamera->GetPosition( &x, &y, &z );
        mpCamera->SetPosition( x+vPositionDelta.x, y+vPositionDelta.y, z+vPositionDelta.z );
    }
    mpCamera->Update();

    //Compute animation as an offset from the current position
    mpCamera->mPosition += float3( vPositionDelta.x, vPositionDelta.y, vPositionDelta.z );
    //END
    return;
}
Exemplo n.º 15
0
void M2EffectRender::CopyParticlesToVertexBuffer( uint32 index, class M2ParticleSystem* ps, ParticleVertex* pVB, D3DXVECTOR3 vEye, D3DXVECTOR3 _vRight, D3DXVECTOR3 _vUp )
{

	noVec3 vRight(0,0,-1);
	noVec3 vUp(0,1,0);

	// position stuff
	const float f = 1;//0.707106781f; // sqrt(2)/2
	noVec3 bv0 = noVec3(-f,+f,0);
	noVec3 bv1 = noVec3(-f,-f,0);		
	noVec3 bv2 = noVec3(+f,-f,0);
	noVec3 bv3 = noVec3(+f,+f,0);		

	UINT iVBIndex = 0;

	uint32 gNumActiveParticles = 0;	
		
	for (size_t i=0; i< 1 ; i++) 
	{
		if (ps->billboard) 
		{
			vRight.Set(_vRight.x, _vRight.y, _vRight.z);
			vUp.Set(_vUp.x, _vUp.y, _vUp.z);
		}
			

		if (ps->ParticleType==0 || ps->ParticleType==2)
		{
			
						

			for (ParticleList::iterator it = ps->particles.begin(); it != ps->particles.end(); ++it) {
				if (ps->tiles.size() - 1 < it->tile) // Alfred, 2009.08.07, error prevent
					break;

				//if (gNumActiveParticles >= MAX_PARTICLES)
				//	return;
								
				M2Particle &p = *it;	
				const float size = it->size;// / 2;
													

				if (ps->billboard)
				{						
					
					// 0 ---- 3
					//
					//
					// 1 ---- 2
					//	// Tri 0 (0,1,3)	
					// it->pos˼ center
					noVec3 v0 = it->pos - (vRight - vUp) * size;					
					noVec3 v1 = it->pos - (vRight + vUp) * size;
					noVec3 v2 = it->pos + (vRight - vUp) * size;
					noVec3 v3 = it->pos + (vRight + vUp) * size;

					pVB[iVBIndex].pos = v0;
					pVB[iVBIndex].color = it->color;
					pVB[iVBIndex].uv = ps->tiles[it->tile].tc[0];
					
					pVB[iVBIndex+1].pos = v1;
					pVB[iVBIndex+1].color = it->color;
					pVB[iVBIndex+1].uv = ps->tiles[it->tile].tc[3];
										
					pVB[iVBIndex+2].pos = v3;
					pVB[iVBIndex+2].color = it->color;
					pVB[iVBIndex+2].uv = ps->tiles[it->tile].tc[1];
					
					pVB[iVBIndex+3].pos = v2;
					pVB[iVBIndex+3].color = it->color;
					pVB[iVBIndex+3].uv = ps->tiles[it->tile].tc[2];

					pVB[iVBIndex+4].pos = v3;
					pVB[iVBIndex+4].color = it->color;
					pVB[iVBIndex+4].uv = ps->tiles[it->tile].tc[1];

					pVB[iVBIndex+5].pos = v1;
					pVB[iVBIndex+5].color = it->color;
					pVB[iVBIndex+5].uv = ps->tiles[it->tile].tc[3];

							
					//if (frame > 10 && frame < 20)
					{
					/*	for (int i = 0; i < 6; i++) {
							LOG_INFO << "Particle : " << iVBIndex +i  << " " <<  pVB[iVBIndex +i].pos.x << " " << pVB[iVBIndex +i].pos.y << 
							" " << pVB[iVBIndex +i].pos.z;*/
							/*noVec3 Pos = (mView * mProj) * pVB[iVBIndex +i].pos;
							LOG_INFO << "Particle : " << iVBIndex +i  << " " <<  Pos.x << " " << Pos.y << 
							" " << Pos.z;*/
						//}
					}

				}
				else 					
				{
					//	// Tri 0 (0,1,3)
					pVB[iVBIndex].pos = it->pos + it->corners[3] * size;
					pVB[iVBIndex].color = it->color;
					pVB[iVBIndex].uv = ps->tiles[it->tile].tc[3];

					pVB[iVBIndex+1].pos = it->pos + it->corners[0] * size;
					pVB[iVBIndex+1].color = it->color;
					pVB[iVBIndex+1].uv = ps->tiles[it->tile].tc[0];

					pVB[iVBIndex+2].pos = it->pos + it->corners[2] * size;
					pVB[iVBIndex+2].color = it->color;
					pVB[iVBIndex+2].uv = ps->tiles[it->tile].tc[2];

					//	// Tri 1 (3,1,2)					
					pVB[iVBIndex+3].pos = it->pos + it->corners[1] * size;
					pVB[iVBIndex+3].color = it->color;
					pVB[iVBIndex+3].uv = ps->tiles[it->tile].tc[1];

					pVB[iVBIndex+4].pos = it->pos + it->corners[2] * size;
					pVB[iVBIndex+4].color = it->color;
					pVB[iVBIndex+4].uv = ps->tiles[it->tile].tc[2];

					pVB[iVBIndex+5].pos = it->pos + it->corners[0] * size;
					pVB[iVBIndex+5].color = it->color;
					pVB[iVBIndex+5].uv = ps->tiles[it->tile].tc[0];
				}

				iVBIndex+=6;
				gNumActiveParticles++;
			}		
		}
		else if (ps->ParticleType==1) { // Sphere particles

						
			for (ParticleList::iterator it = ps->particles.begin(); it != ps->particles.end(); ++it) {
				if (ps->tiles.size() - 1 < it->tile) // Alfred, 2009.08.07, error prevent
					break;

			//	//	// Tri 0 (0,1,3)
			//	pVB[iVBIndex+2].pos = it->pos + it->corners[1] * size;
			//	pVB[iVBIndex+2].color = it->color;
			//	pVB[iVBIndex+2].uv = ps->tiles[it->tile].tc[1];

			//	pVB[iVBIndex+1].pos = it->pos + bv1 * it->size;
			//	pVB[iVBIndex+1].color = it->color;
			//	pVB[iVBIndex+1].uv = ps->tiles[it->tile].tc[3];

			//	pVB[iVBIndex].pos = it->pos + bv0 * it->size;
			//	pVB[iVBIndex].color = it->color;
			//	pVB[iVBIndex].uv = ps->tiles[it->tile].tc[0];

			//	//	// Tri 1 (3,1,2)					
			//	pVB[iVBIndex+5].pos = it->pos + it->corners[3] * size;
			//	pVB[iVBIndex+5].color = it->color;
			//	pVB[iVBIndex+5].uv = ps->tiles[it->tile].tc[2];

			//	pVB[iVBIndex+4].pos = it->pos + it->corners[2] * size;
			//	pVB[iVBIndex+4].color = it->color;
			//	pVB[iVBIndex+4].uv = ps->tiles[it->tile].tc[3];

			//	pVB[iVBIndex+3].pos = it->pos + it->corners[1] * size;
			//	pVB[iVBIndex+3].color = it->color;
			//	pVB[iVBIndex+3].uv = ps->tiles[it->tile].tc[1];

			//	iVBIndex+=6;
			//	gNumActiveParticles+=6;

			//	noVec3 bv0 = noVec3(-f,+f,0);
			//	noVec3 bv1 = noVec3(-f,-f,0);		
			//					
			//	glTexCoord2fv(tiles[it->tile].tc[0]);
			//	glVertex3fv(it->pos + bv0 * it->size);

			//	glTexCoord2fv(tiles[it->tile].tc[1]);
			//	glVertex3fv(it->pos + bv1 * it->size);

			//	glTexCoord2fv(tiles[it->tile].tc[2]);
			//	glVertex3fv(it->origin + bv1 * it->size);

			//	glTexCoord2fv(tiles[it->tile].tc[3]);
			//	glVertex3fv(it->origin + bv0 * it->size);
			}		
		}		
	}		
	ParticleData_.gNumActiveParticles.at(index) = gNumActiveParticles;
}
Exemplo n.º 16
0
void CCampathDrawer::OnPostRenderAllTools()
{
	// Actually we are often called twice per frame due to an engine bug(?), once after 3d skybox
	// and once after world is drawn, maybe we will be even called more times,
	// but we can not care about that for now.
	
	if(!m_Draw)
		return;

	if(!m_VertexShader)
	{
		m_VertexShader = g_AfxShaders.GetVertexShader("afx_line_vs20.fxo");
	}
	IDirect3DVertexShader9 * vertexShader = m_VertexShader->GetVertexShader();

	if(!m_PixelShader)
	{
		m_PixelShader = g_AfxShaders.GetPixelShader("afx_line_ps20.fxo");
	}
	IDirect3DPixelShader9 * pixelShader = m_PixelShader->GetPixelShader();

	if(!(m_Device && vertexShader && m_PixelShader && g_VEngineClient))
	{
		static bool firstError = true;

		if(firstError)
		{
			firstError = false;
			Tier0_Msg(
				"AFXERROR: CCampathDrawer::OnEndScene: Missing required dependencies:%s%s%s%s.\n",
				!m_Device ? " m_Device" : "",
				!vertexShader ? " vertexShader" : "",
				!pixelShader ? " pixelShader" : "",
				!g_VEngineClient ? " g_VEngineClient" : ""
			);
		}

		return;
	}

	// Save device state:

	IDirect3DPixelShader9 * oldPixelShader = 0;
	m_Device->GetPixelShader(&oldPixelShader);
	if(oldPixelShader) oldPixelShader->AddRef();

	IDirect3DVertexShader9 * oldVertexShader = 0;
	m_Device->GetVertexShader(&oldVertexShader);
	if(oldVertexShader) oldVertexShader->AddRef();

	IDirect3DVertexBuffer9 * oldVertexBuffer = 0;
	UINT oldVertexBufferOffset;
	UINT oldVertexBufferStride;
	m_Device->GetStreamSource(0, &oldVertexBuffer, &oldVertexBufferOffset, &oldVertexBufferStride);
	// this is done already according to doc: // if(oldVertexBuffer) oldVertexBuffer->AddRef();

	IDirect3DIndexBuffer9 * oldIndexBuffer = 0;
	m_Device->GetIndices(&oldIndexBuffer);
	// this is done already according to doc: // if(oldIndexBuffer) oldIndexBuffer->AddRef();

	IDirect3DVertexDeclaration9 * oldDeclaration;
	m_Device->GetVertexDeclaration(&oldDeclaration);
	if(oldDeclaration) oldDeclaration->AddRef();

	DWORD oldFVF;
	m_Device->GetFVF(&oldFVF);

	FLOAT oldCViewProj[4][4];
	m_Device->GetVertexShaderConstantF(8, oldCViewProj[0], 4);

	FLOAT oldCScreenInfo[4];
	m_Device->GetVertexShaderConstantF(48, oldCScreenInfo, 1);

	FLOAT oldCPlane0[4];
	m_Device->GetVertexShaderConstantF(49, oldCPlane0, 1);

	FLOAT oldCPlaneN[4];
	m_Device->GetVertexShaderConstantF(50, oldCPlaneN, 1);

	DWORD oldSrgbWriteEnable;
	m_Device->GetRenderState(D3DRS_SRGBWRITEENABLE, &oldSrgbWriteEnable);

	DWORD oldColorWriteEnable;
	m_Device->GetRenderState(D3DRS_COLORWRITEENABLE, &oldColorWriteEnable);

	DWORD oldZEnable;
	m_Device->GetRenderState(D3DRS_ZENABLE, &oldZEnable);

	DWORD oldZWriteEnable;
	m_Device->GetRenderState(D3DRS_ZWRITEENABLE, &oldZWriteEnable);
	
	DWORD oldZFunc;
	m_Device->GetRenderState(D3DRS_ZFUNC, &oldZFunc);

	DWORD oldAlphaTestEnable;
	m_Device->GetRenderState(D3DRS_ALPHATESTENABLE, &oldAlphaTestEnable);

	DWORD oldSeparateAlphaBlendEnable;
	m_Device->GetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, &oldSeparateAlphaBlendEnable);

	DWORD oldAlphaBlendEnable;
	m_Device->GetRenderState(D3DRS_ALPHABLENDENABLE, &oldAlphaBlendEnable);

	DWORD oldBlendOp;
	m_Device->GetRenderState(D3DRS_BLENDOP, &oldBlendOp);

	DWORD oldSrcBlend;
	m_Device->GetRenderState(D3DRS_SRCBLEND, &oldSrcBlend);

	DWORD oldDestBlend;
	m_Device->GetRenderState(D3DRS_DESTBLEND, &oldDestBlend);

	DWORD oldCullMode;
	m_Device->GetRenderState(D3DRS_CULLMODE, &oldCullMode);

	// Draw:
	{
		//Vector3 vvForward, vvUp, vvRight, vvPos;

		double curTime = g_Hook_VClient_RenderView.GetCurTime();
		bool inCampath = 1 <= g_Hook_VClient_RenderView.m_CamPath.GetSize()
			&&	g_Hook_VClient_RenderView.m_CamPath.GetLowerBound() <= curTime
			&& curTime <= g_Hook_VClient_RenderView.m_CamPath.GetUpperBound();
		bool campathCanEval = g_Hook_VClient_RenderView.m_CamPath.CanEval();
		bool campathEnabled = g_Hook_VClient_RenderView.m_CamPath.Enabled_get();
		bool cameraMightBeSelected = false;

		m_Device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
		m_Device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_RED);
		m_Device->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
		m_Device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
		m_Device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
		m_Device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
		m_Device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
		m_Device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
		m_Device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
		m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
		m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
		m_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);

		m_Device->SetVertexShader(vertexShader);

		m_WorldToScreenMatrix = g_VEngineClient->WorldToScreenMatrix();
			
		m_Device->SetVertexShaderConstantF(8, m_WorldToScreenMatrix.m[0], 4);

		// Provide view plane info for line clipping:
		{
			double plane0[4]={0,0,0,1};
			double planeN[4]={1,0,0,1};
			//double planeR[4]={0,-1,0,1};
			//double planeU[4]={0,0,1,1};

			unsigned char P[4];
			unsigned char Q[4];

			double L[4][4];
			double U[4][4];

			double M[4][4] = {
				m_WorldToScreenMatrix.m[0][0], m_WorldToScreenMatrix.m[0][1], m_WorldToScreenMatrix.m[0][2], 0,
				m_WorldToScreenMatrix.m[1][0], m_WorldToScreenMatrix.m[1][1], m_WorldToScreenMatrix.m[1][2], 0,
				m_WorldToScreenMatrix.m[2][0], m_WorldToScreenMatrix.m[2][1], m_WorldToScreenMatrix.m[2][2], 0,
				m_WorldToScreenMatrix.m[3][0], m_WorldToScreenMatrix.m[3][1], m_WorldToScreenMatrix.m[3][2], -1,
			};

			double b0[4] = {
				0 -m_WorldToScreenMatrix.m[0][3],
				0 -m_WorldToScreenMatrix.m[1][3],
				0 -m_WorldToScreenMatrix.m[2][3],
				-m_WorldToScreenMatrix.m[3][3],
			};

			double bN[4] = {
				0 -m_WorldToScreenMatrix.m[0][3],
				0 -m_WorldToScreenMatrix.m[1][3],
				1 -m_WorldToScreenMatrix.m[2][3],
				-m_WorldToScreenMatrix.m[3][3],
			};
			/*
			double bR[4] = {
				1 -m_WorldToScreenMatrix.m[0][3],
				0 -m_WorldToScreenMatrix.m[1][3],
				0 -m_WorldToScreenMatrix.m[2][3],
				-m_WorldToScreenMatrix.m[3][3],
			};

			double bU[4] = {
				0 -m_WorldToScreenMatrix.m[0][3],
				1 -m_WorldToScreenMatrix.m[1][3],
				0 -m_WorldToScreenMatrix.m[2][3],
				-m_WorldToScreenMatrix.m[3][3],
			};
			*/
			if(!LUdecomposition(M, P, Q, L, U))
			{
				Tier0_Warning("AFXERROR in CCampathDrawer::OnPostRenderAllTools: LUdecomposition failed\n");
			}
			else
			{
				SolveWithLU(L, U, P, Q, b0, plane0);
				SolveWithLU(L, U, P, Q, bN, planeN);
				
				//SolveWithLU(L, U, P, Q, bR, planeR);
				//SolveWithLU(L, U, P, Q, bU, planeU);
			}

			/*
			vvPos = Vector3(plane0[0], plane0[1], plane0[2]);
			vvForward = Vector3(planeN[0] -vvPos.X, planeN[1] -vvPos.Y, planeN[2]-vvPos.Z);
			vvForward.Normalize();
			vvRight = Vector3(planeR[0] -vvPos.X, planeR[1] -vvPos.Y, planeR[2]-vvPos.Z);
			vvRight.Normalize();
			vvUp = Vector3(planeU[0] -vvPos.X, planeU[1] -vvPos.Y, planeU[2]-vvPos.Z);
			vvUp.Normalize();
			*/

			/*
			Tier0_Msg("CCampathDrawer::OnPostRenderAllTools: curTime = %f\n",curTime);
			Tier0_Msg("M[0]=%f %f %f %f\nM[1]=%f %f %f %f\nM[2]=%f %f %f %f\nM[3]=%f %f %f %f\n", M[0][0],M[0][1],M[0][2],M[0][3], M[1][0],M[1][1],M[1][2],M[1][3], M[2][0],M[2][1],M[2][2],M[2][3], M[3][0],M[3][1],M[3][2],M[3][3]);
			Tier0_Msg("b0[0]=%f %f %f %f\n", b0[0], b0[1], b0[2], b0[3]);
			Tier0_Msg("bN[0]=%f %f %f %f\n", bN[0], bN[1], bN[2], bN[3]);
			Tier0_Msg("plane0=%f %f %f %f\n", plane0[0], plane0[1], plane0[2], plane0[3]);
			Tier0_Msg("planeN=%f %f %f %f\n", planeN[0], planeN[1], planeN[2], planeN[3]);
			*/

			FLOAT vPlane0[4] = {(float)plane0[0], (float)plane0[1], (float)plane0[2], 0.0f};

			Vector3 planeNormal(planeN[0] -plane0[0], planeN[1] -plane0[1], planeN[2] -plane0[2]);
			planeNormal.Normalize();

			FLOAT vPlaneN[4] = {(float)planeNormal.X, (float)planeNormal.Y, (float)planeNormal.Z, 0.0f};

			m_Device->SetVertexShaderConstantF(49, vPlane0, 1);
			m_Device->SetVertexShaderConstantF(50, vPlaneN, 1);
		}

		m_Device->SetPixelShader(pixelShader);

		m_Device->SetFVF(CCampathDrawer_VertexFVF);

		int screenWidth, screenHeight;
		g_VEngineClient->GetScreenSize(screenWidth, screenHeight);
		FLOAT newCScreenInfo[4] = { 0 != screenWidth ? 1.0f / screenWidth : 0.0f, 0 != screenHeight ? 1.0f / screenHeight : 0.0f, 0.0, 0.0f};

		// Draw trajectory:
		if(2 <= g_Hook_VClient_RenderView.m_CamPath.GetSize() && campathCanEval)
		{
			if(m_RebuildDrawing)
			{
				// Rebuild trajectory points.
				// This operation can be quite expensive (up to O(N^2)),
				// so it should be done only when s.th.
				// changed (which is what we do here).

				m_TrajectoryPoints.clear();
				
				CamPathIterator last = g_Hook_VClient_RenderView.m_CamPath.GetBegin();				
				CamPathIterator it = last;

				TempPoint * pts = new TempPoint[c_CameraTrajectoryMaxPointsPerInterval];

				for(++it; it != g_Hook_VClient_RenderView.m_CamPath.GetEnd(); ++it)
				{
					double delta = it.GetTime() -last.GetTime();

					for(size_t i = 0; i<c_CameraTrajectoryMaxPointsPerInterval; i++)
					{
						double t = last.GetTime() + delta*((double)i/(c_CameraTrajectoryMaxPointsPerInterval-1));

						CamPathValue cpv = g_Hook_VClient_RenderView.m_CamPath.Eval(t);

						pts[i].t = t;
						pts[i].y = Vector3(cpv.X, cpv.Y, cpv.Z);
						pts[i].nextPt = i+1 <c_CameraTrajectoryMaxPointsPerInterval ? &(pts[i+1]) : 0;
					}

					RamerDouglasPeucker(&(pts[0]), &(pts[c_CameraTrajectoryMaxPointsPerInterval-1]), c_CameraTrajectoryEpsilon);

					// add all points except the last one (to avoid duplicates):
					for(TempPoint * pt = &(pts[0]); pt && pt->nextPt; pt = pt->nextPt)
					{
						m_TrajectoryPoints.push_back(pt->t);
					}

					last = it;
				}

				// add last point:
				m_TrajectoryPoints.push_back(pts[c_CameraTrajectoryMaxPointsPerInterval-1].t);

				delete pts;

				m_RebuildDrawing = false;
			}

			newCScreenInfo[2] = c_CameraTrajectoryPixelWidth;
			m_Device->SetVertexShaderConstantF(48, newCScreenInfo, 1);

			AutoPolyLineStart();

			std::list<double>::iterator itPts = m_TrajectoryPoints.begin();

			CamPathIterator itKeysLast = g_Hook_VClient_RenderView.m_CamPath.GetBegin();
			CamPathIterator itKeysNext = itKeysLast;
			++itKeysNext;

			bool hasLastPt = false;
			bool hasNextPt = false;
			bool hasCurPt = false;
			
			double lastPtTime;
			CamPathValue lastPtValue;
			double curPtTime;
			CamPathValue curPtValue;
			double nextPtTime;
			CamPathValue nextPtValue;

			do
			{
				if(hasNextPt)
				{
					hasLastPt = true;
					lastPtTime = curPtTime;
					lastPtValue = curPtValue;

					hasCurPt = true;
					curPtTime = nextPtTime;
					curPtValue = nextPtValue;

					hasNextPt = false;
				}
				else
				{
					hasCurPt = true;
					curPtTime = *itPts;
					curPtValue = g_Hook_VClient_RenderView.m_CamPath.Eval(curPtTime);
					++itPts;
				}

				while(itKeysNext.GetTime() < curPtTime)
				{
					itKeysLast = itKeysNext;
					++itKeysNext;
				}

				if(itPts != m_TrajectoryPoints.end())
				{
					hasNextPt = true;
					nextPtTime = *itPts;
					nextPtValue = g_Hook_VClient_RenderView.m_CamPath.Eval(nextPtTime);
					++itPts;
				}
				else
				{
					// current point is last point.
					hasNextPt = false;
					nextPtValue = curPtValue;
				}

				if(!hasLastPt)
				{
					// current point is first point.
					lastPtValue = curPtValue;
				}

				// emit current point:
				{
					double deltaTime = abs(curTime -curPtTime);

					DWORD colour;

					// determine colour:
					if(deltaTime < 1.0)
					{
						double t = (deltaTime -0.0)/1.0;
						colour = D3DCOLOR_RGBA(
							ValToUCCondInv(255.0*t, curPtValue.Selected),
							ValToUCCondInv(255, curPtValue.Selected),
							ValToUCCondInv(0, curPtValue.Selected),
							(unsigned char)(127*(1.0-t))+128
						);
					}
					else
					if(deltaTime < 2.0)
					{
						double t = (deltaTime -1.0)/1.0;
						colour = D3DCOLOR_RGBA(
							ValToUCCondInv(255, curPtValue.Selected),
							ValToUCCondInv(255.0*(1.0-t), curPtValue.Selected),
							ValToUCCondInv(0, curPtValue.Selected),
							(unsigned char)(64*(1.0-t))+64
						);
					}
					else
					{
						colour = D3DCOLOR_RGBA(
							ValToUCCondInv(255, curPtValue.Selected),
							ValToUCCondInv(0, curPtValue.Selected),
							ValToUCCondInv(0, curPtValue.Selected),
							64
						);
					}

					AutoPolyLinePoint(
						Vector3(lastPtValue.X,lastPtValue.Y,lastPtValue.Z)
						, Vector3(curPtValue.X,curPtValue.Y,curPtValue.Z)
						, colour
						, Vector3(nextPtValue.X,nextPtValue.Y,nextPtValue.Z));
				}
			}
			while(hasNextPt);

			AutoPolyLineFlush();
		}

		// Draw keyframes:
		{
			newCScreenInfo[2] = c_CampathCrossPixelWidth;
			m_Device->SetVertexShaderConstantF(48, newCScreenInfo, 1);

			bool lpSelected = false;
			double lpTime;
			
			/*if(0 < g_Hook_VClient_RenderView.m_CamPath.GetSize())
			{
				// Test for not too unlikely hard case:
				CamPathValue cpv = g_Hook_VClient_RenderView.m_CamPath.GetBegin().GetValue();
				Vector3 current(cpv.X+76, cpv.Y+76, cpv.Z+76);
				Vector3 previous(current.X+76, current.Y-1*4, current.Z);
				Vector3 next(current.X+76, current.Y+1*4, current.Z);
				Vector3 next2(current.X, current.Y+2*4, current.Z);
				Vector3 next3(current.X+76, current.Y+3*4, current.Z);
				Vector3 next4(current.X, current.Y+4*4, current.Z);
				Vector3 next5(current.X+76, current.Y+5*4, current.Z);

				AutoPolyLineStart();
				AutoPolyLinePoint(previous, previous, D3DCOLOR_RGBA(255,0,0,255), current);
				AutoPolyLinePoint(previous, current, D3DCOLOR_RGBA(255,0,0,255), next);
				AutoPolyLinePoint(current, next, D3DCOLOR_RGBA(255,0,0,255), next2);
				AutoPolyLinePoint(next, next2, D3DCOLOR_RGBA(255,0,0,255), next3);
				AutoPolyLinePoint(next2, next3, D3DCOLOR_RGBA(255,0,0,255), next4);
				AutoPolyLinePoint(next3, next4, D3DCOLOR_RGBA(255,0,0,255), next5);
				AutoPolyLinePoint(next4, next5, D3DCOLOR_RGBA(255,0,0,255), next5);
				AutoPolyLineFlush();
			}*/
			
			/*if(0 < g_Hook_VClient_RenderView.m_CamPath.GetSize())
			{
				CamPathValue cpv = g_Hook_VClient_RenderView.m_CamPath.GetBegin().GetValue();

				float x = cpv.X * m_WorldToScreenMatrix.m[0][0] + cpv.Y * m_WorldToScreenMatrix.m[0][1] + cpv.Z * m_WorldToScreenMatrix.m[0][2] +m_WorldToScreenMatrix.m[0][3];
				float y = cpv.X * m_WorldToScreenMatrix.m[1][0] + cpv.Y * m_WorldToScreenMatrix.m[1][1] + cpv.Z * m_WorldToScreenMatrix.m[1][2] +m_WorldToScreenMatrix.m[1][3];
				float z = cpv.X * m_WorldToScreenMatrix.m[2][0] + cpv.Y * m_WorldToScreenMatrix.m[2][1] + cpv.Z * m_WorldToScreenMatrix.m[2][2] +m_WorldToScreenMatrix.m[2][3];
				float w = cpv.X * m_WorldToScreenMatrix.m[3][0] + cpv.Y * m_WorldToScreenMatrix.m[3][1] + cpv.Z * m_WorldToScreenMatrix.m[3][2] +m_WorldToScreenMatrix.m[3][3];

				float iw = w ? 1/w : 0;

				Tier0_Msg("pt: %f %f %f %f -> %f %f %f %f\n",x,y,z,w,x*iw,y*iw,z*iw,w*iw);
			}*/
		
			for(CamPathIterator it = g_Hook_VClient_RenderView.m_CamPath.GetBegin(); it != g_Hook_VClient_RenderView.m_CamPath.GetEnd(); ++it)
			{
				double cpT = it.GetTime();
				CamPathValue cpv = it.GetValue();

				cameraMightBeSelected = cameraMightBeSelected || lpSelected && cpv.Selected && lpTime <= curTime && curTime <= cpT;

				lpSelected = cpv.Selected;
				lpTime = cpT;

				double deltaTime = abs(curTime -cpT);

				bool selected = cpv.Selected;

				DWORD colour;

				// determine colour:
				if(deltaTime < 1.0)
				{
					double t = (deltaTime -0.0)/1.0;
					colour = D3DCOLOR_RGBA(
						ValToUCCondInv(255.0*t, selected),
						ValToUCCondInv(255, selected),
						ValToUCCondInv(0, selected),
						(unsigned char)(127*(1.0-t))+128
					);
				}
				else
				if(deltaTime < 2.0)
				{
					double t = (deltaTime -1.0)/1.0;
					colour = D3DCOLOR_RGBA(
						ValToUCCondInv(255, selected),
						ValToUCCondInv(255.0*(1.0-t), selected),
						ValToUCCondInv(0, selected),
						(unsigned char)(64*(1.0-t))+64
					);
				}
				else
				{
					colour = D3DCOLOR_RGBA(
						ValToUCCondInv(255, selected),
						ValToUCCondInv(0, selected),
						ValToUCCondInv(0, selected),
						64
					);
				}

				// x / forward line:

				AutoSingleLine(
					Vector3(cpv.X -c_CampathCrossRadius, cpv.Y, cpv.Z),
					colour,
					Vector3(cpv.X +c_CampathCrossRadius, cpv.Y, cpv.Z),
					colour
				);

				// y / left line:

				AutoSingleLine(
					Vector3(cpv.X, cpv.Y -c_CampathCrossRadius, cpv.Z),
					colour,
					Vector3(cpv.X, cpv.Y +c_CampathCrossRadius, cpv.Z),
					colour
				);

				// z / up line:

				AutoSingleLine(
					Vector3(cpv.X, cpv.Y, cpv.Z -c_CampathCrossRadius),
					colour,
					Vector3(cpv.X, cpv.Y, cpv.Z +c_CampathCrossRadius),
					colour
				);
			}

			AutoSingleLineFlush();
		}

		// Draw wireframe camera:
		if(inCampath && campathCanEval)
		{
			newCScreenInfo[2] = c_CameraPixelWidth;
			m_Device->SetVertexShaderConstantF(48, newCScreenInfo, 1);

			DWORD colourCam = campathEnabled
				? D3DCOLOR_RGBA(
					ValToUCCondInv(255,cameraMightBeSelected),
					ValToUCCondInv(0,cameraMightBeSelected),
					ValToUCCondInv(255,cameraMightBeSelected),
					128)
				: D3DCOLOR_RGBA(
					ValToUCCondInv(255,cameraMightBeSelected),
					ValToUCCondInv(255,cameraMightBeSelected),
					ValToUCCondInv(255,cameraMightBeSelected),
					128);
			DWORD colourCamUp = campathEnabled
				? D3DCOLOR_RGBA(
					ValToUCCondInv(0,cameraMightBeSelected),
					ValToUCCondInv(255,cameraMightBeSelected),
					ValToUCCondInv(0,cameraMightBeSelected),
					128)
				: D3DCOLOR_RGBA(
					ValToUCCondInv(0,cameraMightBeSelected),
					ValToUCCondInv(0,cameraMightBeSelected),
					ValToUCCondInv(0,cameraMightBeSelected),
					128);

			CamPathValue cpv = g_Hook_VClient_RenderView.m_CamPath.Eval(curTime);

			// limit to values as RenderView hook:
			cpv.Fov = max(1,cpv.Fov);
			cpv.Fov = min(179,cpv.Fov);

			double forward[3], right[3], up[3];
			QEulerAngles ang = cpv.R.ToQREulerAngles().ToQEulerAngles();
			MakeVectors(ang.Roll, ang.Pitch, ang.Yaw, forward, right, up);

			Vector3 vCp(cpv.X, cpv.Y, cpv.Z);
			Vector3 vForward(forward);
			Vector3 vUp(up);
			Vector3 vRight(right);

			//Tier0_Msg("----------------",curTime);
			//Tier0_Msg("currenTime = %f",curTime);
			//Tier0_Msg("vCp = %f %f %f\n", vCp.X, vCp.Y, vCp.Z);

			double a = sin(cpv.Fov * M_PI / 360.0) * c_CameraRadius;
			double b = a;

			int screenWidth, screenHeight;
			g_VEngineClient->GetScreenSize(screenWidth, screenHeight);

			double aspectRatio = screenWidth ? (double)screenHeight / (double)screenWidth : 1.0;

			b *= aspectRatio;

			Vector3 vLU = vCp +(double)c_CameraRadius * vForward -a * vRight +b * vUp;
			Vector3 vRU = vCp +(double)c_CameraRadius * vForward +a * vRight +b * vUp;
			Vector3 vLD = vCp +(double)c_CameraRadius * vForward -a * vRight -b * vUp;
			Vector3 vRD = vCp +(double)c_CameraRadius * vForward +a * vRight -b * vUp;
			Vector3 vMU = vLU +(vRU -vLU)/2;
			Vector3 vMUU = vMU +(double)c_CameraRadius * vUp;

			AutoSingleLine(vCp, colourCam, vLD, colourCam);

			AutoSingleLine(vCp, colourCam, vRD, colourCam);

			AutoSingleLine(vCp, colourCam, vLU, colourCam);

			AutoSingleLine(vCp, colourCam, vRU, colourCam);

			AutoSingleLine(vLD, colourCam, vRD, colourCam);

			AutoSingleLine(vRD, colourCam, vRU, colourCam);

			AutoSingleLine(vRU, colourCam, vLU, colourCam);

			AutoSingleLine(vLU, colourCam, vLD, colourCam);

			AutoSingleLine(vMU, colourCam, vMUU, colourCamUp);

			AutoSingleLineFlush();

			//
			/*

			colourCam = D3DCOLOR_RGBA(255, 0, 0, 255);
			colourCamUp = D3DCOLOR_RGBA(255, 255, 0, 255);

			vCp = vvPos;
			vForward = vvForward;
			vUp = vvUp;
			vRight = vvRight;

			//Tier0_Msg("vCp2 = %f %f %f\n", vCp.X, vCp.Y, vCp.Z);

			vLU = vCp +(double)c_CameraRadius * vForward -a * vRight +b * vUp;
			vRU = vCp +(double)c_CameraRadius * vForward +a * vRight +b * vUp;
			vLD = vCp +(double)c_CameraRadius * vForward -a * vRight -b * vUp;
			vRD = vCp +(double)c_CameraRadius * vForward +a * vRight -b * vUp;
			vMU = vLU +(vRU -vLU)/2;
			vMUU = vMU +(double)c_CameraRadius * vUp;

			AutoSingleLine(vCp, colourCam, vLD, colourCam);

			AutoSingleLine(vCp, colourCam, vRD, colourCam);

			AutoSingleLine(vCp, colourCam, vLU, colourCam);

			AutoSingleLine(vCp, colourCam, vRU, colourCam);

			AutoSingleLine(vLD, colourCam, vRD, colourCam);

			AutoSingleLine(vRD, colourCam, vRU, colourCam);

			AutoSingleLine(vRU, colourCam, vLU, colourCam);

			AutoSingleLine(vLU, colourCam, vLD, colourCam);

			AutoSingleLine(vMU, colourCam, vMUU, colourCamUp);

			AutoSingleLineFlush();
			*/
		}
	}

	// Restore device state:

	m_Device->SetPixelShader(oldPixelShader);
	if(oldPixelShader) oldPixelShader->Release();

	m_Device->SetVertexShader(oldVertexShader);
	if(oldVertexShader) oldVertexShader->Release();

	m_Device->SetStreamSource(0, oldVertexBuffer, oldVertexBufferOffset, oldVertexBufferStride);
	if(oldVertexBuffer) oldVertexBuffer->Release();

	m_Device->SetIndices(oldIndexBuffer);
	if(oldIndexBuffer) oldIndexBuffer->Release();

	m_Device->SetFVF(oldFVF);

	m_Device->SetVertexDeclaration(oldDeclaration);
	if(oldDeclaration) oldDeclaration->Release();

	m_Device->SetVertexShaderConstantF(8, oldCViewProj[0], 4);
	m_Device->SetVertexShaderConstantF(48, oldCScreenInfo, 1);
	m_Device->SetVertexShaderConstantF(49, oldCPlane0, 1);
	m_Device->SetVertexShaderConstantF(50, oldCPlaneN, 1);

	m_Device->SetRenderState(D3DRS_CULLMODE, oldCullMode);
	m_Device->SetRenderState(D3DRS_DESTBLEND, oldDestBlend);
	m_Device->SetRenderState(D3DRS_SRCBLEND, oldSrcBlend);
	m_Device->SetRenderState(D3DRS_BLENDOP, oldBlendOp);
	m_Device->SetRenderState(D3DRS_ALPHABLENDENABLE, oldAlphaBlendEnable);
	m_Device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, oldSeparateAlphaBlendEnable);
	m_Device->SetRenderState(D3DRS_ALPHATESTENABLE, oldAlphaTestEnable);
	m_Device->SetRenderState(D3DRS_ZFUNC, oldZFunc);
	m_Device->SetRenderState(D3DRS_ZWRITEENABLE, oldZWriteEnable);
	m_Device->SetRenderState(D3DRS_ZENABLE, oldZEnable);
	m_Device->SetRenderState(D3DRS_COLORWRITEENABLE, oldColorWriteEnable);
	m_Device->SetRenderState(D3DRS_SRGBWRITEENABLE, oldSrgbWriteEnable);
}
Exemplo n.º 17
0
void VisMouseCamera_cl::TickFunction(float fTimeDiff)
{
  hkvVec3 vMove = hkvVec3::ZeroVector();
  BOOL bUpDownMode = FALSE;

  float dx = m_pInputMap->GetTrigger(API_CAMERA_HORIZONTAL_LOOK);
  float dy = m_pInputMap->GetTrigger(API_CAMERA_VERTICAL_LOOK);

  if (m_pInputMap->GetTrigger(API_CAMERA_ACTION_1) && m_pInputMap->GetTrigger(API_CAMERA_ACTION_2))
    bUpDownMode = TRUE;
  else if (m_pInputMap->GetTrigger(API_CAMERA_ACTION_2))
    m_SpeedMode = 1;
  else if (m_pInputMap->GetTrigger(API_CAMERA_ACTION_3))
    m_SpeedMode = 2;
  else
    m_SpeedMode = 0;

  // handle keyboard status
#if !defined(_VISION_MOBILE) && !defined(_VISION_WINRT)
  if (m_pInputMap->GetTrigger(API_CAMERA_ANY_ACTION))
#endif
  {
    hkvVec3 vDir(hkvNoInitialization), vRight(hkvNoInitialization), vUp(hkvNoInitialization);
    vUp.set(0.f,0.f,1.f);
    if (GetPhysicsObject())
    {
      // local space
      vDir.set(1.f,0.f,0.f);
      vRight.set(0.f,1.f,0.f);
    } 
    else
    {
      hkvMat3 mat(hkvNoInitialization);
      GetRotationMatrix(mat);
      vDir = mat.getAxis(0);
      vRight = mat.getAxis(1);
    }

    float fMaxSpeed = m_fMoveSpeed;
    if (m_SpeedMode == 1)
      fMaxSpeed *= 3.0f;
    else if (m_SpeedMode == 2)
      fMaxSpeed *= 9.0f;

    // Accumulate move directions (multiply in order to take analog input into account).
    vMove += vDir * m_pInputMap->GetTrigger(API_CAMERA_MOVE_FORWARD);
    vMove -= vDir * m_pInputMap->GetTrigger(API_CAMERA_MOVE_BACKWARD);
    vMove -= vRight * m_pInputMap->GetTrigger(API_CAMERA_MOVE_RIGHT);
    vMove += vRight * m_pInputMap->GetTrigger(API_CAMERA_MOVE_LEFT);
    vMove += vUp *  m_pInputMap->GetTrigger(API_CAMERA_MOVE_UP);
    vMove -= vUp * m_pInputMap->GetTrigger(API_CAMERA_MOVE_DOWN);
    vMove *= fMaxSpeed;
   
    // Clamp movement, so that moving diagonally is not faster than moving straight 
    // when using digital input.
    const float fSpeed = vMove.getLength();
    if (fSpeed > fMaxSpeed)
      vMove.setLength(fMaxSpeed);
    vMove *= fTimeDiff;
  }

  if (m_pInputMap->GetTrigger(API_CAMERA_LOOK_CHANGED))
  {
    if (bUpDownMode)
    {
      IncOrientation(-dx * m_fSensitivity, 0, 0);
      vMove.z -= dy * m_fUpDownSpeed;
    }
    else
    {
      IncOrientation(-dx * m_fSensitivity, dy * m_fSensitivity, 0);                   
    }
  }

  switch(m_walkMode)
  {
  case WALK:
    // constrain vMove to the ground
    float len = vMove.getLength();
    vMove.z = 0.f;
    vMove.setLength(len);
    break;
  }

  if (GetPhysicsObject())
  {
    IncMotionDeltaLocalSpace(vMove);
  }
  else
  {
    IncPosition( vMove );
  }
}
Exemplo n.º 18
0
void World::Render()
{
    if( !mWorldInitialized )
        return;

    Renderer* renderer = GraphicSubsystem::Instance()->GetRenderer();
    GD_ASSERT(renderer);

    UInt32 viewWidth = renderer->GetRenderTarget()->GetWidth();
    UInt32 viewHeight = renderer->GetRenderTarget()->GetHeight();

    // Init.
    //renderer->BeginScene( Renderer::PointList );

    renderer->SetViewport( 0, 0, viewWidth, viewHeight );
    renderer->SetClearColor(Color4f(0.0f, 0.0f, 0.0f, 1.0f));
    renderer->SetRenderState( Renderer::Texture2D, false );
    renderer->SetRenderState( Renderer::DepthTest, true );
    //renderer->SetRenderState( Renderer::Lighting, true );
    //renderer->SetCulling( Renderer::CullBackFace );

    // Render.
    renderer->Clear( Renderer::ColorBuffer | Renderer::DepthBuffer );

    renderer->SetMatrixMode(Renderer::ProjectionMatrix);
    renderer->LoadIdentity();

    Camera* currentCamera = GetCurrentCamera();
    renderer->Perspective(currentCamera->GetFovAngle(),
                          viewWidth / static_cast<Float>(viewHeight),
                          currentCamera->GetNearView(), currentCamera->GetFarView());

    renderer->SetMatrixMode(Renderer::ModelViewMatrix);
    renderer->LoadIdentity();
    currentCamera->ApplyViewMatrix();
    /*
    Light light;
    light.mPosition = Vector3f( 4.32f, -3.0f, -3.4f ).Normalize();
    light.mAmbient  = Color4f(1.0f,1.0f, 1.0f,1.0f);
    light.mDiffuse  = Color4f(1.0f,1.0f, 1.0f,1.0f);
    light.mSpecular = Color4f(1.0f,1.0f, 1.0f,1.0f);
    light.mType = Renderer::LightDirectional;
    renderer->SetRenderState( Renderer::Light_i, true, 0 );
    renderer->SetLight( 0, light );*/

#if 0
    Matrix4d modelView;
    renderer->GetModelViewMatrix( modelView );

    Vector3f vRight( modelView[0], modelView[4], modelView[8] );
    Vector3f vUp( modelView[1], modelView[5], modelView[9] );

    Vector3f vBottomLeft  = light.mPosition + (-vRight - vUp).Normalize() * 2;
    Vector3f vBottomRight = light.mPosition + ( vRight - vUp).Normalize() * 2;
    Vector3f vTopRight    = light.mPosition + ( vRight + vUp).Normalize() * 2;
    Vector3f vTopLeft     = light.mPosition + (-vRight + vUp).Normalize() * 2;

    /*renderer->SetRenderState( Renderer::DepthMask, false );
    renderer->SetRenderState( Renderer::Lighting, false );
    renderer->SetRenderState( Renderer::Blend, true );
    renderer->SetBlendFunc( Renderer::BlendSrcAlpha, Renderer::BlendOne );*/
    renderer->SetRenderState( Renderer::Lighting, false );
    renderer->DrawQuad( vBottomLeft, vBottomRight, vTopRight, vTopLeft, false );
    renderer->SetRenderState( Renderer::Lighting, true );
#endif


    renderer->SetAmbiantColor( Color4f(1.0f, 1.0f, 1.0f, 1.0f) );

      /*Light lightPoint;
    lightPoint.mPosition = currentCamera->GetPosition();
    lightPoint.mAmbient  = Color4f(0.00f,0.00f, 0.00f,1.0f);
    lightPoint.mDiffuse  = Color4f(1.0f,1.0f, 1.0f,1.0f);
    lightPoint.mSpecular = Color4f(1.0f,1.0f, 1.0f,1.0f);
    lightPoint.mType = Renderer::LightPoint;
    lightPoint.mAttenuationConstant  = 0;
    lightPoint.mAttenuationLinear    = 0;
    lightPoint.mAttenuationQuadratic = 0.01f;
    renderer->SetRenderState( Renderer::Light_i, true, 0 );
    renderer->SetLight( 0, lightPoint );*/

	// Get the frustum.
	Matrix4f modelViewMatrix;
    Matrix4f projectionMatrix;
    Frustum  frustum;

	renderer->GetModelViewMatrix(modelViewMatrix);
	renderer->GetProjectionMatrix(projectionMatrix);
	frustum.CalculateFrustum(projectionMatrix, modelViewMatrix);

	mNbRenderedEntities = 0;

    // Render the objects in the world.
    /*
    List<Entity*> visibleEntities;
	mSpacePartition->Query(frustum, visibleEntities);
    */
    List<Entity*>::const_iterator itEntity;
    for( itEntity = mEntities.begin(); itEntity != mEntities.end(); ++itEntity )
    {
        if( *itEntity != currentCamera )
        {
			// Do frustum culling.
			if((*itEntity)->GetClass() != Terrain::StaticClass() &&
               (*itEntity)->GetClass() != SkyDome::StaticClass())
			{
				BoundingBox boundingBox = (*itEntity)->GetBoundingBox();

                if( (*itEntity)->GetClass() != ParticleEmitter::StaticClass() )
                {
                    Matrix4f translation = Matrix4f::Translation((*itEntity)->GetPosition());
				    Matrix4f rotation;
				    (*itEntity)->GetOrientation().ToMatrix(rotation);

				    Matrix4f trsMatrix = rotation * translation;
				    boundingBox.SetMin( boundingBox.Min() * trsMatrix );
				    boundingBox.SetMax( boundingBox.Max() * trsMatrix );
                }

				if( frustum.BoxInFrustum(boundingBox) )
				{
					mNbRenderedEntities++;
				}
				else
				{
					continue;
				}
			}

            renderer->PushMatrix();

            if( String((*itEntity)->GetClass()->GetName()) == "SkyDome" )
                renderer->Translate(currentCamera->GetPosition()-Vector3f(0,100,0) );
            else
                renderer->Translate((*itEntity)->GetPosition());

            renderer->Rotate((*itEntity)->GetOrientation());

            if( (*itEntity)->IsSelected() )
                (*itEntity)->RenderSelected();

            (*itEntity)->Render();

            renderer->PopMatrix();
        }
    }

    renderer->SetMatrixMode(Renderer::ModelViewMatrix);
    renderer->LoadIdentity();
    currentCamera->ApplyViewMatrix();

    //renderer->EndScene();
}