//
// Now that have the spaces in the Broad Collision Zone,
//	determine which of those are within the Lookahead Zone.
//
void LookaheadCollisionFilter::Filter(
	list<Space *> * pFiltered,	// in, out
	list<Space *> * pCollided,
	float2 fScreenDimensions,
	list<float2> * fCollisionZonePixels,
	ActionParameter * pActionParameter)
{
	float2 vertices[5];
	vertices[LEFT_TOP] = *(fCollisionZonePixels->begin());
	vertices[RIGHT_TOP] = *(next(fCollisionZonePixels->begin()));
	vertices[RIGHT_BOTTOM] = *(next(next(fCollisionZonePixels->begin())));
	vertices[LEFT_BOTTOM] = *(next(next(next(fCollisionZonePixels->begin()))));
	vertices[4] = *(next(next(next(next(fCollisionZonePixels->begin())))));

	// These never change and don't need to be inside the loops.
	XMVECTOR vecCollidedVertices[4];

	vecCollidedVertices[LEFT_TOP] =
		XMVectorSet(
			GRID->GetColumnWidth() / -2.0f,
			GRID->GetRowHeight() / -2.0f,
			0.0f,
			0.0f);

	vecCollidedVertices[RIGHT_TOP] =
		XMVectorSet(
			GRID->GetColumnWidth() / 2.0f,
			GRID->GetRowHeight() / -2.0f,
			0.0f,
			0.0f);

	vecCollidedVertices[RIGHT_BOTTOM] =
		XMVectorSet(
			(GRID->GetColumnWidth() / 2.0f),
			GRID->GetRowHeight() / 2.0f,
			0.0f,
			0.0f);

	vecCollidedVertices[LEFT_BOTTOM] =
		XMVectorSet(
			GRID->GetColumnWidth() / -2.0f,
			GRID->GetRowHeight() / 2.0f,
			0.0f,
			0.0f);

	// For each line segment of the lookahead zone...
	for (int i = 0; i < 4; i++)
	{
		// Need to determine the line equations 
		//	that make up each side of the lookahead zone.
		//	Need to consider rotation when determining
		//	how to calculate slope of each line.

		// Check which vertex is on the left.
		float2 fPt1 = vertices[i % 4];
		float2 fPt2 = vertices[(i + 1) % 4];

		LineSegment * currentLookaheadZoneLineSegment = 
			new LineSegment(fPt1, fPt2);

		list<Space *>::const_iterator iteratorSpaces;

		// For each of the Spaces in the broad zone,
		//	determine their vertices.
		for (iteratorSpaces = pCollided->begin();
			iteratorSpaces != pCollided->end();
			iteratorSpaces++)
		{
			float2 fCollidedCenter = (*iteratorSpaces)->GetLocationRatio();

			float fCollidedRotation = 
				FLOAT((*iteratorSpaces)->GetAttributes()->LookupValue(A_ROTATION));

			XMMATRIX translationMatrix =
				XMMatrixTransformation2D(
					XMVectorSet(
						fCollidedCenter.x * fScreenDimensions.x,
						fCollidedCenter.y * fScreenDimensions.y,
						0.0f,
						0.0f),
					1.0f,
					XMVectorSet(1.0f, 1.0f, 0.0f, 0.0f),
					XMVectorSet(
						fCollidedCenter.x * fScreenDimensions.x,
						fCollidedCenter.y * fScreenDimensions.y,
						0.0f,
						0.0f),
					0.0f,
					XMVectorSet(
						fCollidedCenter.x * fScreenDimensions.x,
						fCollidedCenter.y * fScreenDimensions.y,
						0.0f,
						0.0f));


			XMMATRIX rotationMatrix =
				XMMatrixTransformation2D(
					XMVectorSet(
						fCollidedCenter.x * fScreenDimensions.x,
						fCollidedCenter.y * fScreenDimensions.y,
						0.0f,
						0.0f),
					1.0f,
					XMVectorSet(1.0f, 1.0f, 0.0f, 0.0f),
					XMVectorSet(
						fCollidedCenter.x * fScreenDimensions.x,
						fCollidedCenter.y * fScreenDimensions.y,
						0.0f,
						0.0f),
					XMConvertToRadians(360.0f - fCollidedRotation),
					XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f));

			XMVECTOR vecTransform[4];

			for (int i = LEFT_TOP; i <= LEFT_BOTTOM; i++)
			{
				vecTransform[i] = XMVector3Transform(vecCollidedVertices[i], translationMatrix * rotationMatrix);
			}

			LineSegment lineSegments[4];

			// Locations (i.e. LEFT_TOP, etc) are relative due east (0 degrees).
			lineSegments[0] = 
				LineSegment
				{
					float2 { XMVectorGetX(vecTransform[LEFT_TOP]), XMVectorGetY(vecTransform[LEFT_TOP]) },
					float2 { XMVectorGetX(vecTransform[RIGHT_TOP]), XMVectorGetY(vecTransform[RIGHT_TOP]) }
				};

			lineSegments[1] =
				LineSegment
				{
					float2{ XMVectorGetX(vecTransform[RIGHT_TOP]), XMVectorGetY(vecTransform[RIGHT_TOP]) },
					float2{ XMVectorGetX(vecTransform[RIGHT_BOTTOM]), XMVectorGetY(vecTransform[RIGHT_BOTTOM]) }
				};

			lineSegments[2] =
				LineSegment
				{
					float2{ XMVectorGetX(vecTransform[RIGHT_BOTTOM]), XMVectorGetY(vecTransform[RIGHT_BOTTOM]) },
					float2{ XMVectorGetX(vecTransform[LEFT_BOTTOM]), XMVectorGetY(vecTransform[LEFT_BOTTOM]) }
				};

			lineSegments[3] =
				LineSegment
				{
					float2{ XMVectorGetX(vecTransform[LEFT_BOTTOM]), XMVectorGetY(vecTransform[LEFT_BOTTOM]) },
					float2{ XMVectorGetX(vecTransform[LEFT_TOP]), XMVectorGetY(vecTransform[LEFT_TOP]) }
				};

			for (int i = 0; i <= 3; i++)
			{
				float fIntersectionX = 0.0f;
				float fIntersectionY = 0.0f;

				if (Utils::DoLinesIntersect(
					*currentLookaheadZoneLineSegment,
					lineSegments[i],
					&fIntersectionX,
					&fIntersectionY))
				{
					pFiltered->push_back(*iteratorSpaces);
				}
			}	
		}

		delete currentLookaheadZoneLineSegment;
	}
}
void D3DCamera::SetPosition(XMFLOAT3& pos)
{
    m_Position = XMVectorSet(pos.x, pos.y, pos.z, 0);
}
Пример #3
0
#include "MaterialTextureOps.h"
#include "MaterialExperimental.h"
#include "MaterialPostprocess.h"

#include "MaterialSystem.h"

static const unsigned int scMaterialSystemMemorySize = 512 * 1024;
static const unsigned int scPhongMaterialsSegmentSize = 512;
static const unsigned int scPlainColorMaterialsSegmentSize = 3;
static const unsigned int scTextured2DMaterialsSegmentSize = 2;
static const unsigned int scMipGeneratorMaterialsSegmentSize = 1;
static const unsigned int scLinearTo2DMaterialsSegmentSize = 3;
static const unsigned int scExperimentalMaterialsSegmentSize = 100;
static const unsigned int scPostprocessMaterialsSegmentSize = 1;

static XMVECTOR sPink = XMVectorSet(1.0f, 0.0f, 1.0f, 1.0f);
static XMVECTOR sBlack = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);


