Ejemplo n.º 1
0
void CameraMain::UpdateCamera()
{
    camRotationMatrix = XMMatrixRotationRollPitchYaw(camPitch, camYaw, 0);
    camTarget = XMVector3TransformCoord(DefaultForward, camRotationMatrix);
    camTarget = XMVector3Normalize(camTarget);

    XMMATRIX RotateYTempMatrix;
    RotateYTempMatrix = XMMatrixRotationY(camYaw);

    camRight = XMVector3TransformCoord(DefaultRight, RotateYTempMatrix);
    camUp = XMVector3TransformCoord(camUp, RotateYTempMatrix);
    camForward = XMVector3TransformCoord(DefaultForward, RotateYTempMatrix);

    camPosition += moveLeftRight*camRight;
    camPosition += moveBackForward*camForward;

    moveLeftRight = 0.0f;
    moveBackForward = 0.0f;

    camTarget = camPosition + camTarget;

    camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);
}
Ejemplo n.º 2
0
void Camera::turn(float dx, float dy)
{
	pitch = dy * 0.0005f;
	yaw = dx * 0.0005f;
	pitch = restrictAngle(pitch); 
	yaw = restrictAngle(yaw); 
	XMVECTOR fwd = XMLoadFloat3(&forward); 
	XMVECTOR camPos = XMLoadFloat3(&position); 
	XMMATRIX rotMat = XMMatrixRotationRollPitchYaw(pitch, yaw, 0.0f); 
	fwd = XMVector3TransformCoord(fwd, rotMat); 
	fwd = XMVector3Normalize(fwd); 
	XMStoreFloat3(&forward, fwd); 
	
}
Ejemplo n.º 3
0
void Entity::UpdateAAB()
{
	XMFLOAT3 vMinf3(+MathHelper::Infinity, +MathHelper::Infinity, +MathHelper::Infinity);
	XMFLOAT3 vMaxf3(-MathHelper::Infinity, -MathHelper::Infinity, -MathHelper::Infinity);
	XMVECTOR vMin = XMLoadFloat3(&vMinf3);
	XMVECTOR vMax = XMLoadFloat3(&vMaxf3);

	for (size_t i = 0; i < mGrid.Vertices.size(); ++i)
	{
		XMVECTOR P = XMLoadFloat3(&mMeshVertices[i].Pos);
		P = XMVector3TransformCoord(P, XMLoadFloat4x4(&mWorld));
		vMin = XMVectorMin(vMin, P);
		vMax = XMVectorMax(vMax, P);
	}
	XMStoreFloat3(&mMeshBox.Center, 0.5f*(vMin + vMax));
	XMStoreFloat3(&mMeshBox.Extents, 0.5f*(vMax - vMin));
}
Ejemplo n.º 4
0
void DX11SpriteBatch::BuildSpriteQuad(const Sprite& sprite, MeshData::SpriteVertex v[4])
{
	const CD3D11_RECT& dest = sprite.DestRect;
	const CD3D11_RECT& src  = sprite.SrcRect;

	// Dest rect defines target in screen space.
	v[0].pos = PointToNdc(dest.left,  dest.bottom, sprite.Z);
	v[1].pos = PointToNdc(dest.left,  dest.top,    sprite.Z);
	v[2].pos = PointToNdc(dest.right, dest.top,    sprite.Z);
	v[3].pos = PointToNdc(dest.right, dest.bottom, sprite.Z);

	// Source rect defines subset of texture to use from sprite sheet.
	v[0].tex = Vector2((float)src.left  / mTexWidth, (float)src.bottom / mTexHeight); 
	v[1].tex = Vector2((float)src.left  / mTexWidth, (float)src.top    / mTexHeight); 
	v[2].tex = Vector2((float)src.right / mTexWidth, (float)src.top    / mTexHeight); 
	v[3].tex = Vector2((float)src.right / mTexWidth, (float)src.bottom / mTexHeight); 

	v[0].color = (u32)sprite.Color;
	v[1].color = (u32)sprite.Color;
	v[2].color = (u32)sprite.Color;
	v[3].color = (u32)sprite.Color;

	// Quad center point.
	float tx = 0.5f*(v[0].pos.x + v[3].pos.x);
	float ty = 0.5f*(v[0].pos.y + v[1].pos.y);

	XMVECTOR scaling     = XMVectorSet(sprite.Scale, sprite.Scale, 1.0f, 0.0f);
	XMVECTOR origin      = XMVectorSet(tx, ty, 0.0f, 0.0f);
	XMVECTOR translation = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	XMMATRIX T           = XMMatrixAffineTransformation2D(scaling, origin, sprite.Angle, translation);

	// Rotate and scale the quad in NDC space.
	for(int i = 0; i < 4; ++i)
	{
		XMFLOAT3 vec = v[i].pos;
		XMVECTOR p = XMLoadFloat3(&vec);
		p = XMVector3TransformCoord(p, T);
		XMStoreFloat3(&vec, p);
		v[i].pos.Set(vec.x, vec.y, vec.z);
	}
}
Ejemplo n.º 5
0
uint32_t Physics::exe_ob(uint32_t const& _x, uint32_t const& _y) const {
	XMVECTOR _pocz, _pocz1, _kier, _kier1;
	comp_ray_click(_pocz, _kier, _x, _y);
	float _t = 1000.0f, _t1;
	uint32_t _uch_wybr = 0x80000000;
	for(uint32_t _uch_ob = 0; _uch_ob < graph_par.no.wez_poj(); ++_uch_ob) {
		if(graph_par.no.sprawdz_pusty(_uch_ob)) continue;
		_pocz1 = XMVector3TransformCoord(_pocz, XMMatrixInverse(
			&XMVectorSet(0,0,0,0), XMLoadFloat4x4(&phys_par.mtx_world[graph_par.no[_uch_ob]])
		));
		_kier1 = XMVector3TransformNormal(_kier, XMMatrixInverse(
			&XMVectorSet(0,0,0,0), XMLoadFloat4x4(&phys_par.mtx_world[graph_par.no[_uch_ob]])
		));
		_t1 = comp_ray_ob(_pocz1, _kier1, graph_par.no[_uch_ob]);
		if(_t1 < _t) {
			_t = _t1;
			_uch_wybr = _uch_ob;
		}
	}
	return _uch_wybr;
}
Ejemplo n.º 6
0
void Projekt::buildShadowTransform()
{
	// Only first "main" light casts a shadow
	// So get light direction and position from first light
	XMVECTOR lightDir = XMLoadFloat3(&mDirLights[0].Direction);

	XMVECTOR lightPos = -2.0f*mSceneBounds.Radius*lightDir;

	XMVECTOR targetPos = XMLoadFloat3(&mSceneBounds.Center);
	XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	XMMATRIX V = XMMatrixLookAtLH(lightPos, targetPos, up);

	// Transform bounding sphere to light space
	XMFLOAT3 sphereCenterLS;
	XMStoreFloat3(&sphereCenterLS, XMVector3TransformCoord(targetPos, V));

	// Orthogonal frustum in light space encloses scene
	float l = sphereCenterLS.x - mSceneBounds.Radius;
	float b = sphereCenterLS.y - mSceneBounds.Radius;
	float n = sphereCenterLS.z - mSceneBounds.Radius;
	float r = sphereCenterLS.x + mSceneBounds.Radius;
	float t = sphereCenterLS.y + mSceneBounds.Radius;
	float f = sphereCenterLS.z + mSceneBounds.Radius;
	XMMATRIX P = XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f);

	// Transform NDC space [-1,+1]^2 to texture space [0,1]^2
	XMMATRIX T(
		0.5f, 0.0f, 0.0f, 0.0f,
		0.0f, -0.5f, 0.0f, 0.0f,
		0.0f, 0.0f, 1.0f, 0.0f,
		0.5f, 0.5f, 0.0f, 1.0f);

	XMMATRIX S = V*P*T;

	XMStoreFloat4x4(&mLightView, V);
	XMStoreFloat4x4(&mLightProj, P);
	XMStoreFloat4x4(&mShadowTransform, S);
}
Ejemplo n.º 7
0
void Camera::UpdateCamera()
{	
	static XMVECTOR DefaultForward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
	static XMVECTOR DefaultRight   = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
	static XMVECTOR camForward     = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
	static XMVECTOR camRight       = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);

	static XMVECTOR camUp  = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
	static XMVECTOR camPosition    = XMVectorSet(0.0f, 2.0f, -5.0f, 0.0f);
	static XMVECTOR camTarget      = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	static XMMATRIX camView;

	//Rotating the Camera by euler angle
	XMMATRIX camRotationMatrix = XMMatrixRotationRollPitchYaw(camPitch, camYaw, 0);
	camTarget         = XMVector3TransformCoord(DefaultForward, camRotationMatrix );
	camTarget         = XMVector3Normalize(camTarget);

	XMMATRIX RotateYTempMatrix;
	RotateYTempMatrix = XMMatrixRotationY(camYaw);

	//We only move the xz plane by axis y
	//Update the camera vector
	camRight   = XMVector3TransformCoord(DefaultRight, RotateYTempMatrix);
	camUp      = XMVector3TransformCoord(camUp, RotateYTempMatrix);
	camForward = XMVector3TransformCoord(DefaultForward, RotateYTempMatrix);

	// Free-Look Camera
	camRight = XMVector3TransformCoord(DefaultRight, camRotationMatrix);
	camForward = XMVector3TransformCoord(DefaultForward, camRotationMatrix);
	camUp = XMVector3Cross(camForward, camRight);

	//Moving the Camera
	camPosition += moveLeftRight*camRight;
	camPosition += moveBackForward*camForward;

	moveLeftRight = 0.0f;
	moveBackForward = 0.0f;

	camTarget = camPosition + camTarget;	

	//Set the camera matrix
	camView = XMMatrixLookAtLH( camPosition, camTarget, camUp );
	XMStoreFloat4x4(&m_camView, XMMatrixTranspose(camView));

	XMStoreFloat4(&m_camPosition, camPosition);
}
Ejemplo n.º 8
0
//--------------------------------------------------------------------------------------
// Name: ComputeMeshBoundingBox()
// Desc: Calculate the bounding box of the transformed mesh.
//--------------------------------------------------------------------------------------
VOID Mesh::ComputeMeshBoundingBox( MESH_DATA* pMesh, const XMMATRIX mat,
                                   XMVECTOR& vMin, XMVECTOR& vMax )
{
    // Initialize bounds to be reset on the first point
    vMin.x = vMin.y = vMin.z = +FLT_MAX;
    vMax.x = vMax.y = vMax.z = -FLT_MAX;

    DWORD dwNumVertices = pMesh->m_dwNumVertices;
    DWORD dwVertexSize = pMesh->m_dwVertexSize;

    BYTE* pVertexData;
    pMesh->m_VB.Lock( 0, 0, ( VOID** )&pVertexData, D3DLOCK_READONLY );

    while( dwNumVertices-- )
    {
        XMFLOAT3* pVertex = ( XMFLOAT3* )pVertexData;
        XMVECTOR vPos = XMVectorSet( pVertex->x, pVertex->y, pVertex->z, 0 );
        vPos = XMVector3TransformCoord( vPos, mat );

        UnionBox( vMin, vMax, vPos, vPos );  // Expand the bounding box to include the point
        pVertexData += dwVertexSize;
    }
    pMesh->m_VB.Unlock();
}
Ejemplo n.º 9
0
void Camera::RotateYaw(float deg)
{
	XMMATRIX rotation = XMMatrixRotationAxis(mUp, deg);

	mEye = XMVector3TransformCoord(mEye, rotation);
}
Ejemplo n.º 10
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;
    }
}
Ejemplo n.º 11
0
void CameraClass::SetupViewMat()
{
	XMFLOAT3 up, position, lookAt;
	float yaw, pitch, roll;
	XMMATRIX rotationMatrix;


	// Setup the vector that points upwards.
	up.x = 0.0f;
	up.y = 1.0f;
	up.z = 0.0f;

	// Setup the position of the camera in the world.
	position.x = m_positionX;
	position.y = m_positionY;
	position.z = m_positionZ;

	// Setup where the camera is looking by default.
	lookAt.x = 0.0f;
	lookAt.y = 0.0f;
	lookAt.z = 1.0f;

	// Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
	pitch = m_rotationX;
	yaw = m_rotationY;
	roll = m_rotationZ;

	// Create the rotation matrix from the yaw, pitch, and roll values.
	//D3DXMatrixRotationYawPitchRoll(&rotationMatrix, yaw, pitch, roll);
	rotationMatrix = XMMatrixRotationRollPitchYaw(pitch, yaw, roll);

	// Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
	//D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix);
	XMStoreFloat3(&lookAt, XMVector3TransformCoord(XMLoadFloat3(&lookAt), rotationMatrix));


	//D3DXVec3TransformCoord(&up, &up, &rotationMatrix);
	XMStoreFloat3(&up, XMVector3TransformCoord(XMLoadFloat3(&up), rotationMatrix));

	// Translate the rotated camera position to the location of the viewer.
	lookAt = XMFLOAT3(position.x + lookAt.x, position.y + lookAt.y, position.z + lookAt.z);

	//	Move in direction your facing
	/*XMFLOAT3 forwardVector;
	forwardVector.x = lookAt.x - position.x;
	forwardVector.y = lookAt.y - position.y;
	forwardVector.z = lookAt.z - position.z;
	XMVector3Normalize(XMLoadFloat3(&forwardVector));

	lookAt.x += forwardVector.x;
	lookAt.y += forwardVector.y;
	lookAt.z += forwardVector.z;

	position.x += forwardVector.x;
	position.y += forwardVector.y;
	position.z += forwardVector.z;*/

	// Finally create the view matrix from the three updated vectors.
	//D3DXMatrixLookAtLH(&m_viewMatrix, &position, &lookAt, &up);
	m_viewMatrix = XMMatrixLookAtLH(XMLoadFloat3(&position), XMLoadFloat3(&lookAt), XMLoadFloat3(&up));

	return;
}
Ejemplo n.º 12
0
Float3 Float3::Transform(const Float3& v, const Float4x4& m)
{
    XMVECTOR vec = v.ToSIMD();
    vec = XMVector3TransformCoord(vec, m.ToSIMD());
    return Float3(vec);
}
Ejemplo n.º 13
0
void Enemy::move(FLOAT dt)
{


	bool dontUpdate = false;

	XMMATRIX startingworldMatrix = XMLoadFloat4x4(&mEnemyStartingWorld);
	XMVECTOR S;
	XMVECTOR P;
	XMVECTOR Q;

	XMMatrixDecompose(&S, &Q, &P, startingworldMatrix);


	XMVECTOR enemyPosition = XMLoadFloat3(&mEnemyPosition);



	FLOAT newPos = XMVectorGetZ(enemyPosition);
	FLOAT oldPos = XMVectorGetZ(P);

	direction = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);



	FLOAT diffX;
	FLOAT diffY;
	FLOAT diffZ;

	diffX = 0;
	diffY = 0;
	diffZ = 0;





	if (travelToPoint == 2)
	{


		diffX = mEnemyPosition.x - mEnemyPositionTwo.x;
		diffY = mEnemyPosition.y - mEnemyPositionTwo.y;
		diffZ = mEnemyPosition.z - mEnemyPositionTwo.z;
		mEnemyPositionThree.x;

	
	
	

		int nothing = 0;
		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}

		//////////////////////////////////
		if (diffX < 0.01)
		{

			mEnemyPosition.x = mEnemyPositionTwo.x;
		}
		if (diffY < 0.01)
		{

			mEnemyPosition.y = mEnemyPositionTwo.y;
		}
		if (diffZ < 0.01)
		{

			mEnemyPosition.z = mEnemyPositionTwo.z;
		}
		////////////////////////////////


		if (mEnemyPosition.x > mEnemyPositionTwo.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		else if (mEnemyPosition.x < mEnemyPositionTwo.x)
		{

			direction += XMVectorSet(1.0f, 0.0f, 0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionTwo.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		else if (mEnemyPosition.z < mEnemyPositionTwo.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionTwo.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		else if (mEnemyPosition.y < mEnemyPositionTwo.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{

		
			if (timesThrough == 0)
			{
				if (mEnemyPositionThree.x == 0)
				{

					dontUpdate = true;
					travelToPoint = 1;

					lastPoint = mEnemyPositionTwo;

				}
				else if (mEnemyPositionThree.x != 0)
				{
					dontUpdate = true;
					travelToPoint = 3;

					lastPoint = mEnemyPositionTwo;

				}
			}
			else
			{
				dontUpdate = true;

				travelToPoint = 1;
				lastPoint = mEnemyPositionTwo;
			}

			int something = 1;
		}

	}



	/////////////////////////////////////////
	else if (travelToPoint == 1)
	{

		timesThrough = 0;

		diffX = mEnemyPosition.x - mEnemyPositionOne.x;
		diffY = mEnemyPosition.y - mEnemyPositionOne.y;
		diffZ = mEnemyPosition.z - mEnemyPositionOne.z;



		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}


		//////////////////////////////////
		if (diffX < 0.01)
		{

			mEnemyPosition.x = mEnemyPositionOne.x;
		}
		if (diffY < 0.01)
		{

			mEnemyPosition.y = mEnemyPositionOne.y;
		}
		if (diffZ < 0.01)
		{

			mEnemyPosition.z = mEnemyPositionOne.z;
		}
		////////////////////////////////



		if (mEnemyPosition.x > mEnemyPositionOne.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		if (mEnemyPosition.x < mEnemyPositionOne.x)
		{

			direction += XMVectorSet(1.0f, 0.0f,0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionOne.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		if (mEnemyPosition.z < mEnemyPositionOne.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionOne.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		if (mEnemyPosition.y < mEnemyPositionOne.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{
			
			travelToPoint = 2;

			lastPoint = mEnemyPositionOne;

		}
	}



	////////////////////////////////////////////////////////////////////////////////
	else if (travelToPoint == 3 && timesThrough == 0)
	{


		diffX = mEnemyPosition.x - mEnemyPositionThree.x;
		diffY = mEnemyPosition.y - mEnemyPositionThree.y;
		diffZ = mEnemyPosition.z - mEnemyPositionThree.z;


		int nothing;
		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}


		//////////////////////////////////
		if (diffX < 0.01)
		{

			mEnemyPosition.x = mEnemyPositionThree.x;
		}
		if (diffY < 0.01)
		{

			mEnemyPosition.y = mEnemyPositionThree.y;
		}
		if (diffZ < 0.01)
		{

			mEnemyPosition.z = mEnemyPositionThree.z;
		}
		////////////////////////////////



		if (mEnemyPosition.x > mEnemyPositionThree.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		if (mEnemyPosition.x < mEnemyPositionThree.x)
		{

			direction += XMVectorSet(1.0f, 0.0f, 0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionThree.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		if (mEnemyPosition.z < mEnemyPositionThree.z)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionThree.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		if (mEnemyPosition.y < mEnemyPositionThree.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{

			if (mEnemyPositionFour.x == NULL)
			{
					


				travelToPoint = 2;
				timesThrough = 1;
			}
			else
			{
				
				travelToPoint = 4;
		
			}
		}
	}


	else if (travelToPoint == 4)
	{


		diffX = mEnemyPosition.x - mEnemyPositionFour.x;
		diffY = mEnemyPosition.y - mEnemyPositionFour.y;
		diffZ = mEnemyPosition.z - mEnemyPositionFour.z;

		if (diffX < 0.0f)
		{

			diffX *= -1;
		}
		if (diffY < 0.0f)
		{

			diffY *= -1;
		}
		if (diffZ < 0.0f)
		{

			diffZ *= -1;
		}

		//////////////////////////////////
		if (diffX < 0.001)
		{

			mEnemyPosition.x = mEnemyPositionFour.x;
		}
		if (diffY < 0.001)
		{

			mEnemyPosition.y = mEnemyPositionFour.y;
		}
		if (diffZ < 0.001)
		{

			mEnemyPosition.z = mEnemyPositionFour.z;
		}
		////////////////////////////////



		if (mEnemyPosition.x > mEnemyPositionFour.x)
		{

			direction += XMVectorSet(-1.0f, 0.0f, 0, 0.0f);


		}
		if (mEnemyPosition.x < mEnemyPositionFour.x)
		{

			direction += XMVectorSet(1.0f, 0.0f,0, 0.0f);

		}



		if (mEnemyPosition.z > mEnemyPositionFour.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);


		}
		if (mEnemyPosition.z < mEnemyPositionFour.z && diffZ > 0.01)
		{

			direction += XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);

		}


		if (mEnemyPosition.y > mEnemyPositionFour.y)
		{

			direction += XMVectorSet(0.0f, -1.0f, 0.0f, 0.0f);


		}
		if (mEnemyPosition.y < mEnemyPositionFour.y)
		{

			direction += XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

		}
		if (diffX < 0.05f && diffY < 0.05f && diffZ < 0.05f)
		{

			
			travelToPoint = 1;

			lastPoint = mEnemyPositionFour;
		}
	}












	XMMATRIX worldMatrix = XMLoadFloat4x4(&mEnemyWorld);
	XMVECTOR r = XMLoadFloat3(&mEnemyPosition);



	// Normalize our destinated direction vector
	direction = XMVector3Normalize(direction);





	/////character spinning make it more smooth

	if (XMVectorGetX(XMVector3Dot(direction, oldCharDirection)) == -1)
	{
		oldCharDirection += XMVectorSet(1.11f, 1.0f, 0.0f, 0.0f);
	}


	///////get characters position in world space
	charPosition = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
	charPosition = XMVector3TransformCoord(charPosition, worldMatrix);



	///// rotate the character
	float destDirLength = 10.0f * dt;



	currCharDirection = (oldCharDirection)+(direction * destDirLength);
	currCharDirection = XMVector3Normalize(currCharDirection);


	// get the angle 
	float charDirAngle = XMVectorGetX(XMVector3AngleBetweenNormals(XMVector3Normalize(currCharDirection), XMVector3Normalize(EnemyForward)));



	if (XMVectorGetY(XMVector3Cross(currCharDirection, EnemyForward)) > 0.0f)
	{
		charDirAngle = -charDirAngle;
	}



	float Speed = speed * dt;



	direction = direction * Speed;



	charPosition = charPosition + direction;



	XMMATRIX rotationMatrix;





	XMMATRIX Translation = XMMatrixTranslation(XMVectorGetX(charPosition), XMVectorGetY(charPosition), XMVectorGetZ(charPosition));

	rotationMatrix = XMMatrixRotationY(charDirAngle - 3.14159265f);		// Subtract PI from angle so the character doesn't run backwards



	worldMatrix = rotationMatrix * Translation;


	XMMatrixDecompose(&S, &Q, &P, worldMatrix);


	XMStoreFloat3(&mEnemyPosition, P);

	XMStoreFloat4(&mEnemyRotationQuad, Q);




	XMStoreFloat4x4(&mEnemyWorld, worldMatrix);



	oldCharDirection = currCharDirection;



}
Ejemplo n.º 14
0
void CameraClass::Render()
{
	XMFLOAT3 up, position, lookAt;
	XMVECTOR upVector, positionVector, lookAtVector;
	float yaw, pitch, roll;
	XMMATRIX rotationMatrix;

	// Setup the vector that points upwards.
	up.x = 0.0f;
	up.y = 1.0f;
	up.z = 0.0f;

	// Load it into a XMVECTOR structure.
	upVector = XMLoadFloat3(&up);

	float playerX = m_playerPos.x;
	float playerY = m_playerPos.y;

	if (playerX >= (m_positionX + (m_screenWidth / 2) - m_screenBarrier)) // (ScreenWidth / 2) - screenBarrier
	{
		m_cameraIsMovingX = true;
		m_cameraPosGoTo.x = playerX;
		if (m_cameraVelocity < 0.0f)
		{
			m_cameraVelocity *= -1.0f;
		}
	}
	else if (playerX <= (m_positionX - (m_screenWidth / 2) + m_screenBarrier))
	{
		m_cameraIsMovingX = true;
		m_cameraPosGoTo.x = playerX;
		if (m_cameraVelocity > 0.0f)
		{
			m_cameraVelocity *= -1.0f;
		}
	}

	if (playerY >= (m_positionY + (m_screenHeight / 2) - m_screenBarrier)) // (ScreenHeight / 2 ) - screenBarrier
	{
		m_cameraIsMovingY = true;
		m_cameraPosGoTo.y = playerY;
		if (m_cameraVelocity < 0.0f)
		{
			m_cameraVelocity *= -1.0f;
		}
	}
	else if (playerY <= (m_positionY - (m_screenHeight / 2) + m_screenBarrier))
	{
		m_cameraIsMovingY = true;
		m_cameraPosGoTo.y = playerY;
		if (m_cameraVelocity > 0.0f)
		{
			m_cameraVelocity *= -1.0f;
		}
	}

	// Setup the position of the camera in the world.
	position.x = m_positionX;
	position.y = m_positionY;
	position.z = m_positionZ;

	// Load it into a XMVECTOR structure.
	positionVector = XMLoadFloat3(&position);

	// Setup where the camera is looking by default.
	lookAt.x = 0.0f;
	lookAt.y = 0.0f;
	lookAt.z = 1.0f;

	// Load it into a XMVECTOR structure.
	lookAtVector = XMLoadFloat3(&lookAt);

	// Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
	pitch = m_rotationX * 0.0174532925f;
	yaw   = m_rotationY * 0.0174532925f;
	roll  = m_rotationZ * 0.0174532925f;

	// Create the rotation matrix from the yaw, pitch, and roll values.
	rotationMatrix = XMMatrixRotationRollPitchYaw(pitch, yaw, roll);

	// Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
	lookAtVector = XMVector3TransformCoord(lookAtVector, rotationMatrix);
	upVector = XMVector3TransformCoord(upVector, rotationMatrix);

	// Translate the rotated camera position to the location of the viewer.
	lookAtVector = XMVectorAdd(positionVector, lookAtVector);

	// Finally create the view matrix from the three updated vectors.
	m_viewMatrix = XMMatrixLookAtLH(positionVector, lookAtVector, upVector);

	return;
}
Ejemplo n.º 15
0
bool CameraHandler::CameraMeshIntersect(GroundModel* model) {
	int fp;
	float y1;
	float y2;
	float y3;
	float avY;
	bool result = false;
	XMVECTOR tempCamPos = this->GetPosition();
	XMFLOAT3 camLocalPos;
	XMMATRIX modelWorldMatrix;
	XMMATRIX modelWorldMatrixInverse;
	int modelWidth = model->getHeightMapInfo().terrainWidth;
	int modelHeight = model->getHeightMapInfo().terrainHeight;

	//Move camera into the models local space
	model->GetWorldMatrix(modelWorldMatrix);
	
	HeightMap::HeightMapInfo hmInfo = model->getHeightMapInfo();

	modelWorldMatrixInverse = XMMatrixInverse(nullptr,modelWorldMatrix);
	
	XMVECTOR camPosLocalMesh = XMVector3TransformCoord(tempCamPos, modelWorldMatrixInverse);	//CamPos in the mesh local space
	
	XMStoreFloat3(&camLocalPos, camPosLocalMesh);
	
	//Check if we are inside the x and z
	if ((camLocalPos.x >= 0 && camLocalPos.x <= modelWidth) &&
		(camLocalPos.z >= 0 && camLocalPos.z <= modelHeight)
		) 
	{

		//Find whitch triangel we are inside
		if ((camLocalPos.x - (int)camLocalPos.x) + (camLocalPos.z - (int)camLocalPos.z) <= 1.0f) {	// Top left triangle
			
			fp = ((int)camLocalPos.x) + ((int) camLocalPos.z * modelWidth);
			y1 = hmInfo.heightMap[fp].y;
			
			if ((int)camLocalPos.z == modelHeight-1) {
				y2 = 0;
			}
			else {
				y2 = hmInfo.heightMap[fp + modelWidth].y;
			}

			if ((int)camLocalPos.x == modelWidth) {
				y3 = 0;
			}
			else {
				y3 = hmInfo.heightMap[fp + 1].y;
			}

			avY = (y1 + y2 + y3) / 3;
			if (avY > 1000) {
				int j = 0;
			}
			this->SetPosition(XMVectorGetX(this->GetPosition()), avY, XMVectorGetZ(this->GetPosition()), false);
		}
		else {										// Bottom right triangle
			int fp = ((int)camLocalPos.x) + ((int)camLocalPos.z * modelWidth);
			y1 = hmInfo.heightMap[fp].y;
			
			if ((int)camLocalPos.z == 0) {
				y2 = 0;
			}
			else {
				y2 = hmInfo.heightMap[fp - modelHeight].y;
			}

			if ((int)camLocalPos.x == 0) {
				y3 = 0;
			}
			else {
				y3 = hmInfo.heightMap[fp - 1].y;
			}
			
			avY = (y1 + y2 + y3) / 3;
			if (avY > 1000) {
				int j = 0;
			}

		}

		XMVECTOR tempV = XMVectorSet(1,avY, 1, 1);
		XMVector3TransformCoord(tempV, modelWorldMatrix);

		this->SetPosition(XMVectorGetX(this->GetPosition()), XMVectorGetY(tempV), XMVectorGetZ(this->GetPosition()), false);
		result = true;
	}
	
	//Check if the point is inside the triangel plane 

	// return bool if it is inside or not which will cancel the questioned action in updateCamera
	return result;
}
Ejemplo n.º 16
0
/*--------------------------------------------
	画面の描画処理
--------------------------------------------*/
HRESULT Render(void)
{
	HRESULT hr;

    // 描画ターゲットのクリア
    g_pImmediateContext->ClearRenderTargetView(
                       g_pRenderTargetView, // クリアする描画ターゲット
                       g_ClearColor);         // クリアする値

	// 深度/ステンシルのクリア
	g_pImmediateContext->ClearDepthStencilView(
			g_pDepthStencilView, // クリアする深度/ステンシル・ビュー
			D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL,   // 深度値とステンシル値をクリアする
			1.0f,                // 深度バッファをクリアする値
			0);                  // ステンシル・バッファをクリアする値

	// ***************************************
	// 定数バッファを更新
	// ビュー変換行列
	XMVECTORF32 eyePosition   = { 0.0f, g_fEye, -g_fEye, 1.0f };  // 視点(カメラの位置)
	XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f, 1.0f };  // 注視点
	XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f, 1.0f };  // カメラの上方向
	XMMATRIX mat = XMMatrixLookAtLH(eyePosition, focusPosition, upDirection);
	XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(mat));
	// 点光源座標
	XMVECTOR vec = XMVector3TransformCoord(XMLoadFloat3(&g_vLightPos), mat);
	XMStoreFloat3(&g_cbCBuffer.Light, vec);
	// ワールド変換行列
	XMFLOAT3 center = g_wfObjKuma.GetBoundingSphereCenter();
	XMMATRIX matTrans = XMMatrixTranslation(-center.x, -center.y, -center.z);

	float scale = 1.0f / g_wfObjKuma.GetBoundingSphereRadius();
	XMMATRIX matScale = XMMatrixScaling(scale, scale, scale);

	FLOAT rotate = (FLOAT)(XM_PI * (timeGetTime() % 3000)) / 1500.0f;
	XMMATRIX matY = XMMatrixRotationY(rotate);

	XMStoreFloat4x4(&g_cbCBuffer.World, XMMatrixTranspose(matTrans * matScale * matY));

	// **********************************************************
	// RSにビューポートを設定
	g_pImmediateContext->RSSetViewports(1, g_ViewPort);

	// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
	g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView);

	// VSに定数バッファを設定
	g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

	// GSに定数バッファを設定
	g_pImmediateContext->GSSetConstantBuffers(0, 1, &g_pCBuffer);

	// PSに定数バッファを設定
	g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
	// PSにサンプラーを設定
	g_pImmediateContext->PSSetSamplers(0, 1, &g_pTextureSampler);

	// 3Dオブジェクトの描画
	RenderObj();
	// シャドウ・ボリュームの描画
	RenderSV();
	// シャドウの描画
	RenderS();

	// ***************************************
	// バック バッファの表示
	hr = g_pSwapChain->Present(	0,	// 画面を直ぐに更新する
								0);	// 画面を実際に更新する

	return hr;
}
Ejemplo n.º 17
0
/*--------------------------------------------
	画面の描画処理
--------------------------------------------*/
HRESULT Render(void)
{
	HRESULT hr;

    // 描画ターゲットのクリア
    g_pImmediateContext->ClearRenderTargetView(
                       g_pRenderTargetView, // クリアする描画ターゲット
                       g_ClearColor);         // クリアする値

	// 深度/ステンシルのクリア
	g_pImmediateContext->ClearDepthStencilView(
			g_pDepthStencilView, // クリアする深度/ステンシル・ビュー
			D3D11_CLEAR_DEPTH,   // 深度値だけをクリアする
			1.0f,                // 深度バッファをクリアする値
			0);                  // ステンシル・バッファをクリアする値(この場合、無関係)

	// ***************************************
	// 立方体の描画

	// 定数バッファ�Aを更新
	// ビュー変換行列
	XMVECTORF32 eyePosition   = { 0.0f, 5.0f, -5.0f, 1.0f };  // 視点(カメラの位置)
	XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f, 1.0f };  // 注視点
	XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f, 1.0f };  // カメラの上方向
	XMMATRIX mat = XMMatrixLookAtLH(eyePosition, focusPosition, upDirection);
	XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(mat));
	// 点光源座標
	XMVECTOR vec = XMVector3TransformCoord(XMLoadFloat3(&g_vLightPos), mat);
	XMStoreFloat3(&g_cbCBuffer.Light, vec);
	// ワールド変換行列
	XMMATRIX matY, matX;
	FLOAT rotate = (FLOAT)(XM_PI * (timeGetTime() % 3000)) / 1500.0f;
	matY = XMMatrixRotationY(rotate);
	rotate = (FLOAT)(XM_PI * (timeGetTime() % 1500)) / 750.0f;
	matX = XMMatrixRotationX(rotate);
	XMStoreFloat4x4(&g_cbCBuffer.World, XMMatrixTranspose(matY * matX));
	// 定数バッファのマップ取得
	D3D11_MAPPED_SUBRESOURCE MappedResource;
	hr = g_pImmediateContext->Map(
	                  g_pCBuffer,              // マップするリソース
	                  0,                       // サブリソースのインデックス番号
	                  D3D11_MAP_WRITE_DISCARD, // 書き込みアクセス
	                  0,                       //
	                  &MappedResource);        // データの書き込み先ポインタ
	if (FAILED(hr))
		return DXTRACE_ERR(L"InitBackBuffer  g_pImmediateContext->Map", hr);  // 失敗
	// データ書き込み
	CopyMemory(MappedResource.pData, &g_cbCBuffer, sizeof(cbCBuffer));
	// マップ解除
	g_pImmediateContext->Unmap(g_pCBuffer, 0);

	// ***************************************
	// IAに頂点バッファを設定
	// IAに入力レイアウト・オブジェクトを設定(頂点バッファなし)
	g_pImmediateContext->IASetInputLayout(NULL);
	// IAにプリミティブの種類を設定
	g_pImmediateContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// VSに頂点シェーダを設定
	g_pImmediateContext->VSSetShader(g_pVertexShader, NULL, 0);
	// VSに定数バッファを設定
	g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

	// GSにジオメトリ・シェーダを設定
	g_pImmediateContext->GSSetShader(g_pGeometryShader, NULL, 0);
	// GSに定数バッファを設定
	g_pImmediateContext->GSSetConstantBuffers(0, 1, &g_pCBuffer);

	// RSにビューポートを設定
	g_pImmediateContext->RSSetViewports(1, g_ViewPort);
	// RSにラスタライザ・ステート・オブジェクトを設定
	g_pImmediateContext->RSSetState(g_pRasterizerState);

	// PSにピクセル・シェーダを設定
	g_pImmediateContext->PSSetShader(g_pPixelShader, NULL, 0);
	// PSに定数バッファを設定
	g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
	// PSにシェーダ・リソース・ビューを設定
	g_pImmediateContext->PSSetShaderResources(
        0,                // 設定する最初のスロット番号
        1,                // 設定するシェーダ・リソース・ビューの数
        &g_pTextureSRV);  // 設定するシェーダ・リソース・ビューの配列
	// PSにサンプラーを設定
	g_pImmediateContext->PSSetSamplers(0, 1, &g_pTextureSampler);

	// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
	g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_bDepthMode ? g_pDepthStencilView : NULL);
	// OMにブレンド・ステート・オブジェクトを設定
	FLOAT BlendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f};
	g_pImmediateContext->OMSetBlendState(g_pBlendState, BlendFactor, 0xffffffff);
	// OMに深度/ステンシル・ステート・オブジェクトを設定
	g_pImmediateContext->OMSetDepthStencilState(g_pDepthStencilState, 0);

	// ***************************************
	// 頂点バッファとインデックス・バッファを使わずに描画する
	g_pImmediateContext->Draw(
			36, // 描画する頂点数
			0); // 最初の頂点ID

	// ***************************************
	// バック バッファの表示
	hr = g_pSwapChain->Present(	0,	// 画面を直ぐに更新する
								0);	// 画面を実際に更新する

	return hr;
}
Ejemplo n.º 18
0
void Camera::RotateYaw(float angleRad)
{
    XMMATRIX rotation = XMMatrixRotationAxis(mUp, angleRad);

    mEye = mAt + XMVector3TransformCoord(mEye - mAt, rotation);
}
Ejemplo n.º 19
0
/*--------------------------------------------
	画面の描画処理
--------------------------------------------*/
HRESULT Render(void)
{
	HRESULT hr;

	// 定数バッファを更新
	// ワールド変換行列
	XMFLOAT3 center = g_wfObjKuma.GetBoundingSphereCenter();
	XMMATRIX matTrans = XMMatrixTranslation(-center.x, -center.y, -center.z);

	float scale = 1.0f / g_wfObjKuma.GetBoundingSphereRadius();
	XMMATRIX matScale = XMMatrixScaling(scale, scale, scale);

	FLOAT rotate = (FLOAT)(XM_PI * (timeGetTime() % 3000)) / 1500.0f;
	XMMATRIX matY = XMMatrixRotationY(rotate);

	XMMATRIX matWorld = matTrans * matScale * matY;
	XMStoreFloat4x4(&g_cbCBuffer.World, XMMatrixTranspose(matWorld));

	// ***************************************
	// シャドウ マップの描画
	if (g_bShadowMappingMode) {
		g_pImmediateContext->ClearState();

		// ビュー変換行列(光源から見る)
		XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f };  // 注視点
		XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f };  // カメラの上方向
		XMMATRIX matShadowMapView = XMMatrixLookAtLH(XMLoadFloat3(&g_vLightPos), focusPosition, upDirection);
		XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(matShadowMapView));

		// 射影変換行列(パースペクティブ(透視法)射影)
		XMMATRIX matShadowMapProj = XMMatrixPerspectiveFovLH(
				XMConvertToRadians(45.0f),		// 視野角45°
				g_ViewPortShadowMap[0].Width / g_ViewPortShadowMap[0].Height,	// アスペクト比
				1.0f,							// 前方投影面までの距離
				400.0f);						// 後方投影面までの距離
		XMStoreFloat4x4(&g_cbCBuffer.Projection, XMMatrixTranspose(matShadowMapProj));

		// 深度/ステンシルのクリア
		g_pImmediateContext->ClearDepthStencilView(g_pShadowMapDSView, D3D11_CLEAR_DEPTH, 1.0f, 0);

		// VSに定数バッファを設定
		g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

		// PSに定数バッファを設定
		g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
		// PSにサンプラーを設定
		g_pImmediateContext->PSSetSamplers(0, 2, g_pTextureSampler);

		// RSにビューポートを設定
		g_pImmediateContext->RSSetViewports(1, g_ViewPortShadowMap);

		// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
		ID3D11RenderTargetView* pRender[1] = { NULL };
		g_pImmediateContext->OMSetRenderTargets(1, pRender, g_pShadowMapDSView);

		// 物体の描画
		RenderObj(true);

		// シャドウマップの設定
		XMMATRIX mat = XMMatrixTranspose(matWorld * matShadowMapView * matShadowMapProj);
		XMStoreFloat4x4(&g_cbCBuffer.SMWorldViewProj, mat);
	}

	// ***************************************
	// ビュー変換行列
	XMVECTORF32 eyePosition   = { 0.0f, g_fEye, -g_fEye, 1.0f };  // 視点(カメラの位置)
	XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f, 1.0f };  // 注視点
	XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f, 1.0f };  // カメラの上方向
	XMMATRIX matView = XMMatrixLookAtLH(eyePosition, focusPosition, upDirection);
	XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(matView));
	// 射影変換行列(パースペクティブ(透視法)射影)
	XMMATRIX matProj = XMMatrixPerspectiveFovLH(
			XMConvertToRadians(30.0f),		// 視野角30°
			g_ViewPort[0].Width / g_ViewPort[0].Height,	// アスペクト比
			1.0f,							// 前方投影面までの距離
			20.0f);						// 後方投影面までの距離
	XMStoreFloat4x4(&g_cbCBuffer.Projection, XMMatrixTranspose(matProj));
	// 点光源座標
	XMVECTOR vec = XMVector3TransformCoord(XMLoadFloat3(&g_vLightPos), matView);
	XMStoreFloat3(&g_cbCBuffer.Light, vec);

	// ***************************************
    // 描画ターゲットのクリア
    g_pImmediateContext->ClearRenderTargetView(
                       g_pRenderTargetView, // クリアする描画ターゲット
                       g_ClearColor);         // クリアする値

	// 深度/ステンシルのクリア
	g_pImmediateContext->ClearDepthStencilView(
			g_pDepthStencilView, // クリアする深度/ステンシル・ビュー
			D3D11_CLEAR_DEPTH,   // 深度値だけをクリアする
			1.0f,                // 深度バッファをクリアする値
			0);                  // ステンシル・バッファをクリアする値(この場合、無関係)

	// ***************************************
	g_pImmediateContext->ClearState();

	// VSに定数バッファを設定
	g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

	// PSに定数バッファを設定
	g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
	// PSにサンプラーを設定
	g_pImmediateContext->PSSetSamplers(0, 2, g_pTextureSampler);

	// RSにビューポートを設定
	g_pImmediateContext->RSSetViewports(1, g_ViewPort);

	// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
	g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_bDepthMode ? g_pDepthStencilView : NULL);

	// 物体の描画
	RenderObj(false);

	// ***************************************
	// バック バッファの表示
	hr = g_pSwapChain->Present(	0,	// 画面を直ぐに更新する
								0);	// 画面を実際に更新する

	return hr;
}
Ejemplo n.º 20
0
float D3DPicking::Pick(const XMMATRIX& worldSpace)
{ 		
	//Loop through each triangle in the object
	for(int i = 0; i < m_IndexData.size()/3; i++)
	{
		//Triangle's vertices V1, V2, V3
		XMVECTOR tri1V1 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
		XMVECTOR tri1V2 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
		XMVECTOR tri1V3 = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);

		//Temporary 3d floats for each vertex
		XMFLOAT3 tV1, tV2, tV3;

		//Get triangle 
		tV1 = m_PosData[m_IndexData[(i*3)+0]];
		tV2 = m_PosData[m_IndexData[(i*3)+1]];
		tV3 = m_PosData[m_IndexData[(i*3)+2]];

		tri1V1 = XMVectorSet(tV1.x, tV1.y, tV1.z, 0.0f);
		tri1V2 = XMVectorSet(tV2.x, tV2.y, tV2.z, 0.0f);
		tri1V3 = XMVectorSet(tV3.x, tV3.y, tV3.z, 0.0f);

		//Transform the vertices to world space
		tri1V1 = XMVector3TransformCoord(tri1V1, worldSpace);
		tri1V2 = XMVector3TransformCoord(tri1V2, worldSpace);
		tri1V3 = XMVector3TransformCoord(tri1V3, worldSpace);

		//Find the normal using U, V coordinates (two edges)
		XMVECTOR U = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
		XMVECTOR V = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
		XMVECTOR faceNormal = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);

		U = tri1V2 - tri1V1;
		V = tri1V3 - tri1V1;

		//Compute face normal by crossing U, V
		faceNormal = XMVector3Cross(U, V);

		faceNormal = XMVector3Normalize(faceNormal);

		//Calculate a point on the triangle for the plane equation
		XMVECTOR triPoint = tri1V1;

		//Get plane equation ("Ax + By + Cz + D = 0") Variables
		float tri1A = XMVectorGetX(faceNormal);
		float tri1B = XMVectorGetY(faceNormal);
		float tri1C = XMVectorGetZ(faceNormal);
		float tri1D = (-tri1A*XMVectorGetX(triPoint) - tri1B*XMVectorGetY(triPoint) - tri1C*XMVectorGetZ(triPoint));

		//Now we find where (on the ray) the ray intersects with the triangles plane
		float ep1, ep2, t = 0.0f;
		float planeIntersectX, planeIntersectY, planeIntersectZ = 0.0f;
		XMVECTOR pointInPlane = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);

		ep1 = (XMVectorGetX(m_pickRayPos) * tri1A) + (XMVectorGetY(m_pickRayPos) * tri1B) + (XMVectorGetZ(m_pickRayPos) * tri1C);
		ep2 = (XMVectorGetX(m_pickRayDir) * tri1A) + (XMVectorGetY(m_pickRayDir) * tri1B) + (XMVectorGetZ(m_pickRayDir) * tri1C);

		//Make sure there are no divide-by-zeros
		if(ep2 != 0.0f)
			t = -(ep1 + tri1D)/(ep2);

		if(t > 0.0f)    //Make sure you don't pick objects behind the camera
		{
			//Get the point on the plane
			planeIntersectX = XMVectorGetX(m_pickRayPos) + XMVectorGetX(m_pickRayDir) * t;
			planeIntersectY = XMVectorGetY(m_pickRayPos) + XMVectorGetY(m_pickRayDir) * t;
			planeIntersectZ = XMVectorGetZ(m_pickRayPos) + XMVectorGetZ(m_pickRayDir) * t;

			pointInPlane = XMVectorSet(planeIntersectX, planeIntersectY, planeIntersectZ, 0.0f);

			//Call function to check if point is in the triangle
			if(PointInTriangle(tri1V1, tri1V2, tri1V3, pointInPlane))
			{
				//Return the distance to the hit, so you can check all the other pickable objects in your scene
				//and choose whichever object is closest to the camera
				return t/2.0f;
			}
		}
	}
	//return the max float value (near infinity) if an object was not picked
	return FLT_MAX;
}
Ejemplo n.º 21
0
//-------------------------------------------
// とりあえずIK
void BoneModel::VMDIkAnimation()
{

	//XMStoreFloat4()
	//XMLoadFloat4()
	if (mBone.empty())return;
	if (mMotion.empty())return;

	DWORD mBoneNum = mBone.size();
	DWORD mIkNum = mIk.size();
	// IK計算
	for (DWORD i = 0; i < mIkNum; i++){
		//{
		//	int i = 0;
		Ik& ik = mIk[i];
		UINT tg_idx = ik.target_bone_index;
		UINT ik_idx = ik.bone_index;

		for (UINT ite = 0; ite<ik.iterations; ++ite){
			for (UINT chn = 0; chn<ik.chain_length; ++chn){
				UINT link_idx = ik.child_bone_index[chn];//
				if (link_idx >= mBoneNum)continue;
				Bone& link_bone = mBone[link_idx];

				//UINT link_pidx = link_bone.mIkBoneIdx;
				UINT link_pidx = link_bone.mHierarchy.mIdxParent;

				//if (link_bone.mIkBoneIdx != 0){
				//	continue;
				//}

				if (link_pidx >= mBoneNum)continue;
				Bone& link_parent = mBone[link_pidx];

				Bone& tg_bone = mBone[tg_idx];
				(void)tg_bone;
				Bone& ik_bone = mBone[ik_idx];
				(void)ik_bone;

				XMVECTOR target_wpos = mBone[tg_idx].mMtxPose.r[3];
				XMVECTOR ik_wpos = mBone[ik_idx].mMtxPose.r[3];
				XMVECTOR lp_wpos = link_parent.mMtxPose.r[3];

				//Linkボーンのローカル空間に変換
				XMVECTOR Determinant;
				XMMATRIX inv_mtx = XMMatrixInverse(&Determinant, link_bone.mMtxPose);
				XMVECTOR tg_pos = XMVector4Transform(target_wpos, inv_mtx);
				XMVECTOR ik_pos = XMVector4Transform(ik_wpos, inv_mtx);
				XMVECTOR lp_pos = XMVector4Transform(lp_wpos, inv_mtx);


				// 回転軸と角度 
				XMVECTOR rot_axis = XMVectorSet(1, 0, 0, 0);
				float ang = 0.0f;
				bool same_dir = false;
				if (!RotDir(tg_pos, ik_pos, ik.control_weight, &rot_axis, &ang)){
					same_dir = true;
				}

				if (!same_dir){

					//tg_dirをik_dirに一致させるための回転
					XMVECTOR rot = XMQuaternionRotationAxis(rot_axis, ang);

					XMVECTOR lrot = FloatToVector(link_bone.mRot);
					XMVECTOR bone_rot_before = lrot;
					link_bone.mRot = VectorToFloat(XMQuaternionMultiply(rot, lrot));

					float dist_tg = XMVectorGetX(XMVector3Length(tg_pos));
					float dist_ik = XMVectorGetX(XMVector3Length(ik_pos));
					(void)dist_ik;
					float dist_lp = XMVectorGetX(XMVector3Length(lp_pos));
					(void)dist_lp;
					float dist_pltg = XMVectorGetX(XMVector3Length(lp_pos - tg_pos));
					float dist_plik = XMVectorGetX(XMVector3Length(lp_pos - ik_pos));
					float dot_tgik = XMVectorGetX(XMVector3Dot(XMVector3Normalize(tg_pos), XMVector3Normalize(ik_pos)));
					(void)dot_tgik;

					// 回転制限
					if (/*link.bLimit*/ 1){
						XMVECTOR rotmax, rotmin;
						//114.5916 = 2
						float a = 2;// XM_PI / 180.0f * 57.25f;
						rotmax = XMVectorSet(a, a, a, 0);//link.vMax;
						rotmin = XMVectorSet(-a, -a, -a, 0);//link.vMin;

						//名前に"ひざ"があったら回転制限
						if (std::string::npos != link_bone.mStrName.find("ひざ")){
							rotmax = XMVectorSet(-XM_PI / 180.0f*0.5f, 0, 0, 0);
							rotmin = XMVectorSet(-XM_PI, 0, 0, 0);
						}
						struct IkLink{
							XMFLOAT4 mMax;
							XMFLOAT4 mMin;
						};
						IkLink link = { VectorToFloat(rotmax), VectorToFloat(rotmin) };
						//Bone& link = link_bone;
						link_bone.mRot = VectorToFloat(LimitAngle(FloatToVector(link_bone.mRot), rotmin, rotmax));

						XMVECTOR angxyz = GetAngle(rot);
						//膝を曲げるための仮処理 かなりてきとう
						if (XMVectorGetX(angxyz) >= 0 &&
							//0.9f < dot_tgik &&
							//dist_tg > dist_ik &&
							dist_pltg > dist_plik &&
							link.mMax.x < 0 && link.mMax.y == link.mMin.y && link.mMax.z == link.mMin.z){
							//親リンクの回転接平面(できるだけこの平面に近づけたほうがよりIK目標に近づける)
							XMVECTOR lp_nor = XMVector3Normalize(-lp_pos);//平面の法線
							//lp_norとの内積が0になる位置を目標にする
							//2つあるので回転制限後の|内積|が小さいほう
							XMVECTOR tng = XMVector3Cross(XMVectorSet(1, 0, 0, 0), lp_nor);
							//+tngと-tngの2つ
							XMVECTOR rot_axis0, rot_axis1;
							float ang0 = 0, ang1 = 0;

							// 回転軸をXに限定
							rot_axis1 = rot_axis0 = XMVectorSet(1, 0, 0, 0);
							XMVECTOR tdir = XMVector3Normalize(XMVectorSetX(tg_pos, 0));
							tng = XMVector3Normalize(XMVectorSetX(tng, 0));
							RotDir(tdir, tng, ik.control_weight, &rot_axis0, &ang0);
							RotDir(tdir, -tng, ik.control_weight, &rot_axis1, &ang1);
							if (XMVectorGetX(rot_axis0) < 0.0f)ang0 = -ang0;
							if (XMVectorGetX(rot_axis1) < 0.0f)ang1 = -ang1;

							//これは絶対違う ぴくぴく対策
							float coef = (dist_pltg - dist_plik) / dist_tg;
							if (coef > 1)coef = 1;
							ang0 *= coef;
							ang1 *= coef;


							//ang0,1は現在の位置からの相対角度 
							// 回転制限を考慮した相対角度に
							float angx_b = XMVectorGetX(GetAngle(bone_rot_before));
							float angx_a0 = angx_b + ang0;
							float angx_a1 = angx_b + ang1;
							if (angx_a0 < link.mMin.x) angx_a0 = link.mMin.x;
							if (angx_a0 > link.mMax.x) angx_a0 = link.mMax.x;
							if (angx_a1 < link.mMin.x) angx_a1 = link.mMin.x;
							if (angx_a1 > link.mMax.x) angx_a1 = link.mMax.x;
							ang0 = angx_a0 - angx_b;
							ang1 = angx_a1 - angx_b;


							XMVECTOR rot0 = XMQuaternionRotationRollPitchYaw(ang0, 0, 0);
							XMVECTOR rot1 = XMQuaternionRotationRollPitchYaw(ang1, 0, 0);

							XMVECTOR tdir0 = XMVector3TransformCoord(tdir, XMMatrixRotationQuaternion(rot0));
							XMVECTOR tdir1 = XMVector3TransformCoord(tdir, XMMatrixRotationQuaternion(rot1));
							float d0 = XMVectorGetX(XMVectorAbs(XMVector3Dot(tdir0, lp_nor)));
							float d1 = XMVectorGetX(XMVectorAbs(XMVector3Dot(tdir1, lp_nor)));
							if (d0 < d1){
								link_bone.mRot = VectorToFloat(XMQuaternionMultiply(rot0, bone_rot_before));
							}
							else{
								link_bone.mRot = VectorToFloat(XMQuaternionMultiply(rot1, bone_rot_before));
							}
						}
					}

				}




				//ワールド行列更新
				link_bone.mMtxPose = SQTMatrix(FloatToVector(link_bone.mScale), FloatToVector(link_bone.mRot), FloatToVector(link_bone.mPos));
				if (link_bone.mHierarchy.mIdxParent < mBoneNum){
					link_bone.mMtxPose = XMMatrixMultiply(link_bone.mMtxPose, mBone[link_bone.mHierarchy.mIdxParent].mMtxPose);
				}

				// 子階層のリンク再計算
				for (int lidown = chn - 1; lidown >= 0; --lidown){
					UINT idx = ik.child_bone_index[lidown];
					if (idx >= mBoneNum)continue;
					Bone& linkb = mBone[idx];
					linkb.mMtxPose = SQTMatrix(FloatToVector(linkb.mScale), FloatToVector(linkb.mRot), FloatToVector(linkb.mPos));
					if (linkb.mHierarchy.mIdxParent < mBoneNum){
						linkb.mMtxPose = XMMatrixMultiply(linkb.mMtxPose, mBone[linkb.mHierarchy.mIdxParent].mMtxPose);
					}
				}

				mBone[tg_idx].mMtxPose = SQTMatrix(FloatToVector(mBone[tg_idx].mScale), FloatToVector(mBone[tg_idx].mRot), FloatToVector(mBone[tg_idx].mPos));
				if (mBone[tg_idx].mHierarchy.mIdxParent < mBoneNum){
					mBone[tg_idx].mMtxPose = XMMatrixMultiply(mBone[tg_idx].mMtxPose, mBone[mBone[tg_idx].mHierarchy.mIdxParent].mMtxPose);
				}
			}
		}


		//Bone& b = mBone[tg_idx];
		//Bone& b2 = mBone[mBone[tg_idx].mHierarchy.mIdxParent];
		//Bone& b3 = mBone[b2.mHierarchy.mIdxParent];
		//int sa = 1;

		//IKの計算結果を子階層に反映
		//UpdatePose();
	}
	UpdatePose();
}
Ejemplo n.º 22
0
// Renders meshes using cascaded shadow mapping
void MeshRenderer::RenderSunShadowMap(ID3D11DeviceContext* context, const Camera& camera)
{
    PIXEvent event(L"Sun Shadow Map Rendering");

    const float MinDistance = reductionDepth.x;
    const float MaxDistance = reductionDepth.y;

    // Compute the split distances based on the partitioning mode
    float CascadeSplits[4] = { 0.0f, 0.0f, 0.0f, 0.0f };

    {
        float lambda = 1.0f;

        float nearClip = camera.NearClip();
        float farClip = camera.FarClip();
        float clipRange = farClip - nearClip;

        float minZ = nearClip + MinDistance * clipRange;
        float maxZ = nearClip + MaxDistance * clipRange;

        float range = maxZ - minZ;
        float ratio = maxZ / minZ;

        for(uint32 i = 0; i < NumCascades; ++i)
        {
            float p = (i + 1) / static_cast<float>(NumCascades);
            float log = minZ * std::pow(ratio, p);
            float uniform = minZ + range * p;
            float d = lambda * (log - uniform) + uniform;
            CascadeSplits[i] = (d - nearClip) / clipRange;
        }
    }

    Float3 c0Extents;
    Float4x4 c0Matrix;

    const Float3 lightDir = AppSettings::SunDirection;

    // Render the meshes to each cascade
    for(uint32 cascadeIdx = 0; cascadeIdx < NumCascades; ++cascadeIdx)
    {
        PIXEvent cascadeEvent((L"Rendering Shadow Map Cascade " + ToString(cascadeIdx)).c_str());

        // Set the viewport
        SetViewport(context, ShadowMapSize, ShadowMapSize);

        // Set the shadow map as the depth target
        ID3D11DepthStencilView* dsv = sunShadowDepthMap.DSView;
        ID3D11RenderTargetView* nullRenderTargets[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { NULL };
        context->OMSetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, nullRenderTargets, dsv);
        context->ClearDepthStencilView(dsv, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);

        // Get the 8 points of the view frustum in world space
        XMVECTOR frustumCornersWS[8] =
        {
            XMVectorSet(-1.0f,  1.0f, 0.0f, 1.0f),
            XMVectorSet( 1.0f,  1.0f, 0.0f, 1.0f),
            XMVectorSet( 1.0f, -1.0f, 0.0f, 1.0f),
            XMVectorSet(-1.0f, -1.0f, 0.0f, 1.0f),
            XMVectorSet(-1.0f,  1.0f, 1.0f, 1.0f),
            XMVectorSet( 1.0f,  1.0f, 1.0f, 1.0f),
            XMVectorSet( 1.0f, -1.0f, 1.0f, 1.0f),
            XMVectorSet(-1.0f, -1.0f, 1.0f, 1.0f),
        };

        float prevSplitDist = cascadeIdx == 0 ? MinDistance : CascadeSplits[cascadeIdx - 1];
        float splitDist = CascadeSplits[cascadeIdx];

        XMVECTOR det;
        XMMATRIX invViewProj = XMMatrixInverse(&det, camera.ViewProjectionMatrix().ToSIMD());
        for(uint32 i = 0; i < 8; ++i)
            frustumCornersWS[i] = XMVector3TransformCoord(frustumCornersWS[i], invViewProj);

        // Get the corners of the current cascade slice of the view frustum
        for(uint32 i = 0; i < 4; ++i)
        {
            XMVECTOR cornerRay = XMVectorSubtract(frustumCornersWS[i + 4], frustumCornersWS[i]);
            XMVECTOR nearCornerRay = XMVectorScale(cornerRay, prevSplitDist);
            XMVECTOR farCornerRay = XMVectorScale(cornerRay, splitDist);
            frustumCornersWS[i + 4] = XMVectorAdd(frustumCornersWS[i], farCornerRay);
            frustumCornersWS[i] = XMVectorAdd(frustumCornersWS[i], nearCornerRay);
        }

        // Calculate the centroid of the view frustum slice
        XMVECTOR frustumCenterVec = XMVectorZero();
        for(uint32 i = 0; i < 8; ++i)
            frustumCenterVec = XMVectorAdd(frustumCenterVec, frustumCornersWS[i]);
        frustumCenterVec = XMVectorScale(frustumCenterVec, 1.0f / 8.0f);
        Float3 frustumCenter = frustumCenterVec;

        // Pick the up vector to use for the light camera
        Float3 upDir = camera.Right();

        Float3 minExtents;
        Float3 maxExtents;

        {
            // Create a temporary view matrix for the light
            Float3 lightCameraPos = frustumCenter;
            Float3 lookAt = frustumCenter - lightDir;
            XMMATRIX lightView = XMMatrixLookAtLH(lightCameraPos.ToSIMD(), lookAt.ToSIMD(), upDir.ToSIMD());

            // Calculate an AABB around the frustum corners
            XMVECTOR mins = XMVectorSet(REAL_MAX, REAL_MAX, REAL_MAX, REAL_MAX);
            XMVECTOR maxes = XMVectorSet(-REAL_MAX, -REAL_MAX, -REAL_MAX, -REAL_MAX);
            for(uint32 i = 0; i < 8; ++i)
            {
                XMVECTOR corner = XMVector3TransformCoord(frustumCornersWS[i], lightView);
                mins = XMVectorMin(mins, corner);
                maxes = XMVectorMax(maxes, corner);
            }

            minExtents = mins;
            maxExtents = maxes;
        }

        // Adjust the min/max to accommodate the filtering size
        float scale = (ShadowMapSize + FilterSize) / static_cast<float>(ShadowMapSize);
        minExtents.x *= scale;
        minExtents.y *= scale;
        maxExtents.x *= scale;
        maxExtents.x *= scale;

        Float3 cascadeExtents = maxExtents - minExtents;

        // Get position of the shadow camera
        Float3 shadowCameraPos = frustumCenter + lightDir * -minExtents.z;

        // Come up with a new orthographic camera for the shadow caster
        OrthographicCamera shadowCamera(minExtents.x, minExtents.y, maxExtents.x,
            maxExtents.y, 0.0f, cascadeExtents.z);
        shadowCamera.SetLookAt(shadowCameraPos, frustumCenter, upDir);

        // Draw the mesh with depth only, using the new shadow camera
        RenderDepth(context, shadowCamera, true, false);

        // Apply the scale/offset matrix, which transforms from [-1,1]
        // post-projection space to [0,1] UV space
        XMMATRIX texScaleBias;
        texScaleBias.r[0] = XMVectorSet(0.5f,  0.0f, 0.0f, 0.0f);
        texScaleBias.r[1] = XMVectorSet(0.0f, -0.5f, 0.0f, 0.0f);
        texScaleBias.r[2] = XMVectorSet(0.0f,  0.0f, 1.0f, 0.0f);
        texScaleBias.r[3] = XMVectorSet(0.5f,  0.5f, 0.0f, 1.0f);
        XMMATRIX shadowMatrix = shadowCamera.ViewProjectionMatrix().ToSIMD();
        shadowMatrix = XMMatrixMultiply(shadowMatrix, texScaleBias);

        // Store the split distance in terms of view space depth
        const float clipDist = camera.FarClip() - camera.NearClip();
        shadowConstants.Data.CascadeSplits[cascadeIdx] = camera.NearClip() + splitDist * clipDist;

        if(cascadeIdx == 0)
        {
            c0Extents = cascadeExtents;
            c0Matrix = shadowMatrix;
            shadowConstants.Data.ShadowMatrix = XMMatrixTranspose(shadowMatrix);
            shadowConstants.Data.CascadeOffsets[0] = Float4(0.0f, 0.0f, 0.0f, 0.0f);
            shadowConstants.Data.CascadeScales[0] = Float4(1.0f, 1.0f, 1.0f, 1.0f);
        }
        else
        {
            // Calculate the position of the lower corner of the cascade partition, in the UV space
            // of the first cascade partition
            Float4x4 invCascadeMat = Float4x4::Invert(shadowMatrix);
            Float3 cascadeCorner = Float3::Transform(Float3(0.0f, 0.0f, 0.0f), invCascadeMat);
            cascadeCorner = Float3::Transform(cascadeCorner, c0Matrix);

            // Do the same for the upper corner
            Float3 otherCorner = Float3::Transform(Float3(1.0f, 1.0f, 1.0f), invCascadeMat);
            otherCorner = Float3::Transform(otherCorner, c0Matrix);

            // Calculate the scale and offset
            Float3 cascadeScale = Float3(1.0f, 1.0f, 1.f) / (otherCorner - cascadeCorner);
            shadowConstants.Data.CascadeOffsets[cascadeIdx] = Float4(-cascadeCorner, 0.0f);
            shadowConstants.Data.CascadeScales[cascadeIdx] = Float4(cascadeScale, 1.0f);
        }

        ConvertToEVSM(context, cascadeIdx, shadowConstants.Data.CascadeScales[cascadeIdx].To3D());
    }
}
//--------------------------------------------------------------------------------------
// Handles mouse input
//--------------------------------------------------------------------------------------
void CALLBACK OnMouse( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext )
{
    if( g_bDrawTerrain )
    {
        if( bRightButtonDown )
        {
            if( g_pInspectionTexture != NULL )
            {
                g_pInspectionTexture = NULL;
            }
            else
            {
                g_pInspectionTexture = g_pTerrainView->GetInspectionTexture();
            }
            g_InspectionSliceIndex = 0;
        }
        return;
    }

    static BOOL MouseDragging = FALSE;
    static XMFLOAT4 DragMouseCursorPos( 0, 0, 0, 0 );
    static XMFLOAT4 DragCameraPos( 0, 0, 0, 0 );

    // vMousePos is the mouse cursor's location on the Z far and near planes in homogenous space
    XMVECTOR vMousePosFar = XMVectorSet( ( (FLOAT)xPos - g_HalfClientWidthPixels ) / g_HalfClientWidthPixels, ( (FLOAT)yPos - g_HalfClientHeightPixels ) / -g_HalfClientHeightPixels, 1, 1 );

    XMMATRIX matView = XMLoadFloat4x4A( &g_matView );
    XMMATRIX matViewProj = matView * XMLoadFloat4x4A( &g_matProjection );
    XMVECTOR vDet;
    XMMATRIX matInvViewProj = XMMatrixInverse( &vDet, matViewProj );

    // vMouseWorldPos is the location in world space of the mouse cursor on the near plane
    XMVECTOR vMouseWorldPosFar = XMVector3TransformCoord( vMousePosFar, matInvViewProj );

    XMVECTOR vCameraPosWorld = XMLoadFloat4A( &g_CameraPos );

    const XMVECTOR vPlaneNormal = XMVectorSet( 0, 1, 0, 0 );
    const XMVECTOR vPlaneDistance = XMVectorZero();

    XMVECTOR vCameraToMouseWorldFar = vMouseWorldPosFar - vCameraPosWorld;

    XMVECTOR t = ( vPlaneDistance - XMVector3Dot( vPlaneNormal, vCameraPosWorld ) ) / XMVector3Dot( vPlaneNormal, vCameraToMouseWorldFar );
    XMVECTOR vMouseCursorWorld = vCameraPosWorld + t * vCameraToMouseWorldFar;

    if( bLeftButtonDown )
    {
        if( !MouseDragging )
        {
            MouseDragging = TRUE;
            XMStoreFloat4( &DragMouseCursorPos, vMouseCursorWorld );
            XMStoreFloat4( &DragCameraPos, vCameraPosWorld );
        }
        else
        {
            XMVECTOR vDragPos = XMLoadFloat4( &DragMouseCursorPos );
            XMVECTOR vCameraDelta = vMouseCursorWorld - vDragPos;

            vCameraPosWorld -= vCameraDelta;

            XMStoreFloat4A( &g_CameraPos, vCameraPosWorld );
            UpdateViewMatrix();
            XMStoreFloat4( &DragCameraPos, vCameraPosWorld );
        }
    }
    else if( MouseDragging )
    {
        MouseDragging = FALSE;
    }

    if( bRightButtonDown )
    {
        ID3D11TiledTexture2D* pCurrentTexture = g_pInspectionTexture;
        g_pInspectionTexture = NULL;

        UINT SceneObjectCount = (UINT)g_SceneObjects.size();
        for( UINT i = 0; i < SceneObjectCount; ++i )
        {
            const SceneObject* pSO = g_SceneObjects[i];
            FLOAT X = pSO->matWorld._41;
            FLOAT Y = pSO->matWorld._43;

            FLOAT DeltaX = fabsf( X - XMVectorGetX( vMouseCursorWorld ) );
            FLOAT DeltaY = fabsf( Y - XMVectorGetZ( vMouseCursorWorld ) );
            if( DeltaX <= 0.5f && DeltaY <= 0.5f )
            {
                g_pInspectionTexture = pSO->Textures[0].pTexture;
                break;
            }
        }

        if( g_pInspectionTexture != pCurrentTexture )
        {
            g_InspectionSliceIndex = 0;
        }
    }

    if( nMouseWheelDelta != 0 )
    {
        const FLOAT LogMoveSpeed = 0.05f * ( (FLOAT)nMouseWheelDelta / 120.0f );

        FLOAT CameraY = XMVectorGetY( vCameraPosWorld );
        float LogYPos = logf( CameraY );
        LogYPos -= LogMoveSpeed;
        
        vCameraPosWorld = XMVectorSetY( vCameraPosWorld, max( 0.001f, expf( LogYPos ) ) );
        XMStoreFloat4A( &g_CameraPos, vCameraPosWorld );
        UpdateViewMatrix();
    }
}
Ejemplo n.º 24
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);


}
Ejemplo n.º 25
0
//--------------------------------------------------------------------------------------
//
// BeginHairFrame
//
// Start of hair rendering.
//
//--------------------------------------------------------------------------------------
void TressFXRenderer::BeginHairFrame(ID3D11DeviceContext* pd3dContext,
                                    DirectX::XMVECTOR eyePoint, DirectX::XMVECTOR lightPosition,
                                    DirectX::XMMATRIX *pModelTransformForHead,  DirectX::XMMATRIX *pViewProj,  DirectX::XMMATRIX *pViewProjLightOut,
                                    float screenWidth, float screenHeight, bool singleHeadTransform)
{
    SetSamplerStates(pd3dContext);

    // Set up camera parameters for when the camera is at the position of the light for rendering the shadow map
    XMMATRIX mViewLight, mProjLight;
    XMVECTOR modelCenter = XMVector3TransformCoord(XMLoadFloat3(&m_pTressFXMesh->m_HairAsset.m_bSphere.center), *pModelTransformForHead);
    XMVECTOR vLightAt = modelCenter;
    XMVECTOR vUp = XMVectorSet(0, 1, 0, 0);
    mViewLight = XMMatrixLookAtLH(lightPosition, vLightAt, vUp);

    XMVECTOR vLightToObject = XMVectorSubtract(lightPosition, modelCenter);
    float dis = XMVectorGetX(XMVector3Length(vLightToObject));

    float min_dis = max(0.001f, dis - m_pTressFXMesh->m_HairAsset.m_bSphere.radius);
    float max_dis = dis + m_pTressFXMesh->m_HairAsset.m_bSphere.radius;

    float halfAngle = 1.5f*asin(m_pTressFXMesh->m_HairAsset.m_bSphere.radius/dis);
    float FOV = 2*halfAngle;

    float ratio = 1;

    mProjLight = XMMatrixPerspectiveFovLH( FOV, ratio, min_dis, max_dis );
    *pViewProjLightOut = mViewLight * mProjLight;

    // Map the per-frame constant buffer
    D3D11_MAPPED_SUBRESOURCE MappedResource;
    pd3dContext->Map( m_pcbPerFrame, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource );
    CB_PER_FRAME* pcbPerFrame = ( CB_PER_FRAME* )MappedResource.pData;

    // camera parameters
    XMMATRIX mViewProj = *pViewProj;
    XMMATRIX mInvViewProj = XMMatrixInverse(0, mViewProj);

    float fRenderWidth =  screenWidth;
    float fRenderHeight = screenHeight;

    // Inverse of viewprojection matrix with viewport mapping
    XMMATRIX mViewport  ( 2.0f/fRenderWidth,  0.0f,                   0.0f, 0.0f,
                            0.0f,               -2.0f/fRenderHeight,    0.0f, 0.0f,
                            0.0f,               0.0f,                   1.0f, 0.0f,
                            -1.0f,              1.0f,                   0.0f, 1.0f );

    XMMATRIX mInvViewProjViewport = mViewport * mInvViewProj;

    pcbPerFrame->m_mViewProj = XMMatrixTranspose(mViewProj);
    pcbPerFrame->m_mInvViewProj = XMMatrixTranspose(mInvViewProj);

    pcbPerFrame->m_mInvViewProjViewport = XMMatrixTranspose(mInvViewProjViewport);

    pcbPerFrame->m_mWorld = XMMatrixTranspose(*pModelTransformForHead);

    XMStoreFloat3(&pcbPerFrame->m_vEye, eyePoint);

    pcbPerFrame->m_fvFOV = XM_PI/4;

    // Light camera parameters
    pcbPerFrame->m_mViewProjLight  = XMMatrixTranspose(*pViewProjLightOut);
    pcbPerFrame->m_fNearLight = min_dis;
    pcbPerFrame->m_fFarLight = max_dis;

    XMStoreFloat4(&pcbPerFrame->m_PointLightPos, lightPosition);
    pcbPerFrame->m_PointLightPos.w = 1;

    // scene light color
    pcbPerFrame->m_AmbientLightColor = m_hairParams.ambientLightColor;
    pcbPerFrame->m_PointLightColor = m_hairParams.pointLightColor;

    // hair material
    pcbPerFrame->m_MatBaseColor =  XMFLOAT4(m_hairParams.color.x, m_hairParams.color.y, m_hairParams.color.z, 1);
    pcbPerFrame->m_MatKValue = XMFLOAT4(m_hairParams.Ka, m_hairParams.Kd, m_hairParams.Ks1, m_hairParams.Ex1);
    pcbPerFrame->m_fHairKs2 = m_hairParams.Ks2;
    pcbPerFrame->m_fHairEx2 = m_hairParams.Ex2;

    pcbPerFrame->m_FiberAlpha = m_hairParams.alpha;
    pcbPerFrame->m_HairSMAlpha = m_hairParams.shadowMapAlpha;

    pcbPerFrame->m_FiberRadius = m_hairParams.thickness;

    pcbPerFrame->m_FiberSpacing = m_hairParams.duplicateStrandSpacing;

    pcbPerFrame->m_bThinTip = (m_hairParams.bThinTip ? 1.f : -1.f);
    pcbPerFrame->m_bExpandPixels = 1;

    pcbPerFrame->m_WinSize = XMFLOAT4((float)screenWidth, (float)screenHeight, 1.0f/(float)screenWidth, 1.0f/(float)screenHeight);

    pcbPerFrame->m_iMaxFragments = m_hairParams.maxFragments;

    pcbPerFrame->m_alphaThreshold = m_hairParams.alphaThreshold;

    pcbPerFrame->m_iTechSM = m_hairParams.shadowTechnique;
    pcbPerFrame->m_bUseCoverage = m_hairParams.bAntialias ? 1 : 0;
    pcbPerFrame->m_iStrandCopies = m_hairParams.strandCopies;

    pcbPerFrame->m_mNumVerticesPerStrand = g_TressFXNumVerticesPerStrand;
    pcbPerFrame->m_mNumFollowHairsPerGuideHair = m_pTressFXMesh->m_HairAsset.m_NumFollowHairsPerGuideHair;
    pcbPerFrame->m_bSingleHeadTransform = singleHeadTransform;

    unsigned optionalSRVs = 0;
    if ((m_pTressFXMesh->m_pStrandTexCoordSRV) && (m_pTressFXMesh->m_pHairTextureSRV))
    {
        optionalSRVs |= PER_STRAND_TEX_COORDS;
        // ignore the material base color when getting hair color from the texture
        pcbPerFrame->m_MatBaseColor =  XMFLOAT4(1, 1, 1, 1);
    }
    pcbPerFrame->m_optionalSRVs = optionalSRVs;

    pd3dContext->Unmap( m_pcbPerFrame, 0 );

    // Set constant buffer for vertex and pixel shader
    pd3dContext->VSSetConstantBuffers( 1, 1, &m_pcbPerFrame );
    pd3dContext->PSSetConstantBuffers( 1, 1, &m_pcbPerFrame );
}
Ejemplo n.º 26
0
    DirectX::BoundingOrientedBox GetBoundsInOrientedSpace(_In_ bool findTightestBounds, _In_ function<bool(XMFLOAT3*)> vertGenerator)
    {
        // we find tight bounds by
        // 1. find the convex hull
        // 2. rotating calipers to find the ideal bounding box - http://en.wikipedia.org/wiki/Rotating_calipers

        // The idea behind rotating calipers is that we keep track of some extreme vertices, and slowly rotate our coordinate frame.
        // As we rotate, a vertex may no-longer be extreme in the new rotated coordinate frame, so we increment the index to the next vertex
        // in the convex hull that is now extreme.

        float zmin = FLT_MAX, zmax = -FLT_MAX;
        auto convexHull = FindConvexHull([&](XMFLOAT2 *planarVert, UINT32 *index) -> bool
        {
            *index = 0; // we dont' care about the index here - only useful when exposing the convex hull directly

            XMFLOAT3 vert;
            bool ret = vertGenerator(&vert);
            if (ret)
            {
                if (vert.z < zmin)
                {
                    zmin = vert.z;
                }

                if (vert.z > zmax)
                {
                    zmax = vert.z;
                }
            }
            *planarVert = { vert.x, vert.y };
            return ret;
        });

        // first we need to set up the calipers - extreme vertices that we will incrementally update as we rotate
        XMFLOAT2 maxv = convexHull[0].first;
        XMFLOAT2 minv = convexHull[0].first;
        struct RotatedBoundingBox
        {
            UINT32 maxx, maxy, minx, miny; // these represent the indices of the max/min x and y coordinates in a rotated coordated frame.
            float area;
            float minwidth;
            float angle;
        };

        // find the initial orientation's bounds:
        RotatedBoundingBox best = { 0, 0, 0, 0, FLT_MAX, FLT_MAX, XM_2PI };
        for (UINT32 i = 1; i < convexHull.size(); ++i)
        {
            const auto vertex = convexHull[i].first;
            if (vertex.x > maxv.x)
            {
                maxv.x = vertex.x;
                best.maxx = i;
            }
            else if (vertex.x < minv.x)
            {
                minv.x = vertex.x;
                best.minx = i;
            }

            if (vertex.y > maxv.y)
            {
                maxv.y = vertex.y;
                best.maxy = i;
            }
            else if (vertex.y < minv.y)
            {
                minv.y = vertex.y;
                best.miny = i;
            }
        }
        best.angle = 0;
        best.area = (maxv.x - minv.x) * (maxv.y - minv.y);
        best.minwidth = min(maxv.x - minv.x, maxv.y - minv.y);

        ASSERT(best.minx != best.maxx); // xmin and xmax indices should never be the same
        ASSERT(best.miny != best.maxy);

        ASSERT(best.minx <= best.maxy); // our vertices should be located around the convex hull xmin->ymax->xmax->ymin
        ASSERT(best.maxy <= best.maxx);
        ASSERT(best.maxx <= best.miny || best.minx == best.miny);
        ASSERT(best.miny <= best.minx + convexHull.size());

        ASSERT(best.minx <= convexHull.size()); // all of the indices should be in the convex hull
        ASSERT(best.maxx <= convexHull.size());
        ASSERT(best.miny <= convexHull.size());
        ASSERT(best.maxy <= convexHull.size());

        ASSERT(best.minx == 0); // we expect minx to be the first vertex in the convex hull

                                // Helper to calculate the rotation if we move from the given vertex to the next vertex in the convex hull
        auto getDeltaVectorForIndex = [&](UINT32 vert)
        {
            // return the delta between the given vertex and the subsequent vertex, so we can determine the angle our bounding box
            // would have to rotate to be parallel with this edge
            auto start = convexHull[vert % convexHull.size()].first;
            auto next = convexHull[(vert + 1) % convexHull.size()].first;

            ASSERT(start.x != next.x || start.y != next.y);

            return XMFLOAT2({ next.x - start.x, next.y - start.y });
        };

        // once we have the extreme vertices, we slowly rotate our coordinate system and adjust them
        // we rotate in such a way that only one extreme vertex changes at a time
        float angle = 0;
        RotatedBoundingBox current = best;

        BoundingOrientedBox bestBoxInPlaneSpace;
        bestBoxInPlaneSpace.Center = { (maxv.x + minv.x) / 2, (maxv.y + minv.y) / 2, (zmax + zmin) / 2 };
        bestBoxInPlaneSpace.Extents = { (maxv.x - minv.x) / 2, (maxv.y - minv.y) / 2, (zmax - zmin) / 2 };
        bestBoxInPlaneSpace.Orientation = { 0, 0, 0, 1 };

        if (findTightestBounds)
        {
            RotatedBoundingBox initial = best;

            // The tightest bounding box will share a side with the convex hull.  We start with a candidate bounding box oriented along
            // the x/y axes and iterate through all orientations where the box is aligned with an edge of the convex hull.  The maximum possible rotations
            // we need to consider is convexHull.size(), which would be a rotation of 90 degrees.
            // Each iteration through the loop, we pick the vertex from our extreme vertices that has the smallest incremental rotation along its outgoing edge.
            // A neat trick is that the other extreme vertices remain extreme in the new rotated orientation.
            while (angle <= XM_PIDIV2 + ROTATING_CALIPERS_EPSILON &&
                current.minx <= initial.maxy &&
                current.maxy <= initial.maxx &&
                current.maxx <= initial.miny &&
                current.miny <= convexHull.size())
            {
                const auto vectForXmin = getDeltaVectorForIndex(current.minx);
                const auto vectForXmax = getDeltaVectorForIndex(current.maxx);
                const auto vectForYmin = getDeltaVectorForIndex(current.miny);
                const auto vectForYmax = getDeltaVectorForIndex(current.maxy);

                UINT32* boundIndices[4] = { &current.minx, &current.maxx, &current.miny, &current.maxy };
                float angles[4] = {
                    atan2(vectForXmin.x, vectForXmin.y),
                    atan2(-vectForXmax.x, -vectForXmax.y),
                    atan2(vectForYmin.y, -vectForYmin.x),
                    atan2(-vectForYmax.y, vectForYmax.x) };

                int index = 0;
                float minAngle = XM_PI * 4 + angle;
                for (int i = 0; i < 4; ++i)
                {
                    if (angles[i] > -ROTATING_CALIPERS_EPSILON && angles[i] < 0)
                    {
                        // the vector between vertices are horizontal/vertical, so angle is close to 0, treat it as zero
                        // this can only occur with a rounding error
                        angles[i] = 0;
                    }
                    else if (angles[i] < 0)
                    {
                        angles[i] += XM_PI * 2;
                    }

                    if (angles[i] < minAngle)
                    {
                        minAngle = angles[i];
                        index = i;
                    }
                }

                *(boundIndices[index]) = ((*(boundIndices[index])) + 1);

                ASSERT(current.minx <= current.maxy); // we should remain ordering of vertices xmin->ymax->xmax->ymin as we rotate
                ASSERT(current.maxy <= current.maxx);
                ASSERT(current.maxx <= current.miny || best.minx == best.miny);
                ASSERT(current.miny <= current.minx + convexHull.size());

                ASSERT(current.minx != current.maxx); // and we shouldn't ever have min and max indices equal
                ASSERT(current.miny != current.maxy);


                // now update our box:
                angle = minAngle;
                current.angle = minAngle;
                if (angle < XM_PIDIV2 + ROTATING_CALIPERS_EPSILON)
                {
                    XMVECTOR vertsInRotatedPlaneSpace[4];
                    const XMMATRIX rotationTransform = XMMatrixRotationZ(angle);
                    for (int i = 0; i < 4; ++i)
                    {
                        vertsInRotatedPlaneSpace[i] = XMVector3TransformCoord(XMLoadFloat2(&convexHull[(*(boundIndices[i])) % convexHull.size()].first), rotationTransform);
                    }

                    BoundingOrientedBox xmBoundsInPlaneSpace;
                    xmBoundsInPlaneSpace.Center = { XMVectorGetX(vertsInRotatedPlaneSpace[0] + vertsInRotatedPlaneSpace[1]) / 2, XMVectorGetY(vertsInRotatedPlaneSpace[2] + vertsInRotatedPlaneSpace[3]) / 2, (zmax + zmin) / 2 };
                    xmBoundsInPlaneSpace.Extents = { XMVectorGetX(vertsInRotatedPlaneSpace[1] - vertsInRotatedPlaneSpace[0]) / 2, XMVectorGetY(vertsInRotatedPlaneSpace[3] - vertsInRotatedPlaneSpace[2]) / 2, (zmax - zmin) / 2 };
                    xmBoundsInPlaneSpace.Orientation = { 0, 0, 0, 1 };
                    xmBoundsInPlaneSpace.Transform(xmBoundsInPlaneSpace, XMMatrixTranspose(rotationTransform)); // rotate back to plane space from rotated plane space

                    const XMFLOAT2 size = { xmBoundsInPlaneSpace.Extents.x * 2, xmBoundsInPlaneSpace.Extents.y * 2 };
                    current.area = size.x * size.y;
                    current.minwidth = min(size.x, size.y);
                    if (current.area < best.area || (current.area == best.area && current.minwidth < best.minwidth))
                    {
                        best = current;
                        bestBoxInPlaneSpace = xmBoundsInPlaneSpace;
                    }
                }
            }
        }

        return bestBoxInPlaneSpace;
    }