//----------------------------------------------------------------------------------
void CMaterial::SetSRV(ID3D11DeviceContext* pDeviceContext, const CShaderResourceInfo& ResourceInfo, ID3D11ShaderResourceView* pSRV) const
{
	ID3D11ShaderResourceView* ppSRV[1] = { pSRV };
	if (ResourceInfo.m_ResourceInfo[eVertexShader].m_NumViews > 0)
	{
		pDeviceContext->VSSetShaderResources(ResourceInfo.m_ResourceInfo[eVertexShader].m_StartSlot, ResourceInfo.m_ResourceInfo[eVertexShader].m_NumViews, ppSRV);
	}

	if (ResourceInfo.m_ResourceInfo[ePixelShader].m_NumViews > 0)
	{
		pDeviceContext->PSSetShaderResources(ResourceInfo.m_ResourceInfo[ePixelShader].m_StartSlot, ResourceInfo.m_ResourceInfo[ePixelShader].m_NumViews, ppSRV);
Пример #4
0
void MazeSide::SetRotation( float x, float y, float z, float w )
{
	_rotation.Reset( XMVectorSet( x, y, z, w ) );
}
QuatApp::QuatApp(HINSTANCE hInstance)
: D3DApp(hInstance), mShapesVB(0), mShapesIB(0), mSkullVB(0), mSkullIB(0), 
  mFloorTexSRV(0), mStoneTexSRV(0), mBrickTexSRV(0),
  mSkullIndexCount(0), mAnimTimePos(0.0f)
{
	mMainWndCaption = L"Quaternion Demo";
	
	mLastMousePos.x = 0;
	mLastMousePos.y = 0;

	mCam.Pitch(XMConvertToRadians(25.0f));
	mCam.SetPosition(0.0f, 8.0f, -20.0f);

	XMMATRIX I = XMMatrixIdentity();
	XMStoreFloat4x4(&mGridWorld, I);

	XMMATRIX boxScale = XMMatrixScaling(3.0f, 1.0f, 3.0f);
	XMMATRIX boxOffset = XMMatrixTranslation(0.0f, 0.5f, 0.0f);
	XMStoreFloat4x4(&mBoxWorld, XMMatrixMultiply(boxScale, boxOffset));

	for(int i = 0; i < 5; ++i)
	{
		XMStoreFloat4x4(&mCylWorld[i*2+0], XMMatrixTranslation(-5.0f, 1.5f, -10.0f + i*5.0f));
		XMStoreFloat4x4(&mCylWorld[i*2+1], XMMatrixTranslation(+5.0f, 1.5f, -10.0f + i*5.0f));

		XMStoreFloat4x4(&mSphereWorld[i*2+0], XMMatrixTranslation(-5.0f, 3.5f, -10.0f + i*5.0f));
		XMStoreFloat4x4(&mSphereWorld[i*2+1], XMMatrixTranslation(+5.0f, 3.5f, -10.0f + i*5.0f));
	}

	mDirLights[0].Ambient  = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
	mDirLights[0].Diffuse  = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
	mDirLights[0].Specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
	mDirLights[0].Direction = XMFLOAT3(0.57735f, -0.57735f, 0.57735f);

	mDirLights[1].Ambient  = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
	mDirLights[1].Diffuse  = XMFLOAT4(0.20f, 0.20f, 0.20f, 1.0f);
	mDirLights[1].Specular = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f);
	mDirLights[1].Direction = XMFLOAT3(-0.57735f, -0.57735f, 0.57735f);

	mDirLights[2].Ambient  = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
	mDirLights[2].Diffuse  = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
	mDirLights[2].Specular = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
	mDirLights[2].Direction = XMFLOAT3(0.0f, -0.707f, -0.707f);

	mGridMat.Ambient  = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
	mGridMat.Diffuse  = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
	mGridMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f);

	mCylinderMat.Ambient  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mCylinderMat.Diffuse  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mCylinderMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f);

	mSphereMat.Ambient  = XMFLOAT4(0.6f, 0.8f, 0.9f, 1.0f);
	mSphereMat.Diffuse  = XMFLOAT4(0.6f, 0.8f, 0.9f, 1.0f);
	mSphereMat.Specular = XMFLOAT4(0.9f, 0.9f, 0.9f, 16.0f);

	mBoxMat.Ambient  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mBoxMat.Diffuse  = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
	mBoxMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f);

	mSkullMat.Ambient  = XMFLOAT4(0.4f, 0.4f, 0.4f, 1.0f);
	mSkullMat.Diffuse  = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
	mSkullMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 16.0f);

	//
	// Define the animation keyframes
	//

	XMVECTOR q0 = XMQuaternionRotationAxis(XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f), XMConvertToRadians(30.0f)); 
	XMVECTOR q1 = XMQuaternionRotationAxis(XMVectorSet(1.0f, 1.0f, 2.0f, 0.0f), XMConvertToRadians(45.0f)); 
	XMVECTOR q2 = XMQuaternionRotationAxis(XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f), XMConvertToRadians(-30.0f)); 
	XMVECTOR q3 = XMQuaternionRotationAxis(XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f), XMConvertToRadians(70.0f)); 

	mSkullAnimation.Keyframes.resize(5);
	mSkullAnimation.Keyframes[0].TimePos = 0.0f;
	mSkullAnimation.Keyframes[0].Translation = XMFLOAT3(-7.0f, 0.0f, 0.0f);
	mSkullAnimation.Keyframes[0].Scale = XMFLOAT3(0.25f, 0.25f, 0.25f);
	XMStoreFloat4(&mSkullAnimation.Keyframes[0].RotationQuat, q0);

	mSkullAnimation.Keyframes[1].TimePos = 2.0f;
	mSkullAnimation.Keyframes[1].Translation = XMFLOAT3(0.0f, 2.0f, 10.0f);
	mSkullAnimation.Keyframes[1].Scale = XMFLOAT3(0.5f, 0.5f, 0.5f);
	XMStoreFloat4(&mSkullAnimation.Keyframes[1].RotationQuat, q1);

	mSkullAnimation.Keyframes[2].TimePos = 4.0f;
	mSkullAnimation.Keyframes[2].Translation = XMFLOAT3(7.0f, 0.0f, 0.0f);
	mSkullAnimation.Keyframes[2].Scale = XMFLOAT3(0.25f, 0.25f, 0.25f);
	XMStoreFloat4(&mSkullAnimation.Keyframes[2].RotationQuat, q2);

	mSkullAnimation.Keyframes[3].TimePos = 6.0f;
	mSkullAnimation.Keyframes[3].Translation = XMFLOAT3(0.0f, 1.0f, -10.0f);
	mSkullAnimation.Keyframes[3].Scale = XMFLOAT3(0.5f, 0.5f, 0.5f);
	XMStoreFloat4(&mSkullAnimation.Keyframes[3].RotationQuat, q3);

	mSkullAnimation.Keyframes[4].TimePos = 8.0f;
	mSkullAnimation.Keyframes[4].Translation = XMFLOAT3(-7.0f, 0.0f, 0.0f);
	mSkullAnimation.Keyframes[4].Scale = XMFLOAT3(0.25f, 0.25f, 0.25f);
	XMStoreFloat4(&mSkullAnimation.Keyframes[4].RotationQuat, q0);
}
Пример #6
0
void Camera::Reset()
{
	mEye = XMVectorSet(0.0f, 15.0f, -30.0f, 0.0f);
	mAt = XMVectorSet(0.0f, 8.0f, 0.0f, 0.0f);
	mUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
}
Пример #7
0
int MainScene1::Initialize(aurora::Engine* engine) { 
  GameView::Initialize(engine);
  
  //core::delegation::one::pair<graphics::Effect,int,void> p(&main_effect_,0);
  func.Bind<graphics::Effect>(main_effect_,&graphics::Effect::Begin);
  func = core::delegation::none::pair<graphics::Effect,int>(main_effect_,&graphics::Effect::Begin);

  aurora::resource::EffectResource* res = engine_->resource_manager.GetResourceById<aurora::resource::EffectResource>(2);
  main_effect_ = res->effect();
  /*main_effect_.Initialize(&engine_->gfx_context());
  int hr;
  hr = main_effect_.CreateFromMemory(res->data_pointer,res->data_length);
  if (FAILED(hr)) {
    return hr;
  }*/
  int hr;

  // Initialize the view matrix
  XMVECTOR Eye = XMVectorSet( 0.0f, 3.0f, -6.0f, 0.0f );
  XMVECTOR At = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
  XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
  camera_.view() = XMMatrixLookAtLH( Eye, At, Up );
  camera_.Perspective();
  camera_.UpdateConstantBuffer();
  //camera_.Ortho2D();
  //camera_.view() = XMMatrixScaling(0.4f,0.4f,0.4f);// * XMMatrixTranslation(0.5,0,0);

  // Create vertex buffer
  SimpleVertex vertices[] =
  {
      { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.5f, 0.0f ) },
      { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.5f, 0.5f ) },
      { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.2f, 0.5f ) },

      { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
      { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

      { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
      { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
      { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
      { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

      { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
      { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

      { XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
      { XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 1.0f ) },

      { XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
      { XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
      { XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
  };

  //D3D11_BUFFER_DESC bd;
  //ZeroMemory( &bd, sizeof(bd) );

  {
  
    g_vb.description.bind_flags = D3D11_BIND_VERTEX_BUFFER;
    g_vb.description.usage = D3D11_USAGE_DEFAULT;
    g_vb.description.byte_width = sizeof( SimpleVertex ) * 24;
    g_vb.description.cpu_access_flags = 0;
    engine_->gfx_context().CreateBuffer(g_vb,NULL);
    //uint32_t index,uint32_t type,
    //graphics::BufferSubresource subresource;
    engine_->gfx_context().device_context()->UpdateSubresource((ID3D11Resource*)g_vb.internal_pointer,0,NULL,vertices,sizeof(vertices),0);
  }

  WORD indices[] =
  {
      3,1,0,
      2,1,3,

      6,4,5,
      7,4,6,

      11,9,8,
      10,9,11,

      14,12,13,
      15,12,14,

      19,17,16,
      18,17,19,

      22,20,21,
      23,20,22
  };

  {

    g_ib.description.bind_flags = D3D11_BIND_INDEX_BUFFER;
    g_ib.description.usage = D3D11_USAGE_DEFAULT;
    g_ib.description.byte_width = sizeof( uint16_t ) * 36;
    g_ib.description.cpu_access_flags = 0;
    engine_->gfx_context().CreateBuffer(g_ib,NULL);
    //uint32_t index,uint32_t type,
    //graphics::BufferSubresource subresource;
    engine_->gfx_context().device_context()->UpdateSubresource((ID3D11Resource*)g_ib.internal_pointer,0,NULL,indices,sizeof(indices),0);
  }



    
  //bd.ByteWidth = sizeof(CBChangeOnResize);
  //hr = gfx_context_.device()->CreateBuffer( &bd, NULL, &g_pCBChangeOnResize );
  //if( FAILED( hr ) )
  //    return hr;
    
  g_pCBChangesEveryFrame.description.bind_flags = D3D11_BIND_CONSTANT_BUFFER;
  g_pCBChangesEveryFrame.description.usage = D3D11_USAGE_DEFAULT;
  g_pCBChangesEveryFrame.description.byte_width = sizeof(ConstantBuffer2Type);
  g_pCBChangesEveryFrame.description.cpu_access_flags = 0;
  hr = engine_->gfx_context().CreateBuffer(g_pCBChangesEveryFrame,NULL);
  if( FAILED( hr ) )
      return hr;

  // Load the Texture
  hr = D3DX11CreateShaderResourceViewFromFile( engine_->gfx_context().device(), "Content\\arial31_0.png", NULL, NULL, &g_pTextureRV, NULL );
  if( FAILED( hr ) )
      return hr;

    
  D3D11_BLEND_DESC BlendStateDescription;
  ZeroMemory(&BlendStateDescription,sizeof(BlendStateDescription));
  BlendStateDescription.AlphaToCoverageEnable = false;
  BlendStateDescription.RenderTarget[0].BlendEnable = true;

  BlendStateDescription.RenderTarget[0].SrcBlend                  = D3D11_BLEND_SRC_ALPHA;        //D3D11_BLEND_SRC_COLOR;
  BlendStateDescription.RenderTarget[0].DestBlend                 = D3D11_BLEND_INV_SRC_ALPHA;//D3D11_BLEND_DEST_COLOR;
  BlendStateDescription.RenderTarget[0].SrcBlendAlpha             = D3D11_BLEND_ONE;//D3D11_BLEND_SRC_ALPHA;
  BlendStateDescription.RenderTarget[0].DestBlendAlpha    = D3D11_BLEND_ONE;//D3D11_BLEND_DEST_ALPHA;
  BlendStateDescription.RenderTarget[0].BlendOp                   = D3D11_BLEND_OP_ADD;
  BlendStateDescription.RenderTarget[0].BlendOpAlpha              = D3D11_BLEND_OP_ADD;
  BlendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
    
  engine_->gfx_context().device()->CreateBlendState(&BlendStateDescription,&blend_state);
  float blendFactor[] = {1,1, 1, 1};
      UINT sampleMask   = 0xffffffff;
  engine_->gfx_context().device_context()->OMSetBlendState(blend_state,blendFactor,sampleMask);
    

  // Initialize the world matrices
  g_World = XMMatrixIdentity();


  motion1.set_context(&engine_->animation());
  motion1.set_from(0);
  motion1.set_to(2);
  motion1.set_max_time(1000000);
  motion1.set_value_ptr(&move_z);
  engine_->animation().tween_list.push_back(&motion1);
  move_z=0;
  motion1.Play();
  return S_OK; 
}
Пример #8
0
HRESULT c_app_scene::on_d3d11_create_device(ID3D11Device *d3d11_device, const DXGI_SURFACE_DESC *backbuf_surface_desc)
{
    HRESULT hr;

    ////////////////////////////////////////////////////////////////////////
    // Compile effect

    d3d11_blob_ptr effect_blob, error_blob;
    V(D3DX11CompileFromFile(fx_file_name.c_str(),           // effect file name
        NULL,                           // defines
        NULL,                           // includes
        NULL,                           // function name
        "fx_5_0",                       // profile
        D3D10_SHADER_DEBUG,             // compile flag
        NULL,                           // compile flag
        NULL,                           // thread pump
        &effect_blob,                   // effect buffer
        &error_blob,                    // error buffer
        NULL));

    V(D3DX11CreateEffectFromMemory(effect_blob->GetBufferPointer(),         // effect buffer pointer
        effect_blob->GetBufferSize(),
        0,
        d3d11_device,
        &m_scene_effect));
    
    m_render_scene_tech = m_scene_effect->GetTechniqueByName(render_scene_tech_name.c_str());
    m_cb0_var = m_scene_effect->GetConstantBufferByName(cb_var_name.c_str());
    m_tex_diffuse = m_scene_effect->GetVariableByName(tex_diffuse_var_name.c_str())->AsShaderResource();
    
    //////////////////////////////////////////////////////////////////////////
    // Create input layout

    const D3D11_INPUT_ELEMENT_DESC input_layout_mesh[] =
    {
        {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}
    };

    unsigned int num_elements = ARRAYSIZE(input_layout_mesh);
    D3DX11_PASS_DESC pass_desc;
    m_render_scene_tech->GetPassByIndex(0)->GetDesc(&pass_desc);
    V(d3d11_device->CreateInputLayout(input_layout_mesh, num_elements, pass_desc.pIAInputSignature, pass_desc.IAInputSignatureSize, &m_mesh_input_layout));
   
    //////////////////////////////////////////////////////////////////////////
    // Create constant buffer

    D3D11_BUFFER_DESC cb_desc;
    cb_desc.Usage =D3D11_USAGE_DEFAULT;
    cb_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cb_desc.CPUAccessFlags = 0; 
    cb_desc.MiscFlags = 0;
    cb_desc.ByteWidth = sizeof(cb0);
    V(d3d11_device->CreateBuffer(&cb_desc, NULL, &m_cb0)); 

    //////////////////////////////////////////////////////////////////////////
    // Load mesh

    m_city_mesh.reset(new CDXUTSDKMesh()); 
    m_scanner_mesh.reset(new CDXUTSDKMesh());
    m_column_mesh.reset(new CDXUTSDKMesh());
   
    SDKMESH_CALLBACKS11 sdkmesh_callbacks;
    sdkmesh_callbacks.pContext = this;
    sdkmesh_callbacks.pCreateIndexBuffer = 0; 
    sdkmesh_callbacks.pCreateVertexBuffer = 0; 
    sdkmesh_callbacks.pCreateTextureFromFile = load_texture_from_file; 
    V(m_city_mesh->Create(d3d11_device, mesh_descs[0].path.c_str(), true, &sdkmesh_callbacks));
    V(m_scanner_mesh->Create(d3d11_device, mesh_descs[1].path.c_str(), true, &sdkmesh_callbacks));
    V(m_column_mesh->Create(d3d11_device, mesh_descs[2].path.c_str(), true, &sdkmesh_callbacks));
    
    //////////////////////////////////////////////////////////////////////////
    // Setup the camera
    
    m_camera.reset(new CModelViewerCamera());
    XMVECTOR lookat = XMVectorSet(0.0f, 0.8f, -2.3f, 1.0f);
    XMVECTOR eye_pos = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
    m_camera->SetViewParams((D3DXVECTOR3*)&lookat, (D3DXVECTOR3*)&eye_pos);

    return S_OK;
}
Пример #9
0
void MyApp::editTerrain()
{
	if (!glb_bOn || !m_LButtonDown)
		return;

	//------------------------------------------------------------
	int w = width(), h = height();

	XMMATRIX P = m_camera.getProjectionMatrix();

	// Compute picking ray in view space.
	float vx = (+2.0f*m_mouseX/w  - 1.0f)/P(0,0);
	float vy = (-2.0f*m_mouseY/h + 1.0f)/P(1,1);

	// Ray definition in view space.
	XMVECTOR rayOrigin = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
	XMVECTOR rayDir    = XMVectorSet(vx, vy, 1.0f, 0.0f);

	// Tranform ray to local space of Mesh.
	XMMATRIX V = m_camera.getViewMatrix();
	XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(V), V);

	rayOrigin = XMVector3TransformCoord(rayOrigin, invView);
	rayDir = XMVector3TransformNormal(rayDir, invView);

	rayDir = XMVector3Normalize(rayDir);
	

	XMFLOAT4 oo, rr;
	XMStoreFloat4(&oo, rayOrigin);
	XMStoreFloat4(&rr, rayDir);


	XMVECTOR a = XMVectorSet(0,0,0,1); // point on plane
	XMVECTOR n = XMVectorSet(0,1,0,0); // plane's normal

	XMVECTOR res = XMVector3Dot((a - rayOrigin), n) / XMVector4Dot(rayDir, n);
	
	float t = XMVectorGetX(res);

	XMVECTOR hit_point = rayOrigin + t*rayDir;
	XMFLOAT4 hp;
	XMStoreFloat4(&hp, hit_point);


	XMFLOAT2 coords;
	coords.x = XMVectorGetX(hit_point) / GRID_WIDTH + 0.5f;
	coords.y = XMVectorGetZ(hit_point) / GRID_WIDTH + 0.5f;
	coords.y = 1.0f - coords.y;

	XMFLOAT4 mo, md;
	XMStoreFloat4(&mo, rayOrigin);
	XMStoreFloat4(&md, rayDir);

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


	// save/set Render Target View
	ID3D11DepthStencilView* dsv;
	ID3D11RenderTargetView* rtv;
	_dxImmedDC->OMGetRenderTargets(1, &rtv, &dsv);
	D3D11_VIEWPORT vp;
	UINT vp_num = 1;
	_dxImmedDC->RSGetViewports(&vp_num, &vp);

	D3D11_VIEWPORT new_vp;
	new_vp.Height = 1024;
	new_vp.Width = 1024;
	new_vp.MaxDepth =1.0f;
	new_vp.MinDepth = 0.0f;
	new_vp.TopLeftX = new_vp.TopLeftY = 0.0f;
	_dxImmedDC->RSSetViewports(1, &new_vp);


	_dxImmedDC->OMSetRenderTargets(1, &m_rtvDynamicHmap, 0);
	
	// save input layout
	ID3D11InputLayout* ia;
	_dxImmedDC->IAGetInputLayout(&ia);

	// set null layout
	_dxImmedDC->IASetInputLayout(0);
	_dxImmedDC->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);

	setBoolVar(m_fxDynamicTerrain, glb_bAdditive, "bAdditive");
	setVectorVar(m_fxDynamicTerrain, (void*)&coords, "vCoords");
	setFloatVar(m_fxDynamicTerrain, glb_Range, "fRange");

	// draw 4 points (-> quad)
	ID3DX11EffectTechnique* tech;
	tech = m_fxDynamicTerrain->GetTechniqueByIndex(0);
	tech->GetPassByIndex(0)->Apply(0, _dxImmedDC);
	_dxImmedDC->Draw(4, 0);

	// restore IA layout, rtv, dsv
	_dxImmedDC->OMSetRenderTargets(1, &rtv, dsv);
	_dxImmedDC->IASetInputLayout(ia);
	_dxImmedDC->OMSetBlendState(0, 0, 0xffffffff);
	_dxImmedDC->OMSetDepthStencilState(0, 0);
	_dxImmedDC->RSSetViewports(1, &vp);


}
Пример #10
0
void wam::UpdateScene(float dt)
{

	if( GetAsyncKeyState('P') & 0x8000 )
		mPhi += 0.01f;
	if( GetAsyncKeyState('p') & 0x8000 )
		mPhi -= 0.01f;
	if( GetAsyncKeyState('O') & 0x8000 )
		mTheta += 0.01f;
	if( GetAsyncKeyState('o') & 0x8000 )
		mTheta -= 0.01f;

	// Convert Spherical to Cartesian coordinates.
	float x = mRadius*sinf(mPhi)*cosf(mTheta);
	float z = mRadius*sinf(mPhi)*sinf(mTheta);
	float y = mRadius*cosf(mPhi) ;

	// Build the view matrix.
	XMVECTOR pos    = XMVectorSet(x, y, z, 1.0f);
	XMVECTOR target = XMVectorZero();
	XMVECTOR up     = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	XMMATRIX V = XMMatrixLookAtLH(pos, target, up);
//	XMStoreFloat4x4(&mView, V);
	mCam.LookAt(pos,target,up);

	if( GetAsyncKeyState('W') & 0x8000 )
		mCam.Walk(10.0f*dt);

	if( GetAsyncKeyState('S') & 0x8000 )
		mCam.Walk(-10.0f*dt);

	if( GetAsyncKeyState('A') & 0x8000 )
		mCam.Strafe(-10.0f*dt);

	if( GetAsyncKeyState('D') & 0x8000 )
		mCam.Strafe(10.0f*dt);



	static float tM=0;
	static float tR=0;
	tM+=dt;
	tR+=dt;
	//update the moles in action
	if(tM > mTimeStepMovement)
	{	
		for(int i=0;i<9;i++)
		{
			float yTarget =mMoleSpeeds[i]>0?mEndY:mStartY;
			if(mMoleSpeeds[i]!=0)
			{
				if((mMoleLocations[i].y + mMoleSpeeds[i])>=mEndY)
					mMoleSpeeds[i]= -mSpeed;
				if((mMoleLocations[i].y + mMoleSpeeds[i])<=mStartY)
					mMoleSpeeds[i] = 0;
				mMoleLocations[i].y += mMoleSpeeds[i]; 
			}
		}
		tM=0.0f;
	}

	if(tR>mTimeStepInitiateMovement)
	{
		bool acceptablePick=false;
		int indexPick=0;
		int guessPick=0;
		while(!acceptablePick && MolesInMotion()<3)
		{
			indexPick = (int)MathHelper::RandF(0,9);
			if(mMoleSpeeds[indexPick]==0)
			{
				acceptablePick=true;
				mMoleSpeeds[indexPick]=mSpeed;
			}
			guessPick++; //ensure that we don't hit an infinite loop if a lot of moles are in action
		}
		tR=MathHelper::RandF(0.7f,3.0f);
	}

	//if appropriate time passed
	//put a new mole into action

}
Пример #11
0
void wam::Pick(int sx, int sy)
{
	
XMMATRIX P = mCam.Proj();

	// Compute picking ray in view space.
	float vx = (+2.0f*sx/mClientWidth  - 1.0f)/P(0,0);
	float vy = (-2.0f*sy/mClientHeight + 1.0f)/P(1,1);

	// Ray definition in view space.
	XMVECTOR rayOrigin = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f);
	XMVECTOR rayDir    = XMVectorSet(vx, vy, 1.0f, 0.0f);

	// Tranform ray to local space of Mesh.
	XMMATRIX V = mCam.View();
	XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(V), V);

	XMMATRIX W = XMLoadFloat4x4(&mGridWorld);
	XMMATRIX invWorld = XMMatrixInverse(&XMMatrixDeterminant(W), W);

	XMMATRIX toLocal = XMMatrixMultiply(invView, invWorld);

	rayOrigin = XMVector3TransformCoord(rayOrigin, toLocal);
	rayDir = XMVector3TransformNormal(rayDir, toLocal);

	// Make the ray direction unit length for the intersection tests.
	rayDir = XMVector3Normalize(rayDir);
	
		XNA::Sphere tmpSphere11,tmpSphere12,tmpSphere13,tmpSphere21,tmpSphere22,tmpSphere23,tmpSphere31,tmpSphere32,tmpSphere33;
		float radius =0.5f;
		tmpSphere11.Radius = radius;
		tmpSphere12.Radius = radius;
		tmpSphere13.Radius = radius;
		tmpSphere21.Radius = radius;
		tmpSphere22.Radius = radius;
		tmpSphere23.Radius = radius;
		tmpSphere31.Radius = radius;
		tmpSphere32.Radius = radius;
		tmpSphere33.Radius = radius;

		tmpSphere11.Center = XMFLOAT3(-5.0f,-1.0f,-5.0f);
		tmpSphere12.Center = XMFLOAT3( 0.0f,-1.0f,-5.0f);
		tmpSphere13.Center = XMFLOAT3( 5.0f,-1.0f,-5.0f);
		tmpSphere21.Center = XMFLOAT3(-5.0f,-1.0f, 0.0f);
		tmpSphere22.Center = XMFLOAT3( 0.0f,-1.0f, 0.0f);
		tmpSphere23.Center = XMFLOAT3( 5.0f,-1.0f, 0.0f);
		tmpSphere31.Center = XMFLOAT3(-5.0f,-1.0f, 5.0f);
		tmpSphere32.Center = XMFLOAT3( 0.0f,-1.0f, 5.0f);
		tmpSphere33.Center = XMFLOAT3( 5.0f,-1.0f, 5.0f);

		UINT PickedSphere=0;
		FLOAT tmpDist;
		//IntersectRaySphere( FXMVECTOR Origin, FXMVECTOR Direction, const Sphere* pVolume, FLOAT* pDist );

		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere11, &tmpDist ))
			PickedSphere= 11;
		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere12, &tmpDist ))
			PickedSphere= 12;
		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere13, &tmpDist ))
			PickedSphere= 13;

		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere21, &tmpDist ))
			PickedSphere= 21;
		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere22, &tmpDist ))
			PickedSphere= 22;
		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere23, &tmpDist ))
			PickedSphere= 23;

		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere31, &tmpDist ))
			PickedSphere= 31;
		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere32, &tmpDist ))
			PickedSphere= 32;
		if(XNA::IntersectRaySphere( rayOrigin, rayDir, &tmpSphere33, &tmpDist ))
			PickedSphere= 33;

		if(PickedSphere!=0)
		{
			int ps =PickedSphere;
		}
	}