Ejemplo n.º 27
0
    void Camera::Update(float dt)
    {
        if (m_IsMovable)
        {
            float lx, ly, rx, ry;
            g_InputHandler.PollThumbstick(lx, ly, rx, ry);

            bool controller = false;
            if (lx < 0.0f || lx > 0.0f)
            {
                m_moveLeftRight = dt * m_speed * lx;
                controller = true;
            }
            if (ly < 0.0f || ly > 0.0f)
            {
                m_moveBackForward = dt * m_speed * ly;
                controller = true;
            }

            if (rx < 0.0f || rx > 0.0f)
            {
                m_camYaw +=  dt * m_rotateSpeed * rx;
                controller = true;
            }
            if (ry < 0.0f || ry > 0.0f)
            {
                m_camPitch += dt * m_rotateSpeed * ry * -1.0f;
                controller = true;
            }

            if (!controller)
            // Handle Input
            if (g_InputHandler.KeyPressed(Keys::A))
            {
                m_moveLeftRight -= dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::W))
            {
                m_moveBackForward += dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::D))
            {
                m_moveLeftRight += dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::S))
            {
                m_moveBackForward -= dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::Left_Shift))
            {
                m_moveUpDown += dt * m_speed;
            }
            if (g_InputHandler.KeyPressed(Keys::Left_Ctrl))
            {
                m_moveUpDown -= dt * m_speed;
            }
        }

        m_camRotationMatrix = XMMatrixRotationRollPitchYaw(m_camPitch, m_camYaw, 0);
        m_camTarget = XMVector3TransformCoord(m_defaultForward, m_camRotationMatrix);
        m_camTarget = XMVector3Normalize(m_camTarget);

        XMMATRIX RotateYTempMatrix;
        RotateYTempMatrix = XMMatrixRotationY(m_camYaw);

        m_camRight = XMVector3TransformCoord(m_defaultRight, RotateYTempMatrix);
        // m_camUp = XMVector3TransformCoord(m_camUp, RotateYTempMatrix);
        m_camForward = XMVector3TransformCoord(m_defaultForward, RotateYTempMatrix);

        m_camPosition += m_moveLeftRight*m_camRight;
        m_camPosition += m_moveBackForward*m_camForward;
        m_camPosition += m_moveUpDown*m_camUp;

        m_moveLeftRight = 0.0f;
        m_moveBackForward = 0.0f;
        m_moveUpDown = 0.0f;

        m_camTarget = m_camPosition + m_camTarget;

        m_camView = XMMatrixLookAtLH( m_camPosition, m_camTarget, m_camUp );
    }