Пример #12
0
//Updates our viewMatrix based on the camera's position
void MyDemoGame::UpdateCamera()
{
	// values used to translate and rotate the camera in response to input
	float translationScale = -0.001f;
	float rotationScale = -.01f;
	//Left ad right arrow keys alter X position

	// make all camera manipulations occur at double speed when holding spacebar
	if (GetAsyncKeyState(VK_SPACE) & 0x8000)
	{
		translationScale *= 2.0f;
		rotationScale *= 2.0f;
	}

	if (GetAsyncKeyState(VK_LEFT) & 0x8000)
	{
		gameCam.setDistanceX(translationScale);
		gameCam.setPosition(gameCam.getDistanceX(), gameCam.getDistanceY(), gameCam.getDistanceZ());
		cameraPosition = XMVectorSet(gameCam.getPositionX(), gameCam.getPositionY(), gameCam.getPositionZ(), 0);
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}
	if (GetAsyncKeyState(VK_RIGHT) & 0x8000)
	{
		gameCam.setDistanceX(-translationScale);
		gameCam.setPosition(gameCam.getDistanceX(), gameCam.getDistanceY(), gameCam.getDistanceZ());
		cameraPosition = XMVectorSet(gameCam.getPositionX(), gameCam.getPositionY(), gameCam.getPositionZ(), 0);
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}

	//Up/Down arrow keys alter Y position
	if (GetAsyncKeyState(VK_DOWN) & 0x8000)
	{
		gameCam.setDistanceY(translationScale);
		gameCam.setPosition(gameCam.getDistanceX(), gameCam.getDistanceY(), gameCam.getDistanceZ());
		cameraPosition = XMVectorSet(gameCam.getPositionX(), gameCam.getPositionY(), gameCam.getPositionZ(), 0);
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}
	if (GetAsyncKeyState(VK_UP) & 0x8000)
	{
		gameCam.setDistanceY(-translationScale);
		gameCam.setPosition(gameCam.getDistanceX(), gameCam.getDistanceY(), gameCam.getDistanceZ());
		cameraPosition = XMVectorSet(gameCam.getPositionX(), gameCam.getPositionY(), gameCam.getPositionZ(), 0);
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}

	//5 and 0 on the numpad alter the Z position
	if (GetAsyncKeyState(VK_NUMPAD0) & 0x8000)
	{
		gameCam.setDistanceZ(translationScale);
		gameCam.setPosition(gameCam.getDistanceX(), gameCam.getDistanceY(), gameCam.getDistanceZ());
		cameraPosition = XMVectorSet(gameCam.getPositionX(), gameCam.getPositionY(), gameCam.getPositionZ(), 0);
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}
	if (GetAsyncKeyState(VK_NUMPAD5) & 0x8000)
	{
		gameCam.setDistanceZ(-translationScale);
		gameCam.setPosition(gameCam.getDistanceX(), gameCam.getDistanceY(), gameCam.getDistanceZ());
		cameraPosition = XMVectorSet(gameCam.getPositionX(), gameCam.getPositionY(), gameCam.getPositionZ(), 0);
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}

	//4 and 6 on the numpad will rotate along the X axis
	if (GetAsyncKeyState(VK_NUMPAD4) & 0x8000)
	{
		gameCam.setRotationDistanceX(rotationScale);
		gameCam.setRotation(gameCam.getRotationDistanceX(), gameCam.getRotationDistanceY(), gameCam.getRotationDistanceZ());
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}
	if (GetAsyncKeyState(VK_NUMPAD6) & 0x8000)
	{
		gameCam.setRotationDistanceX(-rotationScale);
		gameCam.setRotation(gameCam.getRotationDistanceX(), gameCam.getRotationDistanceY(), gameCam.getRotationDistanceZ());
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}

	//8 ad 2 on the unmpad will rotate along the y axis
	if (GetAsyncKeyState(VK_NUMPAD8) & 0x8000)
	{
		gameCam.setRotationDistanceY(-rotationScale);
		gameCam.setRotation(gameCam.getRotationDistanceX(), gameCam.getRotationDistanceY(), gameCam.getRotationDistanceZ());
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}
	if (GetAsyncKeyState(VK_NUMPAD2) & 0x8000)
	{
		gameCam.setRotationDistanceY(rotationScale);
		gameCam.setRotation(gameCam.getRotationDistanceX(), gameCam.getRotationDistanceY(), gameCam.getRotationDistanceZ());
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}

	//reset camera back to original position
	if (GetAsyncKeyState('R') & 0x8000)
	{
		gameCam.reset();
		cameraPosition = XMVectorSet(gameCam.getPositionX(), gameCam.getPositionY(), gameCam.getPositionZ(), 0);
		cameraRotation = XMVectorSet(gameCam.getRotationX(), gameCam.getRotationY(), gameCam.getRotationZ(), 0);
	}

	// return the manipulation scales to their normal values
	translationScale = -0.001f;
	rotationScale = -.01f;

	XMMATRIX V = XMMatrixLookToLH(cameraPosition, cameraRotation, upDirection);
	XMStoreFloat4x4(&viewMatrix, XMMatrixTranspose(V));


}
Пример #13
0
void ForwardPlusRenderer::RenderFinal(const RenderView& view, const RenderTarget& renderTarget)
{
    auto& pass = (MsaaEnabled) ? FinalPassMsaa : FinalPass;

    if (!MsaaEnabled)
    {
        pass->SetRenderTarget(0, renderTarget.Texture->GetRTV());
    }

    pass->Begin();

    XMMATRIX worldToView = XMLoadFloat4x4(&view.WorldToView);
    XMMATRIX worldToProjection = XMMatrixMultiply(worldToView, XMLoadFloat4x4(&view.ViewToProjection));

    // Directional Lights are shared for all objects, so fill up front
    FinalPassPSConstants psConstants{};
    psConstants.NumLights = 0;
    psConstants.TileSize = NUM_PIXELS_PER_GROUP_X;
    psConstants.NumTilesX = RTWidth / NUM_PIXELS_PER_GROUP_X;

    for (auto& light : Lights)
    {
        if (light->GetType() == LightType::Directional)
        {
            psConstants.Lights[psConstants.NumLights].Color = light->GetColor();

            XMFLOAT4X4 localToWorld = light->GetLocalToWorld();
            XMVECTOR lightDir = XMVectorNegate(XMVectorSet(localToWorld.m[2][0], localToWorld.m[2][1], localToWorld.m[2][2], 0.f));
            lightDir = XMVector3TransformNormal(lightDir, worldToView);
            XMStoreFloat3(&psConstants.Lights[psConstants.NumLights].Direction, lightDir);

            ++psConstants.NumLights;
        }
    }

    FinalPassPSCB->Update(&psConstants, sizeof(psConstants));

    // Remainder of data is object-specific
    FinalPassVSConstants constants{};

    for (auto& visual : Visuals)
    {
        XMMATRIX localToWorld = XMLoadFloat4x4(&visual->GetLocalToWorld());
        XMStoreFloat4x4(&constants.LocalToView, XMMatrixMultiply(localToWorld, worldToView));
        XMStoreFloat4x4(&constants.LocalToProjection, XMMatrixMultiply(localToWorld, worldToProjection));

        HRESULT hr = FinalPassVSCB->Update(&constants, sizeof(constants));
        if (FAILED(hr))
        {
            assert(false);
            continue;
        }

        pass->SetPSResource(3, visual->GetAlbedoTexture() ? visual->GetAlbedoTexture()->GetSRV() : nullptr);
        pass->SetPSResource(4, visual->GetNormalTexture() ? visual->GetNormalTexture()->GetSRV() : nullptr);

        pass->Draw(visual);
    }

    pass->End();

    if (MsaaEnabled)
    {
        Context->ResolveSubresource(renderTarget.Texture->GetTexture().Get(), 0, FinalRTMsaa->GetTexture().Get(), 0, FinalRTMsaa->GetDesc().Format);
    }
}
Пример #14
0
void Inky::Update(float dt, bool powerUpActivated, Direction::DIRECTION facingState, XMFLOAT3 blinkyPos, int levelNumber, int pelletCounter)
{
	if (!isDead)
	{
		if (pelletCounter >= 30 && isIdle)
		{
			this->isIdle = false;
			mGhostStates = GHOST_STATES::SCATTER;
		}
		if (!isIdle)
		{
			switch (mGhostStates)
			{
			case SCATTER:
				SetSpeed(levelNumber, GHOST_STATES::SCATTER);
				if (!scatterPathDrawn)
				{
					PrePathFinding(this->mPos.x, this->mPos.z, this->mScatterWaypoints[0]->xPos, this->mScatterWaypoints[0]->zPos);
					if (PostPathFinding())
					{
						this->UpdateCurrentTweenPoint(dt);
						scatterPathDrawn = true;
					}
				}
				if (mTweenPoints.size() != 0)
				{
					if (!this->reachedEnd)
					{
						this->mPos = this->mCurrTweenPoint;
						this->UpdateCurrentTweenPoint(dt);
					}
					else if (this->reachedEnd)
					{
						if (!isLooping)
						{
							this->SetWayPoints(mScatterWaypoints);
							this->isLooping = true;
						}
						if (isLooping == true && this->reachedEnd)
						{
							this->UpdateCurrentTweenPoint(dt);
							this->mPos = this->mCurrTweenPoint;
						}
					}
				}

				if (!powerUpActivated)
				{
					this->mGhostStates = GHOST_STATES::SCATTER;
					mScatterTimer += 5.7142f * dt; //dt currently takes (without mutliplying) 40 seconds to reach 7.0f, 5.7142 comes from 40 / 7 to get the number as accurate as possible.
					if (mScatterTimer >= 7.0f)
					{
						this->mGhostStates = GHOST_STATES::CHASE;
						mScatterTimer = 0.0f;
						reachedEnd = false;
						isLooping = false;
						CleanUpNodesWaypoints();
						mTweenPoints.clear();
					}
				}
				//If the powerup is activated, switch to the FRIGHTENED state
				else if (powerUpActivated)
				{
					SetSpeed(levelNumber, GHOST_STATES::FRIGHTENED);
					CleanUpNodesWaypoints();
					mTweenPoints.clear();
					scatterPathDrawn = false;
					reachedEnd = false;
					isLooping = false;
					mPrevState = mGhostStates;
					this->mGhostStates = GHOST_STATES::FRIGHTENED;
				}
				break;

			case CHASE:
				SetSpeed(levelNumber, GHOST_STATES::CHASE);
				if (!firstChasePathDrawn)
				{
					PrePathFinding(this->mPos.x, this->mPos.z, this->mScatterWaypoints[0]->xPos, this->mScatterWaypoints[0]->zPos);
					if (PostPathFinding())
					{
						this->UpdateCurrentTweenPoint(dt);
						firstChasePathDrawn = true;
					}
				}
				else
				{
					mPathCurrent += dt;
					if (mPathCurrent >= mPathNext)
					{
						if (facingState == Direction::DIRECTION::NORTH || facingState == Direction::DIRECTION::SOUTH)
						{
							//Offset tile = 2 spaces in PuckMan's facing
							offsetTile.xPos = round(MazeLoader::GetPacManData().at(0).pos.x);
							offsetTile.zPos = round(MazeLoader::GetPacManData().at(0).pos.z + (2 * Direction::getDirecitonVector(facingState).m128_f32[2]));
							//Draw a vector from Blinky's current position to the offset tile's position
							XMVECTOR targetTile = XMVectorSet(offsetTile.xPos - blinkyPos.x, 0.0f, offsetTile.zPos - blinkyPos.z, 0.0f);
							//Double the vector length extending forward, this is Inky's target
							targetTile = XMVectorScale(targetTile, 2.0f);

							//Clamp the X and Z value of the targetTile so it cannot choose a tile outside of the level
							float clampedX = MathHelper::Clamp((int)targetTile.m128_f32[0], 0, (int)(MazeLoader::GetMazeWidth()));
							float clampedZ = MathHelper::Clamp((int)targetTile.m128_f32[2], 0, (int)(MazeLoader::GetMazeHeight()));

							//Check if clampedZ is a valid tile, if not move the target tile one more in the opposite direction and try again
							int goalRow = (MazeLoader::GetMazeHeight()) - round(clampedZ + 15.5f);
							int goalCol = round(clampedX + 14.5f) - 1;
							while (MazeLoader::IsBlocked(goalRow, goalCol))
							{
								clampedX -= 1 * Direction::getDirecitonVector(facingState).m128_f32[0];
								clampedZ -= 1 * Direction::getDirecitonVector(facingState).m128_f32[2];
								if (MazeLoader::IsBlocked(clampedZ, clampedX))
								{
									break;
								}
							}

							PrePathFinding(this->mPos.x, this->mPos.z, round(MazeLoader::GetPacManData().at(0).pos.x), round(MazeLoader::GetPacManData().at(0).pos.z));
							if (PostPathFinding())
							{
								this->UpdateCurrentTweenPoint(dt);
								mPathNext += (1.0f / 10.0f);
							}
						}

						else if (facingState == Direction::DIRECTION::WEST || facingState == Direction::DIRECTION::EAST)
						{
							//Offset tile = 2 spaces in PuckMan's facing
							offsetTile.xPos = round(MazeLoader::GetPacManData().at(0).pos.x);
							offsetTile.zPos = round(MazeLoader::GetPacManData().at(0).pos.z + (2 * Direction::getDirecitonVector(facingState).m128_f32[2]));
							//Draw a vector from Blinky's current position to the offset tile's position
							XMVECTOR targetTile = XMVectorSet(offsetTile.xPos - blinkyPos.x, 0.0f, offsetTile.zPos - blinkyPos.z, 0.0f);
							//Double the vector length extending forward, this is Inky's target
							targetTile = XMVectorScale(targetTile, 2.0f);

							//Clamp the X and Z value of the targetTile so it cannot choose a tile outside of the level
							//Subract one from the highest value to zero base it
							float clampedX = MathHelper::Clamp((int)targetTile.m128_f32[0], 0, (int)(MazeLoader::GetMazeWidth()));
							float clampedZ = MathHelper::Clamp((int)targetTile.m128_f32[2], 0, (int)(MazeLoader::GetMazeHeight()));

							//Check if clampedZ is a valid tile, if not move the target tile one more in the opposite direction and try again
							//Because clampedZ and clampedX are already tile based, we can pass it into the function without conversion
							while (MazeLoader::IsBlocked(clampedZ, clampedX))
							{
								clampedX -= 1 * Direction::getDirecitonVector(facingState).m128_f32[0];
								clampedZ -= 1 * Direction::getDirecitonVector(facingState).m128_f32[2];
								if (MazeLoader::IsBlocked(clampedZ, clampedX))
								{
									break;
								}
							}

							PrePathFinding(this->mPos.x, this->mPos.z, round(MazeLoader::GetPacManData().at(0).pos.x), round(MazeLoader::GetPacManData().at(0).pos.z));
							if (PostPathFinding())
							{
								this->UpdateCurrentTweenPoint(dt);
								mPathNext += (1.0f / 10.0f);
							}
						}
					}
				}
				if (mTweenPoints.size() != 0)
				{
					this->mPos = this->mCurrTweenPoint;
					this->UpdateCurrentTweenPoint(dt);
				}

				if (!powerUpActivated)
				{
					mGhostStates = GHOST_STATES::CHASE;
					mChaseTimer += 5.7142f * dt; //dt currently takes (without mutliplying) 40 seconds to reach 7.0f, 5.7142 comes from 40 / 7 to get the number as accurate as possible.
					if (mChaseTimer >= 7.0f) //Chase time is over, time to scatter
					{
						this->mGhostStates = GHOST_STATES::SCATTER;
						mChaseTimer = 0.0f;
						scatterPathDrawn = false;
						reachedEnd = false;
						isLooping = false;
						CleanUpNodesWaypoints();
						mTweenPoints.clear();
					}
				}
				//If the powerup is activated, switch to the FRIGHTENED state
				else if (powerUpActivated)
				{
					SetSpeed(levelNumber, GHOST_STATES::FRIGHTENED);
					CleanUpNodesWaypoints();
					mTweenPoints.clear();
					mPrevState = mGhostStates;
					this->mGhostStates = GHOST_STATES::FRIGHTENED;
					scatterPathDrawn = false;
					firstChasePathDrawn = false;
				}
				break;

				case FRIGHTENED:
					SetSpeed(levelNumber, GHOST_STATES::FRIGHTENED);
					if (!scatterPathDrawn)
					{
						PrePathFinding(this->mPos.x, this->mPos.z, this->mScatterWaypoints[0]->xPos, this->mScatterWaypoints[0]->zPos);
						if (PostPathFinding())
						{
							this->UpdateCurrentTweenPoint(dt);
							scatterPathDrawn = true;
						}
					}
					if (mTweenPoints.size() != 0)
					{
						if (!this->reachedEnd)
						{
							this->mPos = this->mCurrTweenPoint;
							this->UpdateCurrentTweenPoint(dt);

						}
						else if (this->reachedEnd)
						{
							if (!isLooping)
							{
								this->SetWayPoints(mScatterWaypoints);
								this->isLooping = true;
							}
							if (isLooping == true && this->reachedEnd)
							{
								this->UpdateCurrentTweenPoint(dt);
								this->mPos = this->mCurrTweenPoint;
							}
						}
					}
					if (!powerUpActivated)
					{
						mGhostStates = mPrevState;
						mTweenPoints.clear();
					}
					break;
			}
		}
	}
}
Пример #15
0
	void LightPoint::set_position(float x, float y, float z) {
		XMVECTOR position = XMVectorSet(x, y, z, 1.0f);
		set_position(position);
	}
Пример #16
0
void Entity::SetPosition(float x, float y)
{
	m_position = XMVectorSet(x, y, 0, 0);
}
Пример #17
0
VOID
Font::BuildSpriteQuad( Sprite *sprite, SpriteVertex v[ 4 ] )
{
    FLOAT vertLeft = 2.0f * (float) sprite->DestRect.left / ScreenWidth - 1.0f;
    FLOAT vertRight = 2.0f * (float) sprite->DestRect.right / ScreenWidth - 1.0f;
    FLOAT vertTop = 1.0f - 2.0f * (float) sprite->DestRect.top / ScreenHeight;
    FLOAT vertBottom = 1.0f - 2.0f * (float) sprite->DestRect.bottom / ScreenHeight;
    float tx, ty;
    int i;
    XMVECTOR scaling, origin, translation;
    XMMATRIX T;

    v[ 0 ].x        = vertLeft;
    v[ 0 ].y        = vertBottom;
    v[ 0 ].z        = sprite->Z;
    v[ 0 ].Tex.x    = (float)sprite->SrcRect.left  / m_dwTexWidth;
    v[ 0 ].Tex.y    = (float)sprite->SrcRect.bottom / m_dwTexHeight;
    v[ 0 ].Color    = sprite->Color;

    v[ 1 ].x        = vertLeft;
    v[ 1 ].y        = vertTop;
    v[ 1 ].z        = sprite->Z;
    v[ 1 ].Tex.x    = (float)sprite->SrcRect.left  / m_dwTexWidth;
    v[ 1 ].Tex.y    = (float)sprite->SrcRect.top    / m_dwTexHeight;
    v[ 1 ].Color    = sprite->Color;

    v[ 2 ].x        = vertRight;
    v[ 2 ].y        = vertTop;
    v[ 2 ].z        = sprite->Z;
    v[ 2 ].Tex.x    = (float)sprite->SrcRect.right / m_dwTexWidth;
    v[ 2 ].Tex.y    = (float)sprite->SrcRect.top    / m_dwTexHeight;
    v[ 2 ].Color    = sprite->Color;

    v[ 3 ].x        = vertRight;
    v[ 3 ].y        = vertBottom;
    v[ 3 ].z        = sprite->Z;
    v[ 3 ].Tex.x    = (float)sprite->SrcRect.right / m_dwTexWidth;
    v[ 3 ].Tex.y    = (float)sprite->SrcRect.bottom / m_dwTexHeight;
    v[ 3 ].Color    = sprite->Color;

    tx = 0.5f * ( v[ 0 ].x + v[ 3 ].x );
    ty = 0.5f * ( v[ 0 ].y + v[ 1 ].y );

    scaling        = XMVectorSet( sprite->Scale, sprite->Scale, 1.0f, 0.0f );
    origin            = XMVectorSet( tx, ty, 0.0f, 0.0f );
    translation    = XMVectorSet( 0.0f, 0.0f, 0.0f, 0.0f );
    T = XMMatrixAffineTransformation2D( scaling, origin, sprite->Angle, translation );

    for( i = 0; i < 4; ++i )
    {
        XMFLOAT3 xmfloat;
        XMVECTOR p;

        xmfloat.x = v[ i ].x;
        xmfloat.y = v[ i ].y;
        xmfloat.z = v[ i ].z;

        p = XMLoadFloat3( &xmfloat );
        p = XMVector3TransformCoord( p, &T );
        XMStoreFloat3( &xmfloat, p );
        v[ i ].x = xmfloat.x;
        v[ i ].y = xmfloat.y;
        v[ i ].z = xmfloat.z;
    }
}
Пример #18
0
void Entity::SetVelocity(float x, float y)
{
	m_velocity = XMVectorSet(x, y, 0, 0);
}
Пример #19
0
void BasicPlane::Update(float deltaTime)
{
	XMVECTOR forward = XMVector3Rotate(XMVectorSet(0, 0, 1, 0), XMLoadFloat4(&gameObject->transform.rotation));
	XMVECTOR right = XMVector3Rotate(XMVectorSet(1, 0, 0, 0), XMLoadFloat4(&gameObject->transform.rotation));
	XMVECTOR up = XMVector3Rotate(XMVectorSet(0, 1, 0, 0), XMLoadFloat4(&gameObject->transform.rotation));
	Vector3 velocityDirection = particleModel->velocity;
	velocityDirection.Normalize();
	Vector3 velocityForwards = forward * particleModel->velocity.Dot(forward);
	//thrust
	const float maxPlaneThrust = 30 * particleModel->mass;
	const float thrustChangeSpeed = 5 * particleModel->mass;
	static float planeThrust = maxPlaneThrust * 0.0;
	if (GetAsyncKeyState(VK_HOME))
	{
		planeThrust += thrustChangeSpeed * deltaTime;
	}
	if (GetAsyncKeyState(VK_DELETE))
	{
		planeThrust -= thrustChangeSpeed * deltaTime;
	}
	planeThrust = fmax(0.0f, fmin(maxPlaneThrust, planeThrust));
	particleModel->AddForce(forward * planeThrust);
	//lift and drag
	float lift;
	float percentVelocityForwards = particleModel->velocity.Length() < 1e-4 ? 0 : (velocityForwards.Length() / particleModel->velocity.Length());
	lift = 100 * particleModel->velocity.LengthSquared() * (percentVelocityForwards);
	if (planeThrust > 0.25 * maxPlaneThrust)
	{
		planeThrust -= thrustChangeSpeed * 0.5 * deltaTime;
	}
	//float density = 0.5;
	//float area = 10;
	//float liftCoefficient = 0.8f;
	//lift = 0.5 * density * particleModel->velocity.LengthSquared() * area * liftCoefficient;
	particleModel->AddForce(up * lift);
	float drag;
	drag = 300 * particleModel->velocity.LengthSquared() * (percentVelocityForwards * 0.2 + (1.0 - percentVelocityForwards) * 1.0);
	//float dragCoefficient = 0.1f;
	//drag = dragCoefficient * area * density * (particleModel->velocity.LengthSquared() / 2);
	particleModel->AddForce(-velocityDirection * drag);
	//rotate
	const float planeRotateSpeed = XMConvertToRadians(20 * deltaTime);
	XMVECTOR rotate = XMQuaternionIdentity();
	if (GetAsyncKeyState(VK_RIGHT))
	{
		rotate = XMQuaternionMultiply(rotate, XMQuaternionRotationNormal(forward, -planeRotateSpeed));
	}
	else if (GetAsyncKeyState(VK_LEFT))
	{
		rotate = XMQuaternionMultiply(rotate, XMQuaternionRotationNormal(forward, planeRotateSpeed));
	}
	if (GetAsyncKeyState(VK_UP))
	{
		rotate = XMQuaternionMultiply(rotate, XMQuaternionRotationNormal(right, -planeRotateSpeed));
	}
	else if (GetAsyncKeyState(VK_DOWN))
	{
		rotate = XMQuaternionMultiply(rotate, XMQuaternionRotationNormal(right, planeRotateSpeed));
	}
	gameObject->transform.rotation *= rotate;
}
Пример #20
0
void AppTest::PopulateCommandListAsync(uint32_t threadID)
{
	CommandAllocatorArray[threadID]->Reset();

	CommandListArray[threadID]->Reset(CommandAllocatorArray[threadID].Get(), PSO.Get());

	Matrix4 view = Matrix4::LookAt(Vector3(0.0f, 6.0f, 2.0f), Vector3(), Vector3(0.0f, 1.0f, 0.0f));
	Matrix4 proj = Matrix4::Perspective(Math::PiOver4, 1280.0f / 720.0f, 0.1f, 1000.0f);

	XMMATRIX viewXM = XMMatrixLookAtRH(XMVectorSet(0.0f, 20.0f, 50.0f, 1.0f), XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f), XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f));
	XMMATRIX projXM = XMMatrixPerspectiveFovRH(Math::PiOver4, 1280.0f / 720.0f, 1.0f, 10000.0f);

	//Update constant buffer
	CBPerObject perObject;

	void* cbUploadPtr = nullptr;

	const unsigned int start = threadID * (BoxCount / ThreadCount);
	const unsigned int end = start + (BoxCount / ThreadCount);

	//Update the constant buffer view transforms for each object
	for (unsigned int i = start; i < end; i++)
	{
		const float scale = 0.04f * static_cast<float>(i);
		const float timeOffset = 1000.0f;
		const float timeMultiplier = 0.001f;

		XMMATRIX world, invTranspose, worldView, worldViewProj;
		world = XMMatrixScaling(scale, scale, scale) * 
			XMMatrixTranslation(static_cast<float>(i), 0.0f, 0.0f) * 
			XMMatrixRotationY(-static_cast<float>((Timer.GetTotalTime() + timeOffset) * static_cast<float>(i)) * timeMultiplier) * 
			XMMatrixScaling(0.01f, 0.01f, 0.01f);

		worldView = world * viewXM;
		worldViewProj = worldView * projXM;

		memcpy_s(&perObject.World, sizeof(perObject.World), &world, sizeof(world));
		memcpy_s(&perObject.WorldViewProj, sizeof(perObject.WorldViewProj), &worldViewProj, sizeof(worldViewProj));

		//Update the constant buffer data for specified object
		cbUploadPtr = PerObjectConstantBuffers.Map(i);
		memcpy_s(cbUploadPtr, sizeof(CBPerObject), &perObject, sizeof(perObject));
		PerObjectConstantBuffers.Unmap(i);
	}

	if (!UseRootLevelCBV)
	{
		ID3D12DescriptorHeap* descriptorHeap = ConstantBufferDescriptorHeap->GetBaseHeap();
		CommandListArray[threadID]->SetDescriptorHeaps(1, &descriptorHeap);
	}

	CommandListArray[threadID]->SetGraphicsRootSignature(RootSignature.Get());

	CommandListArray[threadID]->RSSetViewports(1, &Viewport);
	CommandListArray[threadID]->RSSetScissorRects(1, &RectScissor);

	SetResourceBarrier(CommandListArray[threadID].Get(), RenderTarget.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);

	CommandListArray[threadID]->OMSetRenderTargets(1, &DescriptorHeap->GetCPUDescriptorHandleForHeapStart(), true, &DSVDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
	CommandListArray[threadID]->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	CommandListArray[threadID]->IASetVertexBuffers(0, 1, &DescViewBufVert);
	CommandListArray[threadID]->IASetIndexBuffer(&DescViewBufIndex);

	D3D12_GPU_DESCRIPTOR_HANDLE descriptorHandle;
	
	if (!UseBundles)
	{
		if (UseRootLevelCBV)
		{
			for (unsigned int i = start; i < end; i++)
			{
				CommandListArray[threadID]->SetGraphicsRootConstantBufferView(0, PerObjectConstantBuffers.GetGPUHandle(i));
				CommandListArray[threadID]->DrawIndexedInstanced(IndexCount, 1, 0, 0, 0);
			}
		}
		else
		{
			for (unsigned int i = start; i < end; i++)
			{
				descriptorHandle.ptr = ConstantBufferDescriptorHeap->GetDescriptorGPUHandle(i);
				CommandListArray[threadID]->SetGraphicsRootDescriptorTable(0, descriptorHandle);
				CommandListArray[threadID]->DrawIndexedInstanced(IndexCount, 1, 0, 0, 0);
			}
		}
	}
	else
	{
		const unsigned int bundleStart = (BundleCount / ThreadCount) * threadID;
		const unsigned int bundleEnd = bundleStart + BundleCount / ThreadCount;

		for (unsigned int i = bundleStart; i < bundleEnd; i++)
		{
			CommandListArray[threadID]->ExecuteBundle(CommandBundleArray[i].Get());
		}
	}

	SetResourceBarrier(CommandListArray[threadID].Get(), RenderTarget.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);

	CommandListArray[threadID]->Close();
}
Пример #21
0
void MazeSide::SetPosition( float x, float y, float z )
{
	_position.Reset( XMVectorSet( x, y, z, 0.0f ) );
}
Пример #22
0
XMVECTOR HydraManager::getPointerPosition(int controllerIndex) const
{
	XMVECTOR position = getPosition(controllerIndex);

	return position + XMVector3Rotate(XMVectorSet(0.0f, 0.0f, mPointerDistance, 0.0f), getRotation(controllerIndex)); 
}
Пример #23
0
void MazeSide::ProcessMaze( EntitySystem& es )
{
	XMVECTOR rotation_conj = XMQuaternionConjugate( *_rotation );

	for( unsigned int y_index = 0; y_index < _size; ++y_index )
	{
		for( unsigned int x_index = 0; x_index < _size; ++x_index )
		{
			char c = _maze_data[ y_index * 31 + x_index ];

			float x_offset = ( float )x_index - ( ( float )_size - 1.0f ) / 2.0f;
			float y_offset = ( ( float )_size - 1.0f ) / 2.0f - (float)y_index;
			XMVECTOR wall_color = XMVectorSet( 0.2f, 0.3f, 1.0f, 1.0f );
			switch( c )
			{
				case 'F':
				{
					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( IDENTITY_QUAT, rotation_conj );
					xd._scale    = XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe90.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case '7':
				{
					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( QUARTER_TURN, rotation_conj );
					xd._scale    = XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe90.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case 'J':
				{
					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( HALF_TURN, rotation_conj );
					xd._scale    = XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe90.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case 'L':
				{
					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( THREE_QUARTER_TURN, rotation_conj );
					xd._scale    = XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe90.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case 'A':
				{
					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( TOP_JOIN, rotation_conj );
					xd._scale    = XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe90.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case '>':
				{
					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( SIDE_JOIN, rotation_conj );
					xd._scale    = XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe90.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case '-':
				{
					/* We ignore it if it's not the first of a sequence */
					if( _maze_data[ y_index * 31 + x_index - 1 ] == '-' )
						break;

					unsigned int count = 1;
					while( _maze_data[ y_index * 31 + x_index + count ] == '-' )
						++count;

					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset + ( ( float ) count - 1.0f )/ 2.0f, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( IDENTITY_QUAT, rotation_conj );
					xd._scale    = XMVectorSet( ( float )count, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe00.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case 'I':
				{
					/* We ignore it if it's not the first of a sequence */
					if( _maze_data[ ( y_index - 1 ) * 31 + x_index ] == 'I' )
						break;

					unsigned int count = 1;
					while( _maze_data[ ( y_index + count ) * 31 + x_index ] == 'I' )
						++count;

					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset - ( ( float )count - 1.0f ) / 2.0f, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( QUARTER_TURN, rotation_conj );
					xd._scale    = XMVectorSet( ( float )count, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe00.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = wall_color;
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}

				case '=':
				{
					Entity e = es.CreateNewEntity();

					XformComponent::Data xd;
					xd._position = *_position + XMVectorSet( x_offset, y_offset, 0.0f, 1.0f );
					xd._position = XMQuaternionMultiply( *_rotation, xd._position );
					xd._position = XMQuaternionMultiply( xd._position, rotation_conj );
					xd._rotation = XMQuaternionMultiply( IDENTITY_QUAT, rotation_conj );
					xd._scale    = XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f );
					es.CreateAndAttachComponent( e, COMPONENT_XFORM, xd );

					RenderableComponent::Data rd;
					rd._mesh_name = "pipe00.x";
					rd._vertex_shader_filename = "test.fx";
					rd._vertex_shader = "VS_Test";
					rd._pixel_shader_filename = "test.fx";
					rd._pixel_shader = "PS_Test";
					rd._color = XMVectorSet( 1.0f, 0.9f, 0.9f, 1.0f );
					es.CreateAndAttachComponent( e, COMPONENT_RENDERABLE, rd );

					_walls.push_back( e );
					break;
				}
			}
		}
	}

	//_sides.push_back( ms );
}
Пример #24
0
VOID DebugDraw::DrawFrustum( const Frustum& frustum, D3DCOLOR Color )
{
    // compute corner points

    XMVECTOR Origin = XMVectorSet( frustum.Origin.x, frustum.Origin.y, frustum.Origin.z, 0 );
    FLOAT Near = frustum.Near;
    FLOAT Far = frustum.Far;
    FLOAT RightSlope = frustum.RightSlope;
    FLOAT LeftSlope = frustum.LeftSlope;
    FLOAT TopSlope = frustum.TopSlope;
    FLOAT BottomSlope = frustum.BottomSlope;

    XMFLOAT3 CornerPoints[8];
    CornerPoints[0] = XMFLOAT3( RightSlope * Near, TopSlope * Near, Near );
    CornerPoints[1] = XMFLOAT3( LeftSlope * Near, TopSlope * Near, Near );
    CornerPoints[2] = XMFLOAT3( LeftSlope * Near, BottomSlope * Near, Near );
    CornerPoints[3] = XMFLOAT3( RightSlope * Near, BottomSlope * Near, Near );

    CornerPoints[4] = XMFLOAT3( RightSlope * Far, TopSlope * Far, Far );
    CornerPoints[5] = XMFLOAT3( LeftSlope * Far, TopSlope * Far, Far );
    CornerPoints[6] = XMFLOAT3( LeftSlope * Far, BottomSlope * Far, Far );
    CornerPoints[7] = XMFLOAT3( RightSlope * Far, BottomSlope * Far, Far );

    XMVECTOR Orientation = XMLoadFloat4( &frustum.Orientation );
    XMMATRIX Mat = XMMatrixRotationQuaternion( Orientation );
    for( UINT i = 0; i < 8; i++ )
    {
        XMVECTOR Result = XMVector3Transform( XMLoadFloat3( &CornerPoints[i] ), Mat );
        Result = XMVectorAdd( Result, Origin );
        XMStoreFloat3( &CornerPoints[i], Result );
    }

    XMFLOAT3 Lines[12 * 2];

    Lines[0] = CornerPoints[0];
    Lines[1] = CornerPoints[1];
    Lines[2] = CornerPoints[1];
    Lines[3] = CornerPoints[2];
    Lines[4] = CornerPoints[2];
    Lines[5] = CornerPoints[3];
    Lines[6] = CornerPoints[3];
    Lines[7] = CornerPoints[0];

    Lines[8] = CornerPoints[0];
    Lines[9] = CornerPoints[4];
    Lines[10] = CornerPoints[1];
    Lines[11] = CornerPoints[5];
    Lines[12] = CornerPoints[2];
    Lines[13] = CornerPoints[6];
    Lines[14] = CornerPoints[3];
    Lines[15] = CornerPoints[7];

    Lines[16] = CornerPoints[4];
    Lines[17] = CornerPoints[5];
    Lines[18] = CornerPoints[5];
    Lines[19] = CornerPoints[6];
    Lines[20] = CornerPoints[6];
    Lines[21] = CornerPoints[7];
    Lines[22] = CornerPoints[7];
    Lines[23] = CornerPoints[4];

    // draw frustum

    SimpleShaders::SetDeclPos();
    SimpleShaders::BeginShader_Transformed_ConstantColor( g_matViewProjection, Color );
    g_pd3dDevice->DrawPrimitiveUP( D3DPT_LINELIST, 12, Lines, sizeof( XMFLOAT3 ) );
    SimpleShaders::EndShader();
}
Пример #25
0
/**
 *  Utility/Rotations.cpp
 *  (c) Jonathan Capps
 *  Created 11 Oct. 2011
 */

#include <Windows.h>
#include <xnamath.h>

extern const XMVECTOR IDENTITY_QUAT = XMQuaternionIdentity();

extern const XMVECTOR QUARTER_TURN = XMQuaternionRotationAxis(
	XMVectorSet( 0.0f, 0.0f, -1.0f, 0.0f ),
	XM_PIDIV2 );

extern const XMVECTOR HALF_TURN = XMQuaternionRotationAxis(
	XMVectorSet( 0.0f, 0.0f, -1.0f, 0.0f ),
	XM_PI );

extern const XMVECTOR THREE_QUARTER_TURN = XMQuaternionRotationAxis(
	XMVectorSet( 0.0f, 0.0f, -1.0f, 0.0f ),
	3.0f * XM_PIDIV2 );

extern const XMVECTOR TOP_JOIN = XMQuaternionRotationRollPitchYaw(
	0.0f, -XM_PIDIV2, 0.0f );

extern const XMVECTOR SIDE_JOIN = XMQuaternionRotationRollPitchYaw(
	-XM_PIDIV2, -XM_PIDIV2, 0.0f );
Пример #26
0
bool TestTriangleStripsDX::InitScene()
{
	XMStoreFloat4(&up, XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f));
	XMStoreFloat4(&eye, XMVectorSet(0.0f, 18.0f, 18.0f, 1.0f));
	XMStoreFloat4(&right, XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f));
	XMStoreFloat4(&center, XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f));

	bg[0] = bgColor.r;
	bg[1] = bgColor.g;
	bg[2] = bgColor.b;
	bg[3] = bgColor.a;

	ID3D11RasterizerState1 *rasterizerState;
	D3D11_RASTERIZER_DESC1 rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));
	rasterizerDesc.CullMode = D3D11_CULL_NONE;
	rasterizerDesc.FillMode = D3D11_FILL_SOLID;
	rasterizerDesc.FrontCounterClockwise = true;

	mDevice->CreateRasterizerState1(&rasterizerDesc, &rasterizerState);
	mDeviceContext->RSSetState(rasterizerState);
	rasterizerState->Release();

	BinaryIO::ReadVector4s(binaryPath + "triangle_strip_plane.bin", vertices);

	D3D11_INPUT_ELEMENT_DESC vertexLayout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};

	D3DCompileFromFile(Util::s2ws(shaderPath + "TestTriangleStripsVert.hlsl").c_str(), NULL, NULL, "vertexShader", "vs_5_0", NULL, NULL, &vertexShaderBuffer, NULL);
	D3DCompileFromFile(Util::s2ws(shaderPath + "TestTriangleStripsFrag.hlsl").c_str(), NULL, NULL, "pixelShader", "ps_5_0", NULL, NULL, &pixelShaderBuffer, NULL);
	mDevice->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &vertexShader);
	mDevice->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &pixelShader);

	D3D11_BUFFER_DESC vertexBufferDesc;
	ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
	vertexBufferDesc.ByteWidth = vertices.size() * sizeof(Vector4);
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;

	D3D11_SUBRESOURCE_DATA vertexBufferData;
	ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
	vertexBufferData.pSysMem = &vertices[0];

	mDevice->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &vertexBuffer);

	mDevice->CreateInputLayout(vertexLayout, 1, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &inputLayout);

	// UPLOAD MVP MATRICES
	XMMATRIX modelMatrix = XMMatrixIdentity();
	XMMATRIX viewMatrix = XMMatrixLookAtRH(XMLoadFloat4(&eye), XMLoadFloat4(&center), XMLoadFloat4(&up));
	XMMATRIX projectionMatrix = XMMatrixPerspectiveFovRH(XMConvertToRadians(60.0f), 800 / 800, 1.0f, 500.0f);

	ID3D11Buffer* modelMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, modelMatrix);
	mDeviceContext->VSSetConstantBuffers(modelMatrixBufferSlot, 1, &modelMatrixBuffer);
	modelMatrixBuffer->Release();

	viewMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, viewMatrix);
	mDeviceContext->VSSetConstantBuffers(viewMatrixBufferSlot, 1, &viewMatrixBuffer);
	viewMatrixBuffer->Release();

	ID3D11Buffer* projectionMatrixBuffer = DXUtil::CreateMatrixBuffer(mDevice, projectionMatrix);
	mDeviceContext->VSSetConstantBuffers(projectionMatrixBufferSlot, 1, &projectionMatrixBuffer);
	projectionMatrixBuffer->Release();

	return true;
}
Пример #27
0
void Camera::OrbitVertical(float angle)
{

	//orbit back to the starting position
	//this orbit angle is not quite right.
	float orbitAngle = XMVectorGetX(XMVector3AngleBetweenVectors(XMLoadFloat3(&XMFLOAT3(0.0, 0.0, 1.0)), XMVector3Cross(GetRightXM(), XMVectorSet(0.0, 1.0, 0.0, 1.0))));
	//special case for when you pass 180
	if (mPosition.x < 0)
		orbitAngle = 180 + (90 - orbitAngle);

	OrbitHorizontal(orbitAngle);


	//get the angle between the right? of the camera and the right? of the world
	float check = XMVectorGetX(XMVector3AngleBetweenVectors(XMLoadFloat3(&XMFLOAT3(0.0, 0.0, 1.0)), XMLoadFloat3(&mLook)));
	if (check < MathHelper::Pi * 0.45 ||
		((mPosition.y > 0 && angle < 0 ) ||
		((mPosition.y < 0 && angle > 0)))
		)
	{
		pitch += angle;
		//pitch the camaera by that angle
		XMVECTOR offsetAngle = XMVector3AngleBetweenVectors(XMLoadFloat3(&XMFLOAT3(1.0, 0.0, 0.0)), XMLoadFloat3(&mRight));
		RotateY(XMVectorGetX(offsetAngle) + 0.001f);

		XMMATRIX matrixRot = XMMatrixRotationX(angle);
		XMStoreFloat3(&mPosition, XMVector3TransformNormal(XMLoadFloat3(&mPosition), matrixRot));
		XMStoreFloat3(&mRight, XMVector3TransformNormal(XMLoadFloat3(&mRight), matrixRot));
	}
	//move back
	OrbitHorizontal(-orbitAngle);

	//look at the center
	XMFLOAT3 zero(0.01, 0.01, 0.01);
	LookAt(mPosition, zero, XMFLOAT3(0.0, 1.0, 0.0));
	
}
Пример #28
0
SH9Color ProjectCubemapToSH9Color(ID3D11DeviceContext* context, ID3D11ShaderResourceView* cubeMap)
{
    ID3D11Texture2DPtr srcTexture;
    cubeMap->GetResource(reinterpret_cast<ID3D11Resource**>(&srcTexture));

    D3D11_TEXTURE2D_DESC srcDesc;
    srcTexture->GetDesc(&srcDesc);

    ID3D11DevicePtr device;
    context->GetDevice(&device);

    ID3D11Texture2DPtr tempTexture;
    D3D11_TEXTURE2D_DESC tempDesc = srcDesc;
    tempDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    tempDesc.MipLevels = 1;
    tempDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
    tempDesc.Usage = D3D11_USAGE_DEFAULT;
    DXCall(device->CreateTexture2D(&tempDesc, NULL, &tempTexture));

    ID3D11UnorderedAccessViewPtr tempUAV;
    DXCall(device->CreateUnorderedAccessView(tempTexture, NULL, &tempUAV));

    ID3D11ShaderResourceViewPtr tempSRV;
    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    srvDesc.Format = srcDesc.Format;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
    srvDesc.Texture2DArray.MostDetailedMip = 0;
    srvDesc.Texture2DArray.MipLevels = srcDesc.MipLevels;
    srvDesc.Texture2DArray.FirstArraySlice = 0;
    srvDesc.Texture2DArray.ArraySize = 6;
    DXCall(device->CreateShaderResourceView(srcTexture, &srvDesc, &tempSRV));

    static const UINT32 TGSize = 1024;
    static ID3D11ComputeShaderPtr decodeShader;
    if(decodeShader.GetInterfacePtr() == NULL)
    {
        CompileOptions opts;
        opts.Add("TGSize_", TGSize);
        decodeShader.Attach(CompileCSFromFile(device, L"SampleFramework11\\Shaders\\DecodeTextureCS.hlsl", 
                                                "DecodeTextureCS", "cs_5_0", opts.Defines()));
    }

    ID3D11ShaderResourceView* srvs[1] = { tempSRV };
    context->CSSetShaderResources(0, 1, srvs);

    ID3D11UnorderedAccessView* uavs[1] = { tempUAV };
    context->CSSetUnorderedAccessViews(0, 1, uavs, NULL);

    context->CSSetShader(decodeShader, NULL, 0);

    context->Dispatch(DispatchSize(TGSize, srcDesc.Width), srcDesc.Height, 6);

    float red[9];
    float green[9];
    float blue[9];

    DXCall(D3DX11SHProjectCubeMap(context, 3, tempTexture, red, green, blue));    

    SH9Color sh;
    for(UINT_PTR i = 0; i < 9; ++i)
        sh.c[i] = XMVectorSet(red[i], green[i], blue[i], 0.0f);

    return sh;
}
	void XM_CALLCONV PrimitveDrawer::DrawCone(FXMVECTOR Position, FXMVECTOR YDirection, float height, float radius, FXMVECTOR Color)
	{
		XMVECTOR rot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, YDirection);
		XMMATRIX world = XMMatrixAffineTransformation(XMVectorSet(radius, height, radius, 1), g_XMZero, rot, Position);
		m_pCone->Draw(world, ViewMatrix, ProjectionMatrix, Color);
	}