Ejemplo n.º 28
0
bool CScene::Picking( int x, int y )
{
	// 2차원 점의 투영 공간으로의 변환
	XMMATRIX p = XMLoadFloat4x4( &( m_pCamera->GetProjectionMatrix( ) ) );
	D3D11_VIEWPORT d3dViewport = m_pCamera->GetViewport( );

	XMFLOAT3 vPickPosition;
	vPickPosition.x = ( ( ( 2.0f * ( x - d3dViewport.TopLeftX ) ) / d3dViewport.Width ) - 1 ) / p( 0, 0 );
	vPickPosition.y = -( ( ( 2.0f * ( y - d3dViewport.TopLeftY ) ) / d3dViewport.Height ) - 1 ) / p( 1, 1 );

	XMVECTOR rayOrigin = XMVectorSet( 0.0f, 0.0f, 0.0f, 1.0f );
	XMVECTOR rayDir = XMVectorSet( vPickPosition.x, vPickPosition.y, 1.0, 0.0f );

	// 2차원 점의 시야공간으로의 변환
	XMMATRIX v = XMLoadFloat4x4( &( m_pCamera->GetViewMatrix( ) ) );
	XMMATRIX invView = XMMatrixInverse( &XMMatrixDeterminant( v ), v );		// determinant = 행렬식

	// 각 물체와 충돌체크
	float fHitDist = FLT_MAX, fNearDist = FLT_MAX;
	XMFLOAT3 vHitPos, vNearPos;
	bool bIntersection = false;
	CGameObject *IntersectionObject = NULL;		// 충돌된 오브젝트 정보를 가짐
	// 여러개의 셰이더를 돌면서 검사함
	for (int i = 1; i < m_nShaders; i++)		// 0번째 셰이더는 스카이박스만 그리므고 검사할 필요가 없음
	{
		for (int j = 0; j < m_ppShaders[i]->getObjectCount( ); j++)
		{
			CGameObject* tempObj = m_ppShaders[i]->getObjects( )[j];

			XMMATRIX w = XMLoadFloat4x4( &( tempObj->m_mtxWorld ) );
			XMMATRIX invWorld = XMMatrixInverse( &XMMatrixDeterminant( w ), w );

			XMMATRIX toLocal = XMMatrixMultiply( invView, invWorld );

			rayOrigin = XMVector3TransformCoord( rayOrigin, toLocal );	// XMVector3TransformCoord 함수는 벡터의 4번째 성분이 1이라고 가정하고 계산, 따라서 점을 변환할 때 사용
			rayDir = XMVector3TransformNormal( rayDir, toLocal );			// XMVector3TransformNormal 함수는 벡터의 4번째 성분이 0이라고 가정하고 계산, 따라서 벡터를 변환할 때 사용

			rayDir = XMVector3Normalize( rayDir );	// 교차 판정을 위해 반직선 방향벡터를 단위길이로 정규화

			// 참일 경우 충돌된 것이므로 현재 가장 가까운 곳에 충돌된 것과 검사
			if (tempObj->CheckRayIntersection( &rayOrigin, &rayDir, &fHitDist, &vHitPos ))
			{
				bIntersection = true;
				if (fNearDist > fHitDist)
				{
					fNearDist = fHitDist;
					IntersectionObject = tempObj;
					vNearPos = vHitPos;
				}
			}
		}
	}

	if (IntersectionObject != NULL)
	{
		pPickedObject = IntersectionObject;
		if (pPickedObject->m_iType == BACK_GROUND)
		{
			vPickPos = vNearPos;
			// vNearPos는 오브젝트의 로컬좌표계이므로 이를 월드좌표계로 변환
			vPickPos = MathHelper::GetInstance( )->Vector3TransformNormal( vPickPos, pPickedObject->m_mtxWorld );
		}
	}
	return bIntersection;
}
Ejemplo n.º 29
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;
		}
	}