Пример #30
0
#include "Cloth.h"
#include <iostream>

XMVECTOR Cloth::GRAVITY = XMVectorSet(0.0f, -.981, 0.0f, 0.0f);

Cloth::Cloth(xml_node<>* clothParams) : timeSpentCalculatingInternalForce(0.0), timeSpentCalculatingExternalForce(0.0) {
  float x, y, z, height, width, mass, stiffness, damping;

  height = convertStringToNumber<float>(clothParams->first_attribute("height")->value());
  width = convertStringToNumber<float>(clothParams->first_attribute("width")->value());
  mass = convertStringToNumber<float>(clothParams->first_attribute("mass")->value());
  windConstant = convertStringToNumber<float>(clothParams->first_attribute("wind_constant")->value());

  xml_node<>* currentNode = clothParams->first_node("top_left_position");
  x = convertStringToNumber<float>(currentNode->first_attribute("x")->value());
  y = convertStringToNumber<float>(currentNode->first_attribute("y")->value());
  z = convertStringToNumber<float>(currentNode->first_attribute("z")->value());

  currentNode = clothParams->first_node("mesh_size");
  rows = convertStringToNumber<int>(currentNode->first_attribute("rows")->value());
  columns = convertStringToNumber<int>(currentNode->first_attribute("columns")->value());

  XMVECTOR topLeft = XMVectorSet(x, y, z, 0.0f);
  createParticles(topLeft, height, width, mass);

  currentNode = clothParams->first_node("structural");
  stiffness = convertStringToNumber<float>(currentNode->first_attribute("spring_coefficient")->value());
  damping = convertStringToNumber<float>(currentNode->first_attribute("damping_coefficient")->value());
  createStructuralLinks(stiffness, damping);

  currentNode = clothParams->first_node("shear